Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

lib-jitsi-meet.js 785KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186
  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.JitsiMeetJS = 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. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. /**
  18. * Creates a JitsiConference object with the given name and properties.
  19. * Note: this constructor is not a part of the public API (objects should be
  20. * created using JitsiConnection.createConference).
  21. * @param options.config properties / settings related to the conference that will be created.
  22. * @param options.name the name of the conference
  23. * @param options.connection the JitsiConnection object for this JitsiConference.
  24. * @constructor
  25. */
  26. function JitsiConference(options) {
  27. if(!options.name || options.name.toLowerCase() !== options.name) {
  28. logger.error("Invalid conference name (no conference name passed or it"
  29. + "contains invalid characters like capital letters)!");
  30. return;
  31. }
  32. this.options = options;
  33. this.connection = this.options.connection;
  34. this.xmpp = this.connection.xmpp;
  35. this.eventEmitter = new EventEmitter();
  36. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  37. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  38. this.rtc = new RTC(this.room, options);
  39. if(!RTC.options.disableAudioLevels)
  40. this.statistics = new Statistics();
  41. setupListeners(this);
  42. this.participants = {};
  43. this.lastDominantSpeaker = null;
  44. this.dtmfManager = null;
  45. this.somebodySupportsDTMF = false;
  46. this.authEnabled = false;
  47. this.authIdentity;
  48. this.startAudioMuted = false;
  49. this.startVideoMuted = false;
  50. this.startMutedPolicy = {audio: false, video: false};
  51. }
  52. /**
  53. * Joins the conference.
  54. * @param password {string} the password
  55. */
  56. JitsiConference.prototype.join = function (password) {
  57. if(this.room)
  58. this.room.join(password);
  59. };
  60. /**
  61. * Check if joined to the conference.
  62. */
  63. JitsiConference.prototype.isJoined = function () {
  64. return this.room && this.room.joined;
  65. };
  66. /**
  67. * Leaves the conference.
  68. */
  69. JitsiConference.prototype.leave = function () {
  70. if(this.xmpp && this.room)
  71. this.xmpp.leaveRoom(this.room.roomjid);
  72. this.room = null;
  73. };
  74. /**
  75. * Returns name of this conference.
  76. */
  77. JitsiConference.prototype.getName = function () {
  78. return this.options.name;
  79. };
  80. /**
  81. * Check if authentication is enabled for this conference.
  82. */
  83. JitsiConference.prototype.isAuthEnabled = function () {
  84. return this.authEnabled;
  85. };
  86. /**
  87. * Check if user is logged in.
  88. */
  89. JitsiConference.prototype.isLoggedIn = function () {
  90. return !!this.authIdentity;
  91. };
  92. /**
  93. * Get authorized login.
  94. */
  95. JitsiConference.prototype.getAuthLogin = function () {
  96. return this.authIdentity;
  97. };
  98. /**
  99. * Check if external authentication is enabled for this conference.
  100. */
  101. JitsiConference.prototype.isExternalAuthEnabled = function () {
  102. return this.room && this.room.moderator.isExternalAuthEnabled();
  103. };
  104. /**
  105. * Get url for external authentication.
  106. * @param {boolean} [urlForPopup] if true then return url for login popup,
  107. * else url of login page.
  108. * @returns {Promise}
  109. */
  110. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  111. return new Promise(function (resolve, reject) {
  112. if (!this.isExternalAuthEnabled()) {
  113. reject();
  114. return;
  115. }
  116. if (urlForPopup) {
  117. this.room.moderator.getPopupLoginUrl(resolve, reject);
  118. } else {
  119. this.room.moderator.getLoginUrl(resolve, reject);
  120. }
  121. }.bind(this));
  122. };
  123. /**
  124. * Returns the local tracks.
  125. */
  126. JitsiConference.prototype.getLocalTracks = function () {
  127. if (this.rtc) {
  128. return this.rtc.localStreams;
  129. } else {
  130. return [];
  131. }
  132. };
  133. /**
  134. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  135. * in JitsiConferenceEvents.
  136. * @param eventId the event ID.
  137. * @param handler handler for the event.
  138. *
  139. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  140. */
  141. JitsiConference.prototype.on = function (eventId, handler) {
  142. if(this.eventEmitter)
  143. this.eventEmitter.on(eventId, handler);
  144. };
  145. /**
  146. * Removes event listener
  147. * @param eventId the event ID.
  148. * @param [handler] optional, the specific handler to unbind
  149. *
  150. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  151. */
  152. JitsiConference.prototype.off = function (eventId, handler) {
  153. if(this.eventEmitter)
  154. this.eventEmitter.removeListener(eventId, handler);
  155. };
  156. // Common aliases for event emitter
  157. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  158. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  159. /**
  160. * Receives notifications from another participants for commands / custom events
  161. * (send by sendPresenceCommand method).
  162. * @param command {String} the name of the command
  163. * @param handler {Function} handler for the command
  164. */
  165. JitsiConference.prototype.addCommandListener = function (command, handler) {
  166. if(this.room)
  167. this.room.addPresenceListener(command, handler);
  168. };
  169. /**
  170. * Removes command listener
  171. * @param command {String} the name of the command
  172. */
  173. JitsiConference.prototype.removeCommandListener = function (command) {
  174. if(this.room)
  175. this.room.removePresenceListener(command);
  176. };
  177. /**
  178. * Sends text message to the other participants in the conference
  179. * @param message the text message.
  180. */
  181. JitsiConference.prototype.sendTextMessage = function (message) {
  182. if(this.room)
  183. this.room.sendMessage(message);
  184. };
  185. /**
  186. * Send presence command.
  187. * @param name the name of the command.
  188. * @param values Object with keys and values that will be send.
  189. **/
  190. JitsiConference.prototype.sendCommand = function (name, values) {
  191. if(this.room) {
  192. this.room.addToPresence(name, values);
  193. this.room.sendPresence();
  194. }
  195. };
  196. /**
  197. * Send presence command one time.
  198. * @param name the name of the command.
  199. * @param values Object with keys and values that will be send.
  200. **/
  201. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  202. this.sendCommand(name, values);
  203. this.removeCommand(name);
  204. };
  205. /**
  206. * Send presence command.
  207. * @param name the name of the command.
  208. * @param values Object with keys and values that will be send.
  209. * @param persistent if false the command will be sent only one time
  210. **/
  211. JitsiConference.prototype.removeCommand = function (name) {
  212. if(this.room)
  213. this.room.removeFromPresence(name);
  214. };
  215. /**
  216. * Sets the display name for this conference.
  217. * @param name the display name to set
  218. */
  219. JitsiConference.prototype.setDisplayName = function(name) {
  220. if(this.room){
  221. // remove previously set nickname
  222. this.room.removeFromPresence("nick");
  223. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  224. this.room.sendPresence();
  225. }
  226. };
  227. /**
  228. * Adds JitsiLocalTrack object to the conference.
  229. * @param track the JitsiLocalTrack object.
  230. */
  231. JitsiConference.prototype.addTrack = function (track) {
  232. this.room.addStream(track.getOriginalStream(), function () {
  233. this.rtc.addLocalStream(track);
  234. if (track.startMuted) {
  235. track.mute();
  236. }
  237. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  238. track.stopHandler = this.removeTrack.bind(this, track);
  239. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  240. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  241. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  242. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  243. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  244. }.bind(this));
  245. };
  246. /**
  247. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  248. * @param audioLevel the audio level
  249. */
  250. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  251. this.eventEmitter.emit(
  252. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  253. this.myUserId(), audioLevel);
  254. };
  255. /**
  256. * Fires TRACK_MUTE_CHANGED change conference event.
  257. * @param track the JitsiTrack object related to the event.
  258. */
  259. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  260. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  261. };
  262. /**
  263. * Removes JitsiLocalTrack object to the conference.
  264. * @param track the JitsiLocalTrack object.
  265. */
  266. JitsiConference.prototype.removeTrack = function (track) {
  267. if(!this.room){
  268. if(this.rtc)
  269. this.rtc.removeLocalStream(track);
  270. return;
  271. }
  272. this.room.removeStream(track.getOriginalStream(), function(){
  273. this.rtc.removeLocalStream(track);
  274. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  275. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  276. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  277. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  278. }.bind(this));
  279. };
  280. /**
  281. * Get role of the local user.
  282. * @returns {string} user role: 'moderator' or 'none'
  283. */
  284. JitsiConference.prototype.getRole = function () {
  285. return this.room.role;
  286. };
  287. /**
  288. * Check if local user is moderator.
  289. * @returns {boolean} true if local user is moderator, false otherwise.
  290. */
  291. JitsiConference.prototype.isModerator = function () {
  292. return this.room.isModerator();
  293. };
  294. /**
  295. * Set password for the room.
  296. * @param {string} password new password for the room.
  297. * @returns {Promise}
  298. */
  299. JitsiConference.prototype.lock = function (password) {
  300. if (!this.isModerator()) {
  301. return Promise.reject();
  302. }
  303. var conference = this;
  304. return new Promise(function (resolve, reject) {
  305. conference.room.lockRoom(password || "", function () {
  306. resolve();
  307. }, function (err) {
  308. reject(err);
  309. }, function () {
  310. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  311. });
  312. });
  313. };
  314. /**
  315. * Remove password from the room.
  316. * @returns {Promise}
  317. */
  318. JitsiConference.prototype.unlock = function () {
  319. return this.lock();
  320. };
  321. /**
  322. * Elects the participant with the given id to be the selected participant or the speaker.
  323. * @param id the identifier of the participant
  324. */
  325. JitsiConference.prototype.selectParticipant = function(participantId) {
  326. if (this.rtc) {
  327. this.rtc.selectedEndpoint(participantId);
  328. }
  329. };
  330. /**
  331. *
  332. * @param id the identifier of the participant
  333. */
  334. JitsiConference.prototype.pinParticipant = function(participantId) {
  335. if (this.rtc) {
  336. this.rtc.pinEndpoint(participantId);
  337. }
  338. };
  339. /**
  340. * Returns the list of participants for this conference.
  341. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  342. */
  343. JitsiConference.prototype.getParticipants = function() {
  344. return Object.keys(this.participants).map(function (key) {
  345. return this.participants[key];
  346. }, this);
  347. };
  348. /**
  349. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  350. * undefined if there isn't one).
  351. * @param id the id of the participant.
  352. */
  353. JitsiConference.prototype.getParticipantById = function(id) {
  354. return this.participants[id];
  355. };
  356. /**
  357. * Kick participant from this conference.
  358. * @param {string} id id of the participant to kick
  359. */
  360. JitsiConference.prototype.kickParticipant = function (id) {
  361. var participant = this.getParticipantById(id);
  362. if (!participant) {
  363. return;
  364. }
  365. this.room.kick(participant.getJid());
  366. };
  367. /**
  368. * Kick participant from this conference.
  369. * @param {string} id id of the participant to kick
  370. */
  371. JitsiConference.prototype.muteParticipant = function (id) {
  372. var participant = this.getParticipantById(id);
  373. if (!participant) {
  374. return;
  375. }
  376. this.room.muteParticipant(participant.getJid(), true);
  377. };
  378. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  379. var id = Strophe.getResourceFromJid(jid);
  380. if (id === 'focus' || this.myUserId() === id) {
  381. return;
  382. }
  383. var participant = new JitsiParticipant(jid, this, nick);
  384. participant._role = role;
  385. this.participants[id] = participant;
  386. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  387. this.xmpp.connection.disco.info(
  388. jid, "node", function(iq) {
  389. participant._supportsDTMF = $(iq).find(
  390. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  391. this.updateDTMFSupport();
  392. }.bind(this)
  393. );
  394. };
  395. JitsiConference.prototype.onMemberLeft = function (jid) {
  396. var id = Strophe.getResourceFromJid(jid);
  397. if (id === 'focus' || this.myUserId() === id) {
  398. return;
  399. }
  400. var participant = this.participants[id];
  401. delete this.participants[id];
  402. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  403. };
  404. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  405. var id = Strophe.getResourceFromJid(jid);
  406. var participant = this.getParticipantById(id);
  407. if (!participant) {
  408. return;
  409. }
  410. participant._role = role;
  411. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  412. };
  413. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  414. var id = Strophe.getResourceFromJid(jid);
  415. var participant = this.getParticipantById(id);
  416. if (!participant) {
  417. return;
  418. }
  419. participant._displayName = displayName;
  420. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  421. };
  422. JitsiConference.prototype.onTrackAdded = function (track) {
  423. var id = track.getParticipantId();
  424. var participant = this.getParticipantById(id);
  425. if (!participant) {
  426. return;
  427. }
  428. // add track to JitsiParticipant
  429. participant._tracks.push(track);
  430. var emitter = this.eventEmitter;
  431. track.addEventListener(
  432. JitsiTrackEvents.TRACK_STOPPED,
  433. function () {
  434. // remove track from JitsiParticipant
  435. var pos = participant._tracks.indexOf(track);
  436. if (pos > -1) {
  437. participant._tracks.splice(pos, 1);
  438. }
  439. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  440. }
  441. );
  442. track.addEventListener(
  443. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  444. function () {
  445. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  446. }
  447. );
  448. track.addEventListener(
  449. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  450. function (audioLevel) {
  451. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  452. }
  453. );
  454. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  455. };
  456. JitsiConference.prototype.updateDTMFSupport = function () {
  457. var somebodySupportsDTMF = false;
  458. var participants = this.getParticipants();
  459. // check if at least 1 participant supports DTMF
  460. for (var i = 0; i < participants.length; i += 1) {
  461. if (participants[i].supportsDTMF()) {
  462. somebodySupportsDTMF = true;
  463. break;
  464. }
  465. }
  466. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  467. this.somebodySupportsDTMF = somebodySupportsDTMF;
  468. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  469. }
  470. };
  471. /**
  472. * Allows to check if there is at least one user in the conference
  473. * that supports DTMF.
  474. * @returns {boolean} true if somebody supports DTMF, false otherwise
  475. */
  476. JitsiConference.prototype.isDTMFSupported = function () {
  477. return this.somebodySupportsDTMF;
  478. };
  479. /**
  480. * Returns the local user's ID
  481. * @return {string} local user's ID
  482. */
  483. JitsiConference.prototype.myUserId = function () {
  484. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  485. };
  486. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  487. if (!this.dtmfManager) {
  488. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  489. if (!connection) {
  490. logger.warn("cannot sendTones: no conneciton");
  491. return;
  492. }
  493. var tracks = this.getLocalTracks().filter(function (track) {
  494. return track.isAudioTrack();
  495. });
  496. if (!tracks.length) {
  497. logger.warn("cannot sendTones: no local audio stream");
  498. return;
  499. }
  500. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  501. }
  502. this.dtmfManager.sendTones(tones, duration, pause);
  503. };
  504. /**
  505. * Returns true if the recording is supproted and false if not.
  506. */
  507. JitsiConference.prototype.isRecordingSupported = function () {
  508. if(this.room)
  509. return this.room.isRecordingSupported();
  510. return false;
  511. };
  512. /**
  513. * Returns null if the recording is not supported, "on" if the recording started
  514. * and "off" if the recording is not started.
  515. */
  516. JitsiConference.prototype.getRecordingState = function () {
  517. if(this.room)
  518. return this.room.getRecordingState();
  519. return "off";
  520. }
  521. /**
  522. * Returns the url of the recorded video.
  523. */
  524. JitsiConference.prototype.getRecordingURL = function () {
  525. if(this.room)
  526. return this.room.getRecordingURL();
  527. return null;
  528. }
  529. /**
  530. * Starts/stops the recording
  531. */
  532. JitsiConference.prototype.toggleRecording = function (options) {
  533. if(this.room)
  534. return this.room.toggleRecording(options, function (status, error) {
  535. this.eventEmitter.emit(
  536. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  537. }.bind(this));
  538. this.eventEmitter.emit(
  539. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  540. new Error("The conference is not created yet!"));
  541. }
  542. /**
  543. * Returns true if the SIP calls are supported and false otherwise
  544. */
  545. JitsiConference.prototype.isSIPCallingSupported = function () {
  546. if(this.room)
  547. return this.room.isSIPCallingSupported();
  548. return false;
  549. }
  550. /**
  551. * Dials a number.
  552. * @param number the number
  553. */
  554. JitsiConference.prototype.dial = function (number) {
  555. if(this.room)
  556. return this.room.dial(number);
  557. return new Promise(function(resolve, reject){
  558. reject(new Error("The conference is not created yet!"))});
  559. }
  560. /**
  561. * Hangup an existing call
  562. */
  563. JitsiConference.prototype.hangup = function () {
  564. if(this.room)
  565. return this.room.hangup();
  566. return new Promise(function(resolve, reject){
  567. reject(new Error("The conference is not created yet!"))});
  568. }
  569. /**
  570. * Returns the phone number for joining the conference.
  571. */
  572. JitsiConference.prototype.getPhoneNumber = function () {
  573. if(this.room)
  574. return this.room.getPhoneNumber();
  575. return null;
  576. }
  577. /**
  578. * Returns the pin for joining the conference with phone.
  579. */
  580. JitsiConference.prototype.getPhonePin = function () {
  581. if(this.room)
  582. return this.room.getPhonePin();
  583. return null;
  584. }
  585. /**
  586. * Returns the connection state for the current room. Its ice connection state
  587. * for its session.
  588. */
  589. JitsiConference.prototype.getConnectionState = function () {
  590. if(this.room)
  591. return this.room.getConnectionState();
  592. return null;
  593. }
  594. /**
  595. * Make all new participants mute their audio/video on join.
  596. * @param policy {Object} object with 2 boolean properties for video and audio:
  597. * @param {boolean} audio if audio should be muted.
  598. * @param {boolean} video if video should be muted.
  599. */
  600. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  601. if (!this.isModerator()) {
  602. return;
  603. }
  604. this.startMutedPolicy = policy;
  605. this.room.removeFromPresence("startmuted");
  606. this.room.addToPresence("startmuted", {
  607. attributes: {
  608. audio: policy.audio,
  609. video: policy.video,
  610. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  611. }
  612. });
  613. this.room.sendPresence();
  614. };
  615. /**
  616. * Returns current start muted policy
  617. * @returns {Object} with 2 proprties - audio and video.
  618. */
  619. JitsiConference.prototype.getStartMutedPolicy = function () {
  620. return this.startMutedPolicy;
  621. };
  622. /**
  623. * Check if audio is muted on join.
  624. */
  625. JitsiConference.prototype.isStartAudioMuted = function () {
  626. return this.startAudioMuted;
  627. };
  628. /**
  629. * Check if video is muted on join.
  630. */
  631. JitsiConference.prototype.isStartVideoMuted = function () {
  632. return this.startVideoMuted;
  633. };
  634. JitsiConference.prototype.getLogs = function () {
  635. var data = this.xmpp.getJingleLog();
  636. var metadata = {};
  637. metadata.time = new Date();
  638. metadata.url = window.location.href;
  639. metadata.ua = navigator.userAgent;
  640. var log = this.xmpp.getXmppLog();
  641. if (log) {
  642. metadata.xmpp = log;
  643. }
  644. data.metadata = metadata;
  645. return data;
  646. };
  647. /**
  648. * Setups the listeners needed for the conference.
  649. * @param conference the conference
  650. */
  651. function setupListeners(conference) {
  652. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  653. conference.rtc.onIncommingCall(event);
  654. if(conference.statistics)
  655. conference.statistics.startRemoteStats(event.peerconnection);
  656. });
  657. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  658. function (data, sid, thessrc) {
  659. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  660. if (track) {
  661. conference.onTrackAdded(track);
  662. }
  663. }
  664. );
  665. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  666. function (value) {
  667. conference.rtc.setAudioMute(value);
  668. }
  669. );
  670. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  671. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  672. });
  673. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  674. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  675. });
  676. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  677. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  678. });
  679. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  680. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  681. });
  682. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  683. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  684. });
  685. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  686. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  687. });
  688. // FIXME
  689. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  690. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  691. // });
  692. conference.room.addListener(XMPPEvents.KICKED, function () {
  693. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  694. });
  695. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  696. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  697. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  698. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  699. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  700. });
  701. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  702. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  703. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  704. });
  705. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  706. function () {
  707. conference.eventEmitter.emit(
  708. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  709. });
  710. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  711. conference.eventEmitter.emit(
  712. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  713. });
  714. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  715. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  716. });
  717. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  718. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  719. });
  720. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  721. conference.authEnabled = authEnabled;
  722. conference.authIdentity = authIdentity;
  723. });
  724. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  725. var id = Strophe.getResourceFromJid(jid);
  726. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  727. });
  728. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  729. if(conference.lastDominantSpeaker !== id && conference.room) {
  730. conference.lastDominantSpeaker = id;
  731. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  732. }
  733. });
  734. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  735. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  736. });
  737. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  738. function (lastNEndpoints, endpointsEnteringLastN) {
  739. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  740. lastNEndpoints, endpointsEnteringLastN);
  741. });
  742. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  743. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  744. });
  745. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
  746. function (audioMuted, videoMuted) {
  747. conference.startAudioMuted = audioMuted;
  748. conference.startVideoMuted = videoMuted;
  749. // mute existing local tracks because this is initial mute from
  750. // Jicofo
  751. conference.getLocalTracks().forEach(function (track) {
  752. if (conference.startAudioMuted && track.isAudioTrack()) {
  753. track.mute();
  754. }
  755. if (conference.startVideoMuted && track.isVideoTrack()) {
  756. track.mute();
  757. }
  758. });
  759. conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
  760. });
  761. conference.room.addPresenceListener("startmuted", function (data, from) {
  762. var isModerator = false;
  763. if (conference.myUserId() === from && conference.isModerator()) {
  764. isModerator = true;
  765. } else {
  766. var participant = conference.getParticipantById(from);
  767. if (participant && participant.isModerator()) {
  768. isModerator = true;
  769. }
  770. }
  771. if (!isModerator) {
  772. return;
  773. }
  774. var startAudioMuted = data.attributes.audio === 'true';
  775. var startVideoMuted = data.attributes.video === 'true';
  776. var updated = false;
  777. if (startAudioMuted !== conference.startMutedPolicy.audio) {
  778. conference.startMutedPolicy.audio = startAudioMuted;
  779. updated = true;
  780. }
  781. if (startVideoMuted !== conference.startMutedPolicy.video) {
  782. conference.startMutedPolicy.video = startVideoMuted;
  783. updated = true;
  784. }
  785. if (updated) {
  786. conference.eventEmitter.emit(
  787. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  788. conference.startMutedPolicy
  789. );
  790. }
  791. });
  792. if(conference.statistics) {
  793. //FIXME: Maybe remove event should not be associated with the conference.
  794. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  795. var userId = null;
  796. var jid = conference.room.getJidBySSRC(ssrc);
  797. if (!jid)
  798. return;
  799. conference.rtc.setAudioLevel(jid, level);
  800. });
  801. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  802. function () {
  803. conference.statistics.dispose();
  804. });
  805. // FIXME: Maybe we should move this.
  806. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  807. // conference.room.updateDeviceAvailability(devices);
  808. // });
  809. }
  810. }
  811. module.exports = JitsiConference;
  812. }).call(this,"/JitsiConference.js")
  813. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":80,"./service/authentication/AuthenticationEvents":83,"./service/xmpp/XMPPEvents":87,"events":44,"jitsi-meet-logger":48}],2:[function(require,module,exports){
  814. /**
  815. * Enumeration with the errors for the conference.
  816. * @type {{string: string}}
  817. */
  818. var JitsiConferenceErrors = {
  819. /**
  820. * Indicates that a password is required in order to join the conference.
  821. */
  822. PASSWORD_REQUIRED: "conference.passwordRequired",
  823. /**
  824. * Indicates that client must be authenticated to create the conference.
  825. */
  826. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  827. /**
  828. * Indicates that password cannot be set for this conference.
  829. */
  830. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  831. /**
  832. * Indicates that a connection error occurred when trying to join a
  833. * conference.
  834. */
  835. CONNECTION_ERROR: "conference.connectionError",
  836. /**
  837. * Indicates that the conference setup failed.
  838. */
  839. SETUP_FAILED: "conference.setup_failed",
  840. /**
  841. * Indicates that there is no available videobridge.
  842. */
  843. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  844. /**
  845. * Many more errors TBD here.
  846. */
  847. };
  848. module.exports = JitsiConferenceErrors;
  849. },{}],3:[function(require,module,exports){
  850. /**
  851. * Enumeration with the events for the conference.
  852. * @type {{string: string}}
  853. */
  854. var JitsiConferenceEvents = {
  855. /**
  856. * A new media track was added to the conference.
  857. */
  858. TRACK_ADDED: "conference.trackAdded",
  859. /**
  860. * The media track was removed from the conference.
  861. */
  862. TRACK_REMOVED: "conference.trackRemoved",
  863. /**
  864. * The dominant speaker was changed.
  865. */
  866. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  867. /**
  868. * A new user joinned the conference.
  869. */
  870. USER_JOINED: "conference.userJoined",
  871. /**
  872. * A user has left the conference.
  873. */
  874. USER_LEFT: "conference.userLeft",
  875. /**
  876. * User role changed.
  877. */
  878. USER_ROLE_CHANGED: "conference.roleChanged",
  879. /**
  880. * New text message was received.
  881. */
  882. MESSAGE_RECEIVED: "conference.messageReceived",
  883. /**
  884. * A user has changed it display name
  885. */
  886. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  887. /**
  888. * A participant avatar has changed.
  889. */
  890. AVATAR_CHANGED: "conference.avatarChanged",
  891. /**
  892. * New connection statistics are received.
  893. */
  894. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  895. /**
  896. * The Last N set is changed.
  897. */
  898. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  899. /**
  900. * You are included / excluded in somebody's last N set
  901. */
  902. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  903. /**
  904. * A media track ( attached to the conference) mute status was changed.
  905. */
  906. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  907. /**
  908. * Audio levels of a media track ( attached to the conference) was changed.
  909. */
  910. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  911. /**
  912. * Indicates that the connection to the conference has been interrupted
  913. * for some reason.
  914. */
  915. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  916. /**
  917. * Indicates that the connection to the conference has been restored.
  918. */
  919. CONNECTION_RESTORED: "conference.connectionRestored",
  920. /**
  921. * Indicates that conference failed.
  922. */
  923. CONFERENCE_FAILED: "conference.failed",
  924. /**
  925. * Indicates that conference has been joined.
  926. */
  927. CONFERENCE_JOINED: "conference.joined",
  928. /**
  929. * Indicates that conference has been left.
  930. */
  931. CONFERENCE_LEFT: "conference.left",
  932. /**
  933. * You are kicked from the conference.
  934. */
  935. KICKED: "conferenece.kicked",
  936. /**
  937. * Indicates that start muted settings changed.
  938. */
  939. START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
  940. /**
  941. * Indicates that the local user has started muted.
  942. */
  943. STARTED_MUTED: "conference.started_muted",
  944. /**
  945. * Indicates that DTMF support changed.
  946. */
  947. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  948. /**
  949. * Indicates that recording state changed.
  950. */
  951. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  952. /**
  953. * Indicates that phone number changed.
  954. */
  955. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  956. };
  957. module.exports = JitsiConferenceEvents;
  958. },{}],4:[function(require,module,exports){
  959. var JitsiConference = require("./JitsiConference");
  960. var XMPP = require("./modules/xmpp/xmpp");
  961. /**
  962. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  963. * JitsiConference interface.
  964. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  965. * @param token the JWT token used to authenticate with the server(optional)
  966. * @param options Object with properties / settings related to connection with the server.
  967. * @constructor
  968. */
  969. function JitsiConnection(appID, token, options) {
  970. this.appID = appID;
  971. this.token = token;
  972. this.options = options;
  973. this.xmpp = new XMPP(options);
  974. this.conferences = {};
  975. }
  976. /**
  977. * Connect the client with the server.
  978. * @param options {object} connecting options (for example authentications parameters).
  979. */
  980. JitsiConnection.prototype.connect = function (options) {
  981. if(!options)
  982. options = {};
  983. this.xmpp.connect(options.id, options.password);
  984. }
  985. /**
  986. * Disconnect the client from the server.
  987. */
  988. JitsiConnection.prototype.disconnect = function () {
  989. this.xmpp.disconnect();
  990. }
  991. /**
  992. * This method allows renewal of the tokens if they are expiring.
  993. * @param token the new token.
  994. */
  995. JitsiConnection.prototype.setToken = function (token) {
  996. this.token = token;
  997. }
  998. /**
  999. * Creates and joins new conference.
  1000. * @param name the name of the conference; if null - a generated name will be
  1001. * provided from the api
  1002. * @param options Object with properties / settings related to the conference
  1003. * that will be created.
  1004. * @returns {JitsiConference} returns the new conference object.
  1005. */
  1006. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1007. this.conferences[name] = new JitsiConference({name: name, config: options,
  1008. connection: this});
  1009. return this.conferences[name];
  1010. }
  1011. /**
  1012. * Subscribes the passed listener to the event.
  1013. * @param event {JitsiConnectionEvents} the connection event.
  1014. * @param listener {Function} the function that will receive the event
  1015. */
  1016. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1017. this.xmpp.addListener(event, listener);
  1018. }
  1019. /**
  1020. * Unsubscribes the passed handler.
  1021. * @param event {JitsiConnectionEvents} the connection event.
  1022. * @param listener {Function} the function that will receive the event
  1023. */
  1024. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1025. this.xmpp.removeListener(event, listener);
  1026. }
  1027. module.exports = JitsiConnection;
  1028. },{"./JitsiConference":1,"./modules/xmpp/xmpp":42}],5:[function(require,module,exports){
  1029. /**
  1030. * Enumeration with the errors for the connection.
  1031. * @type {{string: string}}
  1032. */
  1033. var JitsiConnectionErrors = {
  1034. /**
  1035. * Indicates that a password is required in order to join the conference.
  1036. */
  1037. PASSWORD_REQUIRED: "connection.passwordRequired",
  1038. /**
  1039. * Indicates that a connection error occurred when trying to join a
  1040. * conference.
  1041. */
  1042. CONNECTION_ERROR: "connection.connectionError",
  1043. /**
  1044. * Not specified errors.
  1045. */
  1046. OTHER_ERROR: "connection.otherError"
  1047. };
  1048. module.exports = JitsiConnectionErrors;
  1049. },{}],6:[function(require,module,exports){
  1050. /**
  1051. * Enumeration with the events for the connection.
  1052. * @type {{string: string}}
  1053. */
  1054. var JitsiConnnectionEvents = {
  1055. /**
  1056. * Indicates that the connection has been failed for some reason.
  1057. */
  1058. CONNECTION_FAILED: "connection.connectionFailed",
  1059. /**
  1060. * Indicates that the connection has been established.
  1061. */
  1062. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1063. /**
  1064. * Indicates that the connection has been disconnected.
  1065. */
  1066. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1067. /**
  1068. * Indicates that the perfomed action cannot be executed because the
  1069. * connection is not in the correct state(connected, disconnected, etc.)
  1070. */
  1071. WRONG_STATE: "connection.wrongState"
  1072. };
  1073. module.exports = JitsiConnnectionEvents;
  1074. },{}],7:[function(require,module,exports){
  1075. var JitsiConnection = require("./JitsiConnection");
  1076. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1077. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1078. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1079. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1080. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1081. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1082. var Logger = require("jitsi-meet-logger");
  1083. var RTC = require("./modules/RTC/RTC");
  1084. var Statistics = require("./modules/statistics/statistics");
  1085. var Resolutions = require("./service/RTC/Resolutions");
  1086. function getLowerResolution(resolution) {
  1087. if(!Resolutions[resolution])
  1088. return null;
  1089. var order = Resolutions[resolution].order;
  1090. var res = null;
  1091. var resName = null;
  1092. for(var i in Resolutions) {
  1093. var tmp = Resolutions[i];
  1094. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1095. resName = i;
  1096. res = tmp;
  1097. }
  1098. }
  1099. return resName;
  1100. }
  1101. /**
  1102. * Namespace for the interface of Jitsi Meet Library.
  1103. */
  1104. var LibJitsiMeet = {
  1105. JitsiConnection: JitsiConnection,
  1106. events: {
  1107. conference: JitsiConferenceEvents,
  1108. connection: JitsiConnectionEvents,
  1109. track: JitsiTrackEvents
  1110. },
  1111. errors: {
  1112. conference: JitsiConferenceErrors,
  1113. connection: JitsiConnectionErrors,
  1114. track: JitsiTrackErrors
  1115. },
  1116. logLevels: Logger.levels,
  1117. init: function (options) {
  1118. return RTC.init(options || {});
  1119. },
  1120. /**
  1121. * Returns whether the desktop sharing is enabled or not.
  1122. * @returns {boolean}
  1123. */
  1124. isDesktopSharingEnabled: function () {
  1125. return RTC.isDesktopSharingEnabled();
  1126. },
  1127. setLogLevel: function (level) {
  1128. Logger.setLogLevel(level);
  1129. },
  1130. /**
  1131. * Creates the media tracks and returns them trough the callback.
  1132. * @param options Object with properties / settings specifying the tracks which should be created.
  1133. * should be created or some additional configurations about resolution for example.
  1134. * @param {Array} options.devices the devices that will be requested
  1135. * @param {string} options.resolution resolution constraints
  1136. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1137. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1138. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1139. * @param {string} options.cameraDeviceId
  1140. * @param {string} options.micDeviceId
  1141. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1142. * A promise that returns an array of created JitsiTracks if resolved,
  1143. * or a JitsiConferenceError if rejected.
  1144. */
  1145. createLocalTracks: function (options) {
  1146. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1147. function(tracks) {
  1148. if(!RTC.options.disableAudioLevels)
  1149. for(var i = 0; i < tracks.length; i++) {
  1150. var track = tracks[i];
  1151. var mStream = track.getOriginalStream();
  1152. if(track.getType() === "audio"){
  1153. Statistics.startLocalStats(mStream,
  1154. track.setAudioLevel.bind(track));
  1155. track.addEventListener(
  1156. JitsiTrackEvents.TRACK_STOPPED,
  1157. function(){
  1158. Statistics.stopLocalStats(mStream);
  1159. });
  1160. }
  1161. }
  1162. return tracks;
  1163. }).catch(function (error) {
  1164. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1165. var oldResolution = options.resolution || '360';
  1166. var newResolution = getLowerResolution(oldResolution);
  1167. if(newResolution === null)
  1168. return Promise.reject(error);
  1169. options.resolution = newResolution;
  1170. return LibJitsiMeet.createLocalTracks(options);
  1171. }
  1172. return Promise.reject(error);
  1173. });
  1174. },
  1175. /**
  1176. * Checks if its possible to enumerate available cameras/micropones.
  1177. * @returns {boolean} true if available, false otherwise.
  1178. */
  1179. isDeviceListAvailable: function () {
  1180. return RTC.isDeviceListAvailable();
  1181. },
  1182. /**
  1183. * Returns true if changing the camera / microphone device is supported and
  1184. * false if not.
  1185. * @returns {boolean} true if available, false otherwise.
  1186. */
  1187. isDeviceChangeAvailable: function () {
  1188. return RTC.isDeviceChangeAvailable();
  1189. },
  1190. enumerateDevices: function (callback) {
  1191. RTC.enumerateDevices(callback);
  1192. }
  1193. };
  1194. //Setups the promise object.
  1195. window.Promise = window.Promise || require("es6-promise").Promise;
  1196. module.exports = LibJitsiMeet;
  1197. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/Resolutions":81,"es6-promise":46,"jitsi-meet-logger":48}],8:[function(require,module,exports){
  1198. /* global Strophe */
  1199. /**
  1200. * Represents a participant in (a member of) a conference.
  1201. */
  1202. function JitsiParticipant(jid, conference, displayName){
  1203. this._jid = jid;
  1204. this._id = Strophe.getResourceFromJid(jid);
  1205. this._conference = conference;
  1206. this._displayName = displayName;
  1207. this._supportsDTMF = false;
  1208. this._tracks = [];
  1209. this._role = 'none';
  1210. }
  1211. /**
  1212. * @returns {JitsiConference} The conference that this participant belongs to.
  1213. */
  1214. JitsiParticipant.prototype.getConference = function() {
  1215. return this._conference;
  1216. };
  1217. /**
  1218. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1219. */
  1220. JitsiParticipant.prototype.getTracks = function() {
  1221. return this._tracks;
  1222. };
  1223. /**
  1224. * @returns {String} The ID of this participant.
  1225. */
  1226. JitsiParticipant.prototype.getId = function() {
  1227. return this._id;
  1228. };
  1229. /**
  1230. * @returns {String} The JID of this participant.
  1231. */
  1232. JitsiParticipant.prototype.getJid = function() {
  1233. return this._jid;
  1234. };
  1235. /**
  1236. * @returns {String} The human-readable display name of this participant.
  1237. */
  1238. JitsiParticipant.prototype.getDisplayName = function() {
  1239. return this._displayName;
  1240. };
  1241. /**
  1242. * @returns {Boolean} Whether this participant is a moderator or not.
  1243. */
  1244. JitsiParticipant.prototype.isModerator = function() {
  1245. return this._role === 'moderator';
  1246. };
  1247. // Gets a link to an etherpad instance advertised by the participant?
  1248. //JitsiParticipant.prototype.getEtherpad = function() {
  1249. //
  1250. //}
  1251. /*
  1252. * @returns {Boolean} Whether this participant has muted their audio.
  1253. */
  1254. JitsiParticipant.prototype.isAudioMuted = function() {
  1255. return this.getTracks().reduce(function (track, isAudioMuted) {
  1256. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1257. }, true);
  1258. };
  1259. /*
  1260. * @returns {Boolean} Whether this participant has muted their video.
  1261. */
  1262. JitsiParticipant.prototype.isVideoMuted = function() {
  1263. return this.getTracks().reduce(function (track, isVideoMuted) {
  1264. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1265. }, true);
  1266. };
  1267. /*
  1268. * @returns {???} The latest statistics reported by this participant
  1269. * (i.e. info used to populate the GSM bars)
  1270. * TODO: do we expose this or handle it internally?
  1271. */
  1272. JitsiParticipant.prototype.getLatestStats = function() {
  1273. };
  1274. /**
  1275. * @returns {String} The role of this participant.
  1276. */
  1277. JitsiParticipant.prototype.getRole = function() {
  1278. return this._role;
  1279. };
  1280. /*
  1281. * @returns {Boolean} Whether this participant is
  1282. * the conference focus (i.e. jicofo).
  1283. */
  1284. JitsiParticipant.prototype.isFocus = function() {
  1285. };
  1286. /*
  1287. * @returns {Boolean} Whether this participant is
  1288. * a conference recorder (i.e. jirecon).
  1289. */
  1290. JitsiParticipant.prototype.isRecorder = function() {
  1291. };
  1292. /*
  1293. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1294. */
  1295. JitsiParticipant.prototype.isSipGateway = function() {
  1296. };
  1297. /**
  1298. * @returns {Boolean} Whether this participant
  1299. * is currently sharing their screen.
  1300. */
  1301. JitsiParticipant.prototype.isScreenSharing = function() {
  1302. };
  1303. /**
  1304. * @returns {String} The user agent of this participant
  1305. * (i.e. browser userAgent string).
  1306. */
  1307. JitsiParticipant.prototype.getUserAgent = function() {
  1308. };
  1309. /**
  1310. * Kicks the participant from the conference (requires certain privileges).
  1311. */
  1312. JitsiParticipant.prototype.kick = function() {
  1313. };
  1314. /**
  1315. * Asks this participant to mute themselves.
  1316. */
  1317. JitsiParticipant.prototype.askToMute = function() {
  1318. };
  1319. JitsiParticipant.prototype.supportsDTMF = function () {
  1320. return this._supportsDTMF;
  1321. };
  1322. module.exports = JitsiParticipant;
  1323. },{}],9:[function(require,module,exports){
  1324. module.exports = {
  1325. /**
  1326. * Returns JitsiTrackErrors based on the error object passed by GUM
  1327. * @param error the error
  1328. * @param {Array} devices Array with the requested devices
  1329. */
  1330. parseError: function (error, devices) {
  1331. devices = devices || [];
  1332. if (typeof error == "object" && error.constraintName && error.name
  1333. && (error.name == "ConstraintNotSatisfiedError" ||
  1334. error.name == "OverconstrainedError") &&
  1335. (error.constraintName == "minWidth" ||
  1336. error.constraintName == "maxWidth" ||
  1337. error.constraintName == "minHeight" ||
  1338. error.constraintName == "maxHeight") &&
  1339. devices.indexOf("video") !== -1) {
  1340. return this.UNSUPPORTED_RESOLUTION;
  1341. } else {
  1342. return this.GENERAL;
  1343. }
  1344. },
  1345. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1346. GENERAL: "gum.general"
  1347. };
  1348. },{}],10:[function(require,module,exports){
  1349. var JitsiTrackEvents = {
  1350. /**
  1351. * A media track mute status was changed.
  1352. */
  1353. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1354. /**
  1355. * Audio levels of a this track was changed.
  1356. */
  1357. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1358. /**
  1359. * The media track was removed to the conference.
  1360. */
  1361. TRACK_STOPPED: "track.stopped"
  1362. };
  1363. module.exports = JitsiTrackEvents;
  1364. },{}],11:[function(require,module,exports){
  1365. (function (__filename){
  1366. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1367. function JitsiDTMFManager (localAudio, peerConnection) {
  1368. var tracks = localAudio._getTracks();
  1369. if (!tracks.length) {
  1370. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1371. }
  1372. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1373. logger.debug("Initialized DTMFSender");
  1374. }
  1375. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1376. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1377. };
  1378. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1379. },{"jitsi-meet-logger":48}],12:[function(require,module,exports){
  1380. (function (__filename){
  1381. /* global config, APP, Strophe */
  1382. // cache datachannels to avoid garbage collection
  1383. // https://code.google.com/p/chromium/issues/detail?id=405545
  1384. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1385. var RTCEvents = require("../../service/RTC/RTCEvents");
  1386. /**
  1387. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1388. * @param peerConnection WebRTC peer connection instance.
  1389. */
  1390. function DataChannels(peerConnection, emitter) {
  1391. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1392. this.eventEmitter = emitter;
  1393. this._dataChannels = [];
  1394. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1395. // Although it's not a requirement to open separate channels from both bridge
  1396. // and peer as single channel can be used for sending and receiving data.
  1397. // So either channel opened by the bridge or the one opened here is enough
  1398. // for communication with the bridge.
  1399. /*var dataChannelOptions =
  1400. {
  1401. reliable: true
  1402. };
  1403. var dataChannel
  1404. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1405. // Can be used only when is in open state
  1406. dataChannel.onopen = function ()
  1407. {
  1408. dataChannel.send("My channel !!!");
  1409. };
  1410. dataChannel.onmessage = function (event)
  1411. {
  1412. var msgData = event.data;
  1413. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1414. };*/
  1415. };
  1416. /**
  1417. * Callback triggered by PeerConnection when new data channel is opened
  1418. * on the bridge.
  1419. * @param event the event info object.
  1420. */
  1421. DataChannels.prototype.onDataChannel = function (event) {
  1422. var dataChannel = event.channel;
  1423. var self = this;
  1424. var lastSelectedEndpoint = null;
  1425. dataChannel.onopen = function () {
  1426. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1427. // Code sample for sending string and/or binary data
  1428. // Sends String message to the bridge
  1429. //dataChannel.send("Hello bridge!");
  1430. // Sends 12 bytes binary message to the bridge
  1431. //dataChannel.send(new ArrayBuffer(12));
  1432. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1433. // when the data channel becomes available, tell the bridge about video
  1434. // selections so that it can do adaptive simulcast,
  1435. // we want the notification to trigger even if userJid is undefined,
  1436. // or null.
  1437. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  1438. };
  1439. dataChannel.onerror = function (error) {
  1440. logger.error("Data Channel Error:", error, dataChannel);
  1441. };
  1442. dataChannel.onmessage = function (event) {
  1443. var data = event.data;
  1444. // JSON
  1445. var obj;
  1446. try {
  1447. obj = JSON.parse(data);
  1448. }
  1449. catch (e) {
  1450. logger.error(
  1451. "Failed to parse data channel message as JSON: ",
  1452. data,
  1453. dataChannel);
  1454. }
  1455. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1456. var colibriClass = obj.colibriClass;
  1457. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1458. // Endpoint ID from the Videobridge.
  1459. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1460. logger.info(
  1461. "Data channel new dominant speaker event: ",
  1462. dominantSpeakerEndpoint);
  1463. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1464. }
  1465. else if ("InLastNChangeEvent" === colibriClass) {
  1466. var oldValue = obj.oldValue;
  1467. var newValue = obj.newValue;
  1468. // Make sure that oldValue and newValue are of type boolean.
  1469. var type;
  1470. if ((type = typeof oldValue) !== 'boolean') {
  1471. if (type === 'string') {
  1472. oldValue = (oldValue == "true");
  1473. } else {
  1474. oldValue = new Boolean(oldValue).valueOf();
  1475. }
  1476. }
  1477. if ((type = typeof newValue) !== 'boolean') {
  1478. if (type === 'string') {
  1479. newValue = (newValue == "true");
  1480. } else {
  1481. newValue = new Boolean(newValue).valueOf();
  1482. }
  1483. }
  1484. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1485. }
  1486. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1487. // The new/latest list of last-n endpoint IDs.
  1488. var lastNEndpoints = obj.lastNEndpoints;
  1489. // The list of endpoint IDs which are entering the list of
  1490. // last-n at this time i.e. were not in the old list of last-n
  1491. // endpoint IDs.
  1492. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1493. logger.info(
  1494. "Data channel new last-n event: ",
  1495. lastNEndpoints, endpointsEnteringLastN, obj);
  1496. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1497. lastNEndpoints, endpointsEnteringLastN, obj);
  1498. }
  1499. else {
  1500. logger.debug("Data channel JSON-formatted message: ", obj);
  1501. // The received message appears to be appropriately formatted
  1502. // (i.e. is a JSON object which assigns a value to the mandatory
  1503. // property colibriClass) so don't just swallow it, expose it to
  1504. // public consumption.
  1505. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1506. }
  1507. }
  1508. };
  1509. dataChannel.onclose = function () {
  1510. logger.info("The Data Channel closed", dataChannel);
  1511. var idx = self._dataChannels.indexOf(dataChannel);
  1512. if (idx > -1)
  1513. self._dataChannels = self._dataChannels.splice(idx, 1);
  1514. };
  1515. this._dataChannels.push(dataChannel);
  1516. };
  1517. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1518. this.lastSelectedEndpoint = userResource;
  1519. this._onXXXEndpointChanged("selected", userResource);
  1520. }
  1521. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1522. this._onXXXEndpointChanged("pinnned", userResource);
  1523. }
  1524. /**
  1525. * Notifies Videobridge about a change in the value of a specific
  1526. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1527. *
  1528. * @param xxx the name of the endpoint-related property whose value changed
  1529. * @param userResource the new value of the endpoint-related property after the
  1530. * change
  1531. */
  1532. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1533. // Derive the correct words from xxx such as selected and Selected, pinned
  1534. // and Pinned.
  1535. var head = xxx.charAt(0);
  1536. var tail = xxx.substring(1);
  1537. var lower = head.toLowerCase() + tail;
  1538. var upper = head.toUpperCase() + tail;
  1539. // Notify Videobridge about the specified endpoint change.
  1540. console.log(lower + ' endpoint changed: ', userResource);
  1541. this._some(function (dataChannel) {
  1542. if (dataChannel.readyState == 'open') {
  1543. console.log(
  1544. 'sending ' + lower
  1545. + ' endpoint changed notification to the bridge: ',
  1546. userResource);
  1547. var jsonObject = {};
  1548. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1549. jsonObject[lower + "Endpoint"]
  1550. = (userResource ? userResource : null);
  1551. dataChannel.send(JSON.stringify(jsonObject));
  1552. return true;
  1553. }
  1554. });
  1555. }
  1556. DataChannels.prototype._some = function (callback, thisArg) {
  1557. var dataChannels = this._dataChannels;
  1558. if (dataChannels && dataChannels.length !== 0) {
  1559. if (thisArg)
  1560. return dataChannels.some(callback, thisArg);
  1561. else
  1562. return dataChannels.some(callback);
  1563. } else {
  1564. return false;
  1565. }
  1566. }
  1567. module.exports = DataChannels;
  1568. }).call(this,"/modules/RTC/DataChannels.js")
  1569. },{"../../service/RTC/RTCEvents":80,"jitsi-meet-logger":48}],13:[function(require,module,exports){
  1570. var JitsiTrack = require("./JitsiTrack");
  1571. var RTCBrowserType = require("./RTCBrowserType");
  1572. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1573. var RTCUtils = require("./RTCUtils");
  1574. /**
  1575. * Represents a single media track (either audio or video).
  1576. * @constructor
  1577. */
  1578. function JitsiLocalTrack(stream, videoType,
  1579. resolution)
  1580. {
  1581. this.videoType = videoType;
  1582. this.dontFireRemoveEvent = false;
  1583. this.resolution = resolution;
  1584. this.startMuted = false;
  1585. var self = this;
  1586. JitsiTrack.call(this, null, stream,
  1587. function () {
  1588. if(!this.dontFireRemoveEvent)
  1589. this.eventEmitter.emit(
  1590. JitsiTrackEvents.TRACK_STOPPED);
  1591. this.dontFireRemoveEvent = false;
  1592. }.bind(this));
  1593. }
  1594. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1595. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1596. /**
  1597. * Mutes / unmutes the track.
  1598. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1599. */
  1600. JitsiLocalTrack.prototype._setMute = function (mute) {
  1601. if (this.isMuted() === mute) {
  1602. return;
  1603. }
  1604. if(!this.rtc) {
  1605. this.startMuted = mute;
  1606. return;
  1607. }
  1608. var isAudio = this.type === JitsiTrack.AUDIO;
  1609. this.dontFireRemoveEvent = false;
  1610. if ((window.location.protocol != "https:") ||
  1611. (isAudio) || this.videoType === "desktop" ||
  1612. // FIXME FF does not support 'removeStream' method used to mute
  1613. RTCBrowserType.isFirefox()) {
  1614. var tracks = this._getTracks();
  1615. for (var idx = 0; idx < tracks.length; idx++) {
  1616. tracks[idx].enabled = !mute;
  1617. }
  1618. if(isAudio)
  1619. this.rtc.room.setAudioMute(mute);
  1620. else
  1621. this.rtc.room.setVideoMute(mute);
  1622. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1623. } else {
  1624. if (mute) {
  1625. this.dontFireRemoveEvent = true;
  1626. this.rtc.room.removeStream(this.stream, function () {});
  1627. RTCUtils.stopMediaStream(this.stream);
  1628. if(isAudio)
  1629. this.rtc.room.setAudioMute(mute);
  1630. else
  1631. this.rtc.room.setVideoMute(mute);
  1632. this.stream = null;
  1633. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1634. //FIXME: Maybe here we should set the SRC for the containers to something
  1635. } else {
  1636. var self = this;
  1637. RTCUtils.obtainAudioAndVideoPermissions({
  1638. devices: (isAudio ? ["audio"] : ["video"]),
  1639. resolution: self.resolution})
  1640. .then(function (streams) {
  1641. var stream = null;
  1642. for(var i = 0; i < streams.length; i++) {
  1643. stream = streams[i];
  1644. if(stream.type === self.type) {
  1645. self.stream = stream.stream;
  1646. self.videoType = stream.videoType;
  1647. break;
  1648. }
  1649. }
  1650. if(!stream)
  1651. return;
  1652. for(var i = 0; i < self.containers.length; i++)
  1653. {
  1654. RTCUtils.attachMediaStream(
  1655. self.containers[i], self.stream);
  1656. }
  1657. self.rtc.room.addStream(stream.stream,
  1658. function () {
  1659. if(isAudio)
  1660. self.rtc.room.setAudioMute(mute);
  1661. else
  1662. self.rtc.room.setVideoMute(mute);
  1663. self.eventEmitter.emit(
  1664. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1665. });
  1666. });
  1667. }
  1668. }
  1669. }
  1670. /**
  1671. * Stops sending the media track. And removes it from the HTML.
  1672. * NOTE: Works for local tracks only.
  1673. */
  1674. JitsiLocalTrack.prototype.stop = function () {
  1675. if(!this.stream)
  1676. return;
  1677. if(this.rtc)
  1678. this.rtc.room.removeStream(this.stream, function () {});
  1679. RTCUtils.stopMediaStream(this.stream);
  1680. this.detach();
  1681. }
  1682. /**
  1683. * Returns <tt>true</tt> - if the stream is muted
  1684. * and <tt>false</tt> otherwise.
  1685. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1686. * and <tt>false</tt> otherwise.
  1687. */
  1688. JitsiLocalTrack.prototype.isMuted = function () {
  1689. if (!this.stream)
  1690. return true;
  1691. var tracks = [];
  1692. var isAudio = this.type === JitsiTrack.AUDIO;
  1693. if (isAudio) {
  1694. tracks = this.stream.getAudioTracks();
  1695. } else {
  1696. if (!this.isActive())
  1697. return true;
  1698. tracks = this.stream.getVideoTracks();
  1699. }
  1700. for (var idx = 0; idx < tracks.length; idx++) {
  1701. if(tracks[idx].enabled)
  1702. return false;
  1703. }
  1704. return true;
  1705. };
  1706. /**
  1707. * Private method. Updates rtc property of the track.
  1708. * @param rtc the rtc instance.
  1709. */
  1710. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1711. this.rtc = rtc;
  1712. };
  1713. /**
  1714. * Return true;
  1715. */
  1716. JitsiLocalTrack.prototype.isLocal = function () {
  1717. return true;
  1718. }
  1719. module.exports = JitsiLocalTrack;
  1720. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1721. var JitsiTrack = require("./JitsiTrack");
  1722. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1723. /**
  1724. * Represents a single media track (either audio or video).
  1725. * @param RTC the rtc instance.
  1726. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1727. * @param sid sid for the Media Stream
  1728. * @param ssrc ssrc for the Media Stream
  1729. * @param eventEmitter the event emitter
  1730. * @constructor
  1731. */
  1732. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1733. JitsiTrack.call(this, RTC, data.stream,
  1734. function () {
  1735. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1736. }.bind(this));
  1737. this.rtc = RTC;
  1738. this.sid = sid;
  1739. this.stream = data.stream;
  1740. this.peerjid = data.peerjid;
  1741. this.videoType = data.videoType;
  1742. this.ssrc = ssrc;
  1743. this.muted = false;
  1744. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1745. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1746. this.muted = true;
  1747. }
  1748. }
  1749. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1750. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1751. /**
  1752. * Sets current muted status and fires an events for the change.
  1753. * @param value the muted status.
  1754. */
  1755. JitsiRemoteTrack.prototype.setMute = function (value) {
  1756. if(this.muted === value)
  1757. return;
  1758. this.stream.muted = value;
  1759. this.muted = value;
  1760. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1761. };
  1762. /**
  1763. * Returns the current muted status of the track.
  1764. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1765. */
  1766. JitsiRemoteTrack.prototype.isMuted = function () {
  1767. return this.muted;
  1768. };
  1769. /**
  1770. * Returns the participant id which owns the track.
  1771. * @returns {string} the id of the participants.
  1772. */
  1773. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1774. return Strophe.getResourceFromJid(this.peerjid);
  1775. };
  1776. /**
  1777. * Return false;
  1778. */
  1779. JitsiRemoteTrack.prototype.isLocal = function () {
  1780. return false;
  1781. };
  1782. delete JitsiRemoteTrack.prototype.stop;
  1783. delete JitsiRemoteTrack.prototype.start;
  1784. module.exports = JitsiRemoteTrack;
  1785. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1786. var RTCBrowserType = require("./RTCBrowserType");
  1787. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1788. var EventEmitter = require("events");
  1789. var RTC = require("./RTCUtils");
  1790. /**
  1791. * This implements 'onended' callback normally fired by WebRTC after the stream
  1792. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1793. * @param jitsiTrack our track object holding the original WebRTC stream object
  1794. * to which 'onended' handling will be added.
  1795. */
  1796. function implementOnEndedHandling(jitsiTrack) {
  1797. var stream = jitsiTrack.getOriginalStream();
  1798. var originalStop = stream.stop;
  1799. stream.stop = function () {
  1800. originalStop.apply(stream);
  1801. if (jitsiTrack.isActive()) {
  1802. stream.onended();
  1803. }
  1804. };
  1805. }
  1806. /**
  1807. * Adds onended/oninactive handler to a MediaStream.
  1808. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1809. * @param handler the handler
  1810. */
  1811. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1812. if(RTCBrowserType.isTemasysPluginUsed()) {
  1813. // themasys
  1814. //FIXME: Seems that not working properly.
  1815. if(mediaStream.onended) {
  1816. mediaStream.onended = handler;
  1817. } else if(mediaStream.addEventListener) {
  1818. mediaStream.addEventListener('ended', function () {
  1819. handler(mediaStream);
  1820. });
  1821. } else if(mediaStream.attachEvent) {
  1822. mediaStream.attachEvent('ended', function () {
  1823. handler(mediaStream);
  1824. });
  1825. }
  1826. }
  1827. else {
  1828. if(typeof mediaStream.active !== "undefined")
  1829. mediaStream.oninactive = handler;
  1830. else
  1831. mediaStream.onended = handler;
  1832. }
  1833. }
  1834. /**
  1835. * Represents a single media track (either audio or video).
  1836. * @constructor
  1837. * @param rtc the rtc instance
  1838. * @param stream the stream
  1839. * @param streamInactiveHandler the function that will handle
  1840. * onended/oninactive events of the stream.
  1841. */
  1842. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1843. {
  1844. /**
  1845. * Array with the HTML elements that are displaying the streams.
  1846. * @type {Array}
  1847. */
  1848. this.containers = [];
  1849. this.rtc = rtc;
  1850. this.stream = stream;
  1851. this.eventEmitter = new EventEmitter();
  1852. this.audioLevel = -1;
  1853. this.type = (this.stream.getVideoTracks().length > 0)?
  1854. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1855. if(this.type == "audio") {
  1856. this._getTracks = function () {
  1857. return this.stream.getAudioTracks();
  1858. }.bind(this);
  1859. } else {
  1860. this._getTracks = function () {
  1861. return this.stream.getVideoTracks();
  1862. }.bind(this);
  1863. }
  1864. if (RTCBrowserType.isFirefox() && this.stream) {
  1865. implementOnEndedHandling(this);
  1866. }
  1867. if(stream)
  1868. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1869. }
  1870. /**
  1871. * JitsiTrack video type.
  1872. * @type {string}
  1873. */
  1874. JitsiTrack.VIDEO = "video";
  1875. /**
  1876. * JitsiTrack audio type.
  1877. * @type {string}
  1878. */
  1879. JitsiTrack.AUDIO = "audio";
  1880. /**
  1881. * Returns the type (audio or video) of this track.
  1882. */
  1883. JitsiTrack.prototype.getType = function() {
  1884. return this.type;
  1885. };
  1886. /**
  1887. * Check if this is audiotrack.
  1888. */
  1889. JitsiTrack.prototype.isAudioTrack = function () {
  1890. return this.getType() === JitsiTrack.AUDIO;
  1891. };
  1892. /**
  1893. * Check if this is videotrack.
  1894. */
  1895. JitsiTrack.prototype.isVideoTrack = function () {
  1896. return this.getType() === JitsiTrack.VIDEO;
  1897. };
  1898. /**
  1899. * Returns the RTCMediaStream from the browser (?).
  1900. */
  1901. JitsiTrack.prototype.getOriginalStream = function() {
  1902. return this.stream;
  1903. }
  1904. /**
  1905. * Mutes the track.
  1906. */
  1907. JitsiTrack.prototype.mute = function () {
  1908. this._setMute(true);
  1909. }
  1910. /**
  1911. * Unmutes the stream.
  1912. */
  1913. JitsiTrack.prototype.unmute = function () {
  1914. this._setMute(false);
  1915. }
  1916. /**
  1917. * Attaches the MediaStream of this track to an HTML container (?).
  1918. * Adds the container to the list of containers that are displaying the track.
  1919. * @param container the HTML container
  1920. */
  1921. JitsiTrack.prototype.attach = function (container) {
  1922. if(this.stream)
  1923. require("./RTCUtils").attachMediaStream(container, this.stream);
  1924. this.containers.push(container);
  1925. }
  1926. /**
  1927. * Removes the track from the passed HTML container.
  1928. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1929. */
  1930. JitsiTrack.prototype.detach = function (container) {
  1931. for(var i = 0; i < this.containers.length; i++)
  1932. {
  1933. if(this.containers[i].is(container))
  1934. {
  1935. this.containers.splice(i,1);
  1936. }
  1937. if(!container)
  1938. {
  1939. this.containers[i].find(">video").remove();
  1940. }
  1941. }
  1942. if(container)
  1943. $(container).find(">video").remove();
  1944. }
  1945. /**
  1946. * Stops sending the media track. And removes it from the HTML.
  1947. * NOTE: Works for local tracks only.
  1948. */
  1949. JitsiTrack.prototype.stop = function () {
  1950. }
  1951. /**
  1952. * Returns true if this is a video track and the source of the video is a
  1953. * screen capture as opposed to a camera.
  1954. */
  1955. JitsiTrack.prototype.isScreenSharing = function(){
  1956. }
  1957. /**
  1958. * Returns id of the track.
  1959. * @returns {string} id of the track or null if this is fake track.
  1960. */
  1961. JitsiTrack.prototype._getId = function () {
  1962. var tracks = this.stream.getTracks();
  1963. if(!tracks || tracks.length === 0)
  1964. return null;
  1965. return tracks[0].id;
  1966. };
  1967. /**
  1968. * Returns id of the track.
  1969. * @returns {string} id of the track or null if this is fake track.
  1970. */
  1971. JitsiTrack.prototype.getId = function () {
  1972. return RTC.getStreamID(this.stream);
  1973. };
  1974. /**
  1975. * Checks whether the MediaStream is avtive/not ended.
  1976. * When there is no check for active we don't have information and so
  1977. * will return that stream is active (in case of FF).
  1978. * @returns {boolean} whether MediaStream is active.
  1979. */
  1980. JitsiTrack.prototype.isActive = function () {
  1981. if((typeof this.stream.active !== "undefined"))
  1982. return this.stream.active;
  1983. else
  1984. return true;
  1985. };
  1986. /**
  1987. * Attaches a handler for events(For example - "audio level changed".).
  1988. * All possible event are defined in JitsiTrackEvents.
  1989. * @param eventId the event ID.
  1990. * @param handler handler for the event.
  1991. */
  1992. JitsiTrack.prototype.on = function (eventId, handler) {
  1993. if(this.eventEmitter)
  1994. this.eventEmitter.on(eventId, handler);
  1995. }
  1996. /**
  1997. * Removes event listener
  1998. * @param eventId the event ID.
  1999. * @param [handler] optional, the specific handler to unbind
  2000. */
  2001. JitsiTrack.prototype.off = function (eventId, handler) {
  2002. if(this.eventEmitter)
  2003. this.eventEmitter.removeListener(eventId, handler);
  2004. }
  2005. // Common aliases for event emitter
  2006. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  2007. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  2008. /**
  2009. * Sets the audio level for the stream
  2010. * @param audioLevel the new audio level
  2011. */
  2012. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2013. if(this.audioLevel !== audioLevel) {
  2014. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2015. audioLevel);
  2016. this.audioLevel = audioLevel;
  2017. }
  2018. }
  2019. module.exports = JitsiTrack;
  2020. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":44}],16:[function(require,module,exports){
  2021. /* global APP */
  2022. var EventEmitter = require("events");
  2023. var RTCBrowserType = require("./RTCBrowserType");
  2024. var RTCUtils = require("./RTCUtils.js");
  2025. var JitsiTrack = require("./JitsiTrack");
  2026. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2027. var DataChannels = require("./DataChannels");
  2028. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2029. var DesktopSharingEventTypes
  2030. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2031. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2032. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2033. function createLocalTracks(streams) {
  2034. var newStreams = []
  2035. for (var i = 0; i < streams.length; i++) {
  2036. var localStream = new JitsiLocalTrack(streams[i].stream,
  2037. streams[i].videoType, streams[i].resolution);
  2038. newStreams.push(localStream);
  2039. if (streams[i].isMuted === true)
  2040. localStream.setMute(true);
  2041. }
  2042. return newStreams;
  2043. }
  2044. function RTC(room, options) {
  2045. this.room = room;
  2046. this.localStreams = [];
  2047. //FIXME: we should start removing those streams.
  2048. //FIXME: We should support multiple streams per jid.
  2049. this.remoteStreams = {};
  2050. this.localAudio = null;
  2051. this.localVideo = null;
  2052. this.eventEmitter = new EventEmitter();
  2053. var self = this;
  2054. this.options = options || {};
  2055. room.addPresenceListener("videomuted", function (values, from) {
  2056. if(self.remoteStreams[from]) {
  2057. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  2058. }
  2059. });
  2060. room.addPresenceListener("audiomuted", function (values, from) {
  2061. if(self.remoteStreams[from]) {
  2062. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  2063. }
  2064. });
  2065. }
  2066. /**
  2067. * Creates the local MediaStreams.
  2068. * @param {Object} [options] optional parameters
  2069. * @param {Array} options.devices the devices that will be requested
  2070. * @param {string} options.resolution resolution constraints
  2071. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2072. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2073. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2074. * @param {string} options.cameraDeviceId
  2075. * @param {string} options.micDeviceId
  2076. * @returns {*} Promise object that will receive the new JitsiTracks
  2077. */
  2078. RTC.obtainAudioAndVideoPermissions = function (options) {
  2079. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  2080. }
  2081. RTC.prototype.onIncommingCall = function(event) {
  2082. if(this.options.config.openSctp)
  2083. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2084. for(var i = 0; i < this.localStreams.length; i++)
  2085. if(this.localStreams[i])
  2086. {
  2087. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2088. }
  2089. }
  2090. RTC.prototype.selectedEndpoint = function (id) {
  2091. if(this.dataChannels)
  2092. this.dataChannels.handleSelectedEndpointEvent(id);
  2093. }
  2094. RTC.prototype.pinEndpoint = function (id) {
  2095. if(this.dataChannels)
  2096. this.dataChannels.handlePinnedEndpointEvent(id);
  2097. }
  2098. RTC.prototype.addListener = function (type, listener) {
  2099. this.eventEmitter.on(type, listener);
  2100. };
  2101. RTC.prototype.removeListener = function (eventType, listener) {
  2102. this.eventEmitter.removeListener(eventType, listener);
  2103. };
  2104. RTC.addListener = function (eventType, listener) {
  2105. RTCUtils.addListener(eventType, listener);
  2106. }
  2107. RTC.removeListener = function (eventType, listener) {
  2108. RTCUtils.removeListener(eventType, listener)
  2109. }
  2110. RTC.isRTCReady = function () {
  2111. return RTCUtils.isRTCReady();
  2112. }
  2113. RTC.init = function (options) {
  2114. this.options = options || {};
  2115. return RTCUtils.init(this.options);
  2116. }
  2117. RTC.getDeviceAvailability = function () {
  2118. return RTCUtils.getDeviceAvailability();
  2119. }
  2120. RTC.prototype.addLocalStream = function (stream) {
  2121. this.localStreams.push(stream);
  2122. stream._setRTC(this);
  2123. if (stream.type == "audio") {
  2124. this.localAudio = stream;
  2125. } else {
  2126. this.localVideo = stream;
  2127. }
  2128. };
  2129. /**
  2130. * Set mute for all local audio streams attached to the conference.
  2131. * @param value the mute value
  2132. */
  2133. RTC.prototype.setAudioMute = function (value) {
  2134. for(var i = 0; i < this.localStreams.length; i++) {
  2135. var stream = this.localStreams[i];
  2136. if(stream.getType() !== "audio") {
  2137. continue;
  2138. }
  2139. stream._setMute(value);
  2140. }
  2141. }
  2142. RTC.prototype.removeLocalStream = function (track) {
  2143. var pos = this.localStreams.indexOf(track);
  2144. if (pos > -1) {
  2145. this.localStreams.splice(pos, 1);
  2146. }
  2147. };
  2148. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2149. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2150. if(!data.peerjid)
  2151. return;
  2152. var jid = Strophe.getResourceFromJid(data.peerjid);
  2153. if(!this.remoteStreams[jid]) {
  2154. this.remoteStreams[jid] = {};
  2155. }
  2156. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2157. return remoteStream;
  2158. };
  2159. RTC.getPCConstraints = function () {
  2160. return RTCUtils.pc_constraints;
  2161. };
  2162. RTC.attachMediaStream = function (elSelector, stream) {
  2163. RTCUtils.attachMediaStream(elSelector, stream);
  2164. };
  2165. RTC.getStreamID = function (stream) {
  2166. return RTCUtils.getStreamID(stream);
  2167. };
  2168. RTC.getVideoSrc = function (element) {
  2169. return RTCUtils.getVideoSrc(element);
  2170. };
  2171. /**
  2172. * Returns true if retrieving the the list of input devices is supported and
  2173. * false if not.
  2174. */
  2175. RTC.isDeviceListAvailable = function () {
  2176. return RTCUtils.isDeviceListAvailable();
  2177. };
  2178. /**
  2179. * Returns true if changing the camera / microphone device is supported and
  2180. * false if not.
  2181. */
  2182. RTC.isDeviceChangeAvailable = function () {
  2183. return RTCUtils.isDeviceChangeAvailable();
  2184. }
  2185. /**
  2186. * Allows to receive list of available cameras/microphones.
  2187. * @param {function} callback would receive array of devices as an argument
  2188. */
  2189. RTC.enumerateDevices = function (callback) {
  2190. RTCUtils.enumerateDevices(callback);
  2191. };
  2192. RTC.setVideoSrc = function (element, src) {
  2193. RTCUtils.setVideoSrc(element, src);
  2194. };
  2195. /**
  2196. * A method to handle stopping of the stream.
  2197. * One point to handle the differences in various implementations.
  2198. * @param mediaStream MediaStream object to stop.
  2199. */
  2200. RTC.stopMediaStream = function (mediaStream) {
  2201. RTCUtils.stopMediaStream(mediaStream);
  2202. };
  2203. /**
  2204. * Returns whether the desktop sharing is enabled or not.
  2205. * @returns {boolean}
  2206. */
  2207. RTC.isDesktopSharingEnabled = function () {
  2208. return RTCUtils.isDesktopSharingEnabled();
  2209. }
  2210. RTC.prototype.getVideoElementName = function () {
  2211. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2212. };
  2213. RTC.prototype.dispose = function() {
  2214. };
  2215. RTC.prototype.switchVideoStreams = function (newStream) {
  2216. this.localVideo.stream = newStream;
  2217. this.localStreams = [];
  2218. //in firefox we have only one stream object
  2219. if (this.localAudio.getOriginalStream() != newStream)
  2220. this.localStreams.push(this.localAudio);
  2221. this.localStreams.push(this.localVideo);
  2222. };
  2223. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2224. if(!jid)
  2225. return;
  2226. var resource = Strophe.getResourceFromJid(jid);
  2227. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2228. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2229. }
  2230. module.exports = RTC;
  2231. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/RTCEvents.js":80,"../../service/desktopsharing/DesktopSharingEventTypes":84,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":44}],17:[function(require,module,exports){
  2232. var currentBrowser;
  2233. var browserVersion;
  2234. var isAndroid;
  2235. var RTCBrowserType = {
  2236. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2237. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2238. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2239. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2240. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2241. getBrowserType: function () {
  2242. return currentBrowser;
  2243. },
  2244. isChrome: function () {
  2245. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2246. },
  2247. isOpera: function () {
  2248. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2249. },
  2250. isFirefox: function () {
  2251. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2252. },
  2253. isIExplorer: function () {
  2254. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2255. },
  2256. isSafari: function () {
  2257. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2258. },
  2259. isTemasysPluginUsed: function () {
  2260. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2261. },
  2262. getFirefoxVersion: function () {
  2263. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2264. },
  2265. getChromeVersion: function () {
  2266. return RTCBrowserType.isChrome() ? browserVersion : null;
  2267. },
  2268. usesPlanB: function() {
  2269. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2270. RTCBrowserType.isTemasysPluginUsed();
  2271. },
  2272. usesUnifiedPlan: function() {
  2273. return RTCBrowserType.isFirefox();
  2274. },
  2275. /**
  2276. * Whether the browser is running on an android device.
  2277. */
  2278. isAndroid: function() {
  2279. return isAndroid;
  2280. }
  2281. // Add version getters for other browsers when needed
  2282. };
  2283. // detectOpera() must be called before detectChrome() !!!
  2284. // otherwise Opera wil be detected as Chrome
  2285. function detectChrome() {
  2286. if (navigator.webkitGetUserMedia) {
  2287. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2288. var userAgent = navigator.userAgent.toLowerCase();
  2289. // We can assume that user agent is chrome, because it's
  2290. // enforced when 'ext' streaming method is set
  2291. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2292. console.log("This appears to be Chrome, ver: " + ver);
  2293. return ver;
  2294. }
  2295. return null;
  2296. }
  2297. function detectOpera() {
  2298. var userAgent = navigator.userAgent;
  2299. if (userAgent.match(/Opera|OPR/)) {
  2300. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2301. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2302. console.info("This appears to be Opera, ver: " + version);
  2303. return version;
  2304. }
  2305. return null;
  2306. }
  2307. function detectFirefox() {
  2308. if (navigator.mozGetUserMedia) {
  2309. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2310. var version = parseInt(
  2311. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2312. console.log('This appears to be Firefox, ver: ' + version);
  2313. return version;
  2314. }
  2315. return null;
  2316. }
  2317. function detectSafari() {
  2318. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2319. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2320. console.info("This appears to be Safari");
  2321. // FIXME detect Safari version when needed
  2322. return 1;
  2323. }
  2324. return null;
  2325. }
  2326. function detectIE() {
  2327. var version;
  2328. var ua = window.navigator.userAgent;
  2329. var msie = ua.indexOf('MSIE ');
  2330. if (msie > 0) {
  2331. // IE 10 or older => return version number
  2332. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2333. }
  2334. var trident = ua.indexOf('Trident/');
  2335. if (!version && trident > 0) {
  2336. // IE 11 => return version number
  2337. var rv = ua.indexOf('rv:');
  2338. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2339. }
  2340. var edge = ua.indexOf('Edge/');
  2341. if (!version && edge > 0) {
  2342. // IE 12 => return version number
  2343. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2344. }
  2345. if (version) {
  2346. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2347. console.info("This appears to be IExplorer, ver: " + version);
  2348. }
  2349. return version;
  2350. }
  2351. function detectBrowser() {
  2352. var version;
  2353. var detectors = [
  2354. detectOpera,
  2355. detectChrome,
  2356. detectFirefox,
  2357. detectIE,
  2358. detectSafari
  2359. ];
  2360. // Try all browser detectors
  2361. for (var i = 0; i < detectors.length; i++) {
  2362. version = detectors[i]();
  2363. if (version)
  2364. return version;
  2365. }
  2366. console.warn("Browser type defaults to Safari ver 1");
  2367. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2368. return 1;
  2369. }
  2370. browserVersion = detectBrowser();
  2371. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2372. module.exports = RTCBrowserType;
  2373. },{}],18:[function(require,module,exports){
  2374. (function (__filename){
  2375. /* global config, require, attachMediaStream, getUserMedia,
  2376. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2377. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2378. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2379. */
  2380. /* jshint -W101 */
  2381. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2382. var RTCBrowserType = require("./RTCBrowserType");
  2383. var Resolutions = require("../../service/RTC/Resolutions");
  2384. var RTCEvents = require("../../service/RTC/RTCEvents");
  2385. var AdapterJS = require("./adapter.screenshare");
  2386. var SDPUtil = require("../xmpp/SDPUtil");
  2387. var EventEmitter = require("events");
  2388. var screenObtainer = require("./ScreenObtainer");
  2389. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2390. var eventEmitter = new EventEmitter();
  2391. var devices = {
  2392. audio: true,
  2393. video: true
  2394. };
  2395. var rtcReady = false;
  2396. function setResolutionConstraints(constraints, resolution) {
  2397. var isAndroid = RTCBrowserType.isAndroid();
  2398. if (Resolutions[resolution]) {
  2399. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2400. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2401. }
  2402. else if (isAndroid) {
  2403. // FIXME can't remember if the purpose of this was to always request
  2404. // low resolution on Android ? if yes it should be moved up front
  2405. constraints.video.mandatory.minWidth = 320;
  2406. constraints.video.mandatory.minHeight = 240;
  2407. constraints.video.mandatory.maxFrameRate = 15;
  2408. }
  2409. if (constraints.video.mandatory.minWidth)
  2410. constraints.video.mandatory.maxWidth =
  2411. constraints.video.mandatory.minWidth;
  2412. if (constraints.video.mandatory.minHeight)
  2413. constraints.video.mandatory.maxHeight =
  2414. constraints.video.mandatory.minHeight;
  2415. }
  2416. /**
  2417. * @param {string[]} um required user media types
  2418. *
  2419. * @param {Object} [options={}] optional parameters
  2420. * @param {string} options.resolution
  2421. * @param {number} options.bandwidth
  2422. * @param {number} options.fps
  2423. * @param {string} options.desktopStream
  2424. * @param {string} options.cameraDeviceId
  2425. * @param {string} options.micDeviceId
  2426. * @param {bool} firefox_fake_device
  2427. */
  2428. function getConstraints(um, options) {
  2429. var constraints = {audio: false, video: false};
  2430. if (um.indexOf('video') >= 0) {
  2431. // same behaviour as true
  2432. constraints.video = { mandatory: {}, optional: [] };
  2433. if (options.cameraDeviceId) {
  2434. constraints.video.optional.push({
  2435. sourceId: options.cameraDeviceId
  2436. });
  2437. }
  2438. constraints.video.optional.push({ googLeakyBucket: true });
  2439. setResolutionConstraints(constraints, options.resolution);
  2440. }
  2441. if (um.indexOf('audio') >= 0) {
  2442. if (!RTCBrowserType.isFirefox()) {
  2443. // same behaviour as true
  2444. constraints.audio = { mandatory: {}, optional: []};
  2445. if (options.micDeviceId) {
  2446. constraints.audio.optional.push({
  2447. sourceId: options.micDeviceId
  2448. });
  2449. }
  2450. // if it is good enough for hangouts...
  2451. constraints.audio.optional.push(
  2452. {googEchoCancellation: true},
  2453. {googAutoGainControl: true},
  2454. {googNoiseSupression: true},
  2455. {googHighpassFilter: true},
  2456. {googNoisesuppression2: true},
  2457. {googEchoCancellation2: true},
  2458. {googAutoGainControl2: true}
  2459. );
  2460. } else {
  2461. if (options.micDeviceId) {
  2462. constraints.audio = {
  2463. mandatory: {},
  2464. optional: [{
  2465. sourceId: options.micDeviceId
  2466. }]};
  2467. } else {
  2468. constraints.audio = true;
  2469. }
  2470. }
  2471. }
  2472. if (um.indexOf('screen') >= 0) {
  2473. if (RTCBrowserType.isChrome()) {
  2474. constraints.video = {
  2475. mandatory: {
  2476. chromeMediaSource: "screen",
  2477. googLeakyBucket: true,
  2478. maxWidth: window.screen.width,
  2479. maxHeight: window.screen.height,
  2480. maxFrameRate: 3
  2481. },
  2482. optional: []
  2483. };
  2484. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2485. constraints.video = {
  2486. optional: [
  2487. {
  2488. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2489. }
  2490. ]
  2491. };
  2492. } else if (RTCBrowserType.isFirefox()) {
  2493. constraints.video = {
  2494. mozMediaSource: "window",
  2495. mediaSource: "window"
  2496. };
  2497. } else {
  2498. logger.error(
  2499. "'screen' WebRTC media source is supported only in Chrome" +
  2500. " and with Temasys plugin");
  2501. }
  2502. }
  2503. if (um.indexOf('desktop') >= 0) {
  2504. constraints.video = {
  2505. mandatory: {
  2506. chromeMediaSource: "desktop",
  2507. chromeMediaSourceId: options.desktopStream,
  2508. googLeakyBucket: true,
  2509. maxWidth: window.screen.width,
  2510. maxHeight: window.screen.height,
  2511. maxFrameRate: 3
  2512. },
  2513. optional: []
  2514. };
  2515. }
  2516. if (options.bandwidth) {
  2517. if (!constraints.video) {
  2518. //same behaviour as true
  2519. constraints.video = {mandatory: {}, optional: []};
  2520. }
  2521. constraints.video.optional.push({bandwidth: options.bandwidth});
  2522. }
  2523. if (options.fps) {
  2524. // for some cameras it might be necessary to request 30fps
  2525. // so they choose 30fps mjpg over 10fps yuy2
  2526. if (!constraints.video) {
  2527. // same behaviour as true;
  2528. constraints.video = {mandatory: {}, optional: []};
  2529. }
  2530. constraints.video.mandatory.minFrameRate = options.fps;
  2531. }
  2532. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2533. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2534. // this later can be a problem with some of the tests
  2535. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2536. {
  2537. // seems to be fixed now, removing this experimental fix, as having
  2538. // multiple audio tracks brake the tests
  2539. //constraints.audio = true;
  2540. constraints.fake = true;
  2541. }
  2542. return constraints;
  2543. }
  2544. function setAvailableDevices(um, available) {
  2545. if (um.indexOf("video") != -1) {
  2546. devices.video = available;
  2547. }
  2548. if (um.indexOf("audio") != -1) {
  2549. devices.audio = available;
  2550. }
  2551. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2552. }
  2553. // In case of IE we continue from 'onReady' callback
  2554. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2555. // once it is initialized.
  2556. function onReady (options, GUM) {
  2557. rtcReady = true;
  2558. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2559. screenObtainer.init(eventEmitter, options, GUM);
  2560. }
  2561. /**
  2562. * Apply function with arguments if function exists.
  2563. * Do nothing if function not provided.
  2564. * @param {function} [fn] function to apply
  2565. * @param {Array} [args=[]] arguments for function
  2566. */
  2567. function maybeApply(fn, args) {
  2568. if (fn) {
  2569. fn.apply(null, args || []);
  2570. }
  2571. }
  2572. var getUserMediaStatus = {
  2573. initialized: false,
  2574. callbacks: []
  2575. };
  2576. /**
  2577. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2578. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2579. * @param {Function} getUserMedia native function
  2580. * @returns {Function} wrapped function
  2581. */
  2582. function wrapGetUserMedia(getUserMedia) {
  2583. return function (constraints, successCallback, errorCallback) {
  2584. getUserMedia(constraints, function (stream) {
  2585. maybeApply(successCallback, [stream]);
  2586. if (!getUserMediaStatus.initialized) {
  2587. getUserMediaStatus.initialized = true;
  2588. getUserMediaStatus.callbacks.forEach(function (callback) {
  2589. callback();
  2590. });
  2591. getUserMediaStatus.callbacks.length = 0;
  2592. }
  2593. }, function (error) {
  2594. maybeApply(errorCallback, [error]);
  2595. });
  2596. };
  2597. }
  2598. /**
  2599. * Create stub device which equals to auto selected device.
  2600. * @param {string} kind if that should be `audio` or `video` device
  2601. * @returns {Object} stub device description in `enumerateDevices` format
  2602. */
  2603. function createAutoDeviceInfo(kind) {
  2604. return {
  2605. facing: null,
  2606. label: 'Auto',
  2607. kind: kind,
  2608. deviceId: '',
  2609. groupId: null
  2610. };
  2611. }
  2612. /**
  2613. * Execute function after getUserMedia was executed at least once.
  2614. * @param {Function} callback function to execute after getUserMedia
  2615. */
  2616. function afterUserMediaInitialized(callback) {
  2617. if (getUserMediaStatus.initialized) {
  2618. callback();
  2619. } else {
  2620. getUserMediaStatus.callbacks.push(callback);
  2621. }
  2622. }
  2623. /**
  2624. * Wrapper function which makes enumerateDevices to wait
  2625. * until someone executes getUserMedia first time.
  2626. * @param {Function} enumerateDevices native function
  2627. * @returns {Funtion} wrapped function
  2628. */
  2629. function wrapEnumerateDevices(enumerateDevices) {
  2630. return function (callback) {
  2631. // enumerate devices only after initial getUserMedia
  2632. afterUserMediaInitialized(function () {
  2633. enumerateDevices().then(function (devices) {
  2634. //add auto devices
  2635. devices.unshift(
  2636. createAutoDeviceInfo('audioinput'),
  2637. createAutoDeviceInfo('videoinput')
  2638. );
  2639. callback(devices);
  2640. }, function (err) {
  2641. console.error('cannot enumerate devices: ', err);
  2642. // return only auto devices
  2643. callback([createAutoDeviceInfo('audioInput'),
  2644. createAutoDeviceInfo('videoinput')]);
  2645. });
  2646. });
  2647. };
  2648. }
  2649. /**
  2650. * Use old MediaStreamTrack to get devices list and
  2651. * convert it to enumerateDevices format.
  2652. * @param {Function} callback function to call when received devices list.
  2653. */
  2654. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2655. MediaStreamTrack.getSources(function (sources) {
  2656. var devices = sources.map(function (source) {
  2657. var kind = (source.kind || '').toLowerCase();
  2658. return {
  2659. facing: source.facing || null,
  2660. label: source.label,
  2661. kind: kind ? kind + 'input': null,
  2662. deviceId: source.id,
  2663. groupId: source.groupId || null
  2664. };
  2665. });
  2666. //add auto devices
  2667. devices.unshift(
  2668. createAutoDeviceInfo('audioinput'),
  2669. createAutoDeviceInfo('videoinput')
  2670. );
  2671. callback(devices);
  2672. });
  2673. }
  2674. function obtainDevices(options) {
  2675. if(!options.devices || options.devices.length === 0) {
  2676. return options.successCallback(options.streams || {});
  2677. }
  2678. var device = options.devices.splice(0, 1);
  2679. var devices = [];
  2680. devices.push(device);
  2681. options.deviceGUM[device](function (stream) {
  2682. options.streams = options.streams || {};
  2683. options.streams[device] = stream;
  2684. obtainDevices(options);
  2685. },
  2686. function (error) {
  2687. Object.keys(options.streams).forEach(function(device) {
  2688. RTCUtils.stopMediaStream(options.streams[device]);
  2689. });
  2690. logger.error(
  2691. "failed to obtain " + device + " stream - stop", error);
  2692. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2693. });
  2694. }
  2695. /**
  2696. * Handles the newly created Media Streams.
  2697. * @param streams the new Media Streams
  2698. * @param resolution the resolution of the video streams
  2699. * @returns {*[]} object that describes the new streams
  2700. */
  2701. function handleLocalStream(streams, resolution) {
  2702. var audioStream, videoStream, desktopStream, res = [];
  2703. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2704. // an object with two properties: audioStream, videoStream.
  2705. if (window.webkitMediaStream) {
  2706. var audioVideo = streams.audioVideo;
  2707. if (audioVideo) {
  2708. var audioTracks = audioVideo.getAudioTracks();
  2709. if(audioTracks.length) {
  2710. audioStream = new webkitMediaStream();
  2711. for (var i = 0; i < audioTracks.length; i++) {
  2712. audioStream.addTrack(audioTracks[i]);
  2713. }
  2714. }
  2715. var videoTracks = audioVideo.getVideoTracks();
  2716. if(videoTracks.length) {
  2717. videoStream = new webkitMediaStream();
  2718. for (var j = 0; j < videoTracks.length; j++) {
  2719. videoStream.addTrack(videoTracks[j]);
  2720. }
  2721. }
  2722. }
  2723. if (streams && streams.desktopStream)
  2724. desktopStream = streams.desktopStream;
  2725. }
  2726. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2727. if (streams && streams.audio)
  2728. audioStream = streams.audio;
  2729. if (streams && streams.video)
  2730. videoStream = streams.video;
  2731. if(streams && streams.desktop)
  2732. desktopStream = streams.desktop;
  2733. }
  2734. if (desktopStream)
  2735. res.push({stream: desktopStream,
  2736. type: "video", videoType: "desktop"});
  2737. if(audioStream)
  2738. res.push({stream: audioStream, type: "audio", videoType: null});
  2739. if(videoStream)
  2740. res.push({stream: videoStream, type: "video", videoType: "camera",
  2741. resolution: resolution});
  2742. return res;
  2743. }
  2744. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2745. var RTCUtils = {
  2746. init: function (options) {
  2747. return new Promise(function(resolve, reject) {
  2748. if (RTCBrowserType.isFirefox()) {
  2749. var FFversion = RTCBrowserType.getFirefoxVersion();
  2750. if (FFversion < 40) {
  2751. logger.error(
  2752. "Firefox version too old: " + FFversion +
  2753. ". Required >= 40.");
  2754. reject(new Error("Firefox version too old: " + FFversion +
  2755. ". Required >= 40."));
  2756. return;
  2757. }
  2758. this.peerconnection = mozRTCPeerConnection;
  2759. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2760. this.enumerateDevices = wrapEnumerateDevices(
  2761. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2762. );
  2763. this.pc_constraints = {};
  2764. this.attachMediaStream = function (element, stream) {
  2765. // srcObject is being standardized and FF will eventually
  2766. // support that unprefixed. FF also supports the
  2767. // "element.src = URL.createObjectURL(...)" combo, but that
  2768. // will be deprecated in favour of srcObject.
  2769. //
  2770. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2771. // https://github.com/webrtc/samples/issues/302
  2772. if (!element[0])
  2773. return;
  2774. element[0].mozSrcObject = stream;
  2775. element[0].play();
  2776. };
  2777. this.getStreamID = function (stream) {
  2778. var id = stream.id;
  2779. if (!id) {
  2780. var tracks = stream.getVideoTracks();
  2781. if (!tracks || tracks.length === 0) {
  2782. tracks = stream.getAudioTracks();
  2783. }
  2784. id = tracks[0].id;
  2785. }
  2786. return SDPUtil.filter_special_chars(id);
  2787. };
  2788. this.getVideoSrc = function (element) {
  2789. if (!element)
  2790. return null;
  2791. return element.mozSrcObject;
  2792. };
  2793. this.setVideoSrc = function (element, src) {
  2794. if (element)
  2795. element.mozSrcObject = src;
  2796. };
  2797. RTCSessionDescription = mozRTCSessionDescription;
  2798. RTCIceCandidate = mozRTCIceCandidate;
  2799. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2800. this.peerconnection = webkitRTCPeerConnection;
  2801. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2802. if (navigator.mediaDevices) {
  2803. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2804. this.enumerateDevices = wrapEnumerateDevices(
  2805. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2806. );
  2807. } else {
  2808. this.getUserMedia = getUserMedia;
  2809. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2810. }
  2811. this.attachMediaStream = function (element, stream) {
  2812. // saves the created url for the stream, so we can reuse it
  2813. // and not keep creating urls
  2814. if (!stream.jitsiObjectURL) {
  2815. stream.jitsiObjectURL
  2816. = webkitURL.createObjectURL(stream);
  2817. }
  2818. element.attr('src', stream.jitsiObjectURL);
  2819. };
  2820. this.getStreamID = function (stream) {
  2821. // streams from FF endpoints have the characters '{' and '}'
  2822. // that make jQuery choke.
  2823. return SDPUtil.filter_special_chars(stream.id);
  2824. };
  2825. this.getVideoSrc = function (element) {
  2826. if (!element)
  2827. return null;
  2828. return element.getAttribute("src");
  2829. };
  2830. this.setVideoSrc = function (element, src) {
  2831. if (element)
  2832. element.setAttribute("src", src);
  2833. };
  2834. // DTLS should now be enabled by default but..
  2835. this.pc_constraints = {'optional': [
  2836. {'DtlsSrtpKeyAgreement': 'true'}
  2837. ]};
  2838. if (options.useIPv6) {
  2839. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2840. this.pc_constraints.optional.push({googIPv6: true});
  2841. }
  2842. if (RTCBrowserType.isAndroid()) {
  2843. this.pc_constraints = {}; // disable DTLS on Android
  2844. }
  2845. if (!webkitMediaStream.prototype.getVideoTracks) {
  2846. webkitMediaStream.prototype.getVideoTracks = function () {
  2847. return this.videoTracks;
  2848. };
  2849. }
  2850. if (!webkitMediaStream.prototype.getAudioTracks) {
  2851. webkitMediaStream.prototype.getAudioTracks = function () {
  2852. return this.audioTracks;
  2853. };
  2854. }
  2855. }
  2856. // Detect IE/Safari
  2857. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2858. //AdapterJS.WebRTCPlugin.setLogLevel(
  2859. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2860. var self = this;
  2861. AdapterJS.webRTCReady(function (isPlugin) {
  2862. self.peerconnection = RTCPeerConnection;
  2863. self.getUserMedia = window.getUserMedia;
  2864. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2865. self.attachMediaStream = function (elSel, stream) {
  2866. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2867. return;
  2868. }
  2869. attachMediaStream(elSel[0], stream);
  2870. };
  2871. self.getStreamID = function (stream) {
  2872. var id = SDPUtil.filter_special_chars(stream.label);
  2873. return id;
  2874. };
  2875. self.getVideoSrc = function (element) {
  2876. if (!element) {
  2877. logger.warn("Attempt to get video SRC of null element");
  2878. return null;
  2879. }
  2880. var children = element.children;
  2881. for (var i = 0; i !== children.length; ++i) {
  2882. if (children[i].name === 'streamId') {
  2883. return children[i].value;
  2884. }
  2885. }
  2886. //logger.info(element.id + " SRC: " + src);
  2887. return null;
  2888. };
  2889. self.setVideoSrc = function (element, src) {
  2890. //logger.info("Set video src: ", element, src);
  2891. if (!src) {
  2892. logger.warn("Not attaching video stream, 'src' is null");
  2893. return;
  2894. }
  2895. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2896. var stream = AdapterJS.WebRTCPlugin.plugin
  2897. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2898. attachMediaStream(element, stream);
  2899. };
  2900. onReady(options, self.getUserMediaWithConstraints);
  2901. resolve();
  2902. });
  2903. } else {
  2904. try {
  2905. logger.error('Browser does not appear to be WebRTC-capable');
  2906. } catch (e) {
  2907. }
  2908. reject('Browser does not appear to be WebRTC-capable');
  2909. return;
  2910. }
  2911. // Call onReady() if Temasys plugin is not used
  2912. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2913. onReady(options, this.getUserMediaWithConstraints);
  2914. resolve();
  2915. }
  2916. }.bind(this));
  2917. },
  2918. /**
  2919. * @param {string[]} um required user media types
  2920. * @param {function} success_callback
  2921. * @param {Function} failure_callback
  2922. * @param {Object} [options] optional parameters
  2923. * @param {string} options.resolution
  2924. * @param {number} options.bandwidth
  2925. * @param {number} options.fps
  2926. * @param {string} options.desktopStream
  2927. * @param {string} options.cameraDeviceId
  2928. * @param {string} options.micDeviceId
  2929. **/
  2930. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2931. options = options || {};
  2932. var resolution = options.resolution;
  2933. var constraints = getConstraints(um, options);
  2934. logger.info("Get media constraints", constraints);
  2935. try {
  2936. this.getUserMedia(constraints,
  2937. function (stream) {
  2938. logger.log('onUserMediaSuccess');
  2939. setAvailableDevices(um, true);
  2940. success_callback(stream);
  2941. },
  2942. function (error) {
  2943. setAvailableDevices(um, false);
  2944. logger.warn('Failed to get access to local media. Error ',
  2945. error, constraints);
  2946. if (failure_callback) {
  2947. failure_callback(error, resolution);
  2948. }
  2949. });
  2950. } catch (e) {
  2951. logger.error('GUM failed: ', e);
  2952. if (failure_callback) {
  2953. failure_callback(e);
  2954. }
  2955. }
  2956. },
  2957. /**
  2958. * Creates the local MediaStreams.
  2959. * @param {Object} [options] optional parameters
  2960. * @param {Array} options.devices the devices that will be requested
  2961. * @param {string} options.resolution resolution constraints
  2962. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2963. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2964. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2965. * @param {string} options.cameraDeviceId
  2966. * @param {string} options.micDeviceId
  2967. * @returns {*} Promise object that will receive the new JitsiTracks
  2968. */
  2969. obtainAudioAndVideoPermissions: function (options) {
  2970. var self = this;
  2971. options = options || {};
  2972. return new Promise(function (resolve, reject) {
  2973. var successCallback = function (stream) {
  2974. resolve(handleLocalStream(stream, options.resolution));
  2975. };
  2976. options.devices = options.devices || ['audio', 'video'];
  2977. if(!screenObtainer.isSupported()
  2978. && options.devices.indexOf("desktop") !== -1){
  2979. reject(new Error("Desktop sharing is not supported!"));
  2980. }
  2981. if (RTCBrowserType.isFirefox() ||
  2982. RTCBrowserType.isTemasysPluginUsed()) {
  2983. var GUM = function (device, s, e) {
  2984. this.getUserMediaWithConstraints(device, s, e, options);
  2985. };
  2986. var deviceGUM = {
  2987. "audio": GUM.bind(self, ["audio"]),
  2988. "video": GUM.bind(self, ["video"])
  2989. };
  2990. if(screenObtainer.isSupported()){
  2991. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  2992. screenObtainer);
  2993. }
  2994. // With FF/IE we can't split the stream into audio and video because FF
  2995. // doesn't support media stream constructors. So, we need to get the
  2996. // audio stream separately from the video stream using two distinct GUM
  2997. // calls. Not very user friendly :-( but we don't have many other
  2998. // options neither.
  2999. //
  3000. // Note that we pack those 2 streams in a single object and pass it to
  3001. // the successCallback method.
  3002. obtainDevices({
  3003. devices: options.devices,
  3004. streams: [],
  3005. successCallback: successCallback,
  3006. errorCallback: reject,
  3007. deviceGUM: deviceGUM
  3008. });
  3009. } else {
  3010. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3011. if (hasDesktop) {
  3012. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3013. }
  3014. options.resolution = options.resolution || '360';
  3015. if(options.devices.length) {
  3016. this.getUserMediaWithConstraints(
  3017. options.devices,
  3018. function (stream) {
  3019. if((options.devices.indexOf("audio") !== -1 &&
  3020. !stream.getAudioTracks().length) ||
  3021. (options.devices.indexOf("video") !== -1 &&
  3022. !stream.getVideoTracks().length))
  3023. {
  3024. self.stopMediaStream(stream);
  3025. reject(JitsiTrackErrors.parseError(
  3026. new Error("Unable to get the audio and " +
  3027. "video tracks."),
  3028. options.devices));
  3029. return;
  3030. }
  3031. if(hasDesktop) {
  3032. screenObtainer.obtainStream(
  3033. function (desktopStream) {
  3034. successCallback({audioVideo: stream,
  3035. desktopStream: desktopStream});
  3036. }, function (error) {
  3037. self.stopMediaStream(stream);
  3038. reject(
  3039. JitsiTrackErrors.parseError(error,
  3040. options.devices));
  3041. });
  3042. } else {
  3043. successCallback({audioVideo: stream});
  3044. }
  3045. },
  3046. function (error) {
  3047. reject(JitsiTrackErrors.parseError(error,
  3048. options.devices));
  3049. },
  3050. options);
  3051. } else if (hasDesktop) {
  3052. screenObtainer.obtainStream(
  3053. function (stream) {
  3054. successCallback({desktopStream: stream});
  3055. }, function (error) {
  3056. reject(
  3057. JitsiTrackErrors.parseError(error,
  3058. ["desktop"]));
  3059. });
  3060. }
  3061. }
  3062. }.bind(this));
  3063. },
  3064. addListener: function (eventType, listener) {
  3065. eventEmitter.on(eventType, listener);
  3066. },
  3067. removeListener: function (eventType, listener) {
  3068. eventEmitter.removeListener(eventType, listener);
  3069. },
  3070. getDeviceAvailability: function () {
  3071. return devices;
  3072. },
  3073. isRTCReady: function () {
  3074. return rtcReady;
  3075. },
  3076. /**
  3077. * Checks if its possible to enumerate available cameras/micropones.
  3078. * @returns {boolean} true if available, false otherwise.
  3079. */
  3080. isDeviceListAvailable: function () {
  3081. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3082. if (isEnumerateDevicesAvailable) {
  3083. return true;
  3084. }
  3085. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3086. },
  3087. /**
  3088. * Returns true if changing the camera / microphone device is supported and
  3089. * false if not.
  3090. */
  3091. isDeviceChangeAvailable: function () {
  3092. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3093. RTCBrowserType.isTemasysPluginUsed())
  3094. return true;
  3095. return false;
  3096. },
  3097. /**
  3098. * A method to handle stopping of the stream.
  3099. * One point to handle the differences in various implementations.
  3100. * @param mediaStream MediaStream object to stop.
  3101. */
  3102. stopMediaStream: function (mediaStream) {
  3103. mediaStream.getTracks().forEach(function (track) {
  3104. // stop() not supported with IE
  3105. if (track.stop) {
  3106. track.stop();
  3107. }
  3108. });
  3109. // leave stop for implementation still using it
  3110. if (mediaStream.stop) {
  3111. mediaStream.stop();
  3112. }
  3113. // if we have done createObjectURL, lets clean it
  3114. if (mediaStream.jitsiObjectURL) {
  3115. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3116. }
  3117. },
  3118. /**
  3119. * Returns whether the desktop sharing is enabled or not.
  3120. * @returns {boolean}
  3121. */
  3122. isDesktopSharingEnabled: function () {
  3123. return screenObtainer.isSupported();
  3124. }
  3125. };
  3126. module.exports = RTCUtils;
  3127. }).call(this,"/modules/RTC/RTCUtils.js")
  3128. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":80,"../../service/RTC/Resolutions":81,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":44,"jitsi-meet-logger":48}],19:[function(require,module,exports){
  3129. (function (__filename){
  3130. /* global chrome, $, alert */
  3131. /* jshint -W003 */
  3132. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3133. var RTCBrowserType = require("./RTCBrowserType");
  3134. var AdapterJS = require("./adapter.screenshare");
  3135. var DesktopSharingEventTypes
  3136. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3137. /**
  3138. * Indicates whether the Chrome desktop sharing extension is installed.
  3139. * @type {boolean}
  3140. */
  3141. var chromeExtInstalled = false;
  3142. /**
  3143. * Indicates whether an update of the Chrome desktop sharing extension is
  3144. * required.
  3145. * @type {boolean}
  3146. */
  3147. var chromeExtUpdateRequired = false;
  3148. /**
  3149. * Whether the jidesha extension for firefox is installed for the domain on
  3150. * which we are running. Null designates an unknown value.
  3151. * @type {null}
  3152. */
  3153. var firefoxExtInstalled = null;
  3154. /**
  3155. * If set to true, detection of an installed firefox extension will be started
  3156. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3157. * user tries to enable screen sharing).
  3158. */
  3159. var reDetectFirefoxExtension = false;
  3160. var GUM = null;
  3161. /**
  3162. * Handles obtaining a stream from a screen capture on different browsers.
  3163. */
  3164. var ScreenObtainer = {
  3165. /**
  3166. * The EventEmitter to use to emit events.
  3167. * @type {null}
  3168. */
  3169. eventEmitter: null,
  3170. obtainStream: null,
  3171. /**
  3172. * Initializes the function used to obtain a screen capture
  3173. * (this.obtainStream).
  3174. *
  3175. * If the browser is Chrome, it uses the value of
  3176. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3177. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3178. * use the "screen" media source (if the value is 'webrtc'),
  3179. * or disable screen capture (if the value is other).
  3180. * Note that for the "screen" media source to work the
  3181. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3182. */
  3183. init: function(eventEmitter, options, gum) {
  3184. this.eventEmitter = eventEmitter;
  3185. var obtainDesktopStream = null;
  3186. this.options = options = options || {};
  3187. GUM = gum;
  3188. if (RTCBrowserType.isFirefox())
  3189. initFirefoxExtensionDetection(options);
  3190. // TODO remove this, options.desktopSharing is deprecated.
  3191. var chromeMethod =
  3192. (options.desktopSharingChromeMethod || options.desktopSharing);
  3193. if (RTCBrowserType.isTemasysPluginUsed()) {
  3194. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3195. logger.info("Screensharing not supported by this plugin " +
  3196. "version");
  3197. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3198. logger.info(
  3199. "Screensharing not available with Temasys plugin on" +
  3200. " this site");
  3201. } else {
  3202. obtainDesktopStream = obtainWebRTCScreen;
  3203. logger.info("Using Temasys plugin for desktop sharing");
  3204. }
  3205. } else if (RTCBrowserType.isChrome()) {
  3206. if (chromeMethod == "ext") {
  3207. if (RTCBrowserType.getChromeVersion() >= 34) {
  3208. obtainDesktopStream =
  3209. this.obtainScreenFromExtension;
  3210. logger.info("Using Chrome extension for desktop sharing");
  3211. initChromeExtension(options);
  3212. } else {
  3213. logger.info("Chrome extension not supported until ver 34");
  3214. }
  3215. } else if (chromeMethod == "webrtc") {
  3216. obtainDesktopStream = obtainWebRTCScreen;
  3217. logger.info("Using Chrome WebRTC for desktop sharing");
  3218. }
  3219. } else if (RTCBrowserType.isFirefox()) {
  3220. if (options.desktopSharingFirefoxDisabled) {
  3221. obtainDesktopStream = null;
  3222. } else if (window.location.protocol === "http:"){
  3223. logger.log("Screen sharing is not supported over HTTP. " +
  3224. "Use of HTTPS is required.");
  3225. obtainDesktopStream = null;
  3226. } else {
  3227. obtainDesktopStream = this.obtainScreenOnFirefox;
  3228. }
  3229. }
  3230. if (!obtainDesktopStream) {
  3231. logger.info("Desktop sharing disabled");
  3232. }
  3233. this.obtainStream = obtainDesktopStream;
  3234. },
  3235. /**
  3236. * Checks whether obtaining a screen capture is supported in the current
  3237. * environment.
  3238. * @returns {boolean}
  3239. */
  3240. isSupported: function() {
  3241. return !!this.obtainStream;
  3242. },
  3243. /**
  3244. * Obtains a screen capture stream on Firefox.
  3245. * @param callback
  3246. * @param errorCallback
  3247. */
  3248. obtainScreenOnFirefox:
  3249. function (callback, errorCallback) {
  3250. var self = this;
  3251. var extensionRequired = false;
  3252. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3253. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3254. RTCBrowserType.getFirefoxVersion() <=
  3255. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3256. extensionRequired = true;
  3257. logger.log("Jidesha extension required on firefox version " +
  3258. RTCBrowserType.getFirefoxVersion());
  3259. }
  3260. if (!extensionRequired || firefoxExtInstalled === true) {
  3261. obtainWebRTCScreen(callback, errorCallback);
  3262. return;
  3263. }
  3264. if (reDetectFirefoxExtension) {
  3265. reDetectFirefoxExtension = false;
  3266. initFirefoxExtensionDetection(this.options);
  3267. }
  3268. // Give it some (more) time to initialize, and assume lack of
  3269. // extension if it hasn't.
  3270. if (firefoxExtInstalled === null) {
  3271. window.setTimeout(
  3272. function() {
  3273. if (firefoxExtInstalled === null)
  3274. firefoxExtInstalled = false;
  3275. self.obtainScreenOnFirefox(callback, errorCallback);
  3276. },
  3277. 300
  3278. );
  3279. logger.log("Waiting for detection of jidesha on firefox to " +
  3280. "finish.");
  3281. return;
  3282. }
  3283. // We need an extension and it isn't installed.
  3284. // Make sure we check for the extension when the user clicks again.
  3285. firefoxExtInstalled = null;
  3286. reDetectFirefoxExtension = true;
  3287. // Prompt the user to install the extension
  3288. this.eventEmitter.emit(
  3289. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  3290. this.options.desktopSharingFirefoxExtensionURL);
  3291. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3292. // stuck in 'switching' mode.
  3293. errorCallback('Firefox extension required.');
  3294. },
  3295. /**
  3296. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3297. * 'desktop' stream for returned stream token.
  3298. */
  3299. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3300. if (chromeExtInstalled) {
  3301. doGetStreamFromExtension(this.options, streamCallback,
  3302. failCallback);
  3303. } else {
  3304. if (chromeExtUpdateRequired) {
  3305. alert(
  3306. 'Jitsi Desktop Streamer requires update. ' +
  3307. 'Changes will take effect after next Chrome restart.');
  3308. }
  3309. chrome.webstore.install(
  3310. getWebStoreInstallUrl(this.options),
  3311. function (arg) {
  3312. logger.log("Extension installed successfully", arg);
  3313. chromeExtInstalled = true;
  3314. // We need to give a moment for the endpoint to become
  3315. // available
  3316. window.setTimeout(function () {
  3317. doGetStreamFromExtension(this.options, streamCallback,
  3318. failCallback);
  3319. }, 500);
  3320. },
  3321. function (arg) {
  3322. logger.log("Failed to install the extension", arg);
  3323. failCallback(arg);
  3324. }
  3325. );
  3326. }
  3327. }
  3328. };
  3329. /**
  3330. * Obtains a desktop stream using getUserMedia.
  3331. * For this to work on Chrome, the
  3332. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3333. *
  3334. * On firefox, the document's domain must be white-listed in the
  3335. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3336. * 'about:config'.
  3337. */
  3338. function obtainWebRTCScreen(streamCallback, failCallback) {
  3339. GUM(
  3340. ['screen'],
  3341. streamCallback,
  3342. failCallback
  3343. );
  3344. }
  3345. /**
  3346. * Constructs inline install URL for Chrome desktop streaming extension.
  3347. * The 'chromeExtensionId' must be defined in options parameter.
  3348. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3349. * @returns {string}
  3350. */
  3351. function getWebStoreInstallUrl(options)
  3352. {
  3353. //TODO remove chromeExtensionId (deprecated)
  3354. return "https://chrome.google.com/webstore/detail/" +
  3355. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3356. }
  3357. /**
  3358. * Checks whether an update of the Chrome extension is required.
  3359. * @param minVersion minimal required version
  3360. * @param extVersion current extension version
  3361. * @returns {boolean}
  3362. */
  3363. function isUpdateRequired(minVersion, extVersion) {
  3364. try {
  3365. var s1 = minVersion.split('.');
  3366. var s2 = extVersion.split('.');
  3367. var len = Math.max(s1.length, s2.length);
  3368. for (var i = 0; i < len; i++) {
  3369. var n1 = 0,
  3370. n2 = 0;
  3371. if (i < s1.length)
  3372. n1 = parseInt(s1[i]);
  3373. if (i < s2.length)
  3374. n2 = parseInt(s2[i]);
  3375. if (isNaN(n1) || isNaN(n2)) {
  3376. return true;
  3377. } else if (n1 !== n2) {
  3378. return n1 > n2;
  3379. }
  3380. }
  3381. // will happen if both versions have identical numbers in
  3382. // their components (even if one of them is longer, has more components)
  3383. return false;
  3384. }
  3385. catch (e) {
  3386. logger.error("Failed to parse extension version", e);
  3387. return true;
  3388. }
  3389. }
  3390. function checkChromeExtInstalled(callback, options) {
  3391. if (!chrome || !chrome.runtime) {
  3392. // No API, so no extension for sure
  3393. callback(false, false);
  3394. return;
  3395. }
  3396. chrome.runtime.sendMessage(
  3397. //TODO: remove chromeExtensionId (deprecated)
  3398. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3399. { getVersion: true },
  3400. function (response) {
  3401. if (!response || !response.version) {
  3402. // Communication failure - assume that no endpoint exists
  3403. logger.warn(
  3404. "Extension not installed?: ", chrome.runtime.lastError);
  3405. callback(false, false);
  3406. return;
  3407. }
  3408. // Check installed extension version
  3409. var extVersion = response.version;
  3410. logger.log('Extension version is: ' + extVersion);
  3411. //TODO: remove minChromeExtVersion (deprecated)
  3412. var updateRequired
  3413. = isUpdateRequired(
  3414. (options.desktopSharingChromeMinExtVersion ||
  3415. options.minChromeExtVersion),
  3416. extVersion);
  3417. callback(!updateRequired, updateRequired);
  3418. }
  3419. );
  3420. }
  3421. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3422. // Sends 'getStream' msg to the extension.
  3423. // Extension id must be defined in the config.
  3424. chrome.runtime.sendMessage(
  3425. //TODO: remove chromeExtensionId (deprecated)
  3426. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3427. {
  3428. getStream: true,
  3429. //TODO: remove desktopSharingSources (deprecated).
  3430. sources: (options.desktopSharingChromeSources ||
  3431. options.desktopSharingSources)
  3432. },
  3433. function (response) {
  3434. if (!response) {
  3435. failCallback(chrome.runtime.lastError);
  3436. return;
  3437. }
  3438. logger.log("Response from extension: " + response);
  3439. if (response.streamId) {
  3440. GUM(
  3441. ['desktop'],
  3442. function (stream) {
  3443. streamCallback(stream);
  3444. },
  3445. failCallback,
  3446. {desktopStream: response.streamId});
  3447. } else {
  3448. failCallback("Extension failed to get the stream");
  3449. }
  3450. }
  3451. );
  3452. }
  3453. /**
  3454. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3455. * config.js to support inline installs. Host site must be selected as main
  3456. * website of published extension.
  3457. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3458. */
  3459. function initInlineInstalls(options)
  3460. {
  3461. $("link[rel=chrome-webstore-item]").attr("href",
  3462. getWebStoreInstallUrl(options));
  3463. }
  3464. function initChromeExtension(options) {
  3465. // Initialize Chrome extension inline installs
  3466. initInlineInstalls(options);
  3467. // Check if extension is installed
  3468. checkChromeExtInstalled(function (installed, updateRequired) {
  3469. chromeExtInstalled = installed;
  3470. chromeExtUpdateRequired = updateRequired;
  3471. logger.info(
  3472. "Chrome extension installed: " + chromeExtInstalled +
  3473. " updateRequired: " + chromeExtUpdateRequired);
  3474. }, options);
  3475. }
  3476. /**
  3477. * Starts the detection of an installed jidesha extension for firefox.
  3478. * @param options supports "desktopSharingFirefoxDisabled",
  3479. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3480. */
  3481. function initFirefoxExtensionDetection(options) {
  3482. if (options.desktopSharingFirefoxDisabled) {
  3483. return;
  3484. }
  3485. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3486. return;
  3487. if (!options.desktopSharingFirefoxExtId) {
  3488. firefoxExtInstalled = false;
  3489. return;
  3490. }
  3491. var img = document.createElement('img');
  3492. img.onload = function(){
  3493. logger.log("Detected firefox screen sharing extension.");
  3494. firefoxExtInstalled = true;
  3495. };
  3496. img.onerror = function(){
  3497. logger.log("Detected lack of firefox screen sharing extension.");
  3498. firefoxExtInstalled = false;
  3499. };
  3500. // The jidesha extension exposes an empty image file under the url:
  3501. // "chrome://EXT_ID/content/DOMAIN.png"
  3502. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3503. // DOMAIN is a domain whitelisted by the extension.
  3504. var src = "chrome://" +
  3505. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3506. "/content/" + document.location.hostname + ".png";
  3507. img.setAttribute('src', src);
  3508. }
  3509. module.exports = ScreenObtainer;
  3510. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3511. },{"../../service/desktopsharing/DesktopSharingEventTypes":84,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":48}],20:[function(require,module,exports){
  3512. (function (__filename){
  3513. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3514. var console = require("jitsi-meet-logger").getLogger(__filename);
  3515. // Adapter's interface.
  3516. var AdapterJS = AdapterJS || {};
  3517. // Browserify compatibility
  3518. if(typeof exports !== 'undefined') {
  3519. module.exports = AdapterJS;
  3520. }
  3521. AdapterJS.options = AdapterJS.options || {};
  3522. // uncomment to get virtual webcams
  3523. // AdapterJS.options.getAllCams = true;
  3524. // uncomment to prevent the install prompt when the plugin in not yet installed
  3525. // AdapterJS.options.hidePluginInstallPrompt = true;
  3526. // AdapterJS version
  3527. AdapterJS.VERSION = '0.12.3';
  3528. // This function will be called when the WebRTC API is ready to be used
  3529. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3530. // the plugin
  3531. // You may Override this function to synchronise the start of your application
  3532. // with the WebRTC API being ready.
  3533. // If you decide not to override use this synchronisation, it may result in
  3534. // an extensive CPU usage on the plugin start (once per tab loaded)
  3535. // Params:
  3536. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3537. //
  3538. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3539. // The WebRTC API is ready.
  3540. // Override me and do whatever you want here
  3541. };
  3542. // Sets a callback function to be called when the WebRTC interface is ready.
  3543. // The first argument is the function to callback.\
  3544. // Throws an error if the first argument is not a function
  3545. AdapterJS.webRTCReady = function (callback) {
  3546. if (typeof callback !== 'function') {
  3547. throw new Error('Callback provided is not a function');
  3548. }
  3549. if (true === AdapterJS.onwebrtcreadyDone) {
  3550. // All WebRTC interfaces are ready, just call the callback
  3551. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3552. } else {
  3553. // will be triggered automatically when your browser/plugin is ready.
  3554. AdapterJS.onwebrtcready = callback;
  3555. }
  3556. };
  3557. // Plugin namespace
  3558. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3559. // The object to store plugin information
  3560. AdapterJS.WebRTCPlugin.pluginInfo = {
  3561. prefix : 'Tem',
  3562. plugName : 'TemWebRTCPlugin',
  3563. pluginId : 'plugin0',
  3564. type : 'application/x-temwebrtcplugin',
  3565. onload : '__TemWebRTCReady0',
  3566. portalLink : 'http://skylink.io/plugin/',
  3567. downloadLink : null, //set below
  3568. companyName: 'Temasys'
  3569. };
  3570. if(!!navigator.platform.match(/^Mac/i)) {
  3571. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3572. }
  3573. else if(!!navigator.platform.match(/^Win/i)) {
  3574. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3575. }
  3576. AdapterJS.WebRTCPlugin.TAGS = {
  3577. NONE : 'none',
  3578. AUDIO : 'audio',
  3579. VIDEO : 'video'
  3580. };
  3581. // Unique identifier of each opened page
  3582. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3583. // Use this whenever you want to call the plugin.
  3584. AdapterJS.WebRTCPlugin.plugin = null;
  3585. // Set log level for the plugin once it is ready.
  3586. // The different values are
  3587. // This is an asynchronous function that will run when the plugin is ready
  3588. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3589. // Defines webrtc's JS interface according to the plugin's implementation.
  3590. // Define plugin Browsers as WebRTC Interface.
  3591. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3592. // This function detects whether or not a plugin is installed.
  3593. // Checks if Not IE (firefox, for example), else if it's IE,
  3594. // we're running IE and do something. If not it is not supported.
  3595. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3596. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3597. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3598. // Inject the HTML DOM object element into the page.
  3599. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3600. // States of readiness that the plugin goes through when
  3601. // being injected and stated
  3602. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3603. NONE : 0, // no plugin use
  3604. INITIALIZING : 1, // Detected need for plugin
  3605. INJECTING : 2, // Injecting plugin
  3606. INJECTED: 3, // Plugin element injected but not usable yet
  3607. READY: 4 // Plugin ready to be used
  3608. };
  3609. // Current state of the plugin. You cannot use the plugin before this is
  3610. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3611. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3612. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3613. // Used to make sure AdapterJS.onwebrtcready is only called once
  3614. AdapterJS.onwebrtcreadyDone = false;
  3615. // Log levels for the plugin.
  3616. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3617. /*
  3618. Log outputs are prefixed in some cases.
  3619. INFO: Information reported by the plugin.
  3620. ERROR: Errors originating from within the plugin.
  3621. WEBRTC: Error originating from within the libWebRTC library
  3622. */
  3623. // From the least verbose to the most verbose
  3624. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3625. NONE : 'NONE',
  3626. ERROR : 'ERROR',
  3627. WARNING : 'WARNING',
  3628. INFO: 'INFO',
  3629. VERBOSE: 'VERBOSE',
  3630. SENSITIVE: 'SENSITIVE'
  3631. };
  3632. // Does a waiting check before proceeding to load the plugin.
  3633. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3634. // This methid will use an interval to wait for the plugin to be ready.
  3635. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3636. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3637. // This function will be called when plugin is ready. It sends necessary
  3638. // details to the plugin.
  3639. // The function will wait for the document to be ready and the set the
  3640. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3641. // indicating that it can start being requested.
  3642. // This function is not in the IE/Safari condition brackets so that
  3643. // TemPluginLoaded function might be called on Chrome/Firefox.
  3644. // This function is the only private function that is not encapsulated to
  3645. // allow the plugin method to be called.
  3646. __TemWebRTCReady0 = function () {
  3647. if (document.readyState === 'complete') {
  3648. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3649. AdapterJS.maybeThroughWebRTCReady();
  3650. } else {
  3651. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3652. if (document.readyState === 'complete') {
  3653. // TODO: update comments, we wait for the document to be ready
  3654. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3655. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3656. AdapterJS.maybeThroughWebRTCReady();
  3657. }
  3658. }, 100);
  3659. }
  3660. };
  3661. AdapterJS.maybeThroughWebRTCReady = function() {
  3662. if (!AdapterJS.onwebrtcreadyDone) {
  3663. AdapterJS.onwebrtcreadyDone = true;
  3664. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3665. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3666. }
  3667. }
  3668. };
  3669. // Text namespace
  3670. AdapterJS.TEXT = {
  3671. PLUGIN: {
  3672. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3673. 'to work on this browser.',
  3674. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3675. BUTTON: 'Install Now'
  3676. },
  3677. REFRESH: {
  3678. REQUIRE_REFRESH: 'Please refresh page',
  3679. BUTTON: 'Refresh Page'
  3680. }
  3681. };
  3682. // The result of ice connection states.
  3683. // - starting: Ice connection is starting.
  3684. // - checking: Ice connection is checking.
  3685. // - connected Ice connection is connected.
  3686. // - completed Ice connection is connected.
  3687. // - done Ice connection has been completed.
  3688. // - disconnected Ice connection has been disconnected.
  3689. // - failed Ice connection has failed.
  3690. // - closed Ice connection is closed.
  3691. AdapterJS._iceConnectionStates = {
  3692. starting : 'starting',
  3693. checking : 'checking',
  3694. connected : 'connected',
  3695. completed : 'connected',
  3696. done : 'completed',
  3697. disconnected : 'disconnected',
  3698. failed : 'failed',
  3699. closed : 'closed'
  3700. };
  3701. //The IceConnection states that has been fired for each peer.
  3702. AdapterJS._iceConnectionFiredStates = [];
  3703. // Check if WebRTC Interface is defined.
  3704. AdapterJS.isDefined = null;
  3705. // This function helps to retrieve the webrtc detected browser information.
  3706. // This sets:
  3707. // - webrtcDetectedBrowser: The browser agent name.
  3708. // - webrtcDetectedVersion: The browser version.
  3709. // - webrtcDetectedType: The types of webRTC support.
  3710. // - 'moz': Mozilla implementation of webRTC.
  3711. // - 'webkit': WebKit implementation of webRTC.
  3712. // - 'plugin': Using the plugin implementation.
  3713. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3714. var hasMatch, checkMatch = navigator.userAgent.match(
  3715. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3716. if (/trident/i.test(checkMatch[1])) {
  3717. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3718. webrtcDetectedBrowser = 'IE';
  3719. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3720. } else if (checkMatch[1] === 'Chrome') {
  3721. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3722. if (hasMatch !== null) {
  3723. webrtcDetectedBrowser = 'opera';
  3724. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3725. }
  3726. }
  3727. if (navigator.userAgent.indexOf('Safari')) {
  3728. if (typeof InstallTrigger !== 'undefined') {
  3729. webrtcDetectedBrowser = 'firefox';
  3730. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3731. webrtcDetectedBrowser = 'IE';
  3732. } else if (
  3733. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3734. webrtcDetectedBrowser = 'safari';
  3735. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3736. webrtcDetectedBrowser = 'opera';
  3737. } else if (!!window.chrome) {
  3738. webrtcDetectedBrowser = 'chrome';
  3739. }
  3740. }
  3741. if (!webrtcDetectedBrowser) {
  3742. webrtcDetectedVersion = checkMatch[1];
  3743. }
  3744. if (!webrtcDetectedVersion) {
  3745. try {
  3746. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3747. [navigator.appName, navigator.appVersion, '-?'];
  3748. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3749. checkMatch.splice(1, 1, hasMatch[1]);
  3750. }
  3751. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3752. } catch (error) { }
  3753. }
  3754. };
  3755. // To fix configuration as some browsers does not support
  3756. // the 'urls' attribute.
  3757. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3758. if (pcConfig === null) {
  3759. return;
  3760. }
  3761. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3762. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3763. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3764. delete pcConfig.iceServers[i].urls;
  3765. }
  3766. }
  3767. };
  3768. AdapterJS.addEvent = function(elem, evnt, func) {
  3769. if (elem.addEventListener) { // W3C DOM
  3770. elem.addEventListener(evnt, func, false);
  3771. } else if (elem.attachEvent) {// OLD IE DOM
  3772. elem.attachEvent('on'+evnt, func);
  3773. } else { // No much to do
  3774. elem[evnt] = func;
  3775. }
  3776. };
  3777. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3778. // only inject once the page is ready
  3779. if (document.readyState !== 'complete') {
  3780. return;
  3781. }
  3782. var w = window;
  3783. var i = document.createElement('iframe');
  3784. i.style.position = 'fixed';
  3785. i.style.top = '-41px';
  3786. i.style.left = 0;
  3787. i.style.right = 0;
  3788. i.style.width = '100%';
  3789. i.style.height = '40px';
  3790. i.style.backgroundColor = '#ffffe1';
  3791. i.style.border = 'none';
  3792. i.style.borderBottom = '1px solid #888888';
  3793. i.style.zIndex = '9999999';
  3794. if(typeof i.style.webkitTransition === 'string') {
  3795. i.style.webkitTransition = 'all .5s ease-out';
  3796. } else if(typeof i.style.transition === 'string') {
  3797. i.style.transition = 'all .5s ease-out';
  3798. }
  3799. document.body.appendChild(i);
  3800. c = (i.contentWindow) ? i.contentWindow :
  3801. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3802. c.document.open();
  3803. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3804. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3805. 'middle; cursor: default;">' + text + '</span>');
  3806. if(buttonText && buttonLink) {
  3807. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3808. c.document.close();
  3809. // On click on okay
  3810. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3811. if (!!displayRefreshBar) {
  3812. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3813. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3814. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3815. }
  3816. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3817. e.preventDefault();
  3818. try {
  3819. event.cancelBubble = true;
  3820. } catch(error) { }
  3821. var pluginInstallInterval = setInterval(function(){
  3822. if(! isIE) {
  3823. navigator.plugins.refresh(false);
  3824. }
  3825. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3826. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3827. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3828. function() { // plugin now installed
  3829. clearInterval(pluginInstallInterval);
  3830. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3831. },
  3832. function() {
  3833. // still no plugin detected, nothing to do
  3834. });
  3835. } , 500);
  3836. });
  3837. // On click on Cancel
  3838. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3839. w.document.body.removeChild(i);
  3840. });
  3841. } else {
  3842. c.document.close();
  3843. }
  3844. setTimeout(function() {
  3845. if(typeof i.style.webkitTransform === 'string') {
  3846. i.style.webkitTransform = 'translateY(40px)';
  3847. } else if(typeof i.style.transform === 'string') {
  3848. i.style.transform = 'translateY(40px)';
  3849. } else {
  3850. i.style.top = '0px';
  3851. }
  3852. }, 300);
  3853. };
  3854. // -----------------------------------------------------------
  3855. // Detected webrtc implementation. Types are:
  3856. // - 'moz': Mozilla implementation of webRTC.
  3857. // - 'webkit': WebKit implementation of webRTC.
  3858. // - 'plugin': Using the plugin implementation.
  3859. webrtcDetectedType = null;
  3860. // Detected webrtc datachannel support. Types are:
  3861. // - 'SCTP': SCTP datachannel support.
  3862. // - 'RTP': RTP datachannel support.
  3863. webrtcDetectedDCSupport = null;
  3864. // Set the settings for creating DataChannels, MediaStream for
  3865. // Cross-browser compability.
  3866. // - This is only for SCTP based support browsers.
  3867. // the 'urls' attribute.
  3868. checkMediaDataChannelSettings =
  3869. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3870. if (typeof callback !== 'function') {
  3871. return;
  3872. }
  3873. var beOfferer = true;
  3874. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3875. // Nightly version does not require MozDontOfferDataChannel for interop
  3876. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3877. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3878. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3879. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3880. // Resends an updated version of constraints for MozDataChannel to work
  3881. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3882. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3883. try {
  3884. delete constraints.mandatory.MozDontOfferDataChannel;
  3885. } catch (error) {
  3886. console.error('Failed deleting MozDontOfferDataChannel');
  3887. console.error(error);
  3888. }
  3889. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3890. constraints.mandatory.MozDontOfferDataChannel = true;
  3891. }
  3892. if (!isLocalFirefox) {
  3893. // temporary measure to remove Moz* constraints in non Firefox browsers
  3894. for (var prop in constraints.mandatory) {
  3895. if (constraints.mandatory.hasOwnProperty(prop)) {
  3896. if (prop.indexOf('Moz') !== -1) {
  3897. delete constraints.mandatory[prop];
  3898. }
  3899. }
  3900. }
  3901. }
  3902. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3903. // interopability of the media stream
  3904. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3905. beOfferer = false;
  3906. }
  3907. callback(beOfferer, constraints);
  3908. };
  3909. // Handles the differences for all browsers ice connection state output.
  3910. // - Tested outcomes are:
  3911. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3912. // - Chrome (answerer) : 'checking' > 'connected'
  3913. // - Firefox (offerer) : 'checking' > 'connected'
  3914. // - Firefox (answerer): 'checking' > 'connected'
  3915. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3916. if (typeof callback !== 'function') {
  3917. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3918. return;
  3919. }
  3920. peerId = (peerId) ? peerId : 'peer';
  3921. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3922. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3923. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3924. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3925. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3926. }
  3927. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3928. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3929. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3930. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3931. setTimeout(function () {
  3932. AdapterJS._iceConnectionFiredStates[peerId]
  3933. .push(AdapterJS._iceConnectionStates.done);
  3934. callback(AdapterJS._iceConnectionStates.done);
  3935. }, 1000);
  3936. }
  3937. callback(iceConnectionState);
  3938. }
  3939. return;
  3940. };
  3941. // Firefox:
  3942. // - Creates iceServer from the url for Firefox.
  3943. // - Create iceServer with stun url.
  3944. // - Create iceServer with turn url.
  3945. // - Ignore the transport parameter from TURN url for FF version <=27.
  3946. // - Return null for createIceServer if transport=tcp.
  3947. // - FF 27 and above supports transport parameters in TURN url,
  3948. // - So passing in the full url to create iceServer.
  3949. // Chrome:
  3950. // - Creates iceServer from the url for Chrome M33 and earlier.
  3951. // - Create iceServer with stun url.
  3952. // - Chrome M28 & above uses below TURN format.
  3953. // Plugin:
  3954. // - Creates Ice Server for Plugin Browsers
  3955. // - If Stun - Create iceServer with stun url.
  3956. // - Else - Create iceServer with turn url
  3957. // - This is a WebRTC Function
  3958. createIceServer = null;
  3959. // Firefox:
  3960. // - Creates IceServers for Firefox
  3961. // - Use .url for FireFox.
  3962. // - Multiple Urls support
  3963. // Chrome:
  3964. // - Creates iceServers from the urls for Chrome M34 and above.
  3965. // - .urls is supported since Chrome M34.
  3966. // - Multiple Urls support
  3967. // Plugin:
  3968. // - Creates Ice Servers for Plugin Browsers
  3969. // - Multiple Urls support
  3970. // - This is a WebRTC Function
  3971. createIceServers = null;
  3972. //------------------------------------------------------------
  3973. //The RTCPeerConnection object.
  3974. RTCPeerConnection = null;
  3975. // Creates RTCSessionDescription object for Plugin Browsers
  3976. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3977. RTCSessionDescription : null;
  3978. // Creates RTCIceCandidate object for Plugin Browsers
  3979. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3980. RTCIceCandidate : null;
  3981. // Get UserMedia (only difference is the prefix).
  3982. // Code from Adam Barth.
  3983. getUserMedia = null;
  3984. // Attach a media stream to an element.
  3985. attachMediaStream = null;
  3986. // Re-attach a media stream to an element.
  3987. reattachMediaStream = null;
  3988. // Detected browser agent name. Types are:
  3989. // - 'firefox': Firefox browser.
  3990. // - 'chrome': Chrome browser.
  3991. // - 'opera': Opera browser.
  3992. // - 'safari': Safari browser.
  3993. // - 'IE' - Internet Explorer browser.
  3994. webrtcDetectedBrowser = null;
  3995. // Detected browser version.
  3996. webrtcDetectedVersion = null;
  3997. // Check for browser types and react accordingly
  3998. if (navigator.mozGetUserMedia) {
  3999. webrtcDetectedBrowser = 'firefox';
  4000. webrtcDetectedVersion = parseInt(navigator
  4001. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4002. webrtcDetectedType = 'moz';
  4003. webrtcDetectedDCSupport = 'SCTP';
  4004. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4005. AdapterJS.maybeFixConfiguration(pcConfig);
  4006. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4007. };
  4008. // The RTCSessionDescription object.
  4009. RTCSessionDescription = mozRTCSessionDescription;
  4010. window.RTCSessionDescription = RTCSessionDescription;
  4011. // The RTCIceCandidate object.
  4012. RTCIceCandidate = mozRTCIceCandidate;
  4013. window.RTCIceCandidate = RTCIceCandidate;
  4014. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4015. navigator.getUserMedia = window.getUserMedia;
  4016. // Shim for MediaStreamTrack.getSources.
  4017. MediaStreamTrack.getSources = function(successCb) {
  4018. setTimeout(function() {
  4019. var infos = [
  4020. { kind: 'audio', id: 'default', label:'', facing:'' },
  4021. { kind: 'video', id: 'default', label:'', facing:'' }
  4022. ];
  4023. successCb(infos);
  4024. }, 0);
  4025. };
  4026. createIceServer = function (url, username, password) {
  4027. var iceServer = null;
  4028. var url_parts = url.split(':');
  4029. if (url_parts[0].indexOf('stun') === 0) {
  4030. iceServer = { url : url };
  4031. } else if (url_parts[0].indexOf('turn') === 0) {
  4032. if (webrtcDetectedVersion < 27) {
  4033. var turn_url_parts = url.split('?');
  4034. if (turn_url_parts.length === 1 ||
  4035. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4036. iceServer = {
  4037. url : turn_url_parts[0],
  4038. credential : password,
  4039. username : username
  4040. };
  4041. }
  4042. } else {
  4043. iceServer = {
  4044. url : url,
  4045. credential : password,
  4046. username : username
  4047. };
  4048. }
  4049. }
  4050. return iceServer;
  4051. };
  4052. createIceServers = function (urls, username, password) {
  4053. var iceServers = [];
  4054. for (var i = 0; i < urls.length; i++) {
  4055. var iceServer = createIceServer(urls[i], username, password);
  4056. if (iceServer !== null) {
  4057. iceServers.push(iceServer);
  4058. }
  4059. }
  4060. return iceServers;
  4061. };
  4062. attachMediaStream = function (element, stream) {
  4063. element.mozSrcObject = stream;
  4064. if (stream !== null)
  4065. element.play();
  4066. return element;
  4067. };
  4068. reattachMediaStream = function (to, from) {
  4069. to.mozSrcObject = from.mozSrcObject;
  4070. to.play();
  4071. return to;
  4072. };
  4073. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4074. if (!callback) {
  4075. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4076. ': 1 argument required, but only 0 present.');
  4077. }
  4078. return callback([]);
  4079. };
  4080. // Fake get{Video,Audio}Tracks
  4081. if (!MediaStream.prototype.getVideoTracks) {
  4082. MediaStream.prototype.getVideoTracks = function () {
  4083. return [];
  4084. };
  4085. }
  4086. if (!MediaStream.prototype.getAudioTracks) {
  4087. MediaStream.prototype.getAudioTracks = function () {
  4088. return [];
  4089. };
  4090. }
  4091. AdapterJS.maybeThroughWebRTCReady();
  4092. } else if (navigator.webkitGetUserMedia) {
  4093. webrtcDetectedBrowser = 'chrome';
  4094. webrtcDetectedType = 'webkit';
  4095. webrtcDetectedVersion = parseInt(navigator
  4096. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4097. // check if browser is opera 20+
  4098. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4099. if (checkIfOpera !== null) {
  4100. webrtcDetectedBrowser = 'opera';
  4101. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4102. }
  4103. // check browser datachannel support
  4104. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4105. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4106. webrtcDetectedDCSupport = 'SCTP';
  4107. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4108. webrtcDetectedVersion > 24) {
  4109. webrtcDetectedDCSupport = 'RTP';
  4110. } else {
  4111. webrtcDetectedDCSupport = '';
  4112. }
  4113. createIceServer = function (url, username, password) {
  4114. var iceServer = null;
  4115. var url_parts = url.split(':');
  4116. if (url_parts[0].indexOf('stun') === 0) {
  4117. iceServer = { 'url' : url };
  4118. } else if (url_parts[0].indexOf('turn') === 0) {
  4119. iceServer = {
  4120. 'url' : url,
  4121. 'credential' : password,
  4122. 'username' : username
  4123. };
  4124. }
  4125. return iceServer;
  4126. };
  4127. createIceServers = function (urls, username, password) {
  4128. var iceServers = [];
  4129. if (webrtcDetectedVersion >= 34) {
  4130. iceServers = {
  4131. 'urls' : urls,
  4132. 'credential' : password,
  4133. 'username' : username
  4134. };
  4135. } else {
  4136. for (var i = 0; i < urls.length; i++) {
  4137. var iceServer = createIceServer(urls[i], username, password);
  4138. if (iceServer !== null) {
  4139. iceServers.push(iceServer);
  4140. }
  4141. }
  4142. }
  4143. return iceServers;
  4144. };
  4145. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4146. if (webrtcDetectedVersion < 34) {
  4147. AdapterJS.maybeFixConfiguration(pcConfig);
  4148. }
  4149. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4150. };
  4151. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4152. navigator.getUserMedia = window.getUserMedia;
  4153. attachMediaStream = function (element, stream) {
  4154. if (typeof element.srcObject !== 'undefined') {
  4155. element.srcObject = stream;
  4156. } else if (typeof element.mozSrcObject !== 'undefined') {
  4157. element.mozSrcObject = stream;
  4158. } else if (typeof element.src !== 'undefined') {
  4159. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4160. } else {
  4161. console.log('Error attaching stream to element.');
  4162. }
  4163. return element;
  4164. };
  4165. reattachMediaStream = function (to, from) {
  4166. to.src = from.src;
  4167. return to;
  4168. };
  4169. AdapterJS.maybeThroughWebRTCReady();
  4170. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4171. /Edge\/(\d+).(\d+)$/)) {
  4172. webrtcDetectedBrowser = 'edge';
  4173. webrtcDetectedVersion =
  4174. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4175. // the minimum version still supported by adapter.
  4176. webrtcMinimumVersion = 12;
  4177. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4178. attachMediaStream = function(element, stream) {
  4179. element.srcObject = stream;
  4180. return element;
  4181. };
  4182. reattachMediaStream = function(to, from) {
  4183. to.srcObject = from.srcObject;
  4184. return to;
  4185. };
  4186. AdapterJS.maybeThroughWebRTCReady();
  4187. } else { // TRY TO USE PLUGIN
  4188. // IE 9 is not offering an implementation of console.log until you open a console
  4189. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4190. /* jshint -W020 */
  4191. console = {} || console;
  4192. // Implemented based on console specs from MDN
  4193. // You may override these functions
  4194. console.log = function (arg) {};
  4195. console.info = function (arg) {};
  4196. console.error = function (arg) {};
  4197. console.dir = function (arg) {};
  4198. console.exception = function (arg) {};
  4199. console.trace = function (arg) {};
  4200. console.warn = function (arg) {};
  4201. console.count = function (arg) {};
  4202. console.debug = function (arg) {};
  4203. console.count = function (arg) {};
  4204. console.time = function (arg) {};
  4205. console.timeEnd = function (arg) {};
  4206. console.group = function (arg) {};
  4207. console.groupCollapsed = function (arg) {};
  4208. console.groupEnd = function (arg) {};
  4209. /* jshint +W020 */
  4210. }
  4211. webrtcDetectedType = 'plugin';
  4212. webrtcDetectedDCSupport = 'plugin';
  4213. AdapterJS.parseWebrtcDetectedBrowser();
  4214. isIE = webrtcDetectedBrowser === 'IE';
  4215. /* jshint -W035 */
  4216. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4217. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4218. /* empty because it needs to prevent the function from running. */
  4219. }
  4220. };
  4221. /* jshint +W035 */
  4222. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4223. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4224. // Call immediately if possible
  4225. // Once the plugin is set, the code will always take this path
  4226. callback();
  4227. } else {
  4228. // otherwise start a 100ms interval
  4229. var checkPluginReadyState = setInterval(function () {
  4230. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4231. clearInterval(checkPluginReadyState);
  4232. callback();
  4233. }
  4234. }, 100);
  4235. }
  4236. };
  4237. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4238. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4239. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4240. });
  4241. };
  4242. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4243. // only inject once the page is ready
  4244. if (document.readyState !== 'complete') {
  4245. return;
  4246. }
  4247. // Prevent multiple injections
  4248. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4249. return;
  4250. }
  4251. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4252. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4253. var frag = document.createDocumentFragment();
  4254. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4255. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4256. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4257. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4258. '<param name="pluginId" value="' +
  4259. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4260. '<param name="windowless" value="false" /> ' +
  4261. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4262. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4263. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4264. // uncomment to be able to use virtual cams
  4265. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4266. '</object>';
  4267. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4268. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4269. }
  4270. document.body.appendChild(frag);
  4271. // Need to re-fetch the plugin
  4272. AdapterJS.WebRTCPlugin.plugin =
  4273. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4274. } else {
  4275. // Load Plugin
  4276. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4277. AdapterJS.WebRTCPlugin.plugin.id =
  4278. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4279. // IE will only start the plugin if it's ACTUALLY visible
  4280. if (isIE) {
  4281. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4282. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4283. } else { // The size of the plugin on Safari should be 0x0px
  4284. // so that the autorisation prompt is at the top
  4285. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4286. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4287. }
  4288. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4289. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4290. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4291. '<param name="pluginId" value="' +
  4292. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4293. '<param name="windowless" value="false" /> ' +
  4294. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4295. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4296. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4297. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4298. }
  4299. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4300. };
  4301. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4302. function (comName, plugName, installedCb, notInstalledCb) {
  4303. if (!isIE) {
  4304. var pluginArray = navigator.plugins;
  4305. for (var i = 0; i < pluginArray.length; i++) {
  4306. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4307. installedCb();
  4308. return;
  4309. }
  4310. }
  4311. notInstalledCb();
  4312. } else {
  4313. try {
  4314. var axo = new ActiveXObject(comName + '.' + plugName);
  4315. } catch (e) {
  4316. notInstalledCb();
  4317. return;
  4318. }
  4319. installedCb();
  4320. }
  4321. };
  4322. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4323. if (AdapterJS.WebRTCPlugin.pluginState ===
  4324. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4325. console.error("AdapterJS - WebRTC interface has already been defined");
  4326. return;
  4327. }
  4328. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4329. AdapterJS.isDefined = function (variable) {
  4330. return variable !== null && variable !== undefined;
  4331. };
  4332. createIceServer = function (url, username, password) {
  4333. var iceServer = null;
  4334. var url_parts = url.split(':');
  4335. if (url_parts[0].indexOf('stun') === 0) {
  4336. iceServer = {
  4337. 'url' : url,
  4338. 'hasCredentials' : false
  4339. };
  4340. } else if (url_parts[0].indexOf('turn') === 0) {
  4341. iceServer = {
  4342. 'url' : url,
  4343. 'hasCredentials' : true,
  4344. 'credential' : password,
  4345. 'username' : username
  4346. };
  4347. }
  4348. return iceServer;
  4349. };
  4350. createIceServers = function (urls, username, password) {
  4351. var iceServers = [];
  4352. for (var i = 0; i < urls.length; ++i) {
  4353. iceServers.push(createIceServer(urls[i], username, password));
  4354. }
  4355. return iceServers;
  4356. };
  4357. RTCSessionDescription = function (info) {
  4358. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4359. return AdapterJS.WebRTCPlugin.plugin.
  4360. ConstructSessionDescription(info.type, info.sdp);
  4361. };
  4362. RTCPeerConnection = function (servers, constraints) {
  4363. var iceServers = null;
  4364. if (servers) {
  4365. iceServers = servers.iceServers;
  4366. for (var i = 0; i < iceServers.length; i++) {
  4367. if (iceServers[i].urls && !iceServers[i].url) {
  4368. iceServers[i].url = iceServers[i].urls;
  4369. }
  4370. iceServers[i].hasCredentials = AdapterJS.
  4371. isDefined(iceServers[i].username) &&
  4372. AdapterJS.isDefined(iceServers[i].credential);
  4373. }
  4374. }
  4375. var mandatory = (constraints && constraints.mandatory) ?
  4376. constraints.mandatory : null;
  4377. var optional = (constraints && constraints.optional) ?
  4378. constraints.optional : null;
  4379. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4380. return AdapterJS.WebRTCPlugin.plugin.
  4381. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4382. iceServers, mandatory, optional);
  4383. };
  4384. MediaStreamTrack = {};
  4385. MediaStreamTrack.getSources = function (callback) {
  4386. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4387. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4388. });
  4389. };
  4390. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4391. constraints.audio = constraints.audio || false;
  4392. constraints.video = constraints.video || false;
  4393. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4394. AdapterJS.WebRTCPlugin.plugin.
  4395. getUserMedia(constraints, successCallback, failureCallback);
  4396. });
  4397. };
  4398. window.navigator.getUserMedia = window.getUserMedia;
  4399. attachMediaStream = function (element, stream) {
  4400. if (!element || !element.parentNode) {
  4401. return;
  4402. }
  4403. var streamId;
  4404. if (stream === null) {
  4405. streamId = '';
  4406. } else {
  4407. if (typeof stream.enableSoundTracks !== 'undefined') {
  4408. stream.enableSoundTracks(true);
  4409. }
  4410. streamId = stream.id;
  4411. }
  4412. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4413. var nodeName = element.nodeName.toLowerCase();
  4414. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4415. var tag;
  4416. switch(nodeName) {
  4417. case 'audio':
  4418. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4419. break;
  4420. case 'video':
  4421. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4422. break;
  4423. default:
  4424. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4425. }
  4426. var frag = document.createDocumentFragment();
  4427. var temp = document.createElement('div');
  4428. var classHTML = '';
  4429. if (element.className) {
  4430. classHTML = 'class="' + element.className + '" ';
  4431. } else if (element.attributes && element.attributes['class']) {
  4432. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4433. }
  4434. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4435. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4436. '<param name="pluginId" value="' + elementId + '" /> ' +
  4437. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4438. '<param name="windowless" value="true" /> ' +
  4439. '<param name="streamId" value="' + streamId + '" /> ' +
  4440. '<param name="tag" value="' + tag + '" /> ' +
  4441. '</object>';
  4442. while (temp.firstChild) {
  4443. frag.appendChild(temp.firstChild);
  4444. }
  4445. var height = '';
  4446. var width = '';
  4447. if (element.clientWidth || element.clientHeight) {
  4448. width = element.clientWidth;
  4449. height = element.clientHeight;
  4450. }
  4451. else if (element.width || element.height) {
  4452. width = element.width;
  4453. height = element.height;
  4454. }
  4455. element.parentNode.insertBefore(frag, element);
  4456. frag = document.getElementById(elementId);
  4457. frag.width = width;
  4458. frag.height = height;
  4459. element.parentNode.removeChild(element);
  4460. } else { // already an <object> tag, just change the stream id
  4461. var children = element.children;
  4462. for (var i = 0; i !== children.length; ++i) {
  4463. if (children[i].name === 'streamId') {
  4464. children[i].value = streamId;
  4465. break;
  4466. }
  4467. }
  4468. element.setStreamId(streamId);
  4469. }
  4470. var newElement = document.getElementById(elementId);
  4471. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4472. return newElement;
  4473. };
  4474. reattachMediaStream = function (to, from) {
  4475. var stream = null;
  4476. var children = from.children;
  4477. for (var i = 0; i !== children.length; ++i) {
  4478. if (children[i].name === 'streamId') {
  4479. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4480. stream = AdapterJS.WebRTCPlugin.plugin
  4481. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4482. break;
  4483. }
  4484. }
  4485. if (stream !== null) {
  4486. return attachMediaStream(to, stream);
  4487. } else {
  4488. console.log('Could not find the stream associated with this element');
  4489. }
  4490. };
  4491. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4492. properties = Object.getOwnPropertyNames( prototype );
  4493. for(prop in properties) {
  4494. propName = properties[prop];
  4495. if (typeof(propName.slice) === 'function') {
  4496. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4497. if (isIE) {
  4498. destElem.attachEvent(propName,srcElem[propName]);
  4499. } else {
  4500. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4501. }
  4502. } else {
  4503. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4504. }
  4505. }
  4506. }
  4507. var subPrototype = Object.getPrototypeOf(prototype)
  4508. if(subPrototype != null) {
  4509. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4510. }
  4511. }
  4512. RTCIceCandidate = function (candidate) {
  4513. if (!candidate.sdpMid) {
  4514. candidate.sdpMid = '';
  4515. }
  4516. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4517. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4518. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4519. );
  4520. };
  4521. // inject plugin
  4522. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4523. AdapterJS.WebRTCPlugin.injectPlugin();
  4524. };
  4525. // This function will be called if the plugin is needed (browser different
  4526. // from Chrome or Firefox), but the plugin is not installed.
  4527. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4528. function() {
  4529. AdapterJS.addEvent(document,
  4530. 'readystatechange',
  4531. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4532. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4533. };
  4534. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4535. if (AdapterJS.options.hidePluginInstallPrompt) {
  4536. return;
  4537. }
  4538. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4539. if(downloadLink) { // if download link
  4540. var popupString;
  4541. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4542. popupString = 'This website requires you to install the ' +
  4543. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4544. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4545. ' WebRTC Plugin</a>' +
  4546. ' to work on this browser.';
  4547. } else { // no portal link, just print a generic explanation
  4548. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4549. }
  4550. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4551. } else { // no download link, just print a generic explanation
  4552. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4553. }
  4554. };
  4555. // Try to detect the plugin and act accordingly
  4556. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4557. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4558. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4559. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4560. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4561. }
  4562. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4563. },{"jitsi-meet-logger":48}],21:[function(require,module,exports){
  4564. (function (__filename){
  4565. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4566. function supportsLocalStorage() {
  4567. try {
  4568. return 'localStorage' in window && window.localStorage !== null;
  4569. } catch (e) {
  4570. logger.log("localstorage is not supported");
  4571. return false;
  4572. }
  4573. }
  4574. function generateUniqueId() {
  4575. function _p8() {
  4576. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4577. }
  4578. return _p8() + _p8() + _p8() + _p8();
  4579. }
  4580. function Settings(conferenceID) {
  4581. this.displayName = '';
  4582. this.userId;
  4583. this.confSettings = null;
  4584. this.conferenceID = conferenceID;
  4585. if (supportsLocalStorage()) {
  4586. if(!window.localStorage.getItem(conferenceID))
  4587. this.confSettings = {};
  4588. else
  4589. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4590. if(!this.confSettings.jitsiMeetId) {
  4591. this.confSettings.jitsiMeetId = generateUniqueId();
  4592. logger.log("generated id",
  4593. this.confSettings.jitsiMeetId);
  4594. this.save();
  4595. }
  4596. this.userId = this.confSettings.jitsiMeetId || '';
  4597. this.displayName = this.confSettings.displayname || '';
  4598. } else {
  4599. logger.log("local storage is not supported");
  4600. this.userId = generateUniqueId();
  4601. }
  4602. }
  4603. Settings.prototype.save = function () {
  4604. if(!supportsLocalStorage())
  4605. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4606. }
  4607. Settings.prototype.setDisplayName = function (newDisplayName) {
  4608. this.displayName = newDisplayName;
  4609. if(this.confSettings != null)
  4610. this.confSettings.displayname = displayName;
  4611. this.save();
  4612. return this.displayName;
  4613. },
  4614. Settings.prototype.getSettings = function () {
  4615. return {
  4616. displayName: this.displayName,
  4617. uid: this.userId
  4618. };
  4619. },
  4620. module.exports = Settings;
  4621. }).call(this,"/modules/settings/Settings.js")
  4622. },{"jitsi-meet-logger":48}],22:[function(require,module,exports){
  4623. /* global config */
  4624. /**
  4625. * Provides statistics for the local stream.
  4626. */
  4627. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4628. /**
  4629. * Size of the webaudio analyzer buffer.
  4630. * @type {number}
  4631. */
  4632. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4633. /**
  4634. * Value of the webaudio analyzer smoothing time parameter.
  4635. * @type {number}
  4636. */
  4637. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4638. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4639. var context = null;
  4640. if(window.AudioContext) {
  4641. context = new AudioContext();
  4642. }
  4643. /**
  4644. * Converts time domain data array to audio level.
  4645. * @param samples the time domain data array.
  4646. * @returns {number} the audio level
  4647. */
  4648. function timeDomainDataToAudioLevel(samples) {
  4649. var maxVolume = 0;
  4650. var length = samples.length;
  4651. for (var i = 0; i < length; i++) {
  4652. if (maxVolume < samples[i])
  4653. maxVolume = samples[i];
  4654. }
  4655. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4656. }
  4657. /**
  4658. * Animates audio level change
  4659. * @param newLevel the new audio level
  4660. * @param lastLevel the last audio level
  4661. * @returns {Number} the audio level to be set
  4662. */
  4663. function animateLevel(newLevel, lastLevel) {
  4664. var value = 0;
  4665. var diff = lastLevel - newLevel;
  4666. if(diff > 0.2) {
  4667. value = lastLevel - 0.2;
  4668. }
  4669. else if(diff < -0.4) {
  4670. value = lastLevel + 0.4;
  4671. }
  4672. else {
  4673. value = newLevel;
  4674. }
  4675. return parseFloat(value.toFixed(3));
  4676. }
  4677. /**
  4678. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4679. *
  4680. * @param stream the local stream
  4681. * @param interval stats refresh interval given in ms.
  4682. * @param callback function that receives the audio levels.
  4683. * @constructor
  4684. */
  4685. function LocalStatsCollector(stream, interval, callback) {
  4686. this.stream = stream;
  4687. this.intervalId = null;
  4688. this.intervalMilis = interval;
  4689. this.audioLevel = 0;
  4690. this.callback = callback;
  4691. }
  4692. /**
  4693. * Starts the collecting the statistics.
  4694. */
  4695. LocalStatsCollector.prototype.start = function () {
  4696. if (!context ||
  4697. RTCBrowserType.isTemasysPluginUsed())
  4698. return;
  4699. var analyser = context.createAnalyser();
  4700. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4701. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4702. var source = context.createMediaStreamSource(this.stream);
  4703. source.connect(analyser);
  4704. var self = this;
  4705. this.intervalId = setInterval(
  4706. function () {
  4707. var array = new Uint8Array(analyser.frequencyBinCount);
  4708. analyser.getByteTimeDomainData(array);
  4709. var audioLevel = timeDomainDataToAudioLevel(array);
  4710. if (audioLevel != self.audioLevel) {
  4711. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4712. self.callback(self.audioLevel);
  4713. }
  4714. },
  4715. this.intervalMilis
  4716. );
  4717. };
  4718. /**
  4719. * Stops collecting the statistics.
  4720. */
  4721. LocalStatsCollector.prototype.stop = function () {
  4722. if (this.intervalId) {
  4723. clearInterval(this.intervalId);
  4724. this.intervalId = null;
  4725. }
  4726. };
  4727. module.exports = LocalStatsCollector;
  4728. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4729. (function (__filename){
  4730. /* global require, ssrc2jid */
  4731. /* jshint -W117 */
  4732. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4733. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4734. var StatisticsEvents = require("../../service/statistics/Events");
  4735. /* Whether we support the browser we are running into for logging statistics */
  4736. var browserSupported = RTCBrowserType.isChrome() ||
  4737. RTCBrowserType.isOpera();
  4738. var keyMap = {};
  4739. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4740. "ssrc": "ssrc",
  4741. "packetsReceived": "packetsReceived",
  4742. "packetsLost": "packetsLost",
  4743. "packetsSent": "packetsSent",
  4744. "bytesReceived": "bytesReceived",
  4745. "bytesSent": "bytesSent"
  4746. };
  4747. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4748. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4749. "sendBandwidth": "googAvailableSendBandwidth",
  4750. "remoteAddress": "googRemoteAddress",
  4751. "transportType": "googTransportType",
  4752. "localAddress": "googLocalAddress",
  4753. "activeConnection": "googActiveConnection",
  4754. "ssrc": "ssrc",
  4755. "packetsReceived": "packetsReceived",
  4756. "packetsSent": "packetsSent",
  4757. "packetsLost": "packetsLost",
  4758. "bytesReceived": "bytesReceived",
  4759. "bytesSent": "bytesSent",
  4760. "googFrameHeightReceived": "googFrameHeightReceived",
  4761. "googFrameWidthReceived": "googFrameWidthReceived",
  4762. "googFrameHeightSent": "googFrameHeightSent",
  4763. "googFrameWidthSent": "googFrameWidthSent",
  4764. "audioInputLevel": "audioInputLevel",
  4765. "audioOutputLevel": "audioOutputLevel"
  4766. };
  4767. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4768. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4769. /**
  4770. * Calculates packet lost percent using the number of lost packets and the
  4771. * number of all packet.
  4772. * @param lostPackets the number of lost packets
  4773. * @param totalPackets the number of all packets.
  4774. * @returns {number} packet loss percent
  4775. */
  4776. function calculatePacketLoss(lostPackets, totalPackets) {
  4777. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4778. return 0;
  4779. return Math.round((lostPackets/totalPackets)*100);
  4780. }
  4781. function getStatValue(item, name) {
  4782. var browserType = RTCBrowserType.getBrowserType();
  4783. if (!keyMap[browserType][name])
  4784. throw "The property isn't supported!";
  4785. var key = keyMap[browserType][name];
  4786. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4787. item.stat(key) : item[key];
  4788. }
  4789. function formatAudioLevel(audioLevel) {
  4790. return Math.min(Math.max(audioLevel, 0), 1);
  4791. }
  4792. /**
  4793. * Checks whether a certain record should be included in the logged statistics.
  4794. */
  4795. function acceptStat(reportId, reportType, statName) {
  4796. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4797. return false;
  4798. if (reportType == "ssrc") {
  4799. if (statName == "googTrackId" ||
  4800. statName == "transportId" ||
  4801. statName == "ssrc")
  4802. return false;
  4803. }
  4804. return true;
  4805. }
  4806. /**
  4807. * Checks whether a certain record should be included in the logged statistics.
  4808. */
  4809. function acceptReport(id, type) {
  4810. if (id.substring(0, 15) == "googCertificate" ||
  4811. id.substring(0, 9) == "googTrack" ||
  4812. id.substring(0, 20) == "googLibjingleSession")
  4813. return false;
  4814. if (type == "googComponent")
  4815. return false;
  4816. return true;
  4817. }
  4818. /**
  4819. * Peer statistics data holder.
  4820. * @constructor
  4821. */
  4822. function PeerStats()
  4823. {
  4824. this.ssrc2Loss = {};
  4825. this.ssrc2AudioLevel = {};
  4826. this.ssrc2bitrate = {};
  4827. this.ssrc2resolution = {};
  4828. }
  4829. /**
  4830. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4831. * represented by this instance.
  4832. * @param lossRate new packet loss rate value to be set.
  4833. */
  4834. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4835. {
  4836. this.ssrc2Loss = lossRate;
  4837. };
  4838. /**
  4839. * Sets resolution that belong to the ssrc
  4840. * represented by this instance.
  4841. * @param resolution new resolution value to be set.
  4842. */
  4843. PeerStats.prototype.setSsrcResolution = function (resolution)
  4844. {
  4845. if(resolution === null && this.ssrc2resolution[ssrc])
  4846. {
  4847. delete this.ssrc2resolution[ssrc];
  4848. }
  4849. else if(resolution !== null)
  4850. this.ssrc2resolution[ssrc] = resolution;
  4851. };
  4852. /**
  4853. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4854. * represented by this instance.
  4855. * @param ssrc audio or video RTP stream SSRC.
  4856. * @param bitrate new bitrate value to be set.
  4857. */
  4858. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4859. {
  4860. if(this.ssrc2bitrate[ssrc])
  4861. {
  4862. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4863. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4864. }
  4865. else {
  4866. this.ssrc2bitrate[ssrc] = bitrate;
  4867. }
  4868. };
  4869. /**
  4870. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4871. * the stream which belongs to the peer represented by this instance.
  4872. * @param ssrc RTP stream SSRC for which current audio level value will be
  4873. * updated.
  4874. * @param audioLevel the new audio level value to be set. Value is truncated to
  4875. * fit the range from 0 to 1.
  4876. */
  4877. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4878. {
  4879. // Range limit 0 - 1
  4880. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4881. };
  4882. function ConferenceStats() {
  4883. /**
  4884. * The bandwidth
  4885. * @type {{}}
  4886. */
  4887. this.bandwidth = {};
  4888. /**
  4889. * The bit rate
  4890. * @type {{}}
  4891. */
  4892. this.bitrate = {};
  4893. /**
  4894. * The packet loss rate
  4895. * @type {{}}
  4896. */
  4897. this.packetLoss = null;
  4898. /**
  4899. * Array with the transport information.
  4900. * @type {Array}
  4901. */
  4902. this.transport = [];
  4903. }
  4904. /**
  4905. * <tt>StatsCollector</tt> registers for stats updates of given
  4906. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4907. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4908. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4909. * instance as an event source.
  4910. *
  4911. * @param peerconnection webRTC peer connection object.
  4912. * @param interval stats refresh interval given in ms.
  4913. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4914. * called on stats update.
  4915. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4916. * @constructor
  4917. */
  4918. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4919. {
  4920. this.peerconnection = peerconnection;
  4921. this.baselineAudioLevelsReport = null;
  4922. this.currentAudioLevelsReport = null;
  4923. this.currentStatsReport = null;
  4924. this.baselineStatsReport = null;
  4925. this.audioLevelsIntervalId = null;
  4926. this.eventEmitter = eventEmitter;
  4927. this.config = config || {};
  4928. this.conferenceStats = new ConferenceStats();
  4929. /**
  4930. * Gather PeerConnection stats once every this many milliseconds.
  4931. */
  4932. this.GATHER_INTERVAL = 15000;
  4933. /**
  4934. * Log stats via the focus once every this many milliseconds.
  4935. */
  4936. this.LOG_INTERVAL = 60000;
  4937. /**
  4938. * Gather stats and store them in this.statsToBeLogged.
  4939. */
  4940. this.gatherStatsIntervalId = null;
  4941. /**
  4942. * Send the stats already saved in this.statsToBeLogged to be logged via
  4943. * the focus.
  4944. */
  4945. this.logStatsIntervalId = null;
  4946. /**
  4947. * Stores the statistics which will be send to the focus to be logged.
  4948. */
  4949. this.statsToBeLogged =
  4950. {
  4951. timestamps: [],
  4952. stats: {}
  4953. };
  4954. // Updates stats interval
  4955. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4956. this.statsIntervalId = null;
  4957. this.statsIntervalMilis = statsInterval;
  4958. // Map of ssrcs to PeerStats
  4959. this.ssrc2stats = {};
  4960. }
  4961. module.exports = StatsCollector;
  4962. /**
  4963. * Stops stats updates.
  4964. */
  4965. StatsCollector.prototype.stop = function () {
  4966. if (this.audioLevelsIntervalId) {
  4967. clearInterval(this.audioLevelsIntervalId);
  4968. this.audioLevelsIntervalId = null;
  4969. }
  4970. if (this.statsIntervalId)
  4971. {
  4972. clearInterval(this.statsIntervalId);
  4973. this.statsIntervalId = null;
  4974. }
  4975. if(this.logStatsIntervalId)
  4976. {
  4977. clearInterval(this.logStatsIntervalId);
  4978. this.logStatsIntervalId = null;
  4979. }
  4980. if(this.gatherStatsIntervalId)
  4981. {
  4982. clearInterval(this.gatherStatsIntervalId);
  4983. this.gatherStatsIntervalId = null;
  4984. }
  4985. };
  4986. /**
  4987. * Callback passed to <tt>getStats</tt> method.
  4988. * @param error an error that occurred on <tt>getStats</tt> call.
  4989. */
  4990. StatsCollector.prototype.errorCallback = function (error)
  4991. {
  4992. logger.error("Get stats error", error);
  4993. this.stop();
  4994. };
  4995. /**
  4996. * Starts stats updates.
  4997. */
  4998. StatsCollector.prototype.start = function ()
  4999. {
  5000. var self = this;
  5001. this.audioLevelsIntervalId = setInterval(
  5002. function () {
  5003. // Interval updates
  5004. self.peerconnection.getStats(
  5005. function (report) {
  5006. var results = null;
  5007. if (!report || !report.result ||
  5008. typeof report.result != 'function') {
  5009. results = report;
  5010. }
  5011. else {
  5012. results = report.result();
  5013. }
  5014. //logger.error("Got interval report", results);
  5015. self.currentAudioLevelsReport = results;
  5016. self.processAudioLevelReport();
  5017. self.baselineAudioLevelsReport =
  5018. self.currentAudioLevelsReport;
  5019. },
  5020. self.errorCallback
  5021. );
  5022. },
  5023. self.audioLevelsIntervalMilis
  5024. );
  5025. // if (!this.config.disableStats && browserSupported) {
  5026. // this.statsIntervalId = setInterval(
  5027. // function () {
  5028. // // Interval updates
  5029. // self.peerconnection.getStats(
  5030. // function (report) {
  5031. // var results = null;
  5032. // if (!report || !report.result ||
  5033. // typeof report.result != 'function') {
  5034. // //firefox
  5035. // results = report;
  5036. // }
  5037. // else {
  5038. // //chrome
  5039. // results = report.result();
  5040. // }
  5041. // //logger.error("Got interval report", results);
  5042. // self.currentStatsReport = results;
  5043. // try {
  5044. // self.processStatsReport();
  5045. // }
  5046. // catch (e) {
  5047. // logger.error("Unsupported key:" + e, e);
  5048. // }
  5049. //
  5050. // self.baselineStatsReport = self.currentStatsReport;
  5051. // },
  5052. // self.errorCallback
  5053. // );
  5054. // },
  5055. // self.statsIntervalMilis
  5056. // );
  5057. // }
  5058. //
  5059. // if (this.config.logStats && browserSupported) {
  5060. // this.gatherStatsIntervalId = setInterval(
  5061. // function () {
  5062. // self.peerconnection.getStats(
  5063. // function (report) {
  5064. // self.addStatsToBeLogged(report.result());
  5065. // },
  5066. // function () {
  5067. // }
  5068. // );
  5069. // },
  5070. // this.GATHER_INTERVAL
  5071. // );
  5072. //
  5073. // this.logStatsIntervalId = setInterval(
  5074. // function() { self.logStats(); },
  5075. // this.LOG_INTERVAL);
  5076. // }
  5077. };
  5078. /**
  5079. * Converts the stats to the format used for logging, and saves the data in
  5080. * this.statsToBeLogged.
  5081. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5082. */
  5083. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5084. var self = this;
  5085. var num_records = this.statsToBeLogged.timestamps.length;
  5086. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5087. reports.map(function (report) {
  5088. if (!acceptReport(report.id, report.type))
  5089. return;
  5090. var stat = self.statsToBeLogged.stats[report.id];
  5091. if (!stat) {
  5092. stat = self.statsToBeLogged.stats[report.id] = {};
  5093. }
  5094. stat.type = report.type;
  5095. report.names().map(function (name) {
  5096. if (!acceptStat(report.id, report.type, name))
  5097. return;
  5098. var values = stat[name];
  5099. if (!values) {
  5100. values = stat[name] = [];
  5101. }
  5102. while (values.length < num_records) {
  5103. values.push(null);
  5104. }
  5105. values.push(report.stat(name));
  5106. });
  5107. });
  5108. };
  5109. //FIXME:
  5110. //StatsCollector.prototype.logStats = function () {
  5111. //
  5112. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5113. // return;
  5114. // // Reset the stats
  5115. // this.statsToBeLogged.stats = {};
  5116. // this.statsToBeLogged.timestamps = [];
  5117. //};
  5118. /**
  5119. * Stats processing logic.
  5120. */
  5121. StatsCollector.prototype.processStatsReport = function () {
  5122. if (!this.baselineStatsReport) {
  5123. return;
  5124. }
  5125. for (var idx in this.currentStatsReport) {
  5126. var now = this.currentStatsReport[idx];
  5127. try {
  5128. if (getStatValue(now, 'receiveBandwidth') ||
  5129. getStatValue(now, 'sendBandwidth')) {
  5130. this.conferenceStats.bandwidth = {
  5131. "download": Math.round(
  5132. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5133. "upload": Math.round(
  5134. (getStatValue(now, 'sendBandwidth')) / 1000)
  5135. };
  5136. }
  5137. }
  5138. catch(e){/*not supported*/}
  5139. if(now.type == 'googCandidatePair')
  5140. {
  5141. var ip, type, localIP, active;
  5142. try {
  5143. ip = getStatValue(now, 'remoteAddress');
  5144. type = getStatValue(now, "transportType");
  5145. localIP = getStatValue(now, "localAddress");
  5146. active = getStatValue(now, "activeConnection");
  5147. }
  5148. catch(e){/*not supported*/}
  5149. if(!ip || !type || !localIP || active != "true")
  5150. continue;
  5151. var addressSaved = false;
  5152. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5153. {
  5154. if(this.conferenceStats.transport[i].ip == ip &&
  5155. this.conferenceStats.transport[i].type == type &&
  5156. this.conferenceStats.transport[i].localip == localIP)
  5157. {
  5158. addressSaved = true;
  5159. }
  5160. }
  5161. if(addressSaved)
  5162. continue;
  5163. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5164. continue;
  5165. }
  5166. if(now.type == "candidatepair")
  5167. {
  5168. if(now.state == "succeeded")
  5169. continue;
  5170. var local = this.currentStatsReport[now.localCandidateId];
  5171. var remote = this.currentStatsReport[now.remoteCandidateId];
  5172. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5173. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5174. }
  5175. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5176. now.type != "inboundrtp") {
  5177. continue;
  5178. }
  5179. var before = this.baselineStatsReport[idx];
  5180. if (!before) {
  5181. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5182. continue;
  5183. }
  5184. var ssrc = getStatValue(now, 'ssrc');
  5185. if(!ssrc)
  5186. continue;
  5187. var ssrcStats = this.ssrc2stats[ssrc];
  5188. if (!ssrcStats) {
  5189. ssrcStats = new PeerStats();
  5190. this.ssrc2stats[ssrc] = ssrcStats;
  5191. }
  5192. var isDownloadStream = true;
  5193. var key = 'packetsReceived';
  5194. var packetsNow = getStatValue(now, key);
  5195. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5196. isDownloadStream = false;
  5197. key = 'packetsSent';
  5198. packetsNow = getStatValue(now, key);
  5199. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5200. console.warn("No packetsReceived nor packetsSent stat found");
  5201. continue;
  5202. }
  5203. }
  5204. if (!packetsNow || packetsNow < 0)
  5205. packetsNow = 0;
  5206. var packetsBefore = getStatValue(before, key);
  5207. if (!packetsBefore || packetsBefore < 0)
  5208. packetsBefore = 0;
  5209. var packetRate = packetsNow - packetsBefore;
  5210. if (!packetRate || packetRate < 0)
  5211. packetRate = 0;
  5212. var currentLoss = getStatValue(now, 'packetsLost');
  5213. if (!currentLoss || currentLoss < 0)
  5214. currentLoss = 0;
  5215. var previousLoss = getStatValue(before, 'packetsLost');
  5216. if (!previousLoss || previousLoss < 0)
  5217. previousLoss = 0;
  5218. var lossRate = currentLoss - previousLoss;
  5219. if (!lossRate || lossRate < 0)
  5220. lossRate = 0;
  5221. var packetsTotal = (packetRate + lossRate);
  5222. ssrcStats.setSsrcLoss(ssrc,
  5223. {"packetsTotal": packetsTotal,
  5224. "packetsLost": lossRate,
  5225. "isDownloadStream": isDownloadStream});
  5226. var bytesReceived = 0, bytesSent = 0;
  5227. if(getStatValue(now, "bytesReceived")) {
  5228. bytesReceived = getStatValue(now, "bytesReceived") -
  5229. getStatValue(before, "bytesReceived");
  5230. }
  5231. if (getStatValue(now, "bytesSent")) {
  5232. bytesSent = getStatValue(now, "bytesSent") -
  5233. getStatValue(before, "bytesSent");
  5234. }
  5235. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5236. if (bytesReceived <= 0 || time <= 0) {
  5237. bytesReceived = 0;
  5238. } else {
  5239. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5240. }
  5241. if (bytesSent <= 0 || time <= 0) {
  5242. bytesSent = 0;
  5243. } else {
  5244. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5245. }
  5246. ssrcStats.setSsrcBitrate(ssrc, {
  5247. "download": bytesReceived,
  5248. "upload": bytesSent});
  5249. var resolution = {height: null, width: null};
  5250. try {
  5251. if (getStatValue(now, "googFrameHeightReceived") &&
  5252. getStatValue(now, "googFrameWidthReceived")) {
  5253. resolution.height =
  5254. getStatValue(now, "googFrameHeightReceived");
  5255. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5256. }
  5257. else if (getStatValue(now, "googFrameHeightSent") &&
  5258. getStatValue(now, "googFrameWidthSent")) {
  5259. resolution.height = getStatValue(now, "googFrameHeightSent");
  5260. resolution.width = getStatValue(now, "googFrameWidthSent");
  5261. }
  5262. }
  5263. catch(e){/*not supported*/}
  5264. if (resolution.height && resolution.width) {
  5265. ssrcStats.setSsrcResolution(ssrc, resolution);
  5266. } else {
  5267. ssrcStats.setSsrcResolution(ssrc, null);
  5268. }
  5269. }
  5270. var self = this;
  5271. // Jid stats
  5272. var totalPackets = {download: 0, upload: 0};
  5273. var lostPackets = {download: 0, upload: 0};
  5274. var bitrateDownload = 0;
  5275. var bitrateUpload = 0;
  5276. var resolutions = {};
  5277. Object.keys(this.ssrc2stats).forEach(
  5278. function (jid) {
  5279. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5280. function (ssrc) {
  5281. var type = "upload";
  5282. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5283. type = "download";
  5284. totalPackets[type] +=
  5285. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5286. lostPackets[type] +=
  5287. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5288. }
  5289. );
  5290. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5291. function (ssrc) {
  5292. bitrateDownload +=
  5293. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5294. bitrateUpload +=
  5295. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5296. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5297. }
  5298. );
  5299. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5300. }
  5301. );
  5302. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5303. this.conferenceStats.packetLoss = {
  5304. total:
  5305. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5306. totalPackets.download + totalPackets.upload),
  5307. download:
  5308. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5309. upload:
  5310. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5311. };
  5312. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5313. {
  5314. "bitrate": this.conferenceStats.bitrate,
  5315. "packetLoss": this.conferenceStats.packetLoss,
  5316. "bandwidth": this.conferenceStats.bandwidth,
  5317. "resolution": resolutions,
  5318. "transport": this.conferenceStats.transport
  5319. });
  5320. this.conferenceStats.transport = [];
  5321. };
  5322. /**
  5323. * Stats processing logic.
  5324. */
  5325. StatsCollector.prototype.processAudioLevelReport = function () {
  5326. if (!this.baselineAudioLevelsReport) {
  5327. return;
  5328. }
  5329. for (var idx in this.currentAudioLevelsReport) {
  5330. var now = this.currentAudioLevelsReport[idx];
  5331. //if we don't have "packetsReceived" this is local stream
  5332. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5333. continue;
  5334. }
  5335. var before = this.baselineAudioLevelsReport[idx];
  5336. if (!before) {
  5337. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5338. continue;
  5339. }
  5340. var ssrc = getStatValue(now, 'ssrc');
  5341. if (!ssrc) {
  5342. if((Date.now() - now.timestamp) < 3000)
  5343. logger.warn("No ssrc: ");
  5344. continue;
  5345. }
  5346. var ssrcStats = this.ssrc2stats[ssrc];
  5347. if (!ssrcStats) {
  5348. ssrcStats = new PeerStats();
  5349. this.ssrc2stats[ssrc] = ssrcStats;
  5350. }
  5351. // Audio level
  5352. var audioLevel = null;
  5353. try {
  5354. audioLevel = getStatValue(now, 'audioInputLevel');
  5355. if (!audioLevel)
  5356. audioLevel = getStatValue(now, 'audioOutputLevel');
  5357. }
  5358. catch(e) {/*not supported*/
  5359. logger.warn("Audio Levels are not available in the statistics.");
  5360. clearInterval(this.audioLevelsIntervalId);
  5361. return;
  5362. }
  5363. if (audioLevel) {
  5364. // TODO: can't find specs about what this value really is,
  5365. // but it seems to vary between 0 and around 32k.
  5366. audioLevel = audioLevel / 32767;
  5367. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5368. this.eventEmitter.emit(
  5369. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5370. }
  5371. }
  5372. };
  5373. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5374. },{"../../service/statistics/Events":85,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],24:[function(require,module,exports){
  5375. /* global require, APP */
  5376. var LocalStats = require("./LocalStatsCollector.js");
  5377. var RTPStats = require("./RTPStatsCollector.js");
  5378. var EventEmitter = require("events");
  5379. var StatisticsEvents = require("../../service/statistics/Events");
  5380. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  5381. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5382. //var CallStats = require("./CallStats");
  5383. //var RTCEvents = require("../../service/RTC/RTCEvents");
  5384. //
  5385. //function onDisposeConference(onUnload) {
  5386. // CallStats.sendTerminateEvent();
  5387. // stopRemote();
  5388. // if(onUnload) {
  5389. // stopLocal();
  5390. // eventEmitter.removeAllListeners();
  5391. // }
  5392. //}
  5393. var eventEmitter = new EventEmitter();
  5394. function Statistics() {
  5395. this.rtpStats = null;
  5396. this.eventEmitter = new EventEmitter();
  5397. }
  5398. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5399. if (this.rtpStats) {
  5400. this.rtpStats.stop();
  5401. }
  5402. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5403. this.rtpStats.start();
  5404. }
  5405. Statistics.localStats = [];
  5406. Statistics.startLocalStats = function (stream, callback) {
  5407. var localStats = new LocalStats(stream, 200, callback);
  5408. this.localStats.push(localStats);
  5409. localStats.start();
  5410. }
  5411. Statistics.prototype.addAudioLevelListener = function(listener)
  5412. {
  5413. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5414. }
  5415. Statistics.prototype.removeAudioLevelListener = function(listener)
  5416. {
  5417. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5418. }
  5419. Statistics.prototype.dispose = function () {
  5420. Statistics.stopAllLocalStats();
  5421. this.stopRemote();
  5422. if(this.eventEmitter)
  5423. this.eventEmitter.removeAllListeners();
  5424. if(eventEmitter)
  5425. eventEmitter.removeAllListeners();
  5426. }
  5427. Statistics.stopAllLocalStats = function () {
  5428. for(var i = 0; i < this.localStats.length; i++)
  5429. this.localStats[i].stop();
  5430. this.localStats = [];
  5431. }
  5432. Statistics.stopLocalStats = function (stream) {
  5433. for(var i = 0; i < Statistics.localStats.length; i++)
  5434. if(Statistics.localStats[i].stream === stream){
  5435. var localStats = Statistics.localStats.splice(i, 1);
  5436. localStats.stop();
  5437. break;
  5438. }
  5439. }
  5440. Statistics.prototype.stopRemote = function () {
  5441. if (this.rtpStats) {
  5442. this.rtpStats.stop();
  5443. this.eventEmitter.emit(StatisticsEvents.STOP);
  5444. this.rtpStats = null;
  5445. }
  5446. };
  5447. /**
  5448. * Obtains audio level reported in the stats for specified peer.
  5449. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5450. * audio level.
  5451. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5452. * level.
  5453. * @returns {*} a float form 0 to 1 that represents current audio level or
  5454. * <tt>null</tt> if for any reason the value is not available
  5455. * at this time.
  5456. */
  5457. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5458. var peerStats = this.rtpStats.jid2stats[peerJid];
  5459. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5460. };
  5461. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5462. //
  5463. //var statistics = {
  5464. // /**
  5465. // * Indicates that this audio level is for local jid.
  5466. // * @type {string}
  5467. // */
  5468. // LOCAL_JID: 'local',
  5469. //
  5470. // addConnectionStatsListener: function(listener)
  5471. // {
  5472. // eventEmitter.on("statistics.connectionstats", listener);
  5473. // },
  5474. //
  5475. // removeConnectionStatsListener: function(listener)
  5476. // {
  5477. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5478. // },
  5479. //
  5480. //
  5481. // addRemoteStatsStopListener: function(listener)
  5482. // {
  5483. // eventEmitter.on("statistics.stop", listener);
  5484. // },
  5485. //
  5486. // removeRemoteStatsStopListener: function(listener)
  5487. // {
  5488. // eventEmitter.removeListener("statistics.stop", listener);
  5489. // },
  5490. //
  5491. //
  5492. // stopRemoteStatistics: function()
  5493. // {
  5494. // stopRemote();
  5495. // },
  5496. //
  5497. //// Already implemented with the constructor
  5498. // start: function () {
  5499. // APP.RTC.addStreamListener(onStreamCreated,
  5500. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5501. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5502. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5503. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5504. // startRemoteStats(event.peerconnection);
  5505. //// CallStats.init(event);
  5506. // });
  5507. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5508. //// CallStats.init(session);
  5509. //// });
  5510. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5511. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5512. //// CallStats.sendMuteEvent(mute, "audio");
  5513. //// });
  5514. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5515. //// CallStats.sendSetupFailedEvent();
  5516. //// });
  5517. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5518. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5519. //// CallStats.sendMuteEvent(mute, "video");
  5520. //// });
  5521. // }
  5522. //};
  5523. module.exports = Statistics;
  5524. },{"../../service/statistics/Events":85,"../../service/statistics/constants":86,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":44}],25:[function(require,module,exports){
  5525. /**
  5526. /**
  5527. * @const
  5528. */
  5529. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5530. /**
  5531. * Hexadecimal digits.
  5532. * @const
  5533. */
  5534. var HEX_DIGITS = '0123456789abcdef';
  5535. /**
  5536. * Generates random int within the range [min, max]
  5537. * @param min the minimum value for the generated number
  5538. * @param max the maximum value for the generated number
  5539. * @returns random int number
  5540. */
  5541. function randomInt(min, max) {
  5542. return Math.floor(Math.random() * (max - min + 1)) + min;
  5543. }
  5544. /**
  5545. * Get random element from array or string.
  5546. * @param {Array|string} arr source
  5547. * @returns array element or string character
  5548. */
  5549. function randomElement(arr) {
  5550. return arr[randomInt(0, arr.length - 1)];
  5551. }
  5552. /**
  5553. * Generate random alphanumeric string.
  5554. * @param {number} length expected string length
  5555. * @returns {string} random string of specified length
  5556. */
  5557. function randomAlphanumStr(length) {
  5558. var result = '';
  5559. for (var i = 0; i < length; i += 1) {
  5560. result += randomElement(ALPHANUM);
  5561. }
  5562. return result;
  5563. }
  5564. /**
  5565. * Exported interface.
  5566. */
  5567. var RandomUtil = {
  5568. /**
  5569. * Returns a random hex digit.
  5570. * @returns {*}
  5571. */
  5572. randomHexDigit: function() {
  5573. return randomElement(HEX_DIGITS);
  5574. },
  5575. /**
  5576. * Returns a random string of hex digits with length 'len'.
  5577. * @param len the length.
  5578. */
  5579. randomHexString: function (len) {
  5580. var ret = '';
  5581. while (len--) {
  5582. ret += this.randomHexDigit();
  5583. }
  5584. return ret;
  5585. },
  5586. randomElement: randomElement,
  5587. randomAlphanumStr: randomAlphanumStr
  5588. };
  5589. module.exports = RandomUtil;
  5590. },{}],26:[function(require,module,exports){
  5591. (function (__filename){
  5592. /* global Strophe, $, $pres, $iq, $msg */
  5593. /* jshint -W101,-W069 */
  5594. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5595. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5596. var Moderator = require("./moderator");
  5597. var EventEmitter = require("events");
  5598. var Recorder = require("./recording");
  5599. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  5600. var parser = {
  5601. packet2JSON: function (packet, nodes) {
  5602. var self = this;
  5603. $(packet).children().each(function (index) {
  5604. var tagName = $(this).prop("tagName");
  5605. var node = {
  5606. tagName: tagName
  5607. };
  5608. node.attributes = {};
  5609. $($(this)[0].attributes).each(function( index, attr ) {
  5610. node.attributes[ attr.name ] = attr.value;
  5611. });
  5612. var text = Strophe.getText($(this)[0]);
  5613. if (text) {
  5614. node.value = text;
  5615. }
  5616. node.children = [];
  5617. nodes.push(node);
  5618. self.packet2JSON($(this), node.children);
  5619. });
  5620. },
  5621. JSON2packet: function (nodes, packet) {
  5622. for(var i = 0; i < nodes.length; i++) {
  5623. var node = nodes[i];
  5624. if(!node || node === null){
  5625. continue;
  5626. }
  5627. packet.c(node.tagName, node.attributes);
  5628. if(node.value)
  5629. packet.t(node.value);
  5630. if(node.children)
  5631. this.JSON2packet(node.children, packet);
  5632. packet.up();
  5633. }
  5634. // packet.up();
  5635. }
  5636. };
  5637. /**
  5638. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5639. * @param pres the presence JSON
  5640. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5641. */
  5642. function filterNodeFromPresenceJSON(pres, nodeName){
  5643. var res = [];
  5644. for(var i = 0; i < pres.length; i++)
  5645. if(pres[i].tagName === nodeName)
  5646. res.push(pres[i]);
  5647. return res;
  5648. }
  5649. function ChatRoom(connection, jid, password, XMPP, options) {
  5650. this.eventEmitter = new EventEmitter();
  5651. this.xmpp = XMPP;
  5652. this.connection = connection;
  5653. this.roomjid = Strophe.getBareJidFromJid(jid);
  5654. this.myroomjid = jid;
  5655. this.password = password;
  5656. logger.info("Joined MUC as " + this.myroomjid);
  5657. this.members = {};
  5658. this.presMap = {};
  5659. this.presHandlers = {};
  5660. this.joined = false;
  5661. this.role = 'none';
  5662. this.focusMucJid = null;
  5663. this.bridgeIsDown = false;
  5664. this.options = options || {};
  5665. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5666. this.initPresenceMap();
  5667. this.session = null;
  5668. var self = this;
  5669. this.lastPresences = {};
  5670. this.phoneNumber = null;
  5671. this.phonePin = null;
  5672. }
  5673. ChatRoom.prototype.initPresenceMap = function () {
  5674. this.presMap['to'] = this.myroomjid;
  5675. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5676. this.presMap["nodes"] = [];
  5677. this.presMap["nodes"].push( {
  5678. "tagName": "user-agent",
  5679. "value": navigator.userAgent,
  5680. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5681. });
  5682. };
  5683. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5684. this.presMap["nodes"].push( {
  5685. "tagName": "devices",
  5686. "children": [
  5687. {
  5688. "tagName": "audio",
  5689. "value": devices.audio,
  5690. },
  5691. {
  5692. "tagName": "video",
  5693. "value": devices.video,
  5694. }
  5695. ]
  5696. });
  5697. };
  5698. ChatRoom.prototype.join = function (password) {
  5699. if(password)
  5700. this.password = password;
  5701. var self = this;
  5702. this.moderator.allocateConferenceFocus(function()
  5703. {
  5704. self.sendPresence(true);
  5705. }.bind(this));
  5706. };
  5707. ChatRoom.prototype.sendPresence = function (fromJoin) {
  5708. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  5709. // Too early to send presence - not initialized
  5710. return;
  5711. }
  5712. var pres = $pres({to: this.presMap['to'] });
  5713. pres.c('x', {xmlns: this.presMap['xns']});
  5714. if (this.password) {
  5715. pres.c('password').t(this.password).up();
  5716. }
  5717. pres.up();
  5718. // Send XEP-0115 'c' stanza that contains our capabilities info
  5719. if (this.connection.caps) {
  5720. this.connection.caps.node = this.xmpp.options.clientNode;
  5721. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5722. }
  5723. parser.JSON2packet(this.presMap.nodes, pres);
  5724. this.connection.send(pres);
  5725. };
  5726. ChatRoom.prototype.doLeave = function () {
  5727. logger.log("do leave", this.myroomjid);
  5728. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5729. this.presMap.length = 0;
  5730. this.connection.send(pres);
  5731. };
  5732. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5733. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5734. var getForm = $iq({type: 'get', to: this.roomjid})
  5735. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5736. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5737. var self = this;
  5738. this.connection.sendIQ(getForm, function (form) {
  5739. if (!$(form).find(
  5740. '>query>x[xmlns="jabber:x:data"]' +
  5741. '>field[var="muc#roomconfig_whois"]').length) {
  5742. logger.error('non-anonymous rooms not supported');
  5743. return;
  5744. }
  5745. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5746. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5747. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5748. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5749. .c('value')
  5750. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5751. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5752. .c('value').t('anyone').up().up();
  5753. self.connection.sendIQ(formSubmit);
  5754. }, function (error) {
  5755. logger.error("Error getting room configuration form");
  5756. });
  5757. };
  5758. ChatRoom.prototype.onPresence = function (pres) {
  5759. var from = pres.getAttribute('from');
  5760. // Parse roles.
  5761. var member = {};
  5762. member.show = $(pres).find('>show').text();
  5763. member.status = $(pres).find('>status').text();
  5764. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5765. member.affiliation = tmp.attr('affiliation');
  5766. member.role = tmp.attr('role');
  5767. // Focus recognition
  5768. member.jid = tmp.attr('jid');
  5769. member.isFocus = false;
  5770. if (member.jid
  5771. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5772. member.isFocus = true;
  5773. }
  5774. $(pres).find(">x").remove();
  5775. var nodes = [];
  5776. parser.packet2JSON(pres, nodes);
  5777. this.lastPresences[from] = nodes;
  5778. var jibri = null;
  5779. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  5780. // events
  5781. for(var i = 0; i < nodes.length; i++)
  5782. {
  5783. var node = nodes[i];
  5784. switch(node.tagName)
  5785. {
  5786. case "nick":
  5787. member.nick = node.value;
  5788. break;
  5789. case "userId":
  5790. member.id = node.value;
  5791. break;
  5792. }
  5793. }
  5794. if (from == this.myroomjid) {
  5795. if (member.affiliation == 'owner'
  5796. && this.role !== member.role) {
  5797. this.role = member.role;
  5798. this.eventEmitter.emit(
  5799. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5800. }
  5801. if (!this.joined) {
  5802. this.joined = true;
  5803. console.log("(TIME) MUC joined:\t", window.performance.now());
  5804. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  5805. }
  5806. } else if (this.members[from] === undefined) {
  5807. // new participant
  5808. this.members[from] = member;
  5809. logger.log('entered', from, member);
  5810. if (member.isFocus) {
  5811. this.focusMucJid = from;
  5812. if(!this.recording) {
  5813. this.recording = new Recorder(this.options.recordingType,
  5814. this.eventEmitter, this.connection, this.focusMucJid,
  5815. this.options.jirecon, this.roomjid);
  5816. if(this.lastJibri)
  5817. this.recording.handleJibriPresence(this.lastJibri);
  5818. }
  5819. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5820. }
  5821. else {
  5822. this.eventEmitter.emit(
  5823. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  5824. }
  5825. } else {
  5826. // Presence update for existing participant
  5827. // Watch role change:
  5828. if (this.members[from].role != member.role) {
  5829. this.members[from].role = member.role;
  5830. this.eventEmitter.emit(
  5831. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5832. }
  5833. // store the new display name
  5834. if(member.displayName)
  5835. this.members[from].displayName = member.displayName;
  5836. }
  5837. // after we had fired member or room joined events, lets fire events
  5838. // for the rest info we got in presence
  5839. for(var i = 0; i < nodes.length; i++)
  5840. {
  5841. var node = nodes[i];
  5842. switch(node.tagName)
  5843. {
  5844. case "nick":
  5845. if(!member.isFocus) {
  5846. var displayName = !this.xmpp.options.displayJids
  5847. ? member.nick : Strophe.getResourceFromJid(from);
  5848. if (displayName && displayName.length > 0) {
  5849. this.eventEmitter.emit(
  5850. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5851. }
  5852. }
  5853. break;
  5854. case "bridgeIsDown":
  5855. if(!this.bridgeIsDown) {
  5856. this.bridgeIsDown = true;
  5857. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5858. }
  5859. break;
  5860. case "jibri-recording-status":
  5861. var jibri = node;
  5862. break;
  5863. case "call-control":
  5864. var att = node.attributes;
  5865. if(!att)
  5866. break;
  5867. this.phoneNumber = att.phone || null;
  5868. this.phonePin = att.pin || null;
  5869. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  5870. break;
  5871. default :
  5872. this.processNode(node, from);
  5873. }
  5874. }
  5875. if(!member.isFocus)
  5876. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id);
  5877. // Trigger status message update
  5878. if (member.status) {
  5879. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5880. }
  5881. if(jibri)
  5882. {
  5883. this.lastJibri = jibri;
  5884. if(this.recording)
  5885. this.recording.handleJibriPresence(jibri);
  5886. }
  5887. };
  5888. ChatRoom.prototype.processNode = function (node, from) {
  5889. if(this.presHandlers[node.tagName])
  5890. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  5891. };
  5892. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5893. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5894. msg.c('body', body).up();
  5895. if (nickname) {
  5896. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5897. }
  5898. this.connection.send(msg);
  5899. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5900. };
  5901. ChatRoom.prototype.setSubject = function (subject) {
  5902. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5903. msg.c('subject', subject);
  5904. this.connection.send(msg);
  5905. logger.log("topic changed to " + subject);
  5906. };
  5907. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5908. delete this.lastPresences[jid];
  5909. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5910. this.moderator.onMucMemberLeft(jid);
  5911. };
  5912. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5913. // room destroyed ?
  5914. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5915. '>destroy').length) {
  5916. var reason;
  5917. var reasonSelect = $(pres).find(
  5918. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5919. '>destroy>reason');
  5920. if (reasonSelect.length) {
  5921. reason = reasonSelect.text();
  5922. }
  5923. this.xmpp.leaveRoom(this.roomjid);
  5924. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5925. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5926. return true;
  5927. }
  5928. // Status code 110 indicates that this notification is "self-presence".
  5929. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5930. delete this.members[from];
  5931. this.onParticipantLeft(from);
  5932. }
  5933. // If the status code is 110 this means we're leaving and we would like
  5934. // to remove everyone else from our view, so we trigger the event.
  5935. else if (Object.keys(this.members).length > 1) {
  5936. for (var i in this.members) {
  5937. var member = this.members[i];
  5938. delete this.members[i];
  5939. this.onParticipantLeft(member);
  5940. }
  5941. }
  5942. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5943. if (this.myroomjid === from) {
  5944. this.xmpp.leaveRoom(this.roomjid);
  5945. this.eventEmitter.emit(XMPPEvents.KICKED);
  5946. }
  5947. }
  5948. };
  5949. ChatRoom.prototype.onMessage = function (msg, from) {
  5950. var nick =
  5951. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5952. .text() ||
  5953. Strophe.getResourceFromJid(from);
  5954. var txt = $(msg).find('>body').text();
  5955. var type = msg.getAttribute("type");
  5956. if (type == "error") {
  5957. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5958. $(msg).find('>text').text(), txt);
  5959. return true;
  5960. }
  5961. var subject = $(msg).find('>subject');
  5962. if (subject.length) {
  5963. var subjectText = subject.text();
  5964. if (subjectText || subjectText === "") {
  5965. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5966. logger.log("Subject is changed to " + subjectText);
  5967. }
  5968. }
  5969. // xep-0203 delay
  5970. var stamp = $(msg).find('>delay').attr('stamp');
  5971. if (!stamp) {
  5972. // or xep-0091 delay, UTC timestamp
  5973. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5974. if (stamp) {
  5975. // the format is CCYYMMDDThh:mm:ss
  5976. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5977. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5978. }
  5979. }
  5980. if (txt) {
  5981. logger.log('chat', nick, txt);
  5982. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5983. from, nick, txt, this.myroomjid, stamp);
  5984. }
  5985. };
  5986. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5987. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5988. logger.log('on password required', from);
  5989. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5990. } else if ($(pres).find(
  5991. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5992. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5993. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5994. // enter the room by replying with 'not-authorized'. This would
  5995. // result in reconnection from authorized domain.
  5996. // We're either missing Jicofo/Prosody config for anonymous
  5997. // domains or something is wrong.
  5998. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5999. } else {
  6000. logger.warn('onPresError ', pres);
  6001. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6002. }
  6003. } else {
  6004. logger.warn('onPresError ', pres);
  6005. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6006. }
  6007. };
  6008. ChatRoom.prototype.kick = function (jid) {
  6009. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  6010. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  6011. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  6012. .c('reason').t('You have been kicked.').up().up().up();
  6013. this.connection.sendIQ(
  6014. kickIQ,
  6015. function (result) {
  6016. logger.log('Kick participant with jid: ', jid, result);
  6017. },
  6018. function (error) {
  6019. logger.log('Kick participant error: ', error);
  6020. });
  6021. };
  6022. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  6023. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  6024. var ob = this;
  6025. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  6026. function (res) {
  6027. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  6028. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6029. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6030. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6031. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  6032. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  6033. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  6034. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  6035. ob.connection.sendIQ(formsubmit,
  6036. onSuccess,
  6037. onError);
  6038. } else {
  6039. onNotSupported();
  6040. }
  6041. }, onError);
  6042. };
  6043. ChatRoom.prototype.addToPresence = function (key, values) {
  6044. values.tagName = key;
  6045. this.presMap["nodes"].push(values);
  6046. };
  6047. ChatRoom.prototype.removeFromPresence = function (key) {
  6048. for(var i = 0; i < this.presMap.nodes.length; i++)
  6049. {
  6050. if(key === this.presMap.nodes[i].tagName)
  6051. this.presMap.nodes.splice(i, 1);
  6052. }
  6053. };
  6054. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  6055. this.presHandlers[name] = handler;
  6056. };
  6057. ChatRoom.prototype.removePresenceListener = function (name) {
  6058. delete this.presHandlers[name];
  6059. };
  6060. ChatRoom.prototype.isModerator = function () {
  6061. return this.role === 'moderator';
  6062. };
  6063. ChatRoom.prototype.getMemberRole = function (peerJid) {
  6064. if (this.members[peerJid]) {
  6065. return this.members[peerJid].role;
  6066. }
  6067. return null;
  6068. };
  6069. ChatRoom.prototype.setJingleSession = function(session){
  6070. this.session = session;
  6071. this.session.room = this;
  6072. };
  6073. ChatRoom.prototype.removeStream = function (stream, callback) {
  6074. if(!this.session)
  6075. return;
  6076. this.session.removeStream(stream, callback);
  6077. };
  6078. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  6079. if(this.session) {
  6080. // FIXME: will block switchInProgress on true value in case of exception
  6081. this.session.switchStreams(stream, oldStream, callback, isAudio);
  6082. } else {
  6083. // We are done immediately
  6084. logger.warn("No conference handler or conference not started yet");
  6085. callback();
  6086. }
  6087. };
  6088. ChatRoom.prototype.addStream = function (stream, callback) {
  6089. if(this.session) {
  6090. // FIXME: will block switchInProgress on true value in case of exception
  6091. this.session.addStream(stream, callback);
  6092. } else {
  6093. // We are done immediately
  6094. logger.warn("No conference handler or conference not started yet");
  6095. callback();
  6096. }
  6097. };
  6098. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  6099. var self = this;
  6100. var localCallback = function (mute) {
  6101. self.sendVideoInfoPresence(mute);
  6102. if(callback)
  6103. callback(mute);
  6104. };
  6105. if(this.session)
  6106. {
  6107. this.session.setVideoMute(
  6108. mute, localCallback, options);
  6109. }
  6110. else {
  6111. localCallback(mute);
  6112. }
  6113. };
  6114. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  6115. //This will be for remote streams only
  6116. // if (this.forceMuted && !mute) {
  6117. // logger.info("Asking focus for unmute");
  6118. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  6119. // // FIXME: wait for result before resetting muted status
  6120. // this.forceMuted = false;
  6121. // }
  6122. return this.sendAudioInfoPresence(mute, callback);
  6123. };
  6124. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  6125. this.removeFromPresence("audiomuted");
  6126. this.addToPresence("audiomuted",
  6127. {attributes:
  6128. {"audions": "http://jitsi.org/jitmeet/audio"},
  6129. value: mute.toString()});
  6130. };
  6131. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  6132. this.addAudioInfoToPresence(mute);
  6133. if(this.connection) {
  6134. this.sendPresence();
  6135. }
  6136. if(callback)
  6137. callback();
  6138. };
  6139. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  6140. this.removeFromPresence("videomuted");
  6141. this.addToPresence("videomuted",
  6142. {attributes:
  6143. {"videons": "http://jitsi.org/jitmeet/video"},
  6144. value: mute.toString()});
  6145. };
  6146. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  6147. this.addVideoInfoToPresence(mute);
  6148. if(!this.connection)
  6149. return;
  6150. this.sendPresence();
  6151. };
  6152. ChatRoom.prototype.addListener = function(type, listener) {
  6153. this.eventEmitter.on(type, listener);
  6154. };
  6155. ChatRoom.prototype.removeListener = function (type, listener) {
  6156. this.eventEmitter.removeListener(type, listener);
  6157. };
  6158. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  6159. if(this.lastPresences[data.peerjid])
  6160. {
  6161. var pres = this.lastPresences[data.peerjid];
  6162. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  6163. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  6164. data.videomuted = ((videomuted.length > 0
  6165. && videomuted[0]
  6166. && videomuted[0]["value"] === "true")? true : false);
  6167. data.audiomuted = ((audiomuted.length > 0
  6168. && audiomuted[0]
  6169. && audiomuted[0]["value"] === "true")? true : false);
  6170. }
  6171. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  6172. };
  6173. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  6174. if (!this.session)
  6175. return null;
  6176. return this.session.getSsrcOwner(ssrc);
  6177. };
  6178. /**
  6179. * Returns true if the recording is supproted and false if not.
  6180. */
  6181. ChatRoom.prototype.isRecordingSupported = function () {
  6182. if(this.recording)
  6183. return this.recording.isSupported();
  6184. return false;
  6185. };
  6186. /**
  6187. * Returns null if the recording is not supported, "on" if the recording started
  6188. * and "off" if the recording is not started.
  6189. */
  6190. ChatRoom.prototype.getRecordingState = function () {
  6191. if(this.recording)
  6192. return this.recording.getState();
  6193. return "off";
  6194. }
  6195. /**
  6196. * Returns the url of the recorded video.
  6197. */
  6198. ChatRoom.prototype.getRecordingURL = function () {
  6199. if(this.recording)
  6200. return this.recording.getURL();
  6201. return null;
  6202. }
  6203. /**
  6204. * Starts/stops the recording
  6205. * @param token token for authentication
  6206. * @param statusChangeHandler {function} receives the new status as argument.
  6207. */
  6208. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  6209. if(this.recording)
  6210. return this.recording.toggleRecording(options, statusChangeHandler);
  6211. return statusChangeHandler("error",
  6212. new Error("The conference is not created yet!"));
  6213. }
  6214. /**
  6215. * Returns true if the SIP calls are supported and false otherwise
  6216. */
  6217. ChatRoom.prototype.isSIPCallingSupported = function () {
  6218. if(this.moderator)
  6219. return this.moderator.isSipGatewayEnabled();
  6220. return false;
  6221. }
  6222. /**
  6223. * Dials a number.
  6224. * @param number the number
  6225. */
  6226. ChatRoom.prototype.dial = function (number) {
  6227. return this.connection.rayo.dial(number, "fromnumber",
  6228. Strophe.getNodeFromJid(this.myroomjid), this.password,
  6229. this.focusMucJid);
  6230. }
  6231. /**
  6232. * Hangup an existing call
  6233. */
  6234. ChatRoom.prototype.hangup = function () {
  6235. return this.connection.rayo.hangup();
  6236. }
  6237. /**
  6238. * Returns the phone number for joining the conference.
  6239. */
  6240. ChatRoom.prototype.getPhoneNumber = function () {
  6241. return this.phoneNumber;
  6242. }
  6243. /**
  6244. * Returns the pin for joining the conference with phone.
  6245. */
  6246. ChatRoom.prototype.getPhonePin = function () {
  6247. return this.phonePin;
  6248. }
  6249. /**
  6250. * Returns the connection state for the current session.
  6251. */
  6252. ChatRoom.prototype.getConnectionState = function () {
  6253. if(!this.session)
  6254. return null;
  6255. return this.session.getIceConnectionState();
  6256. }
  6257. /**
  6258. * Mutes remote participant.
  6259. * @param jid of the participant
  6260. * @param mute
  6261. */
  6262. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  6263. logger.info("set mute", mute);
  6264. var iqToFocus = $iq(
  6265. {to: this.focusMucJid, type: 'set'})
  6266. .c('mute', {
  6267. xmlns: 'http://jitsi.org/jitmeet/audio',
  6268. jid: jid
  6269. })
  6270. .t(mute.toString())
  6271. .up();
  6272. this.connection.sendIQ(
  6273. iqToFocus,
  6274. function (result) {
  6275. logger.log('set mute', result);
  6276. },
  6277. function (error) {
  6278. logger.log('set mute error', error);
  6279. });
  6280. }
  6281. ChatRoom.prototype.onMute = function (iq) {
  6282. var from = iq.getAttribute('from');
  6283. if (from !== this.focusMucJid) {
  6284. logger.warn("Ignored mute from non focus peer");
  6285. return false;
  6286. }
  6287. var mute = $(iq).find('mute');
  6288. if (mute.length) {
  6289. var doMuteAudio = mute.text() === "true";
  6290. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  6291. }
  6292. return true;
  6293. }
  6294. module.exports = ChatRoom;
  6295. }).call(this,"/modules/xmpp/ChatRoom.js")
  6296. },{"../../service/xmpp/XMPPEvents":87,"./moderator":34,"./recording":35,"events":44,"jitsi-meet-logger":48}],27:[function(require,module,exports){
  6297. (function (__filename){
  6298. /*
  6299. * JingleSession provides an API to manage a single Jingle session. We will
  6300. * have different implementations depending on the underlying interface used
  6301. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  6302. */
  6303. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6304. function JingleSession(me, sid, connection, service, eventEmitter) {
  6305. /**
  6306. * Our JID.
  6307. */
  6308. this.me = me;
  6309. /**
  6310. * The Jingle session identifier.
  6311. */
  6312. this.sid = sid;
  6313. /**
  6314. * The XMPP connection.
  6315. */
  6316. this.connection = connection;
  6317. /**
  6318. * The XMPP service.
  6319. */
  6320. this.service = service;
  6321. /**
  6322. * The event emitter.
  6323. */
  6324. this.eventEmitter = eventEmitter;
  6325. /**
  6326. * Whether to use dripping or not. Dripping is sending trickle candidates
  6327. * not one-by-one.
  6328. * Note: currently we do not support 'false'.
  6329. */
  6330. this.usedrip = true;
  6331. /**
  6332. * When dripping is used, stores ICE candidates which are to be sent.
  6333. */
  6334. this.drip_container = [];
  6335. // Media constraints. Is this WebRTC only?
  6336. this.media_constraints = null;
  6337. // ICE servers config (RTCConfiguration?).
  6338. this.ice_config = {};
  6339. // The chat room instance associated with the session.
  6340. this.room = null;
  6341. }
  6342. /**
  6343. * Prepares this object to initiate a session.
  6344. * @param peerjid the JID of the remote peer.
  6345. * @param isInitiator whether we will be the Jingle initiator.
  6346. * @param media_constraints
  6347. * @param ice_config
  6348. */
  6349. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  6350. media_constraints, ice_config) {
  6351. this.media_constraints = media_constraints;
  6352. this.ice_config = ice_config;
  6353. if (this.state !== null) {
  6354. logger.error('attempt to initiate on session ' + this.sid +
  6355. 'in state ' + this.state);
  6356. return;
  6357. }
  6358. this.state = 'pending';
  6359. this.initiator = isInitiator ? this.me : peerjid;
  6360. this.responder = !isInitiator ? this.me : peerjid;
  6361. this.peerjid = peerjid;
  6362. this.doInitialize();
  6363. };
  6364. /**
  6365. * Finishes initialization.
  6366. */
  6367. JingleSession.prototype.doInitialize = function() {};
  6368. /**
  6369. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  6370. * Note: currently only used on transport-info
  6371. */
  6372. JingleSession.prototype.addIceCandidates = function(contents) {};
  6373. /**
  6374. * Handles an 'add-source' event.
  6375. *
  6376. * @param contents an array of Jingle 'content' elements.
  6377. */
  6378. JingleSession.prototype.addSources = function(contents) {};
  6379. /**
  6380. * Handles a 'remove-source' event.
  6381. *
  6382. * @param contents an array of Jingle 'content' elements.
  6383. */
  6384. JingleSession.prototype.removeSources = function(contents) {};
  6385. /**
  6386. * Terminates this Jingle session (stops sending media and closes the streams?)
  6387. */
  6388. JingleSession.prototype.terminate = function() {};
  6389. /**
  6390. * Sends a Jingle session-terminate message to the peer and terminates the
  6391. * session.
  6392. * @param reason
  6393. * @param text
  6394. */
  6395. JingleSession.prototype.sendTerminate = function(reason, text) {};
  6396. /**
  6397. * Handles an offer from the remote peer (prepares to accept a session).
  6398. * @param jingle the 'jingle' XML element.
  6399. */
  6400. JingleSession.prototype.setOffer = function(jingle) {};
  6401. /**
  6402. * Handles an answer from the remote peer (prepares to accept a session).
  6403. * @param jingle the 'jingle' XML element.
  6404. */
  6405. JingleSession.prototype.setAnswer = function(jingle) {};
  6406. module.exports = JingleSession;
  6407. }).call(this,"/modules/xmpp/JingleSession.js")
  6408. },{"jitsi-meet-logger":48}],28:[function(require,module,exports){
  6409. (function (__filename){
  6410. /* jshint -W117 */
  6411. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6412. var JingleSession = require("./JingleSession");
  6413. var TraceablePeerConnection = require("./TraceablePeerConnection");
  6414. var SDPDiffer = require("./SDPDiffer");
  6415. var SDPUtil = require("./SDPUtil");
  6416. var SDP = require("./SDP");
  6417. var async = require("async");
  6418. var transform = require("sdp-transform");
  6419. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6420. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6421. var SSRCReplacement = require("./LocalSSRCReplacement");
  6422. var RTC = require("../RTC/RTC");
  6423. // Jingle stuff
  6424. function JingleSessionPC(me, sid, connection, service) {
  6425. JingleSession.call(this, me, sid, connection, service);
  6426. this.initiator = null;
  6427. this.responder = null;
  6428. this.peerjid = null;
  6429. this.state = null;
  6430. this.localSDP = null;
  6431. this.remoteSDP = null;
  6432. this.relayedStreams = [];
  6433. this.usetrickle = true;
  6434. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  6435. this.hadstuncandidate = false;
  6436. this.hadturncandidate = false;
  6437. this.lasticecandidate = false;
  6438. this.statsinterval = null;
  6439. this.reason = null;
  6440. this.addssrc = [];
  6441. this.removessrc = [];
  6442. this.pendingop = null;
  6443. this.switchstreams = false;
  6444. this.addingStreams = false;
  6445. this.wait = true;
  6446. /**
  6447. * A map that stores SSRCs of local streams
  6448. * @type {{}} maps media type('audio' or 'video') to SSRC number
  6449. */
  6450. this.localStreamsSSRC = {};
  6451. this.ssrcOwners = {};
  6452. this.ssrcVideoTypes = {};
  6453. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  6454. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  6455. /**
  6456. * The indicator which determines whether the (local) video has been muted
  6457. * in response to a user command in contrast to an automatic decision made
  6458. * by the application logic.
  6459. */
  6460. this.videoMuteByUser = false;
  6461. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  6462. // We start with the queue paused. We resume it when the signaling state is
  6463. // stable and the ice connection state is connected.
  6464. this.modifySourcesQueue.pause();
  6465. }
  6466. //XXX this is badly broken...
  6467. JingleSessionPC.prototype = JingleSession.prototype;
  6468. JingleSessionPC.prototype.constructor = JingleSessionPC;
  6469. JingleSessionPC.prototype.setOffer = function(offer) {
  6470. this.setRemoteDescription(offer, 'offer');
  6471. };
  6472. JingleSessionPC.prototype.setAnswer = function(answer) {
  6473. this.setRemoteDescription(answer, 'answer');
  6474. };
  6475. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  6476. var signalingState = this.peerconnection.signalingState;
  6477. var iceConnectionState = this.peerconnection.iceConnectionState;
  6478. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  6479. this.modifySourcesQueue.resume();
  6480. } else {
  6481. this.modifySourcesQueue.pause();
  6482. }
  6483. };
  6484. JingleSessionPC.prototype.doInitialize = function () {
  6485. var self = this;
  6486. this.hadstuncandidate = false;
  6487. this.hadturncandidate = false;
  6488. this.lasticecandidate = false;
  6489. // True if reconnect is in progress
  6490. this.isreconnect = false;
  6491. // Set to true if the connection was ever stable
  6492. this.wasstable = false;
  6493. this.peerconnection = new TraceablePeerConnection(
  6494. this.connection.jingle.ice_config,
  6495. RTC.getPCConstraints(),
  6496. this);
  6497. this.peerconnection.onicecandidate = function (event) {
  6498. var protocol;
  6499. if (event && event.candidate) {
  6500. protocol = (typeof event.candidate.protocol === 'string')
  6501. ? event.candidate.protocol.toLowerCase() : '';
  6502. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6503. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6504. return;
  6505. }
  6506. }
  6507. self.sendIceCandidate(event.candidate);
  6508. };
  6509. this.peerconnection.onaddstream = function (event) {
  6510. if (event.stream.id !== 'default') {
  6511. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  6512. self.remoteStreamAdded(event);
  6513. } else {
  6514. // This is a recvonly stream. Clients that implement Unified Plan,
  6515. // such as Firefox use recvonly "streams/channels/tracks" for
  6516. // receiving remote stream/tracks, as opposed to Plan B where there
  6517. // are only 3 channels: audio, video and data.
  6518. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  6519. }
  6520. };
  6521. this.peerconnection.onremovestream = function (event) {
  6522. // Remove the stream from remoteStreams
  6523. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  6524. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  6525. };
  6526. this.peerconnection.onsignalingstatechange = function (event) {
  6527. if (!(self && self.peerconnection)) return;
  6528. if (self.peerconnection.signalingState === 'stable') {
  6529. self.wasstable = true;
  6530. }
  6531. self.updateModifySourcesQueue();
  6532. };
  6533. /**
  6534. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6535. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6536. * RTCPeerConnection.iceConnectionState changes.
  6537. *
  6538. * @param event the event containing information about the change
  6539. */
  6540. this.peerconnection.oniceconnectionstatechange = function (event) {
  6541. if (!(self && self.peerconnection)) return;
  6542. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6543. ":\t", window.performance.now());
  6544. self.updateModifySourcesQueue();
  6545. switch (self.peerconnection.iceConnectionState) {
  6546. case 'connected':
  6547. // Informs interested parties that the connection has been restored.
  6548. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6549. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6550. self.isreconnect = false;
  6551. break;
  6552. case 'disconnected':
  6553. self.isreconnect = true;
  6554. // Informs interested parties that the connection has been interrupted.
  6555. if (self.wasstable)
  6556. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6557. break;
  6558. case 'failed':
  6559. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6560. break;
  6561. }
  6562. onIceConnectionStateChange(self.sid, self);
  6563. };
  6564. this.peerconnection.onnegotiationneeded = function (event) {
  6565. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6566. };
  6567. this.relayedStreams.forEach(function(stream) {
  6568. self.peerconnection.addStream(stream);
  6569. });
  6570. };
  6571. function onIceConnectionStateChange(sid, session) {
  6572. switch (session.peerconnection.iceConnectionState) {
  6573. case 'checking':
  6574. session.timeChecking = (new Date()).getTime();
  6575. session.firstconnect = true;
  6576. break;
  6577. case 'completed': // on caller side
  6578. case 'connected':
  6579. if (session.firstconnect) {
  6580. session.firstconnect = false;
  6581. var metadata = {};
  6582. metadata.setupTime
  6583. = (new Date()).getTime() - session.timeChecking;
  6584. session.peerconnection.getStats(function (res) {
  6585. if(res && res.result) {
  6586. res.result().forEach(function (report) {
  6587. if (report.type == 'googCandidatePair' &&
  6588. report.stat('googActiveConnection') == 'true') {
  6589. metadata.localCandidateType
  6590. = report.stat('googLocalCandidateType');
  6591. metadata.remoteCandidateType
  6592. = report.stat('googRemoteCandidateType');
  6593. // log pair as well so we can get nice pie
  6594. // charts
  6595. metadata.candidatePair
  6596. = report.stat('googLocalCandidateType') +
  6597. ';' +
  6598. report.stat('googRemoteCandidateType');
  6599. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6600. {
  6601. metadata.ipv6 = true;
  6602. }
  6603. }
  6604. });
  6605. }
  6606. });
  6607. }
  6608. break;
  6609. }
  6610. }
  6611. JingleSessionPC.prototype.accept = function () {
  6612. this.state = 'active';
  6613. var pranswer = this.peerconnection.localDescription;
  6614. if (!pranswer || pranswer.type != 'pranswer') {
  6615. return;
  6616. }
  6617. logger.log('going from pranswer to answer');
  6618. if (this.usetrickle) {
  6619. // remove candidates already sent from session-accept
  6620. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6621. for (var i = 0; i < lines.length; i++) {
  6622. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6623. }
  6624. }
  6625. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6626. // FIXME: change any inactive to sendrecv or whatever they were originally
  6627. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6628. }
  6629. var prsdp = new SDP(pranswer.sdp);
  6630. if (this.webrtcIceTcpDisable) {
  6631. prsdp.removeTcpCandidates = true;
  6632. }
  6633. if (this.webrtcIceUdpDisable) {
  6634. prsdp.removeUdpCandidates = true;
  6635. }
  6636. var accept = $iq({to: this.peerjid,
  6637. type: 'set'})
  6638. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6639. action: 'session-accept',
  6640. initiator: this.initiator,
  6641. responder: this.responder,
  6642. sid: this.sid });
  6643. // FIXME why do we generate session-accept in 3 different places ?
  6644. prsdp.toJingle(
  6645. accept,
  6646. this.initiator == this.me ? 'initiator' : 'responder');
  6647. var sdp = this.peerconnection.localDescription.sdp;
  6648. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6649. // FIXME: change any inactive to sendrecv or whatever they were originally
  6650. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6651. }
  6652. var self = this;
  6653. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6654. function () {
  6655. //logger.log('setLocalDescription success');
  6656. self.setLocalDescription();
  6657. SSRCReplacement.processSessionInit(accept);
  6658. self.connection.sendIQ(accept,
  6659. function () {
  6660. var ack = {};
  6661. ack.source = 'answer';
  6662. $(document).trigger('ack.jingle', [self.sid, ack]);
  6663. },
  6664. function (stanza) {
  6665. var error = ($(stanza).find('error').length) ? {
  6666. code: $(stanza).find('error').attr('code'),
  6667. reason: $(stanza).find('error :first')[0].tagName
  6668. }:{};
  6669. error.source = 'answer';
  6670. JingleSessionPC.onJingleError(self.sid, error);
  6671. },
  6672. 10000);
  6673. },
  6674. function (e) {
  6675. logger.error('setLocalDescription failed', e);
  6676. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6677. }
  6678. );
  6679. };
  6680. JingleSessionPC.prototype.terminate = function (reason) {
  6681. this.state = 'ended';
  6682. this.reason = reason;
  6683. this.peerconnection.close();
  6684. if (this.statsinterval !== null) {
  6685. window.clearInterval(this.statsinterval);
  6686. this.statsinterval = null;
  6687. }
  6688. };
  6689. JingleSessionPC.prototype.active = function () {
  6690. return this.state == 'active';
  6691. };
  6692. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6693. var self = this;
  6694. if (candidate && !this.lasticecandidate) {
  6695. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6696. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6697. if (!(ice && jcand)) {
  6698. logger.error('failed to get ice && jcand');
  6699. return;
  6700. }
  6701. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6702. if (jcand.type === 'srflx') {
  6703. this.hadstuncandidate = true;
  6704. } else if (jcand.type === 'relay') {
  6705. this.hadturncandidate = true;
  6706. }
  6707. if (this.usetrickle) {
  6708. if (this.usedrip) {
  6709. if (this.drip_container.length === 0) {
  6710. // start 20ms callout
  6711. window.setTimeout(function () {
  6712. if (self.drip_container.length === 0) return;
  6713. self.sendIceCandidates(self.drip_container);
  6714. self.drip_container = [];
  6715. }, 20);
  6716. }
  6717. this.drip_container.push(candidate);
  6718. return;
  6719. } else {
  6720. self.sendIceCandidate([candidate]);
  6721. }
  6722. }
  6723. } else {
  6724. //logger.log('sendIceCandidate: last candidate.');
  6725. if (!this.usetrickle) {
  6726. //logger.log('should send full offer now...');
  6727. //FIXME why do we generate session-accept in 3 different places ?
  6728. var init = $iq({to: this.peerjid,
  6729. type: 'set'})
  6730. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6731. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6732. initiator: this.initiator,
  6733. sid: this.sid});
  6734. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6735. if (self.webrtcIceTcpDisable) {
  6736. this.localSDP.removeTcpCandidates = true;
  6737. }
  6738. if (self.webrtcIceUdpDisable) {
  6739. this.localSDP.removeUdpCandidates = true;
  6740. }
  6741. var sendJingle = function (ssrc) {
  6742. if(!ssrc)
  6743. ssrc = {};
  6744. self.localSDP.toJingle(
  6745. init,
  6746. self.initiator == self.me ? 'initiator' : 'responder',
  6747. ssrc);
  6748. SSRCReplacement.processSessionInit(init);
  6749. self.connection.sendIQ(init,
  6750. function () {
  6751. //logger.log('session initiate ack');
  6752. var ack = {};
  6753. ack.source = 'offer';
  6754. $(document).trigger('ack.jingle', [self.sid, ack]);
  6755. },
  6756. function (stanza) {
  6757. self.state = 'error';
  6758. self.peerconnection.close();
  6759. var error = ($(stanza).find('error').length) ? {
  6760. code: $(stanza).find('error').attr('code'),
  6761. reason: $(stanza).find('error :first')[0].tagName,
  6762. }:{};
  6763. error.source = 'offer';
  6764. JingleSessionPC.onJingleError(self.sid, error);
  6765. },
  6766. 10000);
  6767. };
  6768. sendJingle();
  6769. }
  6770. this.lasticecandidate = true;
  6771. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6772. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6773. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6774. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6775. }
  6776. }
  6777. };
  6778. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6779. logger.log('sendIceCandidates', candidates);
  6780. var cand = $iq({to: this.peerjid, type: 'set'})
  6781. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6782. action: 'transport-info',
  6783. initiator: this.initiator,
  6784. sid: this.sid});
  6785. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6786. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6787. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6788. if (cands.length > 0) {
  6789. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6790. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6791. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6792. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6793. }).c('transport', ice);
  6794. for (var i = 0; i < cands.length; i++) {
  6795. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6796. }
  6797. // add fingerprint
  6798. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6799. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6800. tmp.required = true;
  6801. cand.c(
  6802. 'fingerprint',
  6803. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6804. .t(tmp.fingerprint);
  6805. delete tmp.fingerprint;
  6806. cand.attrs(tmp);
  6807. cand.up();
  6808. }
  6809. cand.up(); // transport
  6810. cand.up(); // content
  6811. }
  6812. }
  6813. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6814. //logger.log('was this the last candidate', this.lasticecandidate);
  6815. this.connection.sendIQ(cand,
  6816. function () {
  6817. var ack = {};
  6818. ack.source = 'transportinfo';
  6819. $(document).trigger('ack.jingle', [this.sid, ack]);
  6820. },
  6821. function (stanza) {
  6822. var error = ($(stanza).find('error').length) ? {
  6823. code: $(stanza).find('error').attr('code'),
  6824. reason: $(stanza).find('error :first')[0].tagName,
  6825. }:{};
  6826. error.source = 'transportinfo';
  6827. JingleSessionPC.onJingleError(this.sid, error);
  6828. },
  6829. 10000);
  6830. };
  6831. JingleSessionPC.prototype.sendOffer = function () {
  6832. //logger.log('sendOffer...');
  6833. var self = this;
  6834. this.peerconnection.createOffer(function (sdp) {
  6835. self.createdOffer(sdp);
  6836. },
  6837. function (e) {
  6838. logger.error('createOffer failed', e);
  6839. },
  6840. this.media_constraints
  6841. );
  6842. };
  6843. // FIXME createdOffer is never used in jitsi-meet
  6844. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6845. //logger.log('createdOffer', sdp);
  6846. var self = this;
  6847. this.localSDP = new SDP(sdp.sdp);
  6848. //this.localSDP.mangle();
  6849. var sendJingle = function () {
  6850. var init = $iq({to: this.peerjid,
  6851. type: 'set'})
  6852. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6853. action: 'session-initiate',
  6854. initiator: this.initiator,
  6855. sid: this.sid});
  6856. self.localSDP.toJingle(
  6857. init,
  6858. this.initiator == this.me ? 'initiator' : 'responder');
  6859. SSRCReplacement.processSessionInit(init);
  6860. self.connection.sendIQ(init,
  6861. function () {
  6862. var ack = {};
  6863. ack.source = 'offer';
  6864. $(document).trigger('ack.jingle', [self.sid, ack]);
  6865. },
  6866. function (stanza) {
  6867. self.state = 'error';
  6868. self.peerconnection.close();
  6869. var error = ($(stanza).find('error').length) ? {
  6870. code: $(stanza).find('error').attr('code'),
  6871. reason: $(stanza).find('error :first')[0].tagName,
  6872. }:{};
  6873. error.source = 'offer';
  6874. JingleSessionPC.onJingleError(self.sid, error);
  6875. },
  6876. 10000);
  6877. }
  6878. sdp.sdp = this.localSDP.raw;
  6879. this.peerconnection.setLocalDescription(sdp,
  6880. function () {
  6881. if(self.usetrickle)
  6882. {
  6883. sendJingle();
  6884. }
  6885. self.setLocalDescription();
  6886. //logger.log('setLocalDescription success');
  6887. },
  6888. function (e) {
  6889. logger.error('setLocalDescription failed', e);
  6890. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6891. }
  6892. );
  6893. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6894. for (var i = 0; i < cands.length; i++) {
  6895. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6896. if (cand.type == 'srflx') {
  6897. this.hadstuncandidate = true;
  6898. } else if (cand.type == 'relay') {
  6899. this.hadturncandidate = true;
  6900. }
  6901. }
  6902. };
  6903. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6904. var self = this;
  6905. $(contents).each(function (idx, content) {
  6906. var name = $(content).attr('name');
  6907. var mediaType = this.getAttribute('name');
  6908. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6909. ssrcs.each(function () {
  6910. var ssrc = this.getAttribute('ssrc');
  6911. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6912. function () {
  6913. var owner = this.getAttribute('owner');
  6914. self.ssrcOwners[ssrc] = owner;
  6915. }
  6916. );
  6917. });
  6918. });
  6919. };
  6920. /**
  6921. * Returns the SSRC of local audio stream.
  6922. * @param mediaType 'audio' or 'video' media type
  6923. * @returns {*} the SSRC number of local audio or video stream.
  6924. */
  6925. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6926. return this.localStreamsSSRC[mediaType];
  6927. };
  6928. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6929. return this.ssrcOwners[ssrc];
  6930. };
  6931. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6932. //logger.log('setting remote description... ', desctype);
  6933. this.remoteSDP = new SDP('');
  6934. if (this.webrtcIceTcpDisable) {
  6935. this.remoteSDP.removeTcpCandidates = true;
  6936. }
  6937. if (this.webrtcIceUdpDisable) {
  6938. this.remoteSDP.removeUdpCandidates = true;
  6939. }
  6940. this.remoteSDP.fromJingle(elem);
  6941. this.readSsrcInfo($(elem).find(">content"));
  6942. if (this.peerconnection.remoteDescription) {
  6943. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6944. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6945. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6946. for (var i = 0; i < pranswer.media.length; i++) {
  6947. // make sure we have ice ufrag and pwd
  6948. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6949. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6950. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6951. } else {
  6952. logger.warn('no ice ufrag?');
  6953. }
  6954. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6955. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6956. } else {
  6957. logger.warn('no ice pwd?');
  6958. }
  6959. }
  6960. // copy over candidates
  6961. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6962. for (var j = 0; j < lines.length; j++) {
  6963. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6964. }
  6965. }
  6966. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6967. }
  6968. }
  6969. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6970. this.peerconnection.setRemoteDescription(remotedesc,
  6971. function () {
  6972. //logger.log('setRemoteDescription success');
  6973. },
  6974. function (e) {
  6975. logger.error('setRemoteDescription error', e);
  6976. JingleSessionPC.onJingleFatalError(self, e);
  6977. }
  6978. );
  6979. };
  6980. /**
  6981. * Adds remote ICE candidates to this Jingle session.
  6982. * @param elem An array of Jingle "content" elements?
  6983. */
  6984. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6985. var self = this;
  6986. if (this.peerconnection.signalingState == 'closed') {
  6987. return;
  6988. }
  6989. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6990. logger.log('trickle ice candidate arriving before session accept...');
  6991. // create a PRANSWER for setRemoteDescription
  6992. if (!this.remoteSDP) {
  6993. var cobbled = 'v=0\r\n' +
  6994. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6995. 's=-\r\n' +
  6996. 't=0 0\r\n';
  6997. // first, take some things from the local description
  6998. for (var i = 0; i < this.localSDP.media.length; i++) {
  6999. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  7000. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  7001. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  7002. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  7003. }
  7004. cobbled += 'a=inactive\r\n';
  7005. }
  7006. this.remoteSDP = new SDP(cobbled);
  7007. }
  7008. // then add things like ice and dtls from remote candidate
  7009. elem.each(function () {
  7010. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  7011. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7012. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7013. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  7014. var tmp = $(this).find('transport');
  7015. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  7016. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  7017. tmp = $(this).find('transport>fingerprint');
  7018. if (tmp.length) {
  7019. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  7020. } else {
  7021. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  7022. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  7023. }
  7024. break;
  7025. }
  7026. }
  7027. }
  7028. });
  7029. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7030. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  7031. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  7032. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  7033. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  7034. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  7035. }).length == this.remoteSDP.media.length;
  7036. if (iscomplete) {
  7037. logger.log('setting pranswer');
  7038. try {
  7039. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  7040. function() {
  7041. },
  7042. function(e) {
  7043. logger.log('setRemoteDescription pranswer failed', e.toString());
  7044. });
  7045. } catch (e) {
  7046. logger.error('setting pranswer failed', e);
  7047. }
  7048. } else {
  7049. //logger.log('not yet setting pranswer');
  7050. }
  7051. }
  7052. // operate on each content element
  7053. elem.each(function () {
  7054. // would love to deactivate this, but firefox still requires it
  7055. var idx = -1;
  7056. var i;
  7057. for (i = 0; i < self.remoteSDP.media.length; i++) {
  7058. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7059. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7060. idx = i;
  7061. break;
  7062. }
  7063. }
  7064. if (idx == -1) { // fall back to localdescription
  7065. for (i = 0; i < self.localSDP.media.length; i++) {
  7066. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7067. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7068. idx = i;
  7069. break;
  7070. }
  7071. }
  7072. }
  7073. var name = $(this).attr('name');
  7074. // TODO: check ice-pwd and ice-ufrag?
  7075. $(this).find('transport>candidate').each(function () {
  7076. var line, candidate;
  7077. var protocol = this.getAttribute('protocol');
  7078. protocol =
  7079. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  7080. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7081. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7082. return;
  7083. }
  7084. line = SDPUtil.candidateFromJingle(this);
  7085. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  7086. sdpMid: name,
  7087. candidate: line});
  7088. try {
  7089. self.peerconnection.addIceCandidate(candidate);
  7090. } catch (e) {
  7091. logger.error('addIceCandidate failed', e.toString(), line);
  7092. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  7093. err, self.peerconnection);
  7094. }
  7095. });
  7096. });
  7097. };
  7098. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  7099. //logger.log('createAnswer', provisional);
  7100. var self = this;
  7101. this.peerconnection.createAnswer(
  7102. function (sdp) {
  7103. self.createdAnswer(sdp, provisional);
  7104. },
  7105. function (e) {
  7106. logger.error('createAnswer failed', e);
  7107. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7108. },
  7109. this.media_constraints
  7110. );
  7111. };
  7112. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  7113. //logger.log('createAnswer callback');
  7114. var self = this;
  7115. this.localSDP = new SDP(sdp.sdp);
  7116. //this.localSDP.mangle();
  7117. this.usepranswer = provisional === true;
  7118. if (this.usetrickle) {
  7119. if (this.usepranswer) {
  7120. sdp.type = 'pranswer';
  7121. for (var i = 0; i < this.localSDP.media.length; i++) {
  7122. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  7123. }
  7124. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  7125. }
  7126. }
  7127. var self = this;
  7128. var sendJingle = function (ssrcs) {
  7129. // FIXME why do we generate session-accept in 3 different places ?
  7130. var accept = $iq({to: self.peerjid,
  7131. type: 'set'})
  7132. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7133. action: 'session-accept',
  7134. initiator: self.initiator,
  7135. responder: self.responder,
  7136. sid: self.sid });
  7137. if (self.webrtcIceTcpDisable) {
  7138. self.localSDP.removeTcpCandidates = true;
  7139. }
  7140. if (self.webrtcIceUdpDisable) {
  7141. self.localSDP.removeUdpCandidates = true;
  7142. }
  7143. self.localSDP.toJingle(
  7144. accept,
  7145. self.initiator == self.me ? 'initiator' : 'responder',
  7146. ssrcs);
  7147. SSRCReplacement.processSessionInit(accept);
  7148. self.connection.sendIQ(accept,
  7149. function () {
  7150. var ack = {};
  7151. ack.source = 'answer';
  7152. $(document).trigger('ack.jingle', [self.sid, ack]);
  7153. },
  7154. function (stanza) {
  7155. var error = ($(stanza).find('error').length) ? {
  7156. code: $(stanza).find('error').attr('code'),
  7157. reason: $(stanza).find('error :first')[0].tagName,
  7158. }:{};
  7159. error.source = 'answer';
  7160. JingleSessionPC.onJingleError(self.sid, error);
  7161. },
  7162. 10000);
  7163. }
  7164. sdp.sdp = this.localSDP.raw;
  7165. this.peerconnection.setLocalDescription(sdp,
  7166. function () {
  7167. //logger.log('setLocalDescription success');
  7168. if (self.usetrickle && !self.usepranswer) {
  7169. sendJingle();
  7170. }
  7171. self.setLocalDescription();
  7172. },
  7173. function (e) {
  7174. logger.error('setLocalDescription failed', e);
  7175. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7176. }
  7177. );
  7178. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7179. for (var j = 0; j < cands.length; j++) {
  7180. var cand = SDPUtil.parse_icecandidate(cands[j]);
  7181. if (cand.type == 'srflx') {
  7182. this.hadstuncandidate = true;
  7183. } else if (cand.type == 'relay') {
  7184. this.hadturncandidate = true;
  7185. }
  7186. }
  7187. };
  7188. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  7189. var self = this,
  7190. term = $iq({to: this.peerjid,
  7191. type: 'set'})
  7192. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7193. action: 'session-terminate',
  7194. initiator: this.initiator,
  7195. sid: this.sid})
  7196. .c('reason')
  7197. .c(reason || 'success');
  7198. if (text) {
  7199. term.up().c('text').t(text);
  7200. }
  7201. this.connection.sendIQ(term,
  7202. function () {
  7203. self.peerconnection.close();
  7204. self.peerconnection = null;
  7205. self.terminate();
  7206. var ack = {};
  7207. ack.source = 'terminate';
  7208. $(document).trigger('ack.jingle', [self.sid, ack]);
  7209. },
  7210. function (stanza) {
  7211. var error = ($(stanza).find('error').length) ? {
  7212. code: $(stanza).find('error').attr('code'),
  7213. reason: $(stanza).find('error :first')[0].tagName,
  7214. }:{};
  7215. $(document).trigger('ack.jingle', [self.sid, error]);
  7216. },
  7217. 10000);
  7218. if (this.statsinterval !== null) {
  7219. window.clearInterval(this.statsinterval);
  7220. this.statsinterval = null;
  7221. }
  7222. };
  7223. /**
  7224. * Handles a Jingle source-add message for this Jingle session.
  7225. * @param elem An array of Jingle "content" elements.
  7226. */
  7227. JingleSessionPC.prototype.addSource = function (elem) {
  7228. var self = this;
  7229. // FIXME: dirty waiting
  7230. if (!this.peerconnection.localDescription)
  7231. {
  7232. logger.warn("addSource - localDescription not ready yet")
  7233. setTimeout(function()
  7234. {
  7235. self.addSource(elem);
  7236. },
  7237. 200
  7238. );
  7239. return;
  7240. }
  7241. logger.log('addssrc', new Date().getTime());
  7242. logger.log('ice', this.peerconnection.iceConnectionState);
  7243. this.readSsrcInfo(elem);
  7244. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7245. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7246. $(elem).each(function (idx, content) {
  7247. var name = $(content).attr('name');
  7248. var lines = '';
  7249. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7250. var semantics = this.getAttribute('semantics');
  7251. var ssrcs = $(this).find('>source').map(function () {
  7252. return this.getAttribute('ssrc');
  7253. }).get();
  7254. if (ssrcs.length) {
  7255. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7256. }
  7257. });
  7258. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7259. tmp.each(function () {
  7260. var ssrc = $(this).attr('ssrc');
  7261. if(mySdp.containsSSRC(ssrc)){
  7262. /**
  7263. * This happens when multiple participants change their streams at the same time and
  7264. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  7265. * addssrc are scheduled for update IQ. See
  7266. */
  7267. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  7268. return;
  7269. }
  7270. if (sdp.containsSSRC(ssrc)) {
  7271. logger.warn("Source-add request for existing SSRC: " + ssrc);
  7272. return;
  7273. }
  7274. $(this).find('>parameter').each(function () {
  7275. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7276. if ($(this).attr('value') && $(this).attr('value').length)
  7277. lines += ':' + $(this).attr('value');
  7278. lines += '\r\n';
  7279. });
  7280. });
  7281. sdp.media.forEach(function(media, idx) {
  7282. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7283. return;
  7284. sdp.media[idx] += lines;
  7285. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  7286. self.addssrc[idx] += lines;
  7287. });
  7288. sdp.raw = sdp.session + sdp.media.join('');
  7289. });
  7290. this.modifySourcesQueue.push(function() {
  7291. // When a source is added and if this is FF, a new channel is allocated
  7292. // for receiving the added source. We need to diffuse the SSRC of this
  7293. // new recvonly channel to the rest of the peers.
  7294. logger.log('modify sources done');
  7295. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7296. logger.log("SDPs", mySdp, newSdp);
  7297. self.notifyMySSRCUpdate(mySdp, newSdp);
  7298. });
  7299. };
  7300. /**
  7301. * Handles a Jingle source-remove message for this Jingle session.
  7302. * @param elem An array of Jingle "content" elements.
  7303. */
  7304. JingleSessionPC.prototype.removeSource = function (elem) {
  7305. var self = this;
  7306. // FIXME: dirty waiting
  7307. if (!this.peerconnection.localDescription) {
  7308. logger.warn("removeSource - localDescription not ready yet");
  7309. setTimeout(function() {
  7310. self.removeSource(elem);
  7311. },
  7312. 200
  7313. );
  7314. return;
  7315. }
  7316. logger.log('removessrc', new Date().getTime());
  7317. logger.log('ice', this.peerconnection.iceConnectionState);
  7318. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7319. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7320. $(elem).each(function (idx, content) {
  7321. var name = $(content).attr('name');
  7322. var lines = '';
  7323. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7324. var semantics = this.getAttribute('semantics');
  7325. var ssrcs = $(this).find('>source').map(function () {
  7326. return this.getAttribute('ssrc');
  7327. }).get();
  7328. if (ssrcs.length) {
  7329. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7330. }
  7331. });
  7332. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7333. tmp.each(function () {
  7334. var ssrc = $(this).attr('ssrc');
  7335. // This should never happen, but can be useful for bug detection
  7336. if(mySdp.containsSSRC(ssrc)){
  7337. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  7338. return;
  7339. }
  7340. $(this).find('>parameter').each(function () {
  7341. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7342. if ($(this).attr('value') && $(this).attr('value').length)
  7343. lines += ':' + $(this).attr('value');
  7344. lines += '\r\n';
  7345. });
  7346. });
  7347. sdp.media.forEach(function(media, idx) {
  7348. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7349. return;
  7350. sdp.media[idx] += lines;
  7351. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  7352. self.removessrc[idx] += lines;
  7353. });
  7354. sdp.raw = sdp.session + sdp.media.join('');
  7355. });
  7356. this.modifySourcesQueue.push(function() {
  7357. // When a source is removed and if this is FF, the recvonly channel that
  7358. // receives the remote stream is deactivated . We need to diffuse the
  7359. // recvonly SSRC removal to the rest of the peers.
  7360. logger.log('modify sources done');
  7361. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7362. logger.log("SDPs", mySdp, newSdp);
  7363. self.notifyMySSRCUpdate(mySdp, newSdp);
  7364. });
  7365. };
  7366. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  7367. var self = this;
  7368. if (this.peerconnection.signalingState == 'closed') return;
  7369. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  7370. || this.switchstreams || this.addingStreams)){
  7371. // There is nothing to do since scheduled job might have been executed by another succeeding call
  7372. this.setLocalDescription();
  7373. if(successCallback){
  7374. successCallback();
  7375. }
  7376. queueCallback();
  7377. return;
  7378. }
  7379. // Reset switch streams flags
  7380. this.switchstreams = false;
  7381. this.addingStreams = false;
  7382. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7383. // add sources
  7384. this.addssrc.forEach(function(lines, idx) {
  7385. sdp.media[idx] += lines;
  7386. });
  7387. this.addssrc = [];
  7388. // remove sources
  7389. this.removessrc.forEach(function(lines, idx) {
  7390. lines = lines.split('\r\n');
  7391. lines.pop(); // remove empty last element;
  7392. lines.forEach(function(line) {
  7393. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  7394. });
  7395. });
  7396. this.removessrc = [];
  7397. sdp.raw = sdp.session + sdp.media.join('');
  7398. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  7399. function() {
  7400. if(self.signalingState == 'closed') {
  7401. logger.error("createAnswer attempt on closed state");
  7402. queueCallback("createAnswer attempt on closed state");
  7403. return;
  7404. }
  7405. self.peerconnection.createAnswer(
  7406. function(modifiedAnswer) {
  7407. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  7408. if (self.pendingop !== null) {
  7409. var sdp = new SDP(modifiedAnswer.sdp);
  7410. if (sdp.media.length > 1) {
  7411. switch(self.pendingop) {
  7412. case 'mute':
  7413. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  7414. break;
  7415. case 'unmute':
  7416. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  7417. break;
  7418. }
  7419. sdp.raw = sdp.session + sdp.media.join('');
  7420. modifiedAnswer.sdp = sdp.raw;
  7421. }
  7422. self.pendingop = null;
  7423. }
  7424. // FIXME: pushing down an answer while ice connection state
  7425. // is still checking is bad...
  7426. //logger.log(self.peerconnection.iceConnectionState);
  7427. // trying to work around another chrome bug
  7428. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  7429. self.peerconnection.setLocalDescription(modifiedAnswer,
  7430. function() {
  7431. //logger.log('modified setLocalDescription ok');
  7432. self.setLocalDescription();
  7433. if(successCallback){
  7434. successCallback();
  7435. }
  7436. queueCallback();
  7437. },
  7438. function(error) {
  7439. logger.error('modified setLocalDescription failed', error);
  7440. queueCallback(error);
  7441. }
  7442. );
  7443. },
  7444. function(error) {
  7445. logger.error('modified answer failed', error);
  7446. queueCallback(error);
  7447. }
  7448. );
  7449. },
  7450. function(error) {
  7451. logger.error('modify failed', error);
  7452. queueCallback(error);
  7453. }
  7454. );
  7455. };
  7456. /**
  7457. * Switches video streams.
  7458. * @param newStream new stream that will be used as video of this session.
  7459. * @param oldStream old video stream of this session.
  7460. * @param successCallback callback executed after successful stream switch.
  7461. * @param isAudio whether the streams are audio (if true) or video (if false).
  7462. */
  7463. JingleSessionPC.prototype.switchStreams =
  7464. function (newStream, oldStream, successCallback, isAudio) {
  7465. var self = this;
  7466. var sender, newTrack;
  7467. var senderKind = isAudio ? 'audio' : 'video';
  7468. // Remember SDP to figure out added/removed SSRCs
  7469. var oldSdp = null;
  7470. if (self.peerconnection) {
  7471. if (self.peerconnection.localDescription) {
  7472. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7473. }
  7474. if (RTCBrowserType.getBrowserType() ===
  7475. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  7476. // On Firefox we don't replace MediaStreams as this messes up the
  7477. // m-lines (which can't be removed in Plan Unified) and brings a lot
  7478. // of complications. Instead, we use the RTPSender and replace just
  7479. // the track.
  7480. // Find the right sender (for audio or video)
  7481. self.peerconnection.peerconnection.getSenders().some(function (s) {
  7482. if (s.track && s.track.kind === senderKind) {
  7483. sender = s;
  7484. return true;
  7485. }
  7486. });
  7487. if (sender) {
  7488. // We assume that our streams have a single track, either audio
  7489. // or video.
  7490. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  7491. newStream.getVideoTracks()[0];
  7492. sender.replaceTrack(newTrack)
  7493. .then(function() {
  7494. console.log("Replaced a track, isAudio=" + isAudio);
  7495. })
  7496. .catch(function(err) {
  7497. console.log("Failed to replace a track: " + err);
  7498. });
  7499. } else {
  7500. console.log("Cannot switch tracks: no RTPSender.");
  7501. }
  7502. } else {
  7503. self.peerconnection.removeStream(oldStream, true);
  7504. if (newStream) {
  7505. self.peerconnection.addStream(newStream);
  7506. }
  7507. }
  7508. }
  7509. // Conference is not active
  7510. if (!oldSdp) {
  7511. successCallback();
  7512. return;
  7513. }
  7514. self.switchstreams = true;
  7515. self.modifySourcesQueue.push(function() {
  7516. logger.log('modify sources done');
  7517. successCallback();
  7518. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7519. logger.log("SDPs", oldSdp, newSdp);
  7520. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7521. });
  7522. };
  7523. /**
  7524. * Adds streams.
  7525. * @param stream new stream that will be added.
  7526. * @param success_callback callback executed after successful stream addition.
  7527. */
  7528. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7529. var self = this;
  7530. // Remember SDP to figure out added/removed SSRCs
  7531. var oldSdp = null;
  7532. if(this.peerconnection) {
  7533. if(this.peerconnection.localDescription) {
  7534. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7535. }
  7536. if(stream)
  7537. this.peerconnection.addStream(stream);
  7538. }
  7539. // Conference is not active
  7540. if(!oldSdp || !this.peerconnection) {
  7541. callback();
  7542. return;
  7543. }
  7544. this.addingStreams = true;
  7545. this.modifySourcesQueue.push(function() {
  7546. logger.log('modify sources done');
  7547. callback();
  7548. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7549. logger.log("SDPs", oldSdp, newSdp);
  7550. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7551. });
  7552. }
  7553. /**
  7554. * Remove streams.
  7555. * @param stream stream that will be removed.
  7556. * @param success_callback callback executed after successful stream addition.
  7557. */
  7558. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7559. var self = this;
  7560. // Remember SDP to figure out added/removed SSRCs
  7561. var oldSdp = null;
  7562. if(this.peerconnection) {
  7563. if(this.peerconnection.localDescription) {
  7564. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7565. }
  7566. if (RTCBrowserType.getBrowserType() ===
  7567. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  7568. var sender = null;
  7569. // On Firefox we don't replace MediaStreams as this messes up the
  7570. // m-lines (which can't be removed in Plan Unified) and brings a lot
  7571. // of complications. Instead, we use the RTPSender and replace just
  7572. // the track.
  7573. var track = null;
  7574. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  7575. track = stream.getAudioTracks()[0];
  7576. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  7577. {
  7578. track = stream.getVideoTracks()[0];
  7579. }
  7580. if(!track) {
  7581. console.log("Cannot switch tracks: no tracks.");
  7582. return;
  7583. }
  7584. // Find the right sender (for audio or video)
  7585. self.peerconnection.peerconnection.getSenders().some(function (s) {
  7586. if (s.track === track) {
  7587. sender = s;
  7588. return true;
  7589. }
  7590. });
  7591. if (sender) {
  7592. self.peerconnection.peerconnection.removeTrack(sender);
  7593. // .then(function() {
  7594. // console.log("Replaced a track, isAudio=" + isAudio);
  7595. // })
  7596. // .catch(function(err) {
  7597. // console.log("Failed to replace a track: " + err);
  7598. // });
  7599. } else {
  7600. console.log("Cannot switch tracks: no RTPSender.");
  7601. }
  7602. } else if(stream)
  7603. this.peerconnection.removeStream(stream);
  7604. }
  7605. // Conference is not active
  7606. if(!oldSdp || !this.peerconnection) {
  7607. callback();
  7608. return;
  7609. }
  7610. this.addingStreams = true;
  7611. this.modifySourcesQueue.push(function() {
  7612. logger.log('modify sources done');
  7613. callback();
  7614. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7615. logger.log("SDPs", oldSdp, newSdp);
  7616. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7617. });
  7618. }
  7619. /**
  7620. * Figures out added/removed ssrcs and send update IQs.
  7621. * @param old_sdp SDP object for old description.
  7622. * @param new_sdp SDP object for new description.
  7623. */
  7624. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7625. if (!(this.peerconnection.signalingState == 'stable' &&
  7626. this.peerconnection.iceConnectionState == 'connected')){
  7627. logger.log("Too early to send updates");
  7628. return;
  7629. }
  7630. // send source-remove IQ.
  7631. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7632. var remove = $iq({to: this.peerjid, type: 'set'})
  7633. .c('jingle', {
  7634. xmlns: 'urn:xmpp:jingle:1',
  7635. action: 'source-remove',
  7636. initiator: this.initiator,
  7637. sid: this.sid
  7638. }
  7639. );
  7640. var removed = sdpDiffer.toJingle(remove);
  7641. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7642. // it in the current form
  7643. if (removed)
  7644. remove = SSRCReplacement.processSourceRemove(remove);
  7645. if (removed && remove) {
  7646. logger.info("Sending source-remove", remove);
  7647. this.connection.sendIQ(remove,
  7648. function (res) {
  7649. logger.info('got remove result', res);
  7650. },
  7651. function (err) {
  7652. logger.error('got remove error', err);
  7653. }
  7654. );
  7655. } else {
  7656. logger.log('removal not necessary');
  7657. }
  7658. // send source-add IQ.
  7659. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7660. var add = $iq({to: this.peerjid, type: 'set'})
  7661. .c('jingle', {
  7662. xmlns: 'urn:xmpp:jingle:1',
  7663. action: 'source-add',
  7664. initiator: this.initiator,
  7665. sid: this.sid
  7666. }
  7667. );
  7668. var added = sdpDiffer.toJingle(add);
  7669. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7670. // it in the current form
  7671. if (added)
  7672. add = SSRCReplacement.processSourceAdd(add);
  7673. if (added && add) {
  7674. logger.info("Sending source-add", add);
  7675. this.connection.sendIQ(add,
  7676. function (res) {
  7677. logger.info('got add result', res);
  7678. },
  7679. function (err) {
  7680. logger.error('got add error', err);
  7681. }
  7682. );
  7683. } else {
  7684. logger.log('addition not necessary');
  7685. }
  7686. };
  7687. /**
  7688. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7689. *
  7690. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7691. * tracks; otherwise, <tt>false</tt>
  7692. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7693. * tracks have been enabled/disabled. The function may, optionally, return
  7694. * another function which is to be invoked after the whole mute/unmute operation
  7695. * has completed successfully.
  7696. * @param options an object which specifies optional arguments such as the
  7697. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7698. * specifies whether the method was initiated in response to a user command (in
  7699. * contrast to an automatic decision made by the application logic)
  7700. */
  7701. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7702. var byUser;
  7703. if (options) {
  7704. byUser = options.byUser;
  7705. if (typeof byUser === 'undefined') {
  7706. byUser = true;
  7707. }
  7708. } else {
  7709. byUser = true;
  7710. }
  7711. // The user's command to mute the (local) video takes precedence over any
  7712. // automatic decision made by the application logic.
  7713. if (byUser) {
  7714. this.videoMuteByUser = mute;
  7715. } else if (this.videoMuteByUser) {
  7716. return;
  7717. }
  7718. this.hardMuteVideo(mute);
  7719. var self = this;
  7720. var oldSdp = null;
  7721. if(self.peerconnection) {
  7722. if(self.peerconnection.localDescription) {
  7723. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7724. }
  7725. }
  7726. this.modifySourcesQueue.push(function() {
  7727. logger.log('modify sources done');
  7728. callback(mute);
  7729. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7730. logger.log("SDPs", oldSdp, newSdp);
  7731. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7732. });
  7733. };
  7734. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7735. this.pendingop = muted ? 'mute' : 'unmute';
  7736. };
  7737. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7738. var info = $iq({to: this.peerjid,
  7739. type: 'set'})
  7740. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7741. action: 'session-info',
  7742. initiator: this.initiator,
  7743. sid: this.sid });
  7744. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7745. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7746. if (content) {
  7747. info.attrs({'name': content});
  7748. }
  7749. this.connection.send(info);
  7750. };
  7751. JingleSessionPC.prototype.sendRinging = function () {
  7752. var info = $iq({to: this.peerjid,
  7753. type: 'set'})
  7754. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7755. action: 'session-info',
  7756. initiator: this.initiator,
  7757. sid: this.sid });
  7758. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7759. this.connection.send(info);
  7760. };
  7761. JingleSessionPC.prototype.getStats = function (interval) {
  7762. var self = this;
  7763. var recv = {audio: 0, video: 0};
  7764. var lost = {audio: 0, video: 0};
  7765. var lastrecv = {audio: 0, video: 0};
  7766. var lastlost = {audio: 0, video: 0};
  7767. var loss = {audio: 0, video: 0};
  7768. var delta = {audio: 0, video: 0};
  7769. this.statsinterval = window.setInterval(function () {
  7770. if (self && self.peerconnection && self.peerconnection.getStats) {
  7771. self.peerconnection.getStats(function (stats) {
  7772. var results = stats.result();
  7773. // TODO: there are so much statistics you can get from this..
  7774. for (var i = 0; i < results.length; ++i) {
  7775. if (results[i].type == 'ssrc') {
  7776. var packetsrecv = results[i].stat('packetsReceived');
  7777. var packetslost = results[i].stat('packetsLost');
  7778. if (packetsrecv && packetslost) {
  7779. packetsrecv = parseInt(packetsrecv, 10);
  7780. packetslost = parseInt(packetslost, 10);
  7781. if (results[i].stat('googFrameRateReceived')) {
  7782. lastlost.video = lost.video;
  7783. lastrecv.video = recv.video;
  7784. recv.video = packetsrecv;
  7785. lost.video = packetslost;
  7786. } else {
  7787. lastlost.audio = lost.audio;
  7788. lastrecv.audio = recv.audio;
  7789. recv.audio = packetsrecv;
  7790. lost.audio = packetslost;
  7791. }
  7792. }
  7793. }
  7794. }
  7795. delta.audio = recv.audio - lastrecv.audio;
  7796. delta.video = recv.video - lastrecv.video;
  7797. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7798. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7799. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7800. });
  7801. }
  7802. }, interval || 3000);
  7803. return this.statsinterval;
  7804. };
  7805. JingleSessionPC.onJingleError = function (session, error)
  7806. {
  7807. logger.error("Jingle error", error);
  7808. }
  7809. JingleSessionPC.onJingleFatalError = function (session, error)
  7810. {
  7811. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7812. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7813. }
  7814. JingleSessionPC.prototype.setLocalDescription = function () {
  7815. var self = this;
  7816. var newssrcs = [];
  7817. if(!this.peerconnection.localDescription)
  7818. return;
  7819. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7820. var i;
  7821. session.media.forEach(function (media) {
  7822. if (media.ssrcs && media.ssrcs.length > 0) {
  7823. // TODO(gp) maybe exclude FID streams?
  7824. media.ssrcs.forEach(function (ssrc) {
  7825. if (ssrc.attribute !== 'cname') {
  7826. return;
  7827. }
  7828. newssrcs.push({
  7829. 'ssrc': ssrc.id,
  7830. 'type': media.type
  7831. });
  7832. // FIXME allows for only one SSRC per media type
  7833. self.localStreamsSSRC[media.type] = ssrc.id;
  7834. });
  7835. }
  7836. });
  7837. logger.log('new ssrcs', newssrcs);
  7838. // Bind us as local SSRCs owner
  7839. if (newssrcs.length > 0) {
  7840. for (i = 0; i < newssrcs.length; i++) {
  7841. var ssrc = newssrcs[i].ssrc;
  7842. var myJid = self.me;
  7843. self.ssrcOwners[ssrc] = myJid;
  7844. }
  7845. }
  7846. }
  7847. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7848. JingleSessionPC.prototype.sendKeyframe = function () {
  7849. var pc = this.peerconnection;
  7850. logger.log('sendkeyframe', pc.iceConnectionState);
  7851. if (pc.iceConnectionState !== 'connected') return; // safe...
  7852. var self = this;
  7853. pc.setRemoteDescription(
  7854. pc.remoteDescription,
  7855. function () {
  7856. pc.createAnswer(
  7857. function (modifiedAnswer) {
  7858. pc.setLocalDescription(
  7859. modifiedAnswer,
  7860. function () {
  7861. // noop
  7862. },
  7863. function (error) {
  7864. logger.log('triggerKeyframe setLocalDescription failed', error);
  7865. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7866. }
  7867. );
  7868. },
  7869. function (error) {
  7870. logger.log('triggerKeyframe createAnswer failed', error);
  7871. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7872. }
  7873. );
  7874. },
  7875. function (error) {
  7876. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7877. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7878. }
  7879. );
  7880. }
  7881. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7882. var self = this;
  7883. var thessrc;
  7884. var streamId = RTC.getStreamID(data.stream);
  7885. // look up an associated JID for a stream id
  7886. if (!streamId) {
  7887. logger.error("No stream ID for", data.stream);
  7888. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7889. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7890. var ssrclines = this.peerconnection.remoteDescription?
  7891. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7892. ssrclines = ssrclines.filter(function (line) {
  7893. // NOTE(gp) previously we filtered on the mslabel, but that property
  7894. // is not always present.
  7895. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7896. if (RTCBrowserType.isTemasysPluginUsed()) {
  7897. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7898. } else {
  7899. return ((line.indexOf('msid:' + streamId) !== -1));
  7900. }
  7901. });
  7902. if (ssrclines.length) {
  7903. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7904. if (!self.ssrcOwners[thessrc]) {
  7905. logger.error("No SSRC owner known for: " + thessrc);
  7906. return;
  7907. }
  7908. data.peerjid = self.ssrcOwners[thessrc];
  7909. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7910. } else {
  7911. logger.error("No SSRC lines for ", streamId);
  7912. }
  7913. }
  7914. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7915. var isVideo = data.stream.getVideoTracks().length > 0;
  7916. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7917. if (isVideo &&
  7918. data.peerjid && this.peerjid === data.peerjid &&
  7919. data.stream.getVideoTracks().length === 0 &&
  7920. RTC.localVideo.getTracks().length > 0) {
  7921. window.setTimeout(function () {
  7922. self.sendKeyframe();
  7923. }, 3000);
  7924. }
  7925. }
  7926. /**
  7927. * Returns the ice connection state for the peer connection.
  7928. * @returns the ice connection state for the peer connection.
  7929. */
  7930. JingleSessionPC.prototype.getIceConnectionState = function () {
  7931. return this.peerconnection.iceConnectionState;
  7932. }
  7933. module.exports = JingleSessionPC;
  7934. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7935. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":43,"jitsi-meet-logger":48,"sdp-transform":76}],29:[function(require,module,exports){
  7936. (function (__filename){
  7937. /* global $ */
  7938. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7939. /*
  7940. Here we do modifications of local video SSRCs. There are 2 situations we have
  7941. to handle:
  7942. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7943. have no local camera and it is not generated automatically, but SSRC=1 is
  7944. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7945. and we won't be able to request video key frames correctly.
  7946. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7947. in future. It turned out that Chrome may keep on using the SSRC of removed
  7948. video stream in RTCP even though a new one has been created. So we just
  7949. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7950. notifications are blocked once first video SSRC is advertised to the focus.
  7951. What this hack does:
  7952. 1. Stores the SSRC of the first video stream created by
  7953. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7954. b) watching for 'source-add' for new video stream if it has not been
  7955. created in step a)
  7956. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7957. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7958. returned to the other parts of the application.
  7959. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7960. blocks those notifications. This makes Jicofo and all participants think
  7961. that it exists all the time even if the video stream has been removed or
  7962. replaced locally. Thanks to that there is no additional signaling activity
  7963. on video mute or when switching to the desktop stream.
  7964. */
  7965. var SDP = require('./SDP');
  7966. var RandomUtil = require('../util/RandomUtil');
  7967. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7968. /**
  7969. * The hack is enabled on all browsers except FF by default
  7970. * FIXME finish the hack once removeStream method is implemented in FF
  7971. * @type {boolean}
  7972. */
  7973. var isEnabled = !RTCBrowserType.isFirefox();
  7974. /**
  7975. * Stored SSRC of local video stream.
  7976. */
  7977. var localVideoSSRC;
  7978. /**
  7979. * SSRC used for recvonly video stream when we have no local camera.
  7980. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7981. * instead of 1.
  7982. */
  7983. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7984. /**
  7985. * cname for <tt>localRecvOnlySSRC</tt>
  7986. */
  7987. var localRecvOnlyCName;
  7988. /**
  7989. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7990. * from given Jingle IQ.
  7991. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7992. * @param actionName display name of the action which will be printed in log
  7993. * messages.
  7994. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7995. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7996. * other SSRCs left to be signaled after removing it.
  7997. */
  7998. var filterOutSource = function (modifyIq, actionName) {
  7999. var modifyIqTree = $(modifyIq.tree());
  8000. if (!localVideoSSRC)
  8001. return modifyIqTree[0];
  8002. var videoSSRC = modifyIqTree.find(
  8003. '>jingle>content[name="video"]' +
  8004. '>description>source[ssrc="' + localVideoSSRC + '"]');
  8005. if (!videoSSRC.length) {
  8006. return modifyIqTree[0];
  8007. }
  8008. logger.info(
  8009. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  8010. videoSSRC.remove();
  8011. // Check if any sources still left to be added/removed
  8012. if (modifyIqTree.find('>jingle>content>description>source').length) {
  8013. return modifyIqTree[0];
  8014. } else {
  8015. return null;
  8016. }
  8017. };
  8018. /**
  8019. * Scans given Jingle IQ for video SSRC and stores it.
  8020. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  8021. */
  8022. var storeLocalVideoSSRC = function (jingleIq) {
  8023. var videoSSRCs =
  8024. $(jingleIq.tree())
  8025. .find('>jingle>content[name="video"]>description>source');
  8026. videoSSRCs.each(function (idx, ssrcElem) {
  8027. if (localVideoSSRC)
  8028. return;
  8029. // We consider SSRC real only if it has msid attribute
  8030. // recvonly streams in FF do not have it as well as local SSRCs
  8031. // we generate for recvonly streams in Chrome
  8032. var ssrSel = $(ssrcElem);
  8033. var msid = ssrSel.find('>parameter[name="msid"]');
  8034. if (msid.length) {
  8035. var ssrcVal = ssrSel.attr('ssrc');
  8036. if (ssrcVal) {
  8037. localVideoSSRC = ssrcVal;
  8038. logger.info('Stored local video SSRC' +
  8039. ' for future re-use: ' + localVideoSSRC);
  8040. }
  8041. }
  8042. });
  8043. };
  8044. /**
  8045. * Generates new label/mslabel attribute
  8046. * @returns {string} label/mslabel attribute
  8047. */
  8048. function generateLabel() {
  8049. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  8050. "-" + RandomUtil.randomHexString(4) + "-" +
  8051. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  8052. }
  8053. /**
  8054. * Generates new SSRC for local video recvonly stream.
  8055. * FIXME what about eventual SSRC collision ?
  8056. */
  8057. function generateRecvonlySSRC() {
  8058. localVideoSSRC = localRecvOnlySSRC =
  8059. localVideoSSRC ?
  8060. localVideoSSRC : Math.random().toString(10).substring(2, 11);
  8061. localRecvOnlyCName =
  8062. Math.random().toString(36).substring(2);
  8063. localRecvOnlyMSLabel = generateLabel();
  8064. localRecvOnlyLabel = generateLabel();
  8065. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  8066. logger.info(
  8067. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  8068. ", cname: " + localRecvOnlyCName);
  8069. }
  8070. var LocalSSRCReplacement = {
  8071. /**
  8072. * Method must be called before 'session-initiate' or 'session-invite' is
  8073. * sent. Scans the IQ for local video SSRC and stores it if detected.
  8074. *
  8075. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  8076. * which will be scanned for local video SSRC.
  8077. */
  8078. processSessionInit: function (sessionInit) {
  8079. if (!isEnabled)
  8080. return;
  8081. if (localVideoSSRC) {
  8082. logger.error("Local SSRC stored already: " + localVideoSSRC);
  8083. return;
  8084. }
  8085. storeLocalVideoSSRC(sessionInit);
  8086. },
  8087. /**
  8088. * If we have local video SSRC stored searched given
  8089. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  8090. * with the stored one.
  8091. * @param localDescription local description object that will have local
  8092. * video SSRC replaced with the stored one
  8093. * @returns modified <tt>localDescription</tt> object.
  8094. */
  8095. mungeLocalVideoSSRC: function (localDescription) {
  8096. if (!isEnabled)
  8097. return localDescription;
  8098. if (!localDescription) {
  8099. logger.warn("localDescription is null or undefined");
  8100. return localDescription;
  8101. }
  8102. // IF we have local video SSRC stored make sure it is replaced
  8103. // with old SSRC
  8104. var sdp = new SDP(localDescription.sdp);
  8105. if (sdp.media.length < 2)
  8106. return;
  8107. if (localVideoSSRC && sdp.media[1].indexOf("a=ssrc:") !== -1 &&
  8108. !sdp.containsSSRC(localVideoSSRC)) {
  8109. // Get new video SSRC
  8110. var map = sdp.getMediaSsrcMap();
  8111. var videoPart = map[1];
  8112. var videoSSRCs = videoPart.ssrcs;
  8113. var newSSRC = Object.keys(videoSSRCs)[0];
  8114. logger.info(
  8115. "Replacing new video SSRC: " + newSSRC +
  8116. " with " + localVideoSSRC);
  8117. localDescription.sdp =
  8118. sdp.raw.replace(
  8119. new RegExp('a=ssrc:' + newSSRC, 'g'),
  8120. 'a=ssrc:' + localVideoSSRC);
  8121. }
  8122. else if (sdp.media[1].indexOf('a=ssrc:') === -1 &&
  8123. sdp.media[1].indexOf('a=recvonly') !== -1) {
  8124. // Make sure we have any SSRC for recvonly video stream
  8125. if (!localRecvOnlySSRC) {
  8126. generateRecvonlySSRC();
  8127. }
  8128. logger.info('No SSRC in video recvonly stream' +
  8129. ' - adding SSRC: ' + localRecvOnlySSRC);
  8130. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  8131. ' cname:' + localRecvOnlyCName + '\r\n' +
  8132. 'a=ssrc:' + localRecvOnlySSRC +
  8133. ' msid:' + localRecvOnlyMSID + '\r\n' +
  8134. 'a=ssrc:' + localRecvOnlySSRC +
  8135. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  8136. 'a=ssrc:' + localRecvOnlySSRC +
  8137. ' label:' + localRecvOnlyLabel + '\r\n';
  8138. localDescription.sdp = sdp.session + sdp.media.join('');
  8139. }
  8140. return localDescription;
  8141. },
  8142. /**
  8143. * Method must be called before 'source-add' notification is sent. In case
  8144. * we have local video SSRC advertised already it will be removed from the
  8145. * notification. If no other SSRCs are described by given IQ null will be
  8146. * returned which means that there is no point in sending the notification.
  8147. * @param sourceAdd 'source-add' Jingle IQ to be processed
  8148. * @returns modified 'source-add' IQ which can be sent to the focus or
  8149. * <tt>null</tt> if no notification shall be sent. It is no longer
  8150. * a Strophe IQ Builder instance, but DOM element tree.
  8151. */
  8152. processSourceAdd: function (sourceAdd) {
  8153. if (!isEnabled)
  8154. return sourceAdd;
  8155. if (!localVideoSSRC) {
  8156. // Store local SSRC if available
  8157. storeLocalVideoSSRC(sourceAdd);
  8158. return sourceAdd;
  8159. } else {
  8160. return filterOutSource(sourceAdd, 'source-add');
  8161. }
  8162. },
  8163. /**
  8164. * Method must be called before 'source-remove' notification is sent.
  8165. * Removes local video SSRC from the notification. If there are no other
  8166. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  8167. * means that there is no point in sending the notification.
  8168. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  8169. * @returns modified 'source-remove' IQ which can be sent to the focus or
  8170. * <tt>null</tt> if no notification shall be sent. It is no longer
  8171. * a Strophe IQ Builder instance, but DOM element tree.
  8172. */
  8173. processSourceRemove: function (sourceRemove) {
  8174. if (!isEnabled)
  8175. return sourceRemove;
  8176. return filterOutSource(sourceRemove, 'source-remove');
  8177. },
  8178. /**
  8179. * Turns the hack on or off
  8180. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  8181. * to disable it
  8182. */
  8183. setEnabled: function (enabled) {
  8184. isEnabled = enabled;
  8185. }
  8186. };
  8187. module.exports = LocalSSRCReplacement;
  8188. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  8189. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":48}],30:[function(require,module,exports){
  8190. (function (__filename){
  8191. /* jshint -W117 */
  8192. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8193. var SDPUtil = require("./SDPUtil");
  8194. // SDP STUFF
  8195. function SDP(sdp) {
  8196. /**
  8197. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  8198. * @type {boolean}
  8199. */
  8200. this.removeTcpCandidates = false;
  8201. /**
  8202. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  8203. * @type {boolean}
  8204. */
  8205. this.removeUdpCandidates = false;
  8206. this.media = sdp.split('\r\nm=');
  8207. for (var i = 1; i < this.media.length; i++) {
  8208. this.media[i] = 'm=' + this.media[i];
  8209. if (i != this.media.length - 1) {
  8210. this.media[i] += '\r\n';
  8211. }
  8212. }
  8213. this.session = this.media.shift() + '\r\n';
  8214. this.raw = this.session + this.media.join('');
  8215. }
  8216. /**
  8217. * Returns map of MediaChannel mapped per channel idx.
  8218. */
  8219. SDP.prototype.getMediaSsrcMap = function() {
  8220. var self = this;
  8221. var media_ssrcs = {};
  8222. var tmp;
  8223. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  8224. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  8225. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  8226. var media = {
  8227. mediaindex: mediaindex,
  8228. mid: mid,
  8229. ssrcs: {},
  8230. ssrcGroups: []
  8231. };
  8232. media_ssrcs[mediaindex] = media;
  8233. tmp.forEach(function (line) {
  8234. var linessrc = line.substring(7).split(' ')[0];
  8235. // allocate new ChannelSsrc
  8236. if(!media.ssrcs[linessrc]) {
  8237. media.ssrcs[linessrc] = {
  8238. ssrc: linessrc,
  8239. lines: []
  8240. };
  8241. }
  8242. media.ssrcs[linessrc].lines.push(line);
  8243. });
  8244. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  8245. tmp.forEach(function(line){
  8246. var idx = line.indexOf(' ');
  8247. var semantics = line.substr(0, idx).substr(13);
  8248. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8249. if (ssrcs.length) {
  8250. media.ssrcGroups.push({
  8251. semantics: semantics,
  8252. ssrcs: ssrcs
  8253. });
  8254. }
  8255. });
  8256. }
  8257. return media_ssrcs;
  8258. };
  8259. /**
  8260. * Returns <tt>true</tt> if this SDP contains given SSRC.
  8261. * @param ssrc the ssrc to check.
  8262. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  8263. */
  8264. SDP.prototype.containsSSRC = function (ssrc) {
  8265. // FIXME this code is really strange - improve it if you can
  8266. var medias = this.getMediaSsrcMap();
  8267. var result = false;
  8268. Object.keys(medias).forEach(function (mediaindex) {
  8269. if (result)
  8270. return;
  8271. if (medias[mediaindex].ssrcs[ssrc]) {
  8272. result = true;
  8273. }
  8274. });
  8275. return result;
  8276. };
  8277. // remove iSAC and CN from SDP
  8278. SDP.prototype.mangle = function () {
  8279. var i, j, mline, lines, rtpmap, newdesc;
  8280. for (i = 0; i < this.media.length; i++) {
  8281. lines = this.media[i].split('\r\n');
  8282. lines.pop(); // remove empty last element
  8283. mline = SDPUtil.parse_mline(lines.shift());
  8284. if (mline.media != 'audio')
  8285. continue;
  8286. newdesc = '';
  8287. mline.fmt.length = 0;
  8288. for (j = 0; j < lines.length; j++) {
  8289. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  8290. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  8291. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  8292. continue;
  8293. mline.fmt.push(rtpmap.id);
  8294. newdesc += lines[j] + '\r\n';
  8295. } else {
  8296. newdesc += lines[j] + '\r\n';
  8297. }
  8298. }
  8299. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  8300. this.media[i] += newdesc;
  8301. }
  8302. this.raw = this.session + this.media.join('');
  8303. };
  8304. // remove lines matching prefix from session section
  8305. SDP.prototype.removeSessionLines = function(prefix) {
  8306. var self = this;
  8307. var lines = SDPUtil.find_lines(this.session, prefix);
  8308. lines.forEach(function(line) {
  8309. self.session = self.session.replace(line + '\r\n', '');
  8310. });
  8311. this.raw = this.session + this.media.join('');
  8312. return lines;
  8313. }
  8314. // remove lines matching prefix from a media section specified by mediaindex
  8315. // TODO: non-numeric mediaindex could match mid
  8316. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  8317. var self = this;
  8318. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  8319. lines.forEach(function(line) {
  8320. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  8321. });
  8322. this.raw = this.session + this.media.join('');
  8323. return lines;
  8324. }
  8325. // add content's to a jingle element
  8326. SDP.prototype.toJingle = function (elem, thecreator) {
  8327. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  8328. var self = this;
  8329. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  8330. // new bundle plan
  8331. if (SDPUtil.find_line(this.session, 'a=group:')) {
  8332. lines = SDPUtil.find_lines(this.session, 'a=group:');
  8333. for (i = 0; i < lines.length; i++) {
  8334. tmp = lines[i].split(' ');
  8335. var semantics = tmp.shift().substr(8);
  8336. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  8337. for (j = 0; j < tmp.length; j++) {
  8338. elem.c('content', {name: tmp[j]}).up();
  8339. }
  8340. elem.up();
  8341. }
  8342. }
  8343. for (i = 0; i < this.media.length; i++) {
  8344. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  8345. if (!(mline.media === 'audio' ||
  8346. mline.media === 'video' ||
  8347. mline.media === 'application'))
  8348. {
  8349. continue;
  8350. }
  8351. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  8352. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  8353. } else {
  8354. ssrc = false;
  8355. }
  8356. elem.c('content', {creator: thecreator, name: mline.media});
  8357. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  8358. // prefer identifier from a=mid if present
  8359. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  8360. elem.attrs({ name: mid });
  8361. }
  8362. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  8363. elem.c('description',
  8364. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  8365. media: mline.media });
  8366. if (ssrc) {
  8367. elem.attrs({ssrc: ssrc});
  8368. }
  8369. for (j = 0; j < mline.fmt.length; j++) {
  8370. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  8371. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  8372. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  8373. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  8374. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  8375. for (k = 0; k < tmp.length; k++) {
  8376. elem.c('parameter', tmp[k]).up();
  8377. }
  8378. }
  8379. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  8380. elem.up();
  8381. }
  8382. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  8383. elem.c('encryption', {required: 1});
  8384. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  8385. crypto.forEach(function(line) {
  8386. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  8387. });
  8388. elem.up(); // end of encryption
  8389. }
  8390. if (ssrc) {
  8391. // new style mapping
  8392. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8393. // FIXME: group by ssrc and support multiple different ssrcs
  8394. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  8395. if(ssrclines.length > 0) {
  8396. ssrclines.forEach(function (line) {
  8397. var idx = line.indexOf(' ');
  8398. var linessrc = line.substr(0, idx).substr(7);
  8399. if (linessrc != ssrc) {
  8400. elem.up();
  8401. ssrc = linessrc;
  8402. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8403. }
  8404. var kv = line.substr(idx + 1);
  8405. elem.c('parameter');
  8406. if (kv.indexOf(':') == -1) {
  8407. elem.attrs({ name: kv });
  8408. } else {
  8409. var k = kv.split(':', 2)[0];
  8410. elem.attrs({ name: k });
  8411. var v = kv.split(':', 2)[1];
  8412. v = SDPUtil.filter_special_chars(v);
  8413. elem.attrs({ value: v });
  8414. }
  8415. elem.up();
  8416. });
  8417. } else {
  8418. elem.up();
  8419. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8420. elem.c('parameter');
  8421. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  8422. elem.up();
  8423. var msid = null;
  8424. if(mline.media == "audio")
  8425. {
  8426. msid = APP.RTC.localAudio._getId();
  8427. }
  8428. else
  8429. {
  8430. msid = APP.RTC.localVideo._getId();
  8431. }
  8432. if(msid != null)
  8433. {
  8434. msid = SDPUtil.filter_special_chars(msid);
  8435. elem.c('parameter');
  8436. elem.attrs({name: "msid", value:msid});
  8437. elem.up();
  8438. elem.c('parameter');
  8439. elem.attrs({name: "mslabel", value:msid});
  8440. elem.up();
  8441. elem.c('parameter');
  8442. elem.attrs({name: "label", value:msid});
  8443. elem.up();
  8444. }
  8445. }
  8446. elem.up();
  8447. // XEP-0339 handle ssrc-group attributes
  8448. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  8449. ssrc_group_lines.forEach(function(line) {
  8450. var idx = line.indexOf(' ');
  8451. var semantics = line.substr(0, idx).substr(13);
  8452. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8453. if (ssrcs.length) {
  8454. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8455. ssrcs.forEach(function(ssrc) {
  8456. elem.c('source', { ssrc: ssrc })
  8457. .up();
  8458. });
  8459. elem.up();
  8460. }
  8461. });
  8462. }
  8463. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  8464. elem.c('rtcp-mux').up();
  8465. }
  8466. // XEP-0293 -- map a=rtcp-fb:*
  8467. this.rtcpFbToJingle(i, elem, '*');
  8468. // XEP-0294
  8469. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  8470. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  8471. for (j = 0; j < lines.length; j++) {
  8472. tmp = SDPUtil.parse_extmap(lines[j]);
  8473. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  8474. uri: tmp.uri,
  8475. id: tmp.value });
  8476. if (tmp.hasOwnProperty('direction')) {
  8477. switch (tmp.direction) {
  8478. case 'sendonly':
  8479. elem.attrs({senders: 'responder'});
  8480. break;
  8481. case 'recvonly':
  8482. elem.attrs({senders: 'initiator'});
  8483. break;
  8484. case 'sendrecv':
  8485. elem.attrs({senders: 'both'});
  8486. break;
  8487. case 'inactive':
  8488. elem.attrs({senders: 'none'});
  8489. break;
  8490. }
  8491. }
  8492. // TODO: handle params
  8493. elem.up();
  8494. }
  8495. }
  8496. elem.up(); // end of description
  8497. }
  8498. // map ice-ufrag/pwd, dtls fingerprint, candidates
  8499. this.transportToJingle(i, elem);
  8500. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  8501. elem.attrs({senders: 'both'});
  8502. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  8503. elem.attrs({senders: 'initiator'});
  8504. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  8505. elem.attrs({senders: 'responder'});
  8506. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  8507. elem.attrs({senders: 'none'});
  8508. }
  8509. if (mline.port == '0') {
  8510. // estos hack to reject an m-line
  8511. elem.attrs({senders: 'rejected'});
  8512. }
  8513. elem.up(); // end of content
  8514. }
  8515. elem.up();
  8516. return elem;
  8517. };
  8518. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  8519. var tmp, sctpmap, sctpAttrs, fingerprints;
  8520. var self = this;
  8521. elem.c('transport');
  8522. // XEP-0343 DTLS/SCTP
  8523. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  8524. {
  8525. sctpmap = SDPUtil.find_line(
  8526. this.media[mediaindex], 'a=sctpmap:', self.session);
  8527. if (sctpmap)
  8528. {
  8529. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  8530. elem.c('sctpmap',
  8531. {
  8532. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  8533. number: sctpAttrs[0], /* SCTP port */
  8534. protocol: sctpAttrs[1] /* protocol */
  8535. });
  8536. // Optional stream count attribute
  8537. if (sctpAttrs.length > 2)
  8538. elem.attrs({ streams: sctpAttrs[2]});
  8539. elem.up();
  8540. }
  8541. }
  8542. // XEP-0320
  8543. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  8544. fingerprints.forEach(function(line) {
  8545. tmp = SDPUtil.parse_fingerprint(line);
  8546. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  8547. elem.c('fingerprint').t(tmp.fingerprint);
  8548. delete tmp.fingerprint;
  8549. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  8550. if (line) {
  8551. tmp.setup = line.substr(8);
  8552. }
  8553. elem.attrs(tmp);
  8554. elem.up(); // end of fingerprint
  8555. });
  8556. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  8557. if (tmp) {
  8558. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  8559. elem.attrs(tmp);
  8560. // XEP-0176
  8561. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  8562. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  8563. lines.forEach(function (line) {
  8564. var candidate = SDPUtil.candidateToJingle(line);
  8565. var protocol = (candidate &&
  8566. typeof candidate.protocol === 'string')
  8567. ? candidate.protocol.toLowerCase() : '';
  8568. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8569. (self.removeUdpCandidates && protocol === 'udp')) {
  8570. return;
  8571. }
  8572. elem.c('candidate', candidate).up();
  8573. });
  8574. }
  8575. }
  8576. elem.up(); // end of transport
  8577. }
  8578. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  8579. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  8580. lines.forEach(function (line) {
  8581. var tmp = SDPUtil.parse_rtcpfb(line);
  8582. if (tmp.type == 'trr-int') {
  8583. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  8584. elem.up();
  8585. } else {
  8586. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  8587. if (tmp.params.length > 0) {
  8588. elem.attrs({'subtype': tmp.params[0]});
  8589. }
  8590. elem.up();
  8591. }
  8592. });
  8593. };
  8594. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8595. var media = '';
  8596. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8597. if (tmp.length) {
  8598. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8599. if (tmp.attr('value')) {
  8600. media += tmp.attr('value');
  8601. } else {
  8602. media += '0';
  8603. }
  8604. media += '\r\n';
  8605. }
  8606. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8607. tmp.each(function () {
  8608. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8609. if ($(this).attr('subtype')) {
  8610. media += ' ' + $(this).attr('subtype');
  8611. }
  8612. media += '\r\n';
  8613. });
  8614. return media;
  8615. };
  8616. // construct an SDP from a jingle stanza
  8617. SDP.prototype.fromJingle = function (jingle) {
  8618. var self = this;
  8619. this.raw = 'v=0\r\n' +
  8620. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8621. 's=-\r\n' +
  8622. 't=0 0\r\n';
  8623. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8624. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8625. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8626. var contents = $(group).find('>content').map(function (idx, content) {
  8627. return content.getAttribute('name');
  8628. }).get();
  8629. if (contents.length > 0) {
  8630. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8631. }
  8632. });
  8633. }
  8634. this.session = this.raw;
  8635. jingle.find('>content').each(function () {
  8636. var m = self.jingle2media($(this));
  8637. self.media.push(m);
  8638. });
  8639. // reconstruct msid-semantic -- apparently not necessary
  8640. /*
  8641. var msid = SDPUtil.parse_ssrc(this.raw);
  8642. if (msid.hasOwnProperty('mslabel')) {
  8643. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8644. }
  8645. */
  8646. this.raw = this.session + this.media.join('');
  8647. };
  8648. // translate a jingle content element into an an SDP media part
  8649. SDP.prototype.jingle2media = function (content) {
  8650. var media = '',
  8651. desc = content.find('description'),
  8652. ssrc = desc.attr('ssrc'),
  8653. self = this,
  8654. tmp;
  8655. var sctp = content.find(
  8656. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8657. tmp = { media: desc.attr('media') };
  8658. tmp.port = '1';
  8659. if (content.attr('senders') == 'rejected') {
  8660. // estos hack to reject an m-line.
  8661. tmp.port = '0';
  8662. }
  8663. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8664. if (sctp.length)
  8665. tmp.proto = 'DTLS/SCTP';
  8666. else
  8667. tmp.proto = 'RTP/SAVPF';
  8668. } else {
  8669. tmp.proto = 'RTP/AVPF';
  8670. }
  8671. if (!sctp.length) {
  8672. tmp.fmt = desc.find('payload-type').map(
  8673. function () { return this.getAttribute('id'); }).get();
  8674. media += SDPUtil.build_mline(tmp) + '\r\n';
  8675. } else {
  8676. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8677. media += 'a=sctpmap:' + sctp.attr('number') +
  8678. ' ' + sctp.attr('protocol');
  8679. var streamCount = sctp.attr('streams');
  8680. if (streamCount)
  8681. media += ' ' + streamCount + '\r\n';
  8682. else
  8683. media += '\r\n';
  8684. }
  8685. media += 'c=IN IP4 0.0.0.0\r\n';
  8686. if (!sctp.length)
  8687. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8688. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8689. if (tmp.length) {
  8690. if (tmp.attr('ufrag')) {
  8691. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8692. }
  8693. if (tmp.attr('pwd')) {
  8694. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8695. }
  8696. tmp.find('>fingerprint').each(function () {
  8697. // FIXME: check namespace at some point
  8698. media += 'a=fingerprint:' + this.getAttribute('hash');
  8699. media += ' ' + $(this).text();
  8700. media += '\r\n';
  8701. if (this.getAttribute('setup')) {
  8702. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8703. }
  8704. });
  8705. }
  8706. switch (content.attr('senders')) {
  8707. case 'initiator':
  8708. media += 'a=sendonly\r\n';
  8709. break;
  8710. case 'responder':
  8711. media += 'a=recvonly\r\n';
  8712. break;
  8713. case 'none':
  8714. media += 'a=inactive\r\n';
  8715. break;
  8716. case 'both':
  8717. media += 'a=sendrecv\r\n';
  8718. break;
  8719. }
  8720. media += 'a=mid:' + content.attr('name') + '\r\n';
  8721. // <description><rtcp-mux/></description>
  8722. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8723. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8724. if (desc.find('rtcp-mux').length) {
  8725. media += 'a=rtcp-mux\r\n';
  8726. }
  8727. if (desc.find('encryption').length) {
  8728. desc.find('encryption>crypto').each(function () {
  8729. media += 'a=crypto:' + this.getAttribute('tag');
  8730. media += ' ' + this.getAttribute('crypto-suite');
  8731. media += ' ' + this.getAttribute('key-params');
  8732. if (this.getAttribute('session-params')) {
  8733. media += ' ' + this.getAttribute('session-params');
  8734. }
  8735. media += '\r\n';
  8736. });
  8737. }
  8738. desc.find('payload-type').each(function () {
  8739. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8740. if ($(this).find('>parameter').length) {
  8741. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8742. media += $(this).find('parameter').map(function () {
  8743. return (this.getAttribute('name')
  8744. ? (this.getAttribute('name') + '=') : '') +
  8745. this.getAttribute('value');
  8746. }).get().join('; ');
  8747. media += '\r\n';
  8748. }
  8749. // xep-0293
  8750. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8751. });
  8752. // xep-0293
  8753. media += self.rtcpFbFromJingle(desc, '*');
  8754. // xep-0294
  8755. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8756. tmp.each(function () {
  8757. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8758. });
  8759. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8760. var protocol = this.getAttribute('protocol');
  8761. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8762. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8763. (self.removeUdpCandidates && protocol === 'udp')) {
  8764. return;
  8765. }
  8766. media += SDPUtil.candidateFromJingle(this);
  8767. });
  8768. // XEP-0339 handle ssrc-group attributes
  8769. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8770. var semantics = this.getAttribute('semantics');
  8771. var ssrcs = $(this).find('>source').map(function() {
  8772. return this.getAttribute('ssrc');
  8773. }).get();
  8774. if (ssrcs.length) {
  8775. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8776. }
  8777. });
  8778. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8779. tmp.each(function () {
  8780. var ssrc = this.getAttribute('ssrc');
  8781. $(this).find('>parameter').each(function () {
  8782. var name = this.getAttribute('name');
  8783. var value = this.getAttribute('value');
  8784. value = SDPUtil.filter_special_chars(value);
  8785. media += 'a=ssrc:' + ssrc + ' ' + name;
  8786. if (value && value.length)
  8787. media += ':' + value;
  8788. media += '\r\n';
  8789. });
  8790. });
  8791. return media;
  8792. };
  8793. module.exports = SDP;
  8794. }).call(this,"/modules/xmpp/SDP.js")
  8795. },{"./SDPUtil":32,"jitsi-meet-logger":48}],31:[function(require,module,exports){
  8796. var SDPUtil = require("./SDPUtil");
  8797. function SDPDiffer(mySDP, otherSDP)
  8798. {
  8799. this.mySDP = mySDP;
  8800. this.otherSDP = otherSDP;
  8801. }
  8802. /**
  8803. * Returns map of MediaChannel that contains media contained in
  8804. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8805. */
  8806. SDPDiffer.prototype.getNewMedia = function() {
  8807. // this could be useful in Array.prototype.
  8808. function arrayEquals(array) {
  8809. // if the other array is a falsy value, return
  8810. if (!array)
  8811. return false;
  8812. // compare lengths - can save a lot of time
  8813. if (this.length != array.length)
  8814. return false;
  8815. for (var i = 0, l=this.length; i < l; i++) {
  8816. // Check if we have nested arrays
  8817. if (this[i] instanceof Array && array[i] instanceof Array) {
  8818. // recurse into the nested arrays
  8819. if (!this[i].equals(array[i]))
  8820. return false;
  8821. }
  8822. else if (this[i] != array[i]) {
  8823. // Warning - two different object instances will never be
  8824. // equal: {x:20} != {x:20}
  8825. return false;
  8826. }
  8827. }
  8828. return true;
  8829. }
  8830. var myMedias = this.mySDP.getMediaSsrcMap();
  8831. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8832. var newMedia = {};
  8833. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8834. var myMedia = myMedias[othersMediaIdx];
  8835. var othersMedia = othersMedias[othersMediaIdx];
  8836. if(!myMedia && othersMedia) {
  8837. // Add whole channel
  8838. newMedia[othersMediaIdx] = othersMedia;
  8839. return;
  8840. }
  8841. // Look for new ssrcs across the channel
  8842. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8843. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8844. // Allocate channel if we've found ssrc that doesn't exist in
  8845. // our channel
  8846. if(!newMedia[othersMediaIdx]){
  8847. newMedia[othersMediaIdx] = {
  8848. mediaindex: othersMedia.mediaindex,
  8849. mid: othersMedia.mid,
  8850. ssrcs: {},
  8851. ssrcGroups: []
  8852. };
  8853. }
  8854. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8855. }
  8856. });
  8857. // Look for new ssrc groups across the channels
  8858. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8859. // try to match the other ssrc-group with an ssrc-group of ours
  8860. var matched = false;
  8861. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8862. var mySsrcGroup = myMedia.ssrcGroups[i];
  8863. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8864. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8865. [mySsrcGroup.ssrcs])) {
  8866. matched = true;
  8867. break;
  8868. }
  8869. }
  8870. if (!matched) {
  8871. // Allocate channel if we've found an ssrc-group that doesn't
  8872. // exist in our channel
  8873. if(!newMedia[othersMediaIdx]){
  8874. newMedia[othersMediaIdx] = {
  8875. mediaindex: othersMedia.mediaindex,
  8876. mid: othersMedia.mid,
  8877. ssrcs: {},
  8878. ssrcGroups: []
  8879. };
  8880. }
  8881. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8882. }
  8883. });
  8884. });
  8885. return newMedia;
  8886. };
  8887. /**
  8888. * TODO: document!
  8889. */
  8890. SDPDiffer.prototype.toJingle = function(modify) {
  8891. var sdpMediaSsrcs = this.getNewMedia();
  8892. var modified = false;
  8893. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8894. modified = true;
  8895. var media = sdpMediaSsrcs[mediaindex];
  8896. modify.c('content', {name: media.mid});
  8897. modify.c('description',
  8898. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8899. // FIXME: not completely sure this operates on blocks and / or handles
  8900. // different ssrcs correctly
  8901. // generate sources from lines
  8902. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8903. var mediaSsrc = media.ssrcs[ssrcNum];
  8904. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8905. modify.attrs({ssrc: mediaSsrc.ssrc});
  8906. // iterate over ssrc lines
  8907. mediaSsrc.lines.forEach(function (line) {
  8908. var idx = line.indexOf(' ');
  8909. var kv = line.substr(idx + 1);
  8910. modify.c('parameter');
  8911. if (kv.indexOf(':') == -1) {
  8912. modify.attrs({ name: kv });
  8913. } else {
  8914. var nv = kv.split(':', 2);
  8915. var name = nv[0];
  8916. var value = SDPUtil.filter_special_chars(nv[1]);
  8917. modify.attrs({ name: name });
  8918. modify.attrs({ value: value });
  8919. }
  8920. modify.up(); // end of parameter
  8921. });
  8922. modify.up(); // end of source
  8923. });
  8924. // generate source groups from lines
  8925. media.ssrcGroups.forEach(function(ssrcGroup) {
  8926. if (ssrcGroup.ssrcs.length) {
  8927. modify.c('ssrc-group', {
  8928. semantics: ssrcGroup.semantics,
  8929. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8930. });
  8931. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8932. modify.c('source', { ssrc: ssrc })
  8933. .up(); // end of source
  8934. });
  8935. modify.up(); // end of ssrc-group
  8936. }
  8937. });
  8938. modify.up(); // end of description
  8939. modify.up(); // end of content
  8940. });
  8941. return modified;
  8942. };
  8943. module.exports = SDPDiffer;
  8944. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8945. (function (__filename){
  8946. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8947. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8948. SDPUtil = {
  8949. filter_special_chars: function (text) {
  8950. return text.replace(/[\\\/\{,\}\+]/g, "");
  8951. },
  8952. iceparams: function (mediadesc, sessiondesc) {
  8953. var data = null;
  8954. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8955. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8956. data = {
  8957. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8958. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8959. };
  8960. }
  8961. return data;
  8962. },
  8963. parse_iceufrag: function (line) {
  8964. return line.substring(12);
  8965. },
  8966. build_iceufrag: function (frag) {
  8967. return 'a=ice-ufrag:' + frag;
  8968. },
  8969. parse_icepwd: function (line) {
  8970. return line.substring(10);
  8971. },
  8972. build_icepwd: function (pwd) {
  8973. return 'a=ice-pwd:' + pwd;
  8974. },
  8975. parse_mid: function (line) {
  8976. return line.substring(6);
  8977. },
  8978. parse_mline: function (line) {
  8979. var parts = line.substring(2).split(' '),
  8980. data = {};
  8981. data.media = parts.shift();
  8982. data.port = parts.shift();
  8983. data.proto = parts.shift();
  8984. if (parts[parts.length - 1] === '') { // trailing whitespace
  8985. parts.pop();
  8986. }
  8987. data.fmt = parts;
  8988. return data;
  8989. },
  8990. build_mline: function (mline) {
  8991. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8992. },
  8993. parse_rtpmap: function (line) {
  8994. var parts = line.substring(9).split(' '),
  8995. data = {};
  8996. data.id = parts.shift();
  8997. parts = parts[0].split('/');
  8998. data.name = parts.shift();
  8999. data.clockrate = parts.shift();
  9000. data.channels = parts.length ? parts.shift() : '1';
  9001. return data;
  9002. },
  9003. /**
  9004. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  9005. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  9006. * @returns [SCTP port number, protocol, streams]
  9007. */
  9008. parse_sctpmap: function (line)
  9009. {
  9010. var parts = line.substring(10).split(' ');
  9011. var sctpPort = parts[0];
  9012. var protocol = parts[1];
  9013. // Stream count is optional
  9014. var streamCount = parts.length > 2 ? parts[2] : null;
  9015. return [sctpPort, protocol, streamCount];// SCTP port
  9016. },
  9017. build_rtpmap: function (el) {
  9018. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  9019. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  9020. line += '/' + el.getAttribute('channels');
  9021. }
  9022. return line;
  9023. },
  9024. parse_crypto: function (line) {
  9025. var parts = line.substring(9).split(' '),
  9026. data = {};
  9027. data.tag = parts.shift();
  9028. data['crypto-suite'] = parts.shift();
  9029. data['key-params'] = parts.shift();
  9030. if (parts.length) {
  9031. data['session-params'] = parts.join(' ');
  9032. }
  9033. return data;
  9034. },
  9035. parse_fingerprint: function (line) { // RFC 4572
  9036. var parts = line.substring(14).split(' '),
  9037. data = {};
  9038. data.hash = parts.shift();
  9039. data.fingerprint = parts.shift();
  9040. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  9041. return data;
  9042. },
  9043. parse_fmtp: function (line) {
  9044. var parts = line.split(' '),
  9045. i, key, value,
  9046. data = [];
  9047. parts.shift();
  9048. parts = parts.join(' ').split(';');
  9049. for (i = 0; i < parts.length; i++) {
  9050. key = parts[i].split('=')[0];
  9051. while (key.length && key[0] == ' ') {
  9052. key = key.substring(1);
  9053. }
  9054. value = parts[i].split('=')[1];
  9055. if (key && value) {
  9056. data.push({name: key, value: value});
  9057. } else if (key) {
  9058. // rfc 4733 (DTMF) style stuff
  9059. data.push({name: '', value: key});
  9060. }
  9061. }
  9062. return data;
  9063. },
  9064. parse_icecandidate: function (line) {
  9065. var candidate = {},
  9066. elems = line.split(' ');
  9067. candidate.foundation = elems[0].substring(12);
  9068. candidate.component = elems[1];
  9069. candidate.protocol = elems[2].toLowerCase();
  9070. candidate.priority = elems[3];
  9071. candidate.ip = elems[4];
  9072. candidate.port = elems[5];
  9073. // elems[6] => "typ"
  9074. candidate.type = elems[7];
  9075. candidate.generation = 0; // default value, may be overwritten below
  9076. for (var i = 8; i < elems.length; i += 2) {
  9077. switch (elems[i]) {
  9078. case 'raddr':
  9079. candidate['rel-addr'] = elems[i + 1];
  9080. break;
  9081. case 'rport':
  9082. candidate['rel-port'] = elems[i + 1];
  9083. break;
  9084. case 'generation':
  9085. candidate.generation = elems[i + 1];
  9086. break;
  9087. case 'tcptype':
  9088. candidate.tcptype = elems[i + 1];
  9089. break;
  9090. default: // TODO
  9091. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9092. }
  9093. }
  9094. candidate.network = '1';
  9095. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9096. return candidate;
  9097. },
  9098. build_icecandidate: function (cand) {
  9099. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9100. line += ' ';
  9101. switch (cand.type) {
  9102. case 'srflx':
  9103. case 'prflx':
  9104. case 'relay':
  9105. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9106. line += 'raddr';
  9107. line += ' ';
  9108. line += cand['rel-addr'];
  9109. line += ' ';
  9110. line += 'rport';
  9111. line += ' ';
  9112. line += cand['rel-port'];
  9113. line += ' ';
  9114. }
  9115. break;
  9116. }
  9117. if (cand.hasOwnAttribute('tcptype')) {
  9118. line += 'tcptype';
  9119. line += ' ';
  9120. line += cand.tcptype;
  9121. line += ' ';
  9122. }
  9123. line += 'generation';
  9124. line += ' ';
  9125. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9126. return line;
  9127. },
  9128. parse_ssrc: function (desc) {
  9129. // proprietary mapping of a=ssrc lines
  9130. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9131. // and parse according to that
  9132. var lines = desc.split('\r\n'),
  9133. data = {};
  9134. for (var i = 0; i < lines.length; i++) {
  9135. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9136. var idx = lines[i].indexOf(' ');
  9137. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9138. }
  9139. }
  9140. return data;
  9141. },
  9142. parse_rtcpfb: function (line) {
  9143. var parts = line.substr(10).split(' ');
  9144. var data = {};
  9145. data.pt = parts.shift();
  9146. data.type = parts.shift();
  9147. data.params = parts;
  9148. return data;
  9149. },
  9150. parse_extmap: function (line) {
  9151. var parts = line.substr(9).split(' ');
  9152. var data = {};
  9153. data.value = parts.shift();
  9154. if (data.value.indexOf('/') != -1) {
  9155. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9156. data.value = data.value.substr(0, data.value.indexOf('/'));
  9157. } else {
  9158. data.direction = 'both';
  9159. }
  9160. data.uri = parts.shift();
  9161. data.params = parts;
  9162. return data;
  9163. },
  9164. find_line: function (haystack, needle, sessionpart) {
  9165. var lines = haystack.split('\r\n');
  9166. for (var i = 0; i < lines.length; i++) {
  9167. if (lines[i].substring(0, needle.length) == needle) {
  9168. return lines[i];
  9169. }
  9170. }
  9171. if (!sessionpart) {
  9172. return false;
  9173. }
  9174. // search session part
  9175. lines = sessionpart.split('\r\n');
  9176. for (var j = 0; j < lines.length; j++) {
  9177. if (lines[j].substring(0, needle.length) == needle) {
  9178. return lines[j];
  9179. }
  9180. }
  9181. return false;
  9182. },
  9183. find_lines: function (haystack, needle, sessionpart) {
  9184. var lines = haystack.split('\r\n'),
  9185. needles = [];
  9186. for (var i = 0; i < lines.length; i++) {
  9187. if (lines[i].substring(0, needle.length) == needle)
  9188. needles.push(lines[i]);
  9189. }
  9190. if (needles.length || !sessionpart) {
  9191. return needles;
  9192. }
  9193. // search session part
  9194. lines = sessionpart.split('\r\n');
  9195. for (var j = 0; j < lines.length; j++) {
  9196. if (lines[j].substring(0, needle.length) == needle) {
  9197. needles.push(lines[j]);
  9198. }
  9199. }
  9200. return needles;
  9201. },
  9202. candidateToJingle: function (line) {
  9203. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  9204. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  9205. if (line.indexOf('candidate:') === 0) {
  9206. line = 'a=' + line;
  9207. } else if (line.substring(0, 12) != 'a=candidate:') {
  9208. logger.log('parseCandidate called with a line that is not a candidate line');
  9209. logger.log(line);
  9210. return null;
  9211. }
  9212. if (line.substring(line.length - 2) == '\r\n') // chomp it
  9213. line = line.substring(0, line.length - 2);
  9214. var candidate = {},
  9215. elems = line.split(' '),
  9216. i;
  9217. if (elems[6] != 'typ') {
  9218. logger.log('did not find typ in the right place');
  9219. logger.log(line);
  9220. return null;
  9221. }
  9222. candidate.foundation = elems[0].substring(12);
  9223. candidate.component = elems[1];
  9224. candidate.protocol = elems[2].toLowerCase();
  9225. candidate.priority = elems[3];
  9226. candidate.ip = elems[4];
  9227. candidate.port = elems[5];
  9228. // elems[6] => "typ"
  9229. candidate.type = elems[7];
  9230. candidate.generation = '0'; // default, may be overwritten below
  9231. for (i = 8; i < elems.length; i += 2) {
  9232. switch (elems[i]) {
  9233. case 'raddr':
  9234. candidate['rel-addr'] = elems[i + 1];
  9235. break;
  9236. case 'rport':
  9237. candidate['rel-port'] = elems[i + 1];
  9238. break;
  9239. case 'generation':
  9240. candidate.generation = elems[i + 1];
  9241. break;
  9242. case 'tcptype':
  9243. candidate.tcptype = elems[i + 1];
  9244. break;
  9245. default: // TODO
  9246. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9247. }
  9248. }
  9249. candidate.network = '1';
  9250. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9251. return candidate;
  9252. },
  9253. candidateFromJingle: function (cand) {
  9254. var line = 'a=candidate:';
  9255. line += cand.getAttribute('foundation');
  9256. line += ' ';
  9257. line += cand.getAttribute('component');
  9258. line += ' ';
  9259. var protocol = cand.getAttribute('protocol');
  9260. // use tcp candidates for FF
  9261. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  9262. protocol = 'tcp';
  9263. }
  9264. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  9265. line += ' ';
  9266. line += cand.getAttribute('priority');
  9267. line += ' ';
  9268. line += cand.getAttribute('ip');
  9269. line += ' ';
  9270. line += cand.getAttribute('port');
  9271. line += ' ';
  9272. line += 'typ';
  9273. line += ' ' + cand.getAttribute('type');
  9274. line += ' ';
  9275. switch (cand.getAttribute('type')) {
  9276. case 'srflx':
  9277. case 'prflx':
  9278. case 'relay':
  9279. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  9280. line += 'raddr';
  9281. line += ' ';
  9282. line += cand.getAttribute('rel-addr');
  9283. line += ' ';
  9284. line += 'rport';
  9285. line += ' ';
  9286. line += cand.getAttribute('rel-port');
  9287. line += ' ';
  9288. }
  9289. break;
  9290. }
  9291. if (protocol.toLowerCase() == 'tcp') {
  9292. line += 'tcptype';
  9293. line += ' ';
  9294. line += cand.getAttribute('tcptype');
  9295. line += ' ';
  9296. }
  9297. line += 'generation';
  9298. line += ' ';
  9299. line += cand.getAttribute('generation') || '0';
  9300. return line + '\r\n';
  9301. }
  9302. };
  9303. module.exports = SDPUtil;
  9304. }).call(this,"/modules/xmpp/SDPUtil.js")
  9305. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],33:[function(require,module,exports){
  9306. (function (__filename){
  9307. /* global $ */
  9308. var RTC = require('../RTC/RTC');
  9309. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9310. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  9311. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9312. var SSRCReplacement = require("./LocalSSRCReplacement");
  9313. function TraceablePeerConnection(ice_config, constraints, session) {
  9314. var self = this;
  9315. this.session = session;
  9316. var RTCPeerConnectionType = null;
  9317. if (RTCBrowserType.isFirefox()) {
  9318. RTCPeerConnectionType = mozRTCPeerConnection;
  9319. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  9320. RTCPeerConnectionType = RTCPeerConnection;
  9321. } else {
  9322. RTCPeerConnectionType = webkitRTCPeerConnection;
  9323. }
  9324. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  9325. this.updateLog = [];
  9326. this.stats = {};
  9327. this.statsinterval = null;
  9328. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9329. var Interop = require('sdp-interop').Interop;
  9330. this.interop = new Interop();
  9331. var Simulcast = require('sdp-simulcast');
  9332. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  9333. // override as desired
  9334. this.trace = function (what, info) {
  9335. /*logger.warn('WTRACE', what, info);
  9336. if (info && RTCBrowserType.isIExplorer()) {
  9337. if (info.length > 1024) {
  9338. logger.warn('WTRACE', what, info.substr(1024));
  9339. }
  9340. if (info.length > 2048) {
  9341. logger.warn('WTRACE', what, info.substr(2048));
  9342. }
  9343. }*/
  9344. self.updateLog.push({
  9345. time: new Date(),
  9346. type: what,
  9347. value: info || ""
  9348. });
  9349. };
  9350. this.onicecandidate = null;
  9351. this.peerconnection.onicecandidate = function (event) {
  9352. // FIXME: this causes stack overflow with Temasys Plugin
  9353. if (!RTCBrowserType.isTemasysPluginUsed())
  9354. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  9355. if (self.onicecandidate !== null) {
  9356. self.onicecandidate(event);
  9357. }
  9358. };
  9359. this.onaddstream = null;
  9360. this.peerconnection.onaddstream = function (event) {
  9361. self.trace('onaddstream', event.stream.id);
  9362. if (self.onaddstream !== null) {
  9363. self.onaddstream(event);
  9364. }
  9365. };
  9366. this.onremovestream = null;
  9367. this.peerconnection.onremovestream = function (event) {
  9368. self.trace('onremovestream', event.stream.id);
  9369. if (self.onremovestream !== null) {
  9370. self.onremovestream(event);
  9371. }
  9372. };
  9373. this.onsignalingstatechange = null;
  9374. this.peerconnection.onsignalingstatechange = function (event) {
  9375. self.trace('onsignalingstatechange', self.signalingState);
  9376. if (self.onsignalingstatechange !== null) {
  9377. self.onsignalingstatechange(event);
  9378. }
  9379. };
  9380. this.oniceconnectionstatechange = null;
  9381. this.peerconnection.oniceconnectionstatechange = function (event) {
  9382. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  9383. if (self.oniceconnectionstatechange !== null) {
  9384. self.oniceconnectionstatechange(event);
  9385. }
  9386. };
  9387. this.onnegotiationneeded = null;
  9388. this.peerconnection.onnegotiationneeded = function (event) {
  9389. self.trace('onnegotiationneeded');
  9390. if (self.onnegotiationneeded !== null) {
  9391. self.onnegotiationneeded(event);
  9392. }
  9393. };
  9394. self.ondatachannel = null;
  9395. this.peerconnection.ondatachannel = function (event) {
  9396. self.trace('ondatachannel', event);
  9397. if (self.ondatachannel !== null) {
  9398. self.ondatachannel(event);
  9399. }
  9400. };
  9401. // XXX: do all non-firefox browsers which we support also support this?
  9402. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  9403. this.statsinterval = window.setInterval(function() {
  9404. self.peerconnection.getStats(function(stats) {
  9405. var results = stats.result();
  9406. var now = new Date();
  9407. for (var i = 0; i < results.length; ++i) {
  9408. results[i].names().forEach(function (name) {
  9409. var id = results[i].id + '-' + name;
  9410. if (!self.stats[id]) {
  9411. self.stats[id] = {
  9412. startTime: now,
  9413. endTime: now,
  9414. values: [],
  9415. times: []
  9416. };
  9417. }
  9418. self.stats[id].values.push(results[i].stat(name));
  9419. self.stats[id].times.push(now.getTime());
  9420. if (self.stats[id].values.length > self.maxstats) {
  9421. self.stats[id].values.shift();
  9422. self.stats[id].times.shift();
  9423. }
  9424. self.stats[id].endTime = now;
  9425. });
  9426. }
  9427. });
  9428. }, 1000);
  9429. }
  9430. }
  9431. /**
  9432. * Returns a string representation of a SessionDescription object.
  9433. */
  9434. var dumpSDP = function(description) {
  9435. if (typeof description === 'undefined' || description == null) {
  9436. return '';
  9437. }
  9438. return 'type: ' + description.type + '\r\n' + description.sdp;
  9439. };
  9440. /**
  9441. * Takes a SessionDescription object and returns a "normalized" version.
  9442. * Currently it only takes care of ordering the a=ssrc lines.
  9443. */
  9444. var normalizePlanB = function(desc) {
  9445. if (typeof desc !== 'object' || desc === null ||
  9446. typeof desc.sdp !== 'string') {
  9447. logger.warn('An empty description was passed as an argument.');
  9448. return desc;
  9449. }
  9450. var transform = require('sdp-transform');
  9451. var session = transform.parse(desc.sdp);
  9452. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  9453. Array.isArray(session.media)) {
  9454. session.media.forEach(function (mLine) {
  9455. // Chrome appears to be picky about the order in which a=ssrc lines
  9456. // are listed in an m-line when rtx is enabled (and thus there are
  9457. // a=ssrc-group lines with FID semantics). Specifically if we have
  9458. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  9459. // the "a=ssrc:S1" lines, SRD fails.
  9460. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  9461. // first.
  9462. var firstSsrcs = [];
  9463. var newSsrcLines = [];
  9464. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  9465. mLine.ssrcGroups.forEach(function (group) {
  9466. if (typeof group.semantics !== 'undefined' &&
  9467. group.semantics === 'FID') {
  9468. if (typeof group.ssrcs !== 'undefined') {
  9469. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  9470. }
  9471. }
  9472. });
  9473. }
  9474. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  9475. var i;
  9476. for (i = 0; i<mLine.ssrcs.length; i++){
  9477. if (typeof mLine.ssrcs[i] === 'object'
  9478. && typeof mLine.ssrcs[i].id !== 'undefined'
  9479. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  9480. newSsrcLines.push(mLine.ssrcs[i]);
  9481. delete mLine.ssrcs[i];
  9482. }
  9483. }
  9484. for (i = 0; i<mLine.ssrcs.length; i++){
  9485. if (typeof mLine.ssrcs[i] !== 'undefined') {
  9486. newSsrcLines.push(mLine.ssrcs[i]);
  9487. }
  9488. }
  9489. mLine.ssrcs = newSsrcLines;
  9490. }
  9491. });
  9492. }
  9493. var resStr = transform.write(session);
  9494. return new RTCSessionDescription({
  9495. type: desc.type,
  9496. sdp: resStr
  9497. });
  9498. };
  9499. var getters = {
  9500. signalingState: function () {
  9501. return this.peerconnection.signalingState;
  9502. },
  9503. iceConnectionState: function () {
  9504. return this.peerconnection.iceConnectionState;
  9505. },
  9506. localDescription: function() {
  9507. var desc = this.peerconnection.localDescription;
  9508. // FIXME this should probably be after the Unified Plan -> Plan B
  9509. // transformation.
  9510. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  9511. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  9512. // if we're running on FF, transform to Plan B first.
  9513. if (RTCBrowserType.usesUnifiedPlan()) {
  9514. desc = this.interop.toPlanB(desc);
  9515. this.trace('getLocalDescription::postTransform (Plan B)',
  9516. dumpSDP(desc));
  9517. }
  9518. return desc;
  9519. },
  9520. remoteDescription: function() {
  9521. var desc = this.peerconnection.remoteDescription;
  9522. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  9523. // if we're running on FF, transform to Plan B first.
  9524. if (RTCBrowserType.usesUnifiedPlan()) {
  9525. desc = this.interop.toPlanB(desc);
  9526. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  9527. }
  9528. return desc;
  9529. }
  9530. };
  9531. Object.keys(getters).forEach(function (prop) {
  9532. Object.defineProperty(
  9533. TraceablePeerConnection.prototype,
  9534. prop, {
  9535. get: getters[prop]
  9536. }
  9537. );
  9538. });
  9539. TraceablePeerConnection.prototype.addStream = function (stream) {
  9540. this.trace('addStream', stream.id);
  9541. try
  9542. {
  9543. this.peerconnection.addStream(stream);
  9544. }
  9545. catch (e)
  9546. {
  9547. logger.error(e);
  9548. }
  9549. };
  9550. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  9551. this.trace('removeStream', stream.id);
  9552. if(stopStreams) {
  9553. RTC.stopMediaStream(stream);
  9554. }
  9555. try {
  9556. // FF doesn't support this yet.
  9557. if (this.peerconnection.removeStream)
  9558. this.peerconnection.removeStream(stream);
  9559. } catch (e) {
  9560. logger.error(e);
  9561. }
  9562. };
  9563. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  9564. this.trace('createDataChannel', label, opts);
  9565. return this.peerconnection.createDataChannel(label, opts);
  9566. };
  9567. TraceablePeerConnection.prototype.setLocalDescription
  9568. = function (description, successCallback, failureCallback) {
  9569. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  9570. // if we're running on FF, transform to Plan A first.
  9571. if (RTCBrowserType.usesUnifiedPlan()) {
  9572. description = this.interop.toUnifiedPlan(description);
  9573. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  9574. }
  9575. var self = this;
  9576. this.peerconnection.setLocalDescription(description,
  9577. function () {
  9578. self.trace('setLocalDescriptionOnSuccess');
  9579. successCallback();
  9580. },
  9581. function (err) {
  9582. self.trace('setLocalDescriptionOnFailure', err);
  9583. failureCallback(err);
  9584. }
  9585. );
  9586. /*
  9587. if (this.statsinterval === null && this.maxstats > 0) {
  9588. // start gathering stats
  9589. }
  9590. */
  9591. };
  9592. TraceablePeerConnection.prototype.setRemoteDescription
  9593. = function (description, successCallback, failureCallback) {
  9594. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9595. // TODO the focus should squeze or explode the remote simulcast
  9596. description = this.simulcast.mungeRemoteDescription(description);
  9597. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9598. // if we're running on FF, transform to Plan A first.
  9599. if (RTCBrowserType.usesUnifiedPlan()) {
  9600. description = this.interop.toUnifiedPlan(description);
  9601. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9602. }
  9603. if (RTCBrowserType.usesPlanB()) {
  9604. description = normalizePlanB(description);
  9605. }
  9606. var self = this;
  9607. this.peerconnection.setRemoteDescription(description,
  9608. function () {
  9609. self.trace('setRemoteDescriptionOnSuccess');
  9610. successCallback();
  9611. },
  9612. function (err) {
  9613. self.trace('setRemoteDescriptionOnFailure', err);
  9614. failureCallback(err);
  9615. }
  9616. );
  9617. /*
  9618. if (this.statsinterval === null && this.maxstats > 0) {
  9619. // start gathering stats
  9620. }
  9621. */
  9622. };
  9623. TraceablePeerConnection.prototype.close = function () {
  9624. this.trace('stop');
  9625. if (this.statsinterval !== null) {
  9626. window.clearInterval(this.statsinterval);
  9627. this.statsinterval = null;
  9628. }
  9629. this.peerconnection.close();
  9630. };
  9631. TraceablePeerConnection.prototype.createOffer
  9632. = function (successCallback, failureCallback, constraints) {
  9633. var self = this;
  9634. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9635. this.peerconnection.createOffer(
  9636. function (offer) {
  9637. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9638. // NOTE this is not tested because in meet the focus generates the
  9639. // offer.
  9640. // if we're running on FF, transform to Plan B first.
  9641. if (RTCBrowserType.usesUnifiedPlan()) {
  9642. offer = self.interop.toPlanB(offer);
  9643. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9644. }
  9645. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9646. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9647. offer = self.simulcast.mungeLocalDescription(offer);
  9648. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9649. }
  9650. successCallback(offer);
  9651. },
  9652. function(err) {
  9653. self.trace('createOfferOnFailure', err);
  9654. failureCallback(err);
  9655. },
  9656. constraints
  9657. );
  9658. };
  9659. TraceablePeerConnection.prototype.createAnswer
  9660. = function (successCallback, failureCallback, constraints) {
  9661. var self = this;
  9662. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9663. this.peerconnection.createAnswer(
  9664. function (answer) {
  9665. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9666. // if we're running on FF, transform to Plan A first.
  9667. if (RTCBrowserType.usesUnifiedPlan()) {
  9668. answer = self.interop.toPlanB(answer);
  9669. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9670. }
  9671. // munge local video SSRC
  9672. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9673. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9674. answer = self.simulcast.mungeLocalDescription(answer);
  9675. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9676. }
  9677. successCallback(answer);
  9678. },
  9679. function(err) {
  9680. self.trace('createAnswerOnFailure', err);
  9681. failureCallback(err);
  9682. },
  9683. constraints
  9684. );
  9685. };
  9686. TraceablePeerConnection.prototype.addIceCandidate
  9687. = function (candidate, successCallback, failureCallback) {
  9688. //var self = this;
  9689. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9690. this.peerconnection.addIceCandidate(candidate);
  9691. /* maybe later
  9692. this.peerconnection.addIceCandidate(candidate,
  9693. function () {
  9694. self.trace('addIceCandidateOnSuccess');
  9695. successCallback();
  9696. },
  9697. function (err) {
  9698. self.trace('addIceCandidateOnFailure', err);
  9699. failureCallback(err);
  9700. }
  9701. );
  9702. */
  9703. };
  9704. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9705. // TODO: Is this the correct way to handle Opera, Temasys?
  9706. if (RTCBrowserType.isFirefox()) {
  9707. // ignore for now...
  9708. if(!errback)
  9709. errback = function () {};
  9710. this.peerconnection.getStats(null, callback, errback);
  9711. } else {
  9712. this.peerconnection.getStats(callback);
  9713. }
  9714. };
  9715. module.exports = TraceablePeerConnection;
  9716. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9717. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":48,"sdp-interop":66,"sdp-simulcast":69,"sdp-transform":76}],34:[function(require,module,exports){
  9718. (function (__filename){
  9719. /* global $, $iq, Promise, Strophe */
  9720. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9721. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9722. var Settings = require("../settings/Settings");
  9723. var AuthenticationEvents
  9724. = require("../../service/authentication/AuthenticationEvents");
  9725. function createExpBackoffTimer(step) {
  9726. var count = 1;
  9727. return function (reset) {
  9728. // Reset call
  9729. if (reset) {
  9730. count = 1;
  9731. return;
  9732. }
  9733. // Calculate next timeout
  9734. var timeout = Math.pow(2, count - 1);
  9735. count += 1;
  9736. return timeout * step;
  9737. };
  9738. }
  9739. function Moderator(roomName, xmpp, emitter) {
  9740. this.roomName = roomName;
  9741. this.xmppService = xmpp;
  9742. this.getNextTimeout = createExpBackoffTimer(1000);
  9743. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9744. // External authentication stuff
  9745. this.externalAuthEnabled = false;
  9746. this.settings = new Settings(roomName);
  9747. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9748. // it will be enabled automatically if focus detects the component through
  9749. // service discovery.
  9750. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  9751. this.xmppService.options.hosts.call_control !== undefined;
  9752. this.eventEmitter = emitter;
  9753. this.connection = this.xmppService.connection;
  9754. this.focusUserJid;
  9755. //FIXME:
  9756. // Message listener that talks to POPUP window
  9757. function listener(event) {
  9758. if (event.data && event.data.sessionId) {
  9759. if (event.origin !== window.location.origin) {
  9760. logger.warn("Ignoring sessionId from different origin: " +
  9761. event.origin);
  9762. return;
  9763. }
  9764. localStorage.setItem('sessionId', event.data.sessionId);
  9765. // After popup is closed we will authenticate
  9766. }
  9767. }
  9768. // Register
  9769. if (window.addEventListener) {
  9770. window.addEventListener("message", listener, false);
  9771. } else {
  9772. window.attachEvent("onmessage", listener);
  9773. }
  9774. }
  9775. Moderator.prototype.isExternalAuthEnabled = function () {
  9776. return this.externalAuthEnabled;
  9777. };
  9778. Moderator.prototype.isSipGatewayEnabled = function () {
  9779. return this.sipGatewayEnabled;
  9780. };
  9781. Moderator.prototype.onMucMemberLeft = function (jid) {
  9782. logger.info("Someone left is it focus ? " + jid);
  9783. var resource = Strophe.getResourceFromJid(jid);
  9784. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9785. logger.info(
  9786. "Focus has left the room - leaving conference");
  9787. //hangUp();
  9788. // We'd rather reload to have everything re-initialized
  9789. //FIXME: show some message before reload
  9790. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9791. }
  9792. };
  9793. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9794. if (!this.focusUserJid) {
  9795. this.focusUserJid = focusJid;
  9796. logger.info("Focus jid set to: " + this.focusUserJid);
  9797. }
  9798. };
  9799. Moderator.prototype.getFocusUserJid = function () {
  9800. return this.focusUserJid;
  9801. };
  9802. Moderator.prototype.getFocusComponent = function () {
  9803. // Get focus component address
  9804. var focusComponent = this.xmppService.options.hosts.focus;
  9805. // If not specified use default: 'focus.domain'
  9806. if (!focusComponent) {
  9807. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9808. }
  9809. return focusComponent;
  9810. };
  9811. Moderator.prototype.createConferenceIq = function () {
  9812. // Generate create conference IQ
  9813. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9814. // Session Id used for authentication
  9815. var sessionId = localStorage.getItem('sessionId');
  9816. var machineUID = this.settings.getSettings().uid;
  9817. logger.info(
  9818. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9819. elem.c('conference', {
  9820. xmlns: 'http://jitsi.org/protocol/focus',
  9821. room: this.roomName,
  9822. 'machine-uid': machineUID
  9823. });
  9824. if (sessionId) {
  9825. elem.attrs({ 'session-id': sessionId});
  9826. }
  9827. if (this.xmppService.options.hosts.bridge !== undefined) {
  9828. elem.c(
  9829. 'property', {
  9830. name: 'bridge',
  9831. value: this.xmppService.options.hosts.bridge
  9832. }).up();
  9833. }
  9834. if (this.xmppService.options.enforcedBridge !== undefined) {
  9835. elem.c(
  9836. 'property', {
  9837. name: 'enforcedBridge',
  9838. value: this.xmppService.options.enforcedBridge
  9839. }).up();
  9840. }
  9841. // Tell the focus we have Jigasi configured
  9842. if (this.xmppService.options.hosts.call_control !== undefined) {
  9843. elem.c(
  9844. 'property', {
  9845. name: 'call_control',
  9846. value: this.xmppService.options.hosts.call_control
  9847. }).up();
  9848. }
  9849. if (this.xmppService.options.channelLastN !== undefined) {
  9850. elem.c(
  9851. 'property', {
  9852. name: 'channelLastN',
  9853. value: this.xmppService.options.channelLastN
  9854. }).up();
  9855. }
  9856. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9857. elem.c(
  9858. 'property', {
  9859. name: 'adaptiveLastN',
  9860. value: this.xmppService.options.adaptiveLastN
  9861. }).up();
  9862. }
  9863. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9864. elem.c(
  9865. 'property', {
  9866. name: 'adaptiveSimulcast',
  9867. value: this.xmppService.options.adaptiveSimulcast
  9868. }).up();
  9869. }
  9870. if (this.xmppService.options.openSctp !== undefined) {
  9871. elem.c(
  9872. 'property', {
  9873. name: 'openSctp',
  9874. value: this.xmppService.options.openSctp
  9875. }).up();
  9876. }
  9877. if (this.xmppService.options.startAudioMuted !== undefined)
  9878. {
  9879. elem.c(
  9880. 'property', {
  9881. name: 'startAudioMuted',
  9882. value: this.xmppService.options.startAudioMuted
  9883. }).up();
  9884. }
  9885. if (this.xmppService.options.startVideoMuted !== undefined)
  9886. {
  9887. elem.c(
  9888. 'property', {
  9889. name: 'startVideoMuted',
  9890. value: this.xmppService.options.startVideoMuted
  9891. }).up();
  9892. }
  9893. elem.c(
  9894. 'property', {
  9895. name: 'simulcastMode',
  9896. value: 'rewriting'
  9897. }).up();
  9898. elem.up();
  9899. return elem;
  9900. };
  9901. Moderator.prototype.parseSessionId = function (resultIq) {
  9902. var sessionId = $(resultIq).find('conference').attr('session-id');
  9903. if (sessionId) {
  9904. logger.info('Received sessionId: ' + sessionId);
  9905. localStorage.setItem('sessionId', sessionId);
  9906. }
  9907. };
  9908. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9909. this.setFocusUserJid(
  9910. $(resultIq).find('conference').attr('focusjid'));
  9911. var authenticationEnabled
  9912. = $(resultIq).find(
  9913. '>conference>property' +
  9914. '[name=\'authentication\'][value=\'true\']').length > 0;
  9915. logger.info("Authentication enabled: " + authenticationEnabled);
  9916. this.externalAuthEnabled = $(resultIq).find(
  9917. '>conference>property' +
  9918. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9919. console.info(
  9920. 'External authentication enabled: ' + this.externalAuthEnabled);
  9921. if (!this.externalAuthEnabled) {
  9922. // We expect to receive sessionId in 'internal' authentication mode
  9923. this.parseSessionId(resultIq);
  9924. }
  9925. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9926. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9927. authenticationEnabled, authIdentity);
  9928. // Check if focus has auto-detected Jigasi component(this will be also
  9929. // included if we have passed our host from the config)
  9930. if ($(resultIq).find(
  9931. '>conference>property' +
  9932. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9933. this.sipGatewayEnabled = true;
  9934. }
  9935. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9936. };
  9937. // FIXME = we need to show the fact that we're waiting for the focus
  9938. // to the user(or that focus is not available)
  9939. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9940. // Try to use focus user JID from the config
  9941. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9942. // Send create conference IQ
  9943. var iq = this.createConferenceIq();
  9944. var self = this;
  9945. this.connection.sendIQ(
  9946. iq,
  9947. function (result) {
  9948. // Setup config options
  9949. self.parseConfigOptions(result);
  9950. if ('true' === $(result).find('conference').attr('ready')) {
  9951. // Reset both timers
  9952. self.getNextTimeout(true);
  9953. self.getNextErrorTimeout(true);
  9954. // Exec callback
  9955. callback();
  9956. } else {
  9957. var waitMs = self.getNextTimeout();
  9958. logger.info("Waiting for the focus... " + waitMs);
  9959. // Reset error timeout
  9960. self.getNextErrorTimeout(true);
  9961. window.setTimeout(
  9962. function () {
  9963. self.allocateConferenceFocus(callback);
  9964. }, waitMs);
  9965. }
  9966. },
  9967. function (error) {
  9968. // Invalid session ? remove and try again
  9969. // without session ID to get a new one
  9970. var invalidSession
  9971. = $(error).find('>error>session-invalid').length;
  9972. if (invalidSession) {
  9973. logger.info("Session expired! - removing");
  9974. localStorage.removeItem("sessionId");
  9975. }
  9976. if ($(error).find('>error>graceful-shutdown').length) {
  9977. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9978. return;
  9979. }
  9980. // Check for error returned by the reservation system
  9981. var reservationErr = $(error).find('>error>reservation-error');
  9982. if (reservationErr.length) {
  9983. // Trigger error event
  9984. var errorCode = reservationErr.attr('error-code');
  9985. var errorMsg;
  9986. if ($(error).find('>error>text')) {
  9987. errorMsg = $(error).find('>error>text').text();
  9988. }
  9989. self.eventEmitter.emit(
  9990. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9991. return;
  9992. }
  9993. // Not authorized to create new room
  9994. if ($(error).find('>error>not-authorized').length) {
  9995. logger.warn("Unauthorized to start the conference", error);
  9996. var toDomain
  9997. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9998. if (toDomain !==
  9999. this.xmppService.options.hosts.anonymousdomain) {
  10000. //FIXME: "is external" should come either from
  10001. // the focus or config.js
  10002. self.externalAuthEnabled = true;
  10003. }
  10004. self.eventEmitter.emit(
  10005. XMPPEvents.AUTHENTICATION_REQUIRED,
  10006. function () {
  10007. self.allocateConferenceFocus(
  10008. callback);
  10009. });
  10010. return;
  10011. }
  10012. var waitMs = self.getNextErrorTimeout();
  10013. logger.error("Focus error, retry after " + waitMs, error);
  10014. // Show message
  10015. var focusComponent = self.getFocusComponent();
  10016. var retrySec = waitMs / 1000;
  10017. //FIXME: message is duplicated ?
  10018. // Do not show in case of session invalid
  10019. // which means just a retry
  10020. if (!invalidSession) {
  10021. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  10022. focusComponent, retrySec);
  10023. }
  10024. // Reset response timeout
  10025. self.getNextTimeout(true);
  10026. window.setTimeout(
  10027. function () {
  10028. self.allocateConferenceFocus(callback);
  10029. }, waitMs);
  10030. }
  10031. );
  10032. };
  10033. Moderator.prototype.authenticate = function () {
  10034. var self = this;
  10035. return new Promise(function (resolve, reject) {
  10036. self.connection.sendIQ(
  10037. self.createConferenceIq(),
  10038. function (result) {
  10039. self.parseSessionId(result);
  10040. resolve();
  10041. }, function (error) {
  10042. var code = $(error).find('>error').attr('code');
  10043. reject(error, code);
  10044. }
  10045. );
  10046. });
  10047. };
  10048. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  10049. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10050. iq.c('login-url', {
  10051. xmlns: 'http://jitsi.org/protocol/focus',
  10052. room: this.roomName,
  10053. 'machine-uid': this.settings.getSettings().uid
  10054. });
  10055. this.connection.sendIQ(
  10056. iq,
  10057. function (result) {
  10058. var url = $(result).find('login-url').attr('url');
  10059. url = url = decodeURIComponent(url);
  10060. if (url) {
  10061. logger.info("Got auth url: " + url);
  10062. urlCallback(url);
  10063. } else {
  10064. logger.error(
  10065. "Failed to get auth url from the focus", result);
  10066. failureCallback(result);
  10067. }
  10068. },
  10069. function (error) {
  10070. logger.error("Get auth url error", error);
  10071. failureCallback(error);
  10072. }
  10073. );
  10074. };
  10075. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10076. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10077. iq.c('login-url', {
  10078. xmlns: 'http://jitsi.org/protocol/focus',
  10079. room: this.roomName,
  10080. 'machine-uid': this.settings.getSettings().uid,
  10081. popup: true
  10082. });
  10083. this.connection.sendIQ(
  10084. iq,
  10085. function (result) {
  10086. var url = $(result).find('login-url').attr('url');
  10087. url = url = decodeURIComponent(url);
  10088. if (url) {
  10089. logger.info("Got POPUP auth url: " + url);
  10090. urlCallback(url);
  10091. } else {
  10092. logger.error(
  10093. "Failed to get POPUP auth url from the focus", result);
  10094. failureCallback(result);
  10095. }
  10096. },
  10097. function (error) {
  10098. logger.error('Get POPUP auth url error', error);
  10099. failureCallback(error);
  10100. }
  10101. );
  10102. };
  10103. Moderator.prototype.logout = function (callback) {
  10104. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10105. var sessionId = localStorage.getItem('sessionId');
  10106. if (!sessionId) {
  10107. callback();
  10108. return;
  10109. }
  10110. iq.c('logout', {
  10111. xmlns: 'http://jitsi.org/protocol/focus',
  10112. 'session-id': sessionId
  10113. });
  10114. this.connection.sendIQ(
  10115. iq,
  10116. function (result) {
  10117. var logoutUrl = $(result).find('logout').attr('logout-url');
  10118. if (logoutUrl) {
  10119. logoutUrl = decodeURIComponent(logoutUrl);
  10120. }
  10121. logger.info("Log out OK, url: " + logoutUrl, result);
  10122. localStorage.removeItem('sessionId');
  10123. callback(logoutUrl);
  10124. },
  10125. function (error) {
  10126. logger.error("Logout error", error);
  10127. }
  10128. );
  10129. };
  10130. module.exports = Moderator;
  10131. }).call(this,"/modules/xmpp/moderator.js")
  10132. },{"../../service/authentication/AuthenticationEvents":83,"../../service/xmpp/XMPPEvents":87,"../settings/Settings":21,"jitsi-meet-logger":48}],35:[function(require,module,exports){
  10133. (function (__filename){
  10134. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10135. Toolbar, Util, Promise */
  10136. var XMPPEvents = require("../../service/XMPP/XMPPEvents");
  10137. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10138. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10139. roomjid) {
  10140. this.eventEmitter = eventEmitter;
  10141. this.connection = connection;
  10142. this.state = "off";
  10143. this.focusMucJid = focusMucJid;
  10144. this.jirecon = jirecon;
  10145. this.url = null;
  10146. this.type = type;
  10147. this._isSupported = ((type === Recording.types.JIBRI)
  10148. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  10149. /**
  10150. * The ID of the jirecon recording session. Jirecon generates it when we
  10151. * initially start recording, and it needs to be used in subsequent requests
  10152. * to jirecon.
  10153. */
  10154. this.jireconRid = null;
  10155. this.roomjid = roomjid;
  10156. }
  10157. Recording.types = {
  10158. COLIBRI: "colibri",
  10159. JIRECON: "jirecon",
  10160. JIBRI: "jibri"
  10161. };
  10162. Recording.prototype.handleJibriPresence = function (jibri) {
  10163. var attributes = jibri.attributes;
  10164. if(!attributes)
  10165. return;
  10166. this._isSupported =
  10167. (attributes.status && attributes.status !== "undefined");
  10168. if(this._isSupported) {
  10169. this.url = attributes.url || null;
  10170. this.state = attributes.status || "off";
  10171. }
  10172. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  10173. };
  10174. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  10175. options) {
  10176. if (state == this.state){
  10177. errCallback(new Error("Invalid state!"));
  10178. }
  10179. options = options || {};
  10180. // FIXME jibri does not accept IQ without 'url' attribute set ?
  10181. var iq = $iq({to: this.focusMucJid, type: 'set'})
  10182. .c('jibri', {
  10183. "xmlns": 'http://jitsi.org/protocol/jibri',
  10184. "action": (state === 'on') ? 'start' : 'stop',
  10185. "streamid": options.streamId,
  10186. "follow-entity": options.followEntity
  10187. }).up();
  10188. logger.log('Set jibri recording: '+state, iq.nodeTree);
  10189. console.log(iq.nodeTree);
  10190. this.connection.sendIQ(
  10191. iq,
  10192. function (result) {
  10193. callback($(result).find('jibri').attr('state'),
  10194. $(result).find('jibri').attr('url'));
  10195. },
  10196. function (error) {
  10197. logger.log('Failed to start recording, error: ', error);
  10198. errCallback(error);
  10199. });
  10200. };
  10201. Recording.prototype.setRecordingJirecon =
  10202. function (state, callback, errCallback, options) {
  10203. if (state == this.state){
  10204. errCallback(new Error("Invalid state!"));
  10205. }
  10206. var iq = $iq({to: this.jirecon, type: 'set'})
  10207. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  10208. action: (state === 'on') ? 'start' : 'stop',
  10209. mucjid: this.roomjid});
  10210. if (state === 'off'){
  10211. iq.attrs({rid: this.jireconRid});
  10212. }
  10213. console.log('Start recording');
  10214. var self = this;
  10215. this.connection.sendIQ(
  10216. iq,
  10217. function (result) {
  10218. // TODO wait for an IQ with the real status, since this is
  10219. // provisional?
  10220. self.jireconRid = $(result).find('recording').attr('rid');
  10221. console.log('Recording ' +
  10222. ((state === 'on') ? 'started' : 'stopped') +
  10223. '(jirecon)' + result);
  10224. self.state = state;
  10225. if (state === 'off'){
  10226. self.jireconRid = null;
  10227. }
  10228. callback(state);
  10229. },
  10230. function (error) {
  10231. console.log('Failed to start recording, error: ', error);
  10232. errCallback(error);
  10233. });
  10234. };
  10235. // Sends a COLIBRI message which enables or disables (according to 'state')
  10236. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  10237. // with the new recording state, according to the IQ.
  10238. Recording.prototype.setRecordingColibri =
  10239. function (state, callback, errCallback, options) {
  10240. var elem = $iq({to: this.focusMucJid, type: 'set'});
  10241. elem.c('conference', {
  10242. xmlns: 'http://jitsi.org/protocol/colibri'
  10243. });
  10244. elem.c('recording', {state: state, token: options.token});
  10245. var self = this;
  10246. this.connection.sendIQ(elem,
  10247. function (result) {
  10248. console.log('Set recording "', state, '". Result:', result);
  10249. var recordingElem = $(result).find('>conference>recording');
  10250. var newState = recordingElem.attr('state');
  10251. self.state = newState;
  10252. callback(newState);
  10253. if (newState === 'pending') {
  10254. self.connection.addHandler(function(iq){
  10255. var state = $(iq).find('recording').attr('state');
  10256. if (state) {
  10257. self.state = newState;
  10258. callback(state);
  10259. }
  10260. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  10261. }
  10262. },
  10263. function (error) {
  10264. console.warn(error);
  10265. errCallback(error);
  10266. }
  10267. );
  10268. };
  10269. Recording.prototype.setRecording =
  10270. function (state, callback, errCallback, options) {
  10271. switch(this.type){
  10272. case Recording.types.JIRECON:
  10273. this.setRecordingJirecon(state, callback, errCallback, options);
  10274. break;
  10275. case Recording.types.COLIBRI:
  10276. this.setRecordingColibri(state, callback, errCallback, options);
  10277. break;
  10278. case Recording.types.JIBRI:
  10279. this.setRecordingJibri(state, callback, errCallback, options);
  10280. break;
  10281. default:
  10282. console.error("Unknown recording type!");
  10283. return;
  10284. }
  10285. };
  10286. /**
  10287. *Starts/stops the recording
  10288. * @param token token for authentication
  10289. * @param statusChangeHandler {function} receives the new status as argument.
  10290. */
  10291. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  10292. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  10293. (!options.streamId && this.type === Recording.types.JIBRI)){
  10294. statusChangeHandler("error", new Error("No token passed!"));
  10295. logger.error("No token passed!");
  10296. return;
  10297. }
  10298. var oldState = this.state;
  10299. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  10300. var self = this;
  10301. this.setRecording(newState,
  10302. function (state, url) {
  10303. logger.log("New recording state: ", state);
  10304. if (state && state !== oldState) {
  10305. self.state = state;
  10306. self.url = url;
  10307. statusChangeHandler(state);
  10308. } else {
  10309. statusChangeHandler("error", new Error("Status not changed!"));
  10310. }
  10311. }, function (error) {
  10312. statusChangeHandler("error", error);
  10313. }, options);
  10314. };
  10315. /**
  10316. * Returns true if the recording is supproted and false if not.
  10317. */
  10318. Recording.prototype.isSupported = function () {
  10319. return this._isSupported;
  10320. };
  10321. /**
  10322. * Returns null if the recording is not supported, "on" if the recording started
  10323. * and "off" if the recording is not started.
  10324. */
  10325. Recording.prototype.getState = function () {
  10326. return this.state;
  10327. };
  10328. /**
  10329. * Returns the url of the recorded video.
  10330. */
  10331. Recording.prototype.getURL = function () {
  10332. return this.url;
  10333. };
  10334. module.exports = Recording;
  10335. }).call(this,"/modules/xmpp/recording.js")
  10336. },{"../../service/XMPP/XMPPEvents":82,"jitsi-meet-logger":48}],36:[function(require,module,exports){
  10337. (function (__filename){
  10338. /* jshint -W117 */
  10339. /* a simple MUC connection plugin
  10340. * can only handle a single MUC room
  10341. */
  10342. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10343. var ChatRoom = require("./ChatRoom");
  10344. module.exports = function(XMPP) {
  10345. Strophe.addConnectionPlugin('emuc', {
  10346. connection: null,
  10347. rooms: {},//map with the rooms
  10348. init: function (conn) {
  10349. this.connection = conn;
  10350. // add handlers (just once)
  10351. this.connection.addHandler(this.onPresence.bind(this), null,
  10352. 'presence', null, null, null, null);
  10353. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  10354. null, 'presence', 'unavailable', null);
  10355. this.connection.addHandler(this.onPresenceError.bind(this), null,
  10356. 'presence', 'error', null);
  10357. this.connection.addHandler(this.onMessage.bind(this), null,
  10358. 'message', null, null);
  10359. this.connection.addHandler(this.onMute.bind(this),
  10360. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  10361. },
  10362. createRoom: function (jid, password, options) {
  10363. var roomJid = Strophe.getBareJidFromJid(jid);
  10364. if (this.rooms[roomJid]) {
  10365. logger.error("You are already in the room!");
  10366. return;
  10367. }
  10368. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  10369. return this.rooms[roomJid];
  10370. },
  10371. doLeave: function (jid) {
  10372. this.rooms[jid].doLeave();
  10373. delete this.rooms[jid];
  10374. },
  10375. onPresence: function (pres) {
  10376. var from = pres.getAttribute('from');
  10377. // What is this for? A workaround for something?
  10378. if (pres.getAttribute('type')) {
  10379. return true;
  10380. }
  10381. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10382. if(!room)
  10383. return;
  10384. // Parse status.
  10385. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  10386. room.createNonAnonymousRoom();
  10387. }
  10388. room.onPresence(pres);
  10389. return true;
  10390. },
  10391. onPresenceUnavailable: function (pres) {
  10392. var from = pres.getAttribute('from');
  10393. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10394. if(!room)
  10395. return;
  10396. room.onPresenceUnavailable(pres, from);
  10397. return true;
  10398. },
  10399. onPresenceError: function (pres) {
  10400. var from = pres.getAttribute('from');
  10401. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10402. if(!room)
  10403. return;
  10404. room.onPresenceError(pres, from);
  10405. return true;
  10406. },
  10407. onMessage: function (msg) {
  10408. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  10409. var from = msg.getAttribute('from');
  10410. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10411. if(!room)
  10412. return;
  10413. room.onMessage(msg, from);
  10414. return true;
  10415. },
  10416. setJingleSession: function (from, session) {
  10417. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10418. if(!room)
  10419. return;
  10420. room.setJingleSession(session);
  10421. },
  10422. onMute: function(iq) {
  10423. var from = iq.getAttribute('from');
  10424. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10425. if(!room)
  10426. return;
  10427. room.onMute(iq);
  10428. return true;
  10429. }
  10430. });
  10431. };
  10432. }).call(this,"/modules/xmpp/strophe.emuc.js")
  10433. },{"./ChatRoom":26,"jitsi-meet-logger":48}],37:[function(require,module,exports){
  10434. (function (__filename){
  10435. /* jshint -W117 */
  10436. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10437. var JingleSession = require("./JingleSessionPC");
  10438. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10439. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10440. module.exports = function(XMPP, eventEmitter) {
  10441. Strophe.addConnectionPlugin('jingle', {
  10442. connection: null,
  10443. sessions: {},
  10444. jid2session: {},
  10445. ice_config: {iceServers: []},
  10446. media_constraints: {
  10447. mandatory: {
  10448. 'OfferToReceiveAudio': true,
  10449. 'OfferToReceiveVideo': true
  10450. }
  10451. // MozDontOfferDataChannel: true when this is firefox
  10452. },
  10453. init: function (conn) {
  10454. this.connection = conn;
  10455. if (this.connection.disco) {
  10456. // http://xmpp.org/extensions/xep-0167.html#support
  10457. // http://xmpp.org/extensions/xep-0176.html#support
  10458. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  10459. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  10460. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  10461. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  10462. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  10463. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  10464. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  10465. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  10466. || RTCBrowserType.isTemasysPluginUsed()) {
  10467. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  10468. }
  10469. // this is dealt with by SDP O/A so we don't need to announce this
  10470. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  10471. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  10472. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  10473. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  10474. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  10475. }
  10476. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  10477. },
  10478. onJingle: function (iq) {
  10479. var sid = $(iq).find('jingle').attr('sid');
  10480. var action = $(iq).find('jingle').attr('action');
  10481. var fromJid = iq.getAttribute('from');
  10482. // send ack first
  10483. var ack = $iq({type: 'result',
  10484. to: fromJid,
  10485. id: iq.getAttribute('id')
  10486. });
  10487. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  10488. var sess = this.sessions[sid];
  10489. if ('session-initiate' != action) {
  10490. if (sess === null) {
  10491. ack.type = 'error';
  10492. ack.c('error', {type: 'cancel'})
  10493. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10494. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10495. this.connection.send(ack);
  10496. return true;
  10497. }
  10498. // local jid is not checked
  10499. if (fromJid != sess.peerjid) {
  10500. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  10501. ack.type = 'error';
  10502. ack.c('error', {type: 'cancel'})
  10503. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10504. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10505. this.connection.send(ack);
  10506. return true;
  10507. }
  10508. } else if (sess !== undefined) {
  10509. // existing session with same session id
  10510. // this might be out-of-order if the sess.peerjid is the same as from
  10511. ack.type = 'error';
  10512. ack.c('error', {type: 'cancel'})
  10513. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  10514. logger.warn('duplicate session id', sid);
  10515. this.connection.send(ack);
  10516. return true;
  10517. }
  10518. // FIXME: check for a defined action
  10519. this.connection.send(ack);
  10520. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  10521. switch (action) {
  10522. case 'session-initiate':
  10523. console.log("(TIME) received session-initiate:\t",
  10524. window.performance.now());
  10525. var startMuted = $(iq).find('jingle>startmuted');
  10526. if (startMuted && startMuted.length > 0) {
  10527. var audioMuted = startMuted.attr("audio");
  10528. var videoMuted = startMuted.attr("video");
  10529. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  10530. audioMuted === "true", videoMuted === "true");
  10531. }
  10532. sess = new JingleSession(
  10533. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  10534. this.connection, XMPP);
  10535. // configure session
  10536. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  10537. this.connection.emuc.setJingleSession(fromBareJid, sess);
  10538. sess.media_constraints = this.media_constraints;
  10539. sess.ice_config = this.ice_config;
  10540. sess.initialize(fromJid, false);
  10541. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  10542. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  10543. sess.setOffer($(iq).find('>jingle'));
  10544. this.sessions[sess.sid] = sess;
  10545. this.jid2session[sess.peerjid] = sess;
  10546. // the callback should either
  10547. // .sendAnswer and .accept
  10548. // or .sendTerminate -- not necessarily synchronous
  10549. sess.sendAnswer();
  10550. sess.accept();
  10551. break;
  10552. case 'session-accept':
  10553. sess.setAnswer($(iq).find('>jingle'));
  10554. sess.accept();
  10555. break;
  10556. case 'session-terminate':
  10557. // If this is not the focus sending the terminate, we have
  10558. // nothing more to do here.
  10559. if (Object.keys(this.sessions).length < 1
  10560. || !(this.sessions[Object.keys(this.sessions)[0]]
  10561. instanceof JingleSession))
  10562. {
  10563. break;
  10564. }
  10565. logger.log('terminating...', sess.sid);
  10566. sess.terminate();
  10567. this.terminate(sess.sid);
  10568. if ($(iq).find('>jingle>reason').length) {
  10569. $(document).trigger('callterminated.jingle', [
  10570. sess.sid,
  10571. sess.peerjid,
  10572. $(iq).find('>jingle>reason>:first')[0].tagName,
  10573. $(iq).find('>jingle>reason>text').text()
  10574. ]);
  10575. } else {
  10576. $(document).trigger('callterminated.jingle',
  10577. [sess.sid, sess.peerjid]);
  10578. }
  10579. break;
  10580. case 'transport-info':
  10581. sess.addIceCandidate($(iq).find('>jingle>content'));
  10582. break;
  10583. case 'session-info':
  10584. var affected;
  10585. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10586. $(document).trigger('ringing.jingle', [sess.sid]);
  10587. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10588. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10589. $(document).trigger('mute.jingle', [sess.sid, affected]);
  10590. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10591. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10592. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  10593. }
  10594. break;
  10595. case 'addsource': // FIXME: proprietary, un-jingleish
  10596. case 'source-add': // FIXME: proprietary
  10597. sess.addSource($(iq).find('>jingle>content'));
  10598. break;
  10599. case 'removesource': // FIXME: proprietary, un-jingleish
  10600. case 'source-remove': // FIXME: proprietary
  10601. sess.removeSource($(iq).find('>jingle>content'));
  10602. break;
  10603. default:
  10604. logger.warn('jingle action not implemented', action);
  10605. break;
  10606. }
  10607. return true;
  10608. },
  10609. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  10610. if (sid === null || sid === undefined) {
  10611. for (sid in this.sessions) {
  10612. if (this.sessions[sid].state != 'ended') {
  10613. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10614. this.sessions[sid].terminate();
  10615. }
  10616. delete this.jid2session[this.sessions[sid].peerjid];
  10617. delete this.sessions[sid];
  10618. }
  10619. } else if (this.sessions.hasOwnProperty(sid)) {
  10620. if (this.sessions[sid].state != 'ended') {
  10621. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10622. this.sessions[sid].terminate();
  10623. }
  10624. delete this.jid2session[this.sessions[sid].peerjid];
  10625. delete this.sessions[sid];
  10626. }
  10627. },
  10628. getStunAndTurnCredentials: function () {
  10629. // get stun and turn configuration from server via xep-0215
  10630. // uses time-limited credentials as described in
  10631. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  10632. //
  10633. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  10634. // for a prosody module which implements this
  10635. //
  10636. // currently, this doesn't work with updateIce and therefore credentials with a long
  10637. // validity have to be fetched before creating the peerconnection
  10638. // TODO: implement refresh via updateIce as described in
  10639. // https://code.google.com/p/webrtc/issues/detail?id=1650
  10640. var self = this;
  10641. this.connection.sendIQ(
  10642. $iq({type: 'get', to: this.connection.domain})
  10643. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  10644. function (res) {
  10645. var iceservers = [];
  10646. $(res).find('>services>service').each(function (idx, el) {
  10647. el = $(el);
  10648. var dict = {};
  10649. var type = el.attr('type');
  10650. switch (type) {
  10651. case 'stun':
  10652. dict.url = 'stun:' + el.attr('host');
  10653. if (el.attr('port')) {
  10654. dict.url += ':' + el.attr('port');
  10655. }
  10656. iceservers.push(dict);
  10657. break;
  10658. case 'turn':
  10659. case 'turns':
  10660. dict.url = type + ':';
  10661. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  10662. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  10663. dict.url += el.attr('username') + '@';
  10664. } else {
  10665. dict.username = el.attr('username'); // only works in M28
  10666. }
  10667. }
  10668. dict.url += el.attr('host');
  10669. if (el.attr('port') && el.attr('port') != '3478') {
  10670. dict.url += ':' + el.attr('port');
  10671. }
  10672. if (el.attr('transport') && el.attr('transport') != 'udp') {
  10673. dict.url += '?transport=' + el.attr('transport');
  10674. }
  10675. if (el.attr('password')) {
  10676. dict.credential = el.attr('password');
  10677. }
  10678. iceservers.push(dict);
  10679. break;
  10680. }
  10681. });
  10682. self.ice_config.iceServers = iceservers;
  10683. },
  10684. function (err) {
  10685. logger.warn('getting turn credentials failed', err);
  10686. logger.warn('is mod_turncredentials or similar installed?');
  10687. }
  10688. );
  10689. // implement push?
  10690. },
  10691. /**
  10692. * Returns the data saved in 'updateLog' in a format to be logged.
  10693. */
  10694. getLog: function () {
  10695. var data = {};
  10696. var self = this;
  10697. Object.keys(this.sessions).forEach(function (sid) {
  10698. var session = self.sessions[sid];
  10699. if (session.peerconnection && session.peerconnection.updateLog) {
  10700. // FIXME: should probably be a .dump call
  10701. data["jingle_" + session.sid] = {
  10702. updateLog: session.peerconnection.updateLog,
  10703. stats: session.peerconnection.stats,
  10704. url: window.location.href
  10705. };
  10706. }
  10707. });
  10708. return data;
  10709. }
  10710. });
  10711. };
  10712. }).call(this,"/modules/xmpp/strophe.jingle.js")
  10713. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":48}],38:[function(require,module,exports){
  10714. /* global Strophe */
  10715. module.exports = function () {
  10716. Strophe.addConnectionPlugin('logger', {
  10717. // logs raw stanzas and makes them available for download as JSON
  10718. connection: null,
  10719. log: [],
  10720. init: function (conn) {
  10721. this.connection = conn;
  10722. this.connection.rawInput = this.log_incoming.bind(this);
  10723. this.connection.rawOutput = this.log_outgoing.bind(this);
  10724. },
  10725. log_incoming: function (stanza) {
  10726. this.log.push([new Date().getTime(), 'incoming', stanza]);
  10727. },
  10728. log_outgoing: function (stanza) {
  10729. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  10730. }
  10731. });
  10732. };
  10733. },{}],39:[function(require,module,exports){
  10734. (function (__filename){
  10735. /* global $, $iq, Strophe */
  10736. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10737. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10738. /**
  10739. * Ping every 20 sec
  10740. */
  10741. var PING_INTERVAL = 20000;
  10742. /**
  10743. * Ping timeout error after 15 sec of waiting.
  10744. */
  10745. var PING_TIMEOUT = 15000;
  10746. /**
  10747. * Will close the connection after 3 consecutive ping errors.
  10748. */
  10749. var PING_THRESHOLD = 3;
  10750. /**
  10751. * XEP-0199 ping plugin.
  10752. *
  10753. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  10754. */
  10755. module.exports = function (XMPP, eventEmitter) {
  10756. Strophe.addConnectionPlugin('ping', {
  10757. connection: null,
  10758. failedPings: 0,
  10759. /**
  10760. * Initializes the plugin. Method called by Strophe.
  10761. * @param connection Strophe connection instance.
  10762. */
  10763. init: function (connection) {
  10764. this.connection = connection;
  10765. Strophe.addNamespace('PING', "urn:xmpp:ping");
  10766. },
  10767. /**
  10768. * Sends "ping" to given <tt>jid</tt>
  10769. * @param jid the JID to which ping request will be sent.
  10770. * @param success callback called on success.
  10771. * @param error callback called on error.
  10772. * @param timeout ms how long are we going to wait for the response. On
  10773. * timeout <tt>error<//t> callback is called with undefined error
  10774. * argument.
  10775. */
  10776. ping: function (jid, success, error, timeout) {
  10777. var iq = $iq({type: 'get', to: jid});
  10778. iq.c('ping', {xmlns: Strophe.NS.PING});
  10779. this.connection.sendIQ(iq, success, error, timeout);
  10780. },
  10781. /**
  10782. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  10783. * @param jid the JID to be checked for ping support.
  10784. * @param callback function with boolean argument which will be
  10785. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  10786. */
  10787. hasPingSupport: function (jid, callback) {
  10788. this.connection.disco.info(
  10789. jid, null,
  10790. function (result) {
  10791. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  10792. callback(ping.length > 0);
  10793. },
  10794. function (error) {
  10795. logger.error("Ping feature discovery error", error);
  10796. callback(false);
  10797. }
  10798. );
  10799. },
  10800. /**
  10801. * Starts to send ping in given interval to specified remote JID.
  10802. * This plugin supports only one such task and <tt>stopInterval</tt>
  10803. * must be called before starting a new one.
  10804. * @param remoteJid remote JID to which ping requests will be sent to.
  10805. * @param interval task interval in ms.
  10806. */
  10807. startInterval: function (remoteJid, interval) {
  10808. if (this.intervalId) {
  10809. logger.error("Ping task scheduled already");
  10810. return;
  10811. }
  10812. if (!interval)
  10813. interval = PING_INTERVAL;
  10814. var self = this;
  10815. this.intervalId = window.setInterval(function () {
  10816. self.ping(remoteJid,
  10817. function (result) {
  10818. // Ping OK
  10819. self.failedPings = 0;
  10820. },
  10821. function (error) {
  10822. self.failedPings += 1;
  10823. logger.error(
  10824. "Ping " + (error ? "error" : "timeout"), error);
  10825. if (self.failedPings >= PING_THRESHOLD) {
  10826. self.connection.disconnect();
  10827. }
  10828. }, PING_TIMEOUT);
  10829. }, interval);
  10830. logger.info("XMPP pings will be sent every " + interval + " ms");
  10831. },
  10832. /**
  10833. * Stops current "ping" interval task.
  10834. */
  10835. stopInterval: function () {
  10836. if (this.intervalId) {
  10837. window.clearInterval(this.intervalId);
  10838. this.intervalId = null;
  10839. this.failedPings = 0;
  10840. logger.info("Ping interval cleared");
  10841. }
  10842. }
  10843. });
  10844. };
  10845. }).call(this,"/modules/xmpp/strophe.ping.js")
  10846. },{"../../service/xmpp/XMPPEvents":87,"jitsi-meet-logger":48}],40:[function(require,module,exports){
  10847. (function (__filename){
  10848. /* jshint -W117 */
  10849. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10850. module.exports = function() {
  10851. Strophe.addConnectionPlugin('rayo',
  10852. {
  10853. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10854. connection: null,
  10855. init: function (conn) {
  10856. this.connection = conn;
  10857. if (this.connection.disco) {
  10858. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10859. }
  10860. this.connection.addHandler(
  10861. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  10862. null, null);
  10863. },
  10864. onRayo: function (iq) {
  10865. logger.info("Rayo IQ", iq);
  10866. },
  10867. dial: function (to, from, roomName, roomPass, focusMucJid) {
  10868. var self = this;
  10869. return new Promise(function (resolve, reject) {
  10870. if(!focusMucJid) {
  10871. reject(new Error("Internal error!"));
  10872. return;
  10873. }
  10874. var req = $iq(
  10875. {
  10876. type: 'set',
  10877. to: focusMucJid
  10878. }
  10879. );
  10880. req.c('dial',
  10881. {
  10882. xmlns: self.RAYO_XMLNS,
  10883. to: to,
  10884. from: from
  10885. });
  10886. req.c('header',
  10887. {
  10888. name: 'JvbRoomName',
  10889. value: roomName
  10890. }).up();
  10891. if (roomPass !== null && roomPass.length) {
  10892. req.c('header',
  10893. {
  10894. name: 'JvbRoomPassword',
  10895. value: roomPass
  10896. }).up();
  10897. }
  10898. self.connection.sendIQ(
  10899. req,
  10900. function (result) {
  10901. logger.info('Dial result ', result);
  10902. var resource = $(result).find('ref').attr('uri');
  10903. self.call_resource =
  10904. resource.substr('xmpp:'.length);
  10905. logger.info(
  10906. "Received call resource: " +
  10907. self.call_resource);
  10908. resolve();
  10909. },
  10910. function (error) {
  10911. logger.info('Dial error ', error);
  10912. reject(error);
  10913. }
  10914. );
  10915. });
  10916. },
  10917. hangup: function () {
  10918. var self = this;
  10919. return new Promise(function (resolve, reject) {
  10920. if (!self.call_resource) {
  10921. reject(new Error("No call in progress"));
  10922. logger.warn("No call in progress");
  10923. return;
  10924. }
  10925. var req = $iq(
  10926. {
  10927. type: 'set',
  10928. to: self.call_resource
  10929. }
  10930. );
  10931. req.c('hangup',
  10932. {
  10933. xmlns: self.RAYO_XMLNS
  10934. });
  10935. self.connection.sendIQ(
  10936. req,
  10937. function (result) {
  10938. logger.info('Hangup result ', result);
  10939. self.call_resource = null;
  10940. resolve();
  10941. },
  10942. function (error) {
  10943. logger.info('Hangup error ', error);
  10944. self.call_resource = null;
  10945. reject(new Error('Hangup error '));
  10946. }
  10947. );
  10948. });
  10949. }
  10950. }
  10951. );
  10952. };
  10953. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10954. },{"jitsi-meet-logger":48}],41:[function(require,module,exports){
  10955. (function (__filename){
  10956. /* global Strophe */
  10957. /**
  10958. * Strophe logger implementation. Logs from level WARN and above.
  10959. */
  10960. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10961. module.exports = function () {
  10962. Strophe.log = function (level, msg) {
  10963. switch (level) {
  10964. case Strophe.LogLevel.WARN:
  10965. logger.warn("Strophe: " + msg);
  10966. break;
  10967. case Strophe.LogLevel.ERROR:
  10968. case Strophe.LogLevel.FATAL:
  10969. logger.error("Strophe: " + msg);
  10970. break;
  10971. }
  10972. };
  10973. Strophe.getStatusString = function (status) {
  10974. switch (status) {
  10975. case Strophe.Status.ERROR:
  10976. return "ERROR";
  10977. case Strophe.Status.CONNECTING:
  10978. return "CONNECTING";
  10979. case Strophe.Status.CONNFAIL:
  10980. return "CONNFAIL";
  10981. case Strophe.Status.AUTHENTICATING:
  10982. return "AUTHENTICATING";
  10983. case Strophe.Status.AUTHFAIL:
  10984. return "AUTHFAIL";
  10985. case Strophe.Status.CONNECTED:
  10986. return "CONNECTED";
  10987. case Strophe.Status.DISCONNECTED:
  10988. return "DISCONNECTED";
  10989. case Strophe.Status.DISCONNECTING:
  10990. return "DISCONNECTING";
  10991. case Strophe.Status.ATTACHED:
  10992. return "ATTACHED";
  10993. default:
  10994. return "unknown";
  10995. }
  10996. };
  10997. };
  10998. }).call(this,"/modules/xmpp/strophe.util.js")
  10999. },{"jitsi-meet-logger":48}],42:[function(require,module,exports){
  11000. (function (__filename){
  11001. /* global $, APP, config, Strophe*/
  11002. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11003. var EventEmitter = require("events");
  11004. var Pako = require("pako");
  11005. var RTCEvents = require("../../service/RTC/RTCEvents");
  11006. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11007. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  11008. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  11009. var RTC = require("../RTC/RTC");
  11010. var authenticatedUser = false;
  11011. function createConnection(bosh) {
  11012. bosh = bosh || '/http-bind';
  11013. // Append token as URL param
  11014. if (this.token) {
  11015. bosh += bosh.indexOf('?') == -1 ?
  11016. '?token=' + this.token : '&token=' + this.token;
  11017. }
  11018. return new Strophe.Connection(bosh);
  11019. };
  11020. //!!!!!!!!!! FIXME: ...
  11021. function initStrophePlugins(XMPP)
  11022. {
  11023. require("./strophe.emuc")(XMPP);
  11024. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  11025. // require("./strophe.moderate")(XMPP, eventEmitter);
  11026. require("./strophe.util")();
  11027. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  11028. require("./strophe.rayo")();
  11029. require("./strophe.logger")();
  11030. }
  11031. //!!!!!!!!!! FIXME: ...
  11032. ///**
  11033. // * If given <tt>localStream</tt> is video one this method will advertise it's
  11034. // * video type in MUC presence.
  11035. // * @param localStream new or modified <tt>LocalStream</tt>.
  11036. // */
  11037. //function broadcastLocalVideoType(localStream) {
  11038. // if (localStream.videoType)
  11039. // XMPP.addToPresence('videoType', localStream.videoType);
  11040. //}
  11041. //
  11042. //function registerListeners() {
  11043. // RTC.addStreamListener(
  11044. // broadcastLocalVideoType,
  11045. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  11046. // );
  11047. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  11048. // XMPP.addToPresence("devices", devices);
  11049. // });
  11050. //}
  11051. function XMPP(options) {
  11052. this.eventEmitter = new EventEmitter();
  11053. this.connection = null;
  11054. this.disconnectInProgress = false;
  11055. this.forceMuted = false;
  11056. this.options = options;
  11057. initStrophePlugins(this);
  11058. // registerListeners();
  11059. this.connection = createConnection(options.bosh);
  11060. }
  11061. XMPP.prototype.getConnection = function(){ return connection; };
  11062. XMPP.prototype._connect = function (jid, password) {
  11063. var self = this;
  11064. // connection.connect() starts the connection process.
  11065. //
  11066. // As the connection process proceeds, the user supplied callback will
  11067. // be triggered multiple times with status updates. The callback should
  11068. // take two arguments - the status code and the error condition.
  11069. //
  11070. // The status code will be one of the values in the Strophe.Status
  11071. // constants. The error condition will be one of the conditions defined
  11072. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11073. //
  11074. // The Parameters wait, hold and route are optional and only relevant
  11075. // for BOSH connections. Please see XEP 124 for a more detailed
  11076. // explanation of the optional parameters.
  11077. //
  11078. // Connection status constants for use by the connection handler
  11079. // callback.
  11080. //
  11081. // Status.ERROR - An error has occurred (websockets specific)
  11082. // Status.CONNECTING - The connection is currently being made
  11083. // Status.CONNFAIL - The connection attempt failed
  11084. // Status.AUTHENTICATING - The connection is authenticating
  11085. // Status.AUTHFAIL - The authentication attempt failed
  11086. // Status.CONNECTED - The connection has succeeded
  11087. // Status.DISCONNECTED - The connection has been terminated
  11088. // Status.DISCONNECTING - The connection is currently being terminated
  11089. // Status.ATTACHED - The connection has been attached
  11090. var anonymousConnectionFailed = false;
  11091. var connectionFailed = false;
  11092. var lastErrorMsg;
  11093. this.connection.connect(jid, password, function (status, msg) {
  11094. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11095. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11096. if (status === Strophe.Status.CONNECTED) {
  11097. if (self.options.useStunTurn) {
  11098. self.connection.jingle.getStunAndTurnCredentials();
  11099. }
  11100. logger.info("My Jabber ID: " + self.connection.jid);
  11101. // Schedule ping ?
  11102. var pingJid = self.connection.domain;
  11103. self.connection.ping.hasPingSupport(
  11104. pingJid,
  11105. function (hasPing) {
  11106. if (hasPing)
  11107. self.connection.ping.startInterval(pingJid);
  11108. else
  11109. logger.warn("Ping NOT supported by " + pingJid);
  11110. }
  11111. );
  11112. if (password)
  11113. authenticatedUser = true;
  11114. if (self.connection && self.connection.connected &&
  11115. Strophe.getResourceFromJid(self.connection.jid)) {
  11116. // .connected is true while connecting?
  11117. // self.connection.send($pres());
  11118. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11119. Strophe.getResourceFromJid(self.connection.jid));
  11120. }
  11121. } else if (status === Strophe.Status.CONNFAIL) {
  11122. if (msg === 'x-strophe-bad-non-anon-jid') {
  11123. anonymousConnectionFailed = true;
  11124. }
  11125. else
  11126. {
  11127. connectionFailed = true;
  11128. }
  11129. lastErrorMsg = msg;
  11130. } else if (status === Strophe.Status.DISCONNECTED) {
  11131. // Stop ping interval
  11132. self.connection.ping.stopInterval();
  11133. self.disconnectInProgress = false;
  11134. if (anonymousConnectionFailed) {
  11135. // prompt user for username and password
  11136. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11137. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11138. } else if(connectionFailed) {
  11139. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11140. JitsiConnectionErrors.OTHER_ERROR,
  11141. msg ? msg : lastErrorMsg);
  11142. } else {
  11143. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  11144. msg ? msg : lastErrorMsg);
  11145. }
  11146. } else if (status === Strophe.Status.AUTHFAIL) {
  11147. // wrong password or username, prompt user
  11148. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11149. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11150. }
  11151. });
  11152. }
  11153. XMPP.prototype.connect = function (jid, password) {
  11154. if(!jid) {
  11155. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  11156. // Force authenticated domain if room is appended with '?login=true'
  11157. if (this.options.hosts.anonymousdomain &&
  11158. window.location.search.indexOf("login=true") !== -1) {
  11159. configDomain = this.options.hosts.domain;
  11160. }
  11161. jid = configDomain || window.location.hostname;
  11162. }
  11163. return this._connect(jid, password);
  11164. };
  11165. XMPP.prototype.createRoom = function (roomName, options) {
  11166. var roomjid = roomName + '@' + this.options.hosts.muc;
  11167. if (options.useNicks) {
  11168. if (options.nick) {
  11169. roomjid += '/' + options.nick;
  11170. } else {
  11171. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  11172. }
  11173. } else {
  11174. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  11175. if(!authenticatedUser)
  11176. tmpJid = tmpJid.substr(0, 8);
  11177. roomjid += '/' + tmpJid;
  11178. }
  11179. return this.connection.emuc.createRoom(roomjid, null, options);
  11180. }
  11181. XMPP.prototype.addListener = function(type, listener) {
  11182. this.eventEmitter.on(type, listener);
  11183. };
  11184. XMPP.prototype.removeListener = function (type, listener) {
  11185. this.eventEmitter.removeListener(type, listener);
  11186. };
  11187. //FIXME: this should work with the room
  11188. XMPP.prototype.leaveRoom = function (jid) {
  11189. var handler = this.connection.jingle.jid2session[jid];
  11190. if (handler && handler.peerconnection) {
  11191. // FIXME: probably removing streams is not required and close() should
  11192. // be enough
  11193. if (RTC.localAudio) {
  11194. handler.peerconnection.removeStream(
  11195. RTC.localAudio.getOriginalStream(), true);
  11196. }
  11197. if (RTC.localVideo) {
  11198. handler.peerconnection.removeStream(
  11199. RTC.localVideo.getOriginalStream(), true);
  11200. }
  11201. handler.peerconnection.close();
  11202. }
  11203. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  11204. this.connection.emuc.doLeave(jid);
  11205. };
  11206. /**
  11207. * Sends 'data' as a log message to the focus. Returns true iff a message
  11208. * was sent.
  11209. * @param data
  11210. * @returns {boolean} true iff a message was sent.
  11211. */
  11212. XMPP.prototype.sendLogs = function (data) {
  11213. if(!this.connection.emuc.focusMucJid)
  11214. return false;
  11215. var deflate = true;
  11216. var content = JSON.stringify(data);
  11217. if (deflate) {
  11218. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  11219. }
  11220. content = Base64.encode(content);
  11221. // XEP-0337-ish
  11222. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  11223. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  11224. id: 'PeerConnectionStats'});
  11225. message.c('message').t(content).up();
  11226. if (deflate) {
  11227. message.c('tag', {name: "deflated", value: "true"}).up();
  11228. }
  11229. message.up();
  11230. this.connection.send(message);
  11231. return true;
  11232. };
  11233. // Gets the logs from strophe.jingle.
  11234. XMPP.prototype.getJingleLog = function () {
  11235. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  11236. };
  11237. // Gets the logs from strophe.
  11238. XMPP.prototype.getXmppLog = function () {
  11239. return this.connection.logger ? this.connection.logger.log : null;
  11240. };
  11241. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  11242. this.connection.rayo.dial(to, from, roomName,roomPass);
  11243. };
  11244. XMPP.prototype.setMute = function (jid, mute) {
  11245. this.connection.moderate.setMute(jid, mute);
  11246. };
  11247. XMPP.prototype.eject = function (jid) {
  11248. this.connection.moderate.eject(jid);
  11249. };
  11250. XMPP.prototype.getSessions = function () {
  11251. return this.connection.jingle.sessions;
  11252. };
  11253. XMPP.prototype.disconnect = function () {
  11254. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  11255. {
  11256. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  11257. return;
  11258. }
  11259. this.disconnectInProgress = true;
  11260. this.connection.disconnect();
  11261. };
  11262. /**
  11263. * Gets the SSRC of local media stream.
  11264. * @param mediaType the media type that tells whether we want to get
  11265. * the SSRC of local audio or video stream.
  11266. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  11267. * not available.
  11268. */
  11269. XMPP.prototype.getLocalSSRC = function (mediaType) {
  11270. if (this.connection.jingle.activecall &&
  11271. this.connection.jingle.activecall.peerconnection) {
  11272. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  11273. } else {
  11274. return null;
  11275. }
  11276. };
  11277. module.exports = XMPP;
  11278. }).call(this,"/modules/xmpp/xmpp.js")
  11279. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":80,"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"./strophe.emuc":36,"./strophe.jingle":37,"./strophe.logger":38,"./strophe.ping":39,"./strophe.rayo":40,"./strophe.util":41,"events":44,"jitsi-meet-logger":48,"pako":49}],43:[function(require,module,exports){
  11280. (function (process){
  11281. /*!
  11282. * async
  11283. * https://github.com/caolan/async
  11284. *
  11285. * Copyright 2010-2014 Caolan McMahon
  11286. * Released under the MIT license
  11287. */
  11288. /*jshint onevar: false, indent:4 */
  11289. /*global setImmediate: false, setTimeout: false, console: false */
  11290. (function () {
  11291. var async = {};
  11292. // global on the server, window in the browser
  11293. var root, previous_async;
  11294. root = this;
  11295. if (root != null) {
  11296. previous_async = root.async;
  11297. }
  11298. async.noConflict = function () {
  11299. root.async = previous_async;
  11300. return async;
  11301. };
  11302. function only_once(fn) {
  11303. var called = false;
  11304. return function() {
  11305. if (called) throw new Error("Callback was already called.");
  11306. called = true;
  11307. fn.apply(root, arguments);
  11308. }
  11309. }
  11310. //// cross-browser compatiblity functions ////
  11311. var _toString = Object.prototype.toString;
  11312. var _isArray = Array.isArray || function (obj) {
  11313. return _toString.call(obj) === '[object Array]';
  11314. };
  11315. var _each = function (arr, iterator) {
  11316. if (arr.forEach) {
  11317. return arr.forEach(iterator);
  11318. }
  11319. for (var i = 0; i < arr.length; i += 1) {
  11320. iterator(arr[i], i, arr);
  11321. }
  11322. };
  11323. var _map = function (arr, iterator) {
  11324. if (arr.map) {
  11325. return arr.map(iterator);
  11326. }
  11327. var results = [];
  11328. _each(arr, function (x, i, a) {
  11329. results.push(iterator(x, i, a));
  11330. });
  11331. return results;
  11332. };
  11333. var _reduce = function (arr, iterator, memo) {
  11334. if (arr.reduce) {
  11335. return arr.reduce(iterator, memo);
  11336. }
  11337. _each(arr, function (x, i, a) {
  11338. memo = iterator(memo, x, i, a);
  11339. });
  11340. return memo;
  11341. };
  11342. var _keys = function (obj) {
  11343. if (Object.keys) {
  11344. return Object.keys(obj);
  11345. }
  11346. var keys = [];
  11347. for (var k in obj) {
  11348. if (obj.hasOwnProperty(k)) {
  11349. keys.push(k);
  11350. }
  11351. }
  11352. return keys;
  11353. };
  11354. //// exported async module functions ////
  11355. //// nextTick implementation with browser-compatible fallback ////
  11356. if (typeof process === 'undefined' || !(process.nextTick)) {
  11357. if (typeof setImmediate === 'function') {
  11358. async.nextTick = function (fn) {
  11359. // not a direct alias for IE10 compatibility
  11360. setImmediate(fn);
  11361. };
  11362. async.setImmediate = async.nextTick;
  11363. }
  11364. else {
  11365. async.nextTick = function (fn) {
  11366. setTimeout(fn, 0);
  11367. };
  11368. async.setImmediate = async.nextTick;
  11369. }
  11370. }
  11371. else {
  11372. async.nextTick = process.nextTick;
  11373. if (typeof setImmediate !== 'undefined') {
  11374. async.setImmediate = function (fn) {
  11375. // not a direct alias for IE10 compatibility
  11376. setImmediate(fn);
  11377. };
  11378. }
  11379. else {
  11380. async.setImmediate = async.nextTick;
  11381. }
  11382. }
  11383. async.each = function (arr, iterator, callback) {
  11384. callback = callback || function () {};
  11385. if (!arr.length) {
  11386. return callback();
  11387. }
  11388. var completed = 0;
  11389. _each(arr, function (x) {
  11390. iterator(x, only_once(done) );
  11391. });
  11392. function done(err) {
  11393. if (err) {
  11394. callback(err);
  11395. callback = function () {};
  11396. }
  11397. else {
  11398. completed += 1;
  11399. if (completed >= arr.length) {
  11400. callback();
  11401. }
  11402. }
  11403. }
  11404. };
  11405. async.forEach = async.each;
  11406. async.eachSeries = function (arr, iterator, callback) {
  11407. callback = callback || function () {};
  11408. if (!arr.length) {
  11409. return callback();
  11410. }
  11411. var completed = 0;
  11412. var iterate = function () {
  11413. iterator(arr[completed], function (err) {
  11414. if (err) {
  11415. callback(err);
  11416. callback = function () {};
  11417. }
  11418. else {
  11419. completed += 1;
  11420. if (completed >= arr.length) {
  11421. callback();
  11422. }
  11423. else {
  11424. iterate();
  11425. }
  11426. }
  11427. });
  11428. };
  11429. iterate();
  11430. };
  11431. async.forEachSeries = async.eachSeries;
  11432. async.eachLimit = function (arr, limit, iterator, callback) {
  11433. var fn = _eachLimit(limit);
  11434. fn.apply(null, [arr, iterator, callback]);
  11435. };
  11436. async.forEachLimit = async.eachLimit;
  11437. var _eachLimit = function (limit) {
  11438. return function (arr, iterator, callback) {
  11439. callback = callback || function () {};
  11440. if (!arr.length || limit <= 0) {
  11441. return callback();
  11442. }
  11443. var completed = 0;
  11444. var started = 0;
  11445. var running = 0;
  11446. (function replenish () {
  11447. if (completed >= arr.length) {
  11448. return callback();
  11449. }
  11450. while (running < limit && started < arr.length) {
  11451. started += 1;
  11452. running += 1;
  11453. iterator(arr[started - 1], function (err) {
  11454. if (err) {
  11455. callback(err);
  11456. callback = function () {};
  11457. }
  11458. else {
  11459. completed += 1;
  11460. running -= 1;
  11461. if (completed >= arr.length) {
  11462. callback();
  11463. }
  11464. else {
  11465. replenish();
  11466. }
  11467. }
  11468. });
  11469. }
  11470. })();
  11471. };
  11472. };
  11473. var doParallel = function (fn) {
  11474. return function () {
  11475. var args = Array.prototype.slice.call(arguments);
  11476. return fn.apply(null, [async.each].concat(args));
  11477. };
  11478. };
  11479. var doParallelLimit = function(limit, fn) {
  11480. return function () {
  11481. var args = Array.prototype.slice.call(arguments);
  11482. return fn.apply(null, [_eachLimit(limit)].concat(args));
  11483. };
  11484. };
  11485. var doSeries = function (fn) {
  11486. return function () {
  11487. var args = Array.prototype.slice.call(arguments);
  11488. return fn.apply(null, [async.eachSeries].concat(args));
  11489. };
  11490. };
  11491. var _asyncMap = function (eachfn, arr, iterator, callback) {
  11492. arr = _map(arr, function (x, i) {
  11493. return {index: i, value: x};
  11494. });
  11495. if (!callback) {
  11496. eachfn(arr, function (x, callback) {
  11497. iterator(x.value, function (err) {
  11498. callback(err);
  11499. });
  11500. });
  11501. } else {
  11502. var results = [];
  11503. eachfn(arr, function (x, callback) {
  11504. iterator(x.value, function (err, v) {
  11505. results[x.index] = v;
  11506. callback(err);
  11507. });
  11508. }, function (err) {
  11509. callback(err, results);
  11510. });
  11511. }
  11512. };
  11513. async.map = doParallel(_asyncMap);
  11514. async.mapSeries = doSeries(_asyncMap);
  11515. async.mapLimit = function (arr, limit, iterator, callback) {
  11516. return _mapLimit(limit)(arr, iterator, callback);
  11517. };
  11518. var _mapLimit = function(limit) {
  11519. return doParallelLimit(limit, _asyncMap);
  11520. };
  11521. // reduce only has a series version, as doing reduce in parallel won't
  11522. // work in many situations.
  11523. async.reduce = function (arr, memo, iterator, callback) {
  11524. async.eachSeries(arr, function (x, callback) {
  11525. iterator(memo, x, function (err, v) {
  11526. memo = v;
  11527. callback(err);
  11528. });
  11529. }, function (err) {
  11530. callback(err, memo);
  11531. });
  11532. };
  11533. // inject alias
  11534. async.inject = async.reduce;
  11535. // foldl alias
  11536. async.foldl = async.reduce;
  11537. async.reduceRight = function (arr, memo, iterator, callback) {
  11538. var reversed = _map(arr, function (x) {
  11539. return x;
  11540. }).reverse();
  11541. async.reduce(reversed, memo, iterator, callback);
  11542. };
  11543. // foldr alias
  11544. async.foldr = async.reduceRight;
  11545. var _filter = function (eachfn, arr, iterator, callback) {
  11546. var results = [];
  11547. arr = _map(arr, function (x, i) {
  11548. return {index: i, value: x};
  11549. });
  11550. eachfn(arr, function (x, callback) {
  11551. iterator(x.value, function (v) {
  11552. if (v) {
  11553. results.push(x);
  11554. }
  11555. callback();
  11556. });
  11557. }, function (err) {
  11558. callback(_map(results.sort(function (a, b) {
  11559. return a.index - b.index;
  11560. }), function (x) {
  11561. return x.value;
  11562. }));
  11563. });
  11564. };
  11565. async.filter = doParallel(_filter);
  11566. async.filterSeries = doSeries(_filter);
  11567. // select alias
  11568. async.select = async.filter;
  11569. async.selectSeries = async.filterSeries;
  11570. var _reject = function (eachfn, arr, iterator, callback) {
  11571. var results = [];
  11572. arr = _map(arr, function (x, i) {
  11573. return {index: i, value: x};
  11574. });
  11575. eachfn(arr, function (x, callback) {
  11576. iterator(x.value, function (v) {
  11577. if (!v) {
  11578. results.push(x);
  11579. }
  11580. callback();
  11581. });
  11582. }, function (err) {
  11583. callback(_map(results.sort(function (a, b) {
  11584. return a.index - b.index;
  11585. }), function (x) {
  11586. return x.value;
  11587. }));
  11588. });
  11589. };
  11590. async.reject = doParallel(_reject);
  11591. async.rejectSeries = doSeries(_reject);
  11592. var _detect = function (eachfn, arr, iterator, main_callback) {
  11593. eachfn(arr, function (x, callback) {
  11594. iterator(x, function (result) {
  11595. if (result) {
  11596. main_callback(x);
  11597. main_callback = function () {};
  11598. }
  11599. else {
  11600. callback();
  11601. }
  11602. });
  11603. }, function (err) {
  11604. main_callback();
  11605. });
  11606. };
  11607. async.detect = doParallel(_detect);
  11608. async.detectSeries = doSeries(_detect);
  11609. async.some = function (arr, iterator, main_callback) {
  11610. async.each(arr, function (x, callback) {
  11611. iterator(x, function (v) {
  11612. if (v) {
  11613. main_callback(true);
  11614. main_callback = function () {};
  11615. }
  11616. callback();
  11617. });
  11618. }, function (err) {
  11619. main_callback(false);
  11620. });
  11621. };
  11622. // any alias
  11623. async.any = async.some;
  11624. async.every = function (arr, iterator, main_callback) {
  11625. async.each(arr, function (x, callback) {
  11626. iterator(x, function (v) {
  11627. if (!v) {
  11628. main_callback(false);
  11629. main_callback = function () {};
  11630. }
  11631. callback();
  11632. });
  11633. }, function (err) {
  11634. main_callback(true);
  11635. });
  11636. };
  11637. // all alias
  11638. async.all = async.every;
  11639. async.sortBy = function (arr, iterator, callback) {
  11640. async.map(arr, function (x, callback) {
  11641. iterator(x, function (err, criteria) {
  11642. if (err) {
  11643. callback(err);
  11644. }
  11645. else {
  11646. callback(null, {value: x, criteria: criteria});
  11647. }
  11648. });
  11649. }, function (err, results) {
  11650. if (err) {
  11651. return callback(err);
  11652. }
  11653. else {
  11654. var fn = function (left, right) {
  11655. var a = left.criteria, b = right.criteria;
  11656. return a < b ? -1 : a > b ? 1 : 0;
  11657. };
  11658. callback(null, _map(results.sort(fn), function (x) {
  11659. return x.value;
  11660. }));
  11661. }
  11662. });
  11663. };
  11664. async.auto = function (tasks, callback) {
  11665. callback = callback || function () {};
  11666. var keys = _keys(tasks);
  11667. var remainingTasks = keys.length
  11668. if (!remainingTasks) {
  11669. return callback();
  11670. }
  11671. var results = {};
  11672. var listeners = [];
  11673. var addListener = function (fn) {
  11674. listeners.unshift(fn);
  11675. };
  11676. var removeListener = function (fn) {
  11677. for (var i = 0; i < listeners.length; i += 1) {
  11678. if (listeners[i] === fn) {
  11679. listeners.splice(i, 1);
  11680. return;
  11681. }
  11682. }
  11683. };
  11684. var taskComplete = function () {
  11685. remainingTasks--
  11686. _each(listeners.slice(0), function (fn) {
  11687. fn();
  11688. });
  11689. };
  11690. addListener(function () {
  11691. if (!remainingTasks) {
  11692. var theCallback = callback;
  11693. // prevent final callback from calling itself if it errors
  11694. callback = function () {};
  11695. theCallback(null, results);
  11696. }
  11697. });
  11698. _each(keys, function (k) {
  11699. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  11700. var taskCallback = function (err) {
  11701. var args = Array.prototype.slice.call(arguments, 1);
  11702. if (args.length <= 1) {
  11703. args = args[0];
  11704. }
  11705. if (err) {
  11706. var safeResults = {};
  11707. _each(_keys(results), function(rkey) {
  11708. safeResults[rkey] = results[rkey];
  11709. });
  11710. safeResults[k] = args;
  11711. callback(err, safeResults);
  11712. // stop subsequent errors hitting callback multiple times
  11713. callback = function () {};
  11714. }
  11715. else {
  11716. results[k] = args;
  11717. async.setImmediate(taskComplete);
  11718. }
  11719. };
  11720. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  11721. var ready = function () {
  11722. return _reduce(requires, function (a, x) {
  11723. return (a && results.hasOwnProperty(x));
  11724. }, true) && !results.hasOwnProperty(k);
  11725. };
  11726. if (ready()) {
  11727. task[task.length - 1](taskCallback, results);
  11728. }
  11729. else {
  11730. var listener = function () {
  11731. if (ready()) {
  11732. removeListener(listener);
  11733. task[task.length - 1](taskCallback, results);
  11734. }
  11735. };
  11736. addListener(listener);
  11737. }
  11738. });
  11739. };
  11740. async.retry = function(times, task, callback) {
  11741. var DEFAULT_TIMES = 5;
  11742. var attempts = [];
  11743. // Use defaults if times not passed
  11744. if (typeof times === 'function') {
  11745. callback = task;
  11746. task = times;
  11747. times = DEFAULT_TIMES;
  11748. }
  11749. // Make sure times is a number
  11750. times = parseInt(times, 10) || DEFAULT_TIMES;
  11751. var wrappedTask = function(wrappedCallback, wrappedResults) {
  11752. var retryAttempt = function(task, finalAttempt) {
  11753. return function(seriesCallback) {
  11754. task(function(err, result){
  11755. seriesCallback(!err || finalAttempt, {err: err, result: result});
  11756. }, wrappedResults);
  11757. };
  11758. };
  11759. while (times) {
  11760. attempts.push(retryAttempt(task, !(times-=1)));
  11761. }
  11762. async.series(attempts, function(done, data){
  11763. data = data[data.length - 1];
  11764. (wrappedCallback || callback)(data.err, data.result);
  11765. });
  11766. }
  11767. // If a callback is passed, run this as a controll flow
  11768. return callback ? wrappedTask() : wrappedTask
  11769. };
  11770. async.waterfall = function (tasks, callback) {
  11771. callback = callback || function () {};
  11772. if (!_isArray(tasks)) {
  11773. var err = new Error('First argument to waterfall must be an array of functions');
  11774. return callback(err);
  11775. }
  11776. if (!tasks.length) {
  11777. return callback();
  11778. }
  11779. var wrapIterator = function (iterator) {
  11780. return function (err) {
  11781. if (err) {
  11782. callback.apply(null, arguments);
  11783. callback = function () {};
  11784. }
  11785. else {
  11786. var args = Array.prototype.slice.call(arguments, 1);
  11787. var next = iterator.next();
  11788. if (next) {
  11789. args.push(wrapIterator(next));
  11790. }
  11791. else {
  11792. args.push(callback);
  11793. }
  11794. async.setImmediate(function () {
  11795. iterator.apply(null, args);
  11796. });
  11797. }
  11798. };
  11799. };
  11800. wrapIterator(async.iterator(tasks))();
  11801. };
  11802. var _parallel = function(eachfn, tasks, callback) {
  11803. callback = callback || function () {};
  11804. if (_isArray(tasks)) {
  11805. eachfn.map(tasks, function (fn, callback) {
  11806. if (fn) {
  11807. fn(function (err) {
  11808. var args = Array.prototype.slice.call(arguments, 1);
  11809. if (args.length <= 1) {
  11810. args = args[0];
  11811. }
  11812. callback.call(null, err, args);
  11813. });
  11814. }
  11815. }, callback);
  11816. }
  11817. else {
  11818. var results = {};
  11819. eachfn.each(_keys(tasks), function (k, callback) {
  11820. tasks[k](function (err) {
  11821. var args = Array.prototype.slice.call(arguments, 1);
  11822. if (args.length <= 1) {
  11823. args = args[0];
  11824. }
  11825. results[k] = args;
  11826. callback(err);
  11827. });
  11828. }, function (err) {
  11829. callback(err, results);
  11830. });
  11831. }
  11832. };
  11833. async.parallel = function (tasks, callback) {
  11834. _parallel({ map: async.map, each: async.each }, tasks, callback);
  11835. };
  11836. async.parallelLimit = function(tasks, limit, callback) {
  11837. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  11838. };
  11839. async.series = function (tasks, callback) {
  11840. callback = callback || function () {};
  11841. if (_isArray(tasks)) {
  11842. async.mapSeries(tasks, function (fn, callback) {
  11843. if (fn) {
  11844. fn(function (err) {
  11845. var args = Array.prototype.slice.call(arguments, 1);
  11846. if (args.length <= 1) {
  11847. args = args[0];
  11848. }
  11849. callback.call(null, err, args);
  11850. });
  11851. }
  11852. }, callback);
  11853. }
  11854. else {
  11855. var results = {};
  11856. async.eachSeries(_keys(tasks), function (k, callback) {
  11857. tasks[k](function (err) {
  11858. var args = Array.prototype.slice.call(arguments, 1);
  11859. if (args.length <= 1) {
  11860. args = args[0];
  11861. }
  11862. results[k] = args;
  11863. callback(err);
  11864. });
  11865. }, function (err) {
  11866. callback(err, results);
  11867. });
  11868. }
  11869. };
  11870. async.iterator = function (tasks) {
  11871. var makeCallback = function (index) {
  11872. var fn = function () {
  11873. if (tasks.length) {
  11874. tasks[index].apply(null, arguments);
  11875. }
  11876. return fn.next();
  11877. };
  11878. fn.next = function () {
  11879. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11880. };
  11881. return fn;
  11882. };
  11883. return makeCallback(0);
  11884. };
  11885. async.apply = function (fn) {
  11886. var args = Array.prototype.slice.call(arguments, 1);
  11887. return function () {
  11888. return fn.apply(
  11889. null, args.concat(Array.prototype.slice.call(arguments))
  11890. );
  11891. };
  11892. };
  11893. var _concat = function (eachfn, arr, fn, callback) {
  11894. var r = [];
  11895. eachfn(arr, function (x, cb) {
  11896. fn(x, function (err, y) {
  11897. r = r.concat(y || []);
  11898. cb(err);
  11899. });
  11900. }, function (err) {
  11901. callback(err, r);
  11902. });
  11903. };
  11904. async.concat = doParallel(_concat);
  11905. async.concatSeries = doSeries(_concat);
  11906. async.whilst = function (test, iterator, callback) {
  11907. if (test()) {
  11908. iterator(function (err) {
  11909. if (err) {
  11910. return callback(err);
  11911. }
  11912. async.whilst(test, iterator, callback);
  11913. });
  11914. }
  11915. else {
  11916. callback();
  11917. }
  11918. };
  11919. async.doWhilst = function (iterator, test, callback) {
  11920. iterator(function (err) {
  11921. if (err) {
  11922. return callback(err);
  11923. }
  11924. var args = Array.prototype.slice.call(arguments, 1);
  11925. if (test.apply(null, args)) {
  11926. async.doWhilst(iterator, test, callback);
  11927. }
  11928. else {
  11929. callback();
  11930. }
  11931. });
  11932. };
  11933. async.until = function (test, iterator, callback) {
  11934. if (!test()) {
  11935. iterator(function (err) {
  11936. if (err) {
  11937. return callback(err);
  11938. }
  11939. async.until(test, iterator, callback);
  11940. });
  11941. }
  11942. else {
  11943. callback();
  11944. }
  11945. };
  11946. async.doUntil = function (iterator, test, callback) {
  11947. iterator(function (err) {
  11948. if (err) {
  11949. return callback(err);
  11950. }
  11951. var args = Array.prototype.slice.call(arguments, 1);
  11952. if (!test.apply(null, args)) {
  11953. async.doUntil(iterator, test, callback);
  11954. }
  11955. else {
  11956. callback();
  11957. }
  11958. });
  11959. };
  11960. async.queue = function (worker, concurrency) {
  11961. if (concurrency === undefined) {
  11962. concurrency = 1;
  11963. }
  11964. function _insert(q, data, pos, callback) {
  11965. if (!q.started){
  11966. q.started = true;
  11967. }
  11968. if (!_isArray(data)) {
  11969. data = [data];
  11970. }
  11971. if(data.length == 0) {
  11972. // call drain immediately if there are no tasks
  11973. return async.setImmediate(function() {
  11974. if (q.drain) {
  11975. q.drain();
  11976. }
  11977. });
  11978. }
  11979. _each(data, function(task) {
  11980. var item = {
  11981. data: task,
  11982. callback: typeof callback === 'function' ? callback : null
  11983. };
  11984. if (pos) {
  11985. q.tasks.unshift(item);
  11986. } else {
  11987. q.tasks.push(item);
  11988. }
  11989. if (q.saturated && q.tasks.length === q.concurrency) {
  11990. q.saturated();
  11991. }
  11992. async.setImmediate(q.process);
  11993. });
  11994. }
  11995. var workers = 0;
  11996. var q = {
  11997. tasks: [],
  11998. concurrency: concurrency,
  11999. saturated: null,
  12000. empty: null,
  12001. drain: null,
  12002. started: false,
  12003. paused: false,
  12004. push: function (data, callback) {
  12005. _insert(q, data, false, callback);
  12006. },
  12007. kill: function () {
  12008. q.drain = null;
  12009. q.tasks = [];
  12010. },
  12011. unshift: function (data, callback) {
  12012. _insert(q, data, true, callback);
  12013. },
  12014. process: function () {
  12015. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  12016. var task = q.tasks.shift();
  12017. if (q.empty && q.tasks.length === 0) {
  12018. q.empty();
  12019. }
  12020. workers += 1;
  12021. var next = function () {
  12022. workers -= 1;
  12023. if (task.callback) {
  12024. task.callback.apply(task, arguments);
  12025. }
  12026. if (q.drain && q.tasks.length + workers === 0) {
  12027. q.drain();
  12028. }
  12029. q.process();
  12030. };
  12031. var cb = only_once(next);
  12032. worker(task.data, cb);
  12033. }
  12034. },
  12035. length: function () {
  12036. return q.tasks.length;
  12037. },
  12038. running: function () {
  12039. return workers;
  12040. },
  12041. idle: function() {
  12042. return q.tasks.length + workers === 0;
  12043. },
  12044. pause: function () {
  12045. if (q.paused === true) { return; }
  12046. q.paused = true;
  12047. q.process();
  12048. },
  12049. resume: function () {
  12050. if (q.paused === false) { return; }
  12051. q.paused = false;
  12052. q.process();
  12053. }
  12054. };
  12055. return q;
  12056. };
  12057. async.priorityQueue = function (worker, concurrency) {
  12058. function _compareTasks(a, b){
  12059. return a.priority - b.priority;
  12060. };
  12061. function _binarySearch(sequence, item, compare) {
  12062. var beg = -1,
  12063. end = sequence.length - 1;
  12064. while (beg < end) {
  12065. var mid = beg + ((end - beg + 1) >>> 1);
  12066. if (compare(item, sequence[mid]) >= 0) {
  12067. beg = mid;
  12068. } else {
  12069. end = mid - 1;
  12070. }
  12071. }
  12072. return beg;
  12073. }
  12074. function _insert(q, data, priority, callback) {
  12075. if (!q.started){
  12076. q.started = true;
  12077. }
  12078. if (!_isArray(data)) {
  12079. data = [data];
  12080. }
  12081. if(data.length == 0) {
  12082. // call drain immediately if there are no tasks
  12083. return async.setImmediate(function() {
  12084. if (q.drain) {
  12085. q.drain();
  12086. }
  12087. });
  12088. }
  12089. _each(data, function(task) {
  12090. var item = {
  12091. data: task,
  12092. priority: priority,
  12093. callback: typeof callback === 'function' ? callback : null
  12094. };
  12095. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12096. if (q.saturated && q.tasks.length === q.concurrency) {
  12097. q.saturated();
  12098. }
  12099. async.setImmediate(q.process);
  12100. });
  12101. }
  12102. // Start with a normal queue
  12103. var q = async.queue(worker, concurrency);
  12104. // Override push to accept second parameter representing priority
  12105. q.push = function (data, priority, callback) {
  12106. _insert(q, data, priority, callback);
  12107. };
  12108. // Remove unshift function
  12109. delete q.unshift;
  12110. return q;
  12111. };
  12112. async.cargo = function (worker, payload) {
  12113. var working = false,
  12114. tasks = [];
  12115. var cargo = {
  12116. tasks: tasks,
  12117. payload: payload,
  12118. saturated: null,
  12119. empty: null,
  12120. drain: null,
  12121. drained: true,
  12122. push: function (data, callback) {
  12123. if (!_isArray(data)) {
  12124. data = [data];
  12125. }
  12126. _each(data, function(task) {
  12127. tasks.push({
  12128. data: task,
  12129. callback: typeof callback === 'function' ? callback : null
  12130. });
  12131. cargo.drained = false;
  12132. if (cargo.saturated && tasks.length === payload) {
  12133. cargo.saturated();
  12134. }
  12135. });
  12136. async.setImmediate(cargo.process);
  12137. },
  12138. process: function process() {
  12139. if (working) return;
  12140. if (tasks.length === 0) {
  12141. if(cargo.drain && !cargo.drained) cargo.drain();
  12142. cargo.drained = true;
  12143. return;
  12144. }
  12145. var ts = typeof payload === 'number'
  12146. ? tasks.splice(0, payload)
  12147. : tasks.splice(0, tasks.length);
  12148. var ds = _map(ts, function (task) {
  12149. return task.data;
  12150. });
  12151. if(cargo.empty) cargo.empty();
  12152. working = true;
  12153. worker(ds, function () {
  12154. working = false;
  12155. var args = arguments;
  12156. _each(ts, function (data) {
  12157. if (data.callback) {
  12158. data.callback.apply(null, args);
  12159. }
  12160. });
  12161. process();
  12162. });
  12163. },
  12164. length: function () {
  12165. return tasks.length;
  12166. },
  12167. running: function () {
  12168. return working;
  12169. }
  12170. };
  12171. return cargo;
  12172. };
  12173. var _console_fn = function (name) {
  12174. return function (fn) {
  12175. var args = Array.prototype.slice.call(arguments, 1);
  12176. fn.apply(null, args.concat([function (err) {
  12177. var args = Array.prototype.slice.call(arguments, 1);
  12178. if (typeof console !== 'undefined') {
  12179. if (err) {
  12180. if (console.error) {
  12181. console.error(err);
  12182. }
  12183. }
  12184. else if (console[name]) {
  12185. _each(args, function (x) {
  12186. console[name](x);
  12187. });
  12188. }
  12189. }
  12190. }]));
  12191. };
  12192. };
  12193. async.log = _console_fn('log');
  12194. async.dir = _console_fn('dir');
  12195. /*async.info = _console_fn('info');
  12196. async.warn = _console_fn('warn');
  12197. async.error = _console_fn('error');*/
  12198. async.memoize = function (fn, hasher) {
  12199. var memo = {};
  12200. var queues = {};
  12201. hasher = hasher || function (x) {
  12202. return x;
  12203. };
  12204. var memoized = function () {
  12205. var args = Array.prototype.slice.call(arguments);
  12206. var callback = args.pop();
  12207. var key = hasher.apply(null, args);
  12208. if (key in memo) {
  12209. async.nextTick(function () {
  12210. callback.apply(null, memo[key]);
  12211. });
  12212. }
  12213. else if (key in queues) {
  12214. queues[key].push(callback);
  12215. }
  12216. else {
  12217. queues[key] = [callback];
  12218. fn.apply(null, args.concat([function () {
  12219. memo[key] = arguments;
  12220. var q = queues[key];
  12221. delete queues[key];
  12222. for (var i = 0, l = q.length; i < l; i++) {
  12223. q[i].apply(null, arguments);
  12224. }
  12225. }]));
  12226. }
  12227. };
  12228. memoized.memo = memo;
  12229. memoized.unmemoized = fn;
  12230. return memoized;
  12231. };
  12232. async.unmemoize = function (fn) {
  12233. return function () {
  12234. return (fn.unmemoized || fn).apply(null, arguments);
  12235. };
  12236. };
  12237. async.times = function (count, iterator, callback) {
  12238. var counter = [];
  12239. for (var i = 0; i < count; i++) {
  12240. counter.push(i);
  12241. }
  12242. return async.map(counter, iterator, callback);
  12243. };
  12244. async.timesSeries = function (count, iterator, callback) {
  12245. var counter = [];
  12246. for (var i = 0; i < count; i++) {
  12247. counter.push(i);
  12248. }
  12249. return async.mapSeries(counter, iterator, callback);
  12250. };
  12251. async.seq = function (/* functions... */) {
  12252. var fns = arguments;
  12253. return function () {
  12254. var that = this;
  12255. var args = Array.prototype.slice.call(arguments);
  12256. var callback = args.pop();
  12257. async.reduce(fns, args, function (newargs, fn, cb) {
  12258. fn.apply(that, newargs.concat([function () {
  12259. var err = arguments[0];
  12260. var nextargs = Array.prototype.slice.call(arguments, 1);
  12261. cb(err, nextargs);
  12262. }]))
  12263. },
  12264. function (err, results) {
  12265. callback.apply(that, [err].concat(results));
  12266. });
  12267. };
  12268. };
  12269. async.compose = function (/* functions... */) {
  12270. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  12271. };
  12272. var _applyEach = function (eachfn, fns /*args...*/) {
  12273. var go = function () {
  12274. var that = this;
  12275. var args = Array.prototype.slice.call(arguments);
  12276. var callback = args.pop();
  12277. return eachfn(fns, function (fn, cb) {
  12278. fn.apply(that, args.concat([cb]));
  12279. },
  12280. callback);
  12281. };
  12282. if (arguments.length > 2) {
  12283. var args = Array.prototype.slice.call(arguments, 2);
  12284. return go.apply(this, args);
  12285. }
  12286. else {
  12287. return go;
  12288. }
  12289. };
  12290. async.applyEach = doParallel(_applyEach);
  12291. async.applyEachSeries = doSeries(_applyEach);
  12292. async.forever = function (fn, callback) {
  12293. function next(err) {
  12294. if (err) {
  12295. if (callback) {
  12296. return callback(err);
  12297. }
  12298. throw err;
  12299. }
  12300. fn(next);
  12301. }
  12302. next();
  12303. };
  12304. // Node.js
  12305. if (typeof module !== 'undefined' && module.exports) {
  12306. module.exports = async;
  12307. }
  12308. // AMD / RequireJS
  12309. else if (typeof define !== 'undefined' && define.amd) {
  12310. define([], function () {
  12311. return async;
  12312. });
  12313. }
  12314. // included directly via <script> tag
  12315. else {
  12316. root.async = async;
  12317. }
  12318. }());
  12319. }).call(this,require('_process'))
  12320. },{"_process":45}],44:[function(require,module,exports){
  12321. // Copyright Joyent, Inc. and other Node contributors.
  12322. //
  12323. // Permission is hereby granted, free of charge, to any person obtaining a
  12324. // copy of this software and associated documentation files (the
  12325. // "Software"), to deal in the Software without restriction, including
  12326. // without limitation the rights to use, copy, modify, merge, publish,
  12327. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12328. // persons to whom the Software is furnished to do so, subject to the
  12329. // following conditions:
  12330. //
  12331. // The above copyright notice and this permission notice shall be included
  12332. // in all copies or substantial portions of the Software.
  12333. //
  12334. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12335. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12336. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12337. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12338. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12339. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12340. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12341. function EventEmitter() {
  12342. this._events = this._events || {};
  12343. this._maxListeners = this._maxListeners || undefined;
  12344. }
  12345. module.exports = EventEmitter;
  12346. // Backwards-compat with node 0.10.x
  12347. EventEmitter.EventEmitter = EventEmitter;
  12348. EventEmitter.prototype._events = undefined;
  12349. EventEmitter.prototype._maxListeners = undefined;
  12350. // By default EventEmitters will print a warning if more than 10 listeners are
  12351. // added to it. This is a useful default which helps finding memory leaks.
  12352. EventEmitter.defaultMaxListeners = 10;
  12353. // Obviously not all Emitters should be limited to 10. This function allows
  12354. // that to be increased. Set to zero for unlimited.
  12355. EventEmitter.prototype.setMaxListeners = function(n) {
  12356. if (!isNumber(n) || n < 0 || isNaN(n))
  12357. throw TypeError('n must be a positive number');
  12358. this._maxListeners = n;
  12359. return this;
  12360. };
  12361. EventEmitter.prototype.emit = function(type) {
  12362. var er, handler, len, args, i, listeners;
  12363. if (!this._events)
  12364. this._events = {};
  12365. // If there is no 'error' event listener then throw.
  12366. if (type === 'error') {
  12367. if (!this._events.error ||
  12368. (isObject(this._events.error) && !this._events.error.length)) {
  12369. er = arguments[1];
  12370. if (er instanceof Error) {
  12371. throw er; // Unhandled 'error' event
  12372. }
  12373. throw TypeError('Uncaught, unspecified "error" event.');
  12374. }
  12375. }
  12376. handler = this._events[type];
  12377. if (isUndefined(handler))
  12378. return false;
  12379. if (isFunction(handler)) {
  12380. switch (arguments.length) {
  12381. // fast cases
  12382. case 1:
  12383. handler.call(this);
  12384. break;
  12385. case 2:
  12386. handler.call(this, arguments[1]);
  12387. break;
  12388. case 3:
  12389. handler.call(this, arguments[1], arguments[2]);
  12390. break;
  12391. // slower
  12392. default:
  12393. len = arguments.length;
  12394. args = new Array(len - 1);
  12395. for (i = 1; i < len; i++)
  12396. args[i - 1] = arguments[i];
  12397. handler.apply(this, args);
  12398. }
  12399. } else if (isObject(handler)) {
  12400. len = arguments.length;
  12401. args = new Array(len - 1);
  12402. for (i = 1; i < len; i++)
  12403. args[i - 1] = arguments[i];
  12404. listeners = handler.slice();
  12405. len = listeners.length;
  12406. for (i = 0; i < len; i++)
  12407. listeners[i].apply(this, args);
  12408. }
  12409. return true;
  12410. };
  12411. EventEmitter.prototype.addListener = function(type, listener) {
  12412. var m;
  12413. if (!isFunction(listener))
  12414. throw TypeError('listener must be a function');
  12415. if (!this._events)
  12416. this._events = {};
  12417. // To avoid recursion in the case that type === "newListener"! Before
  12418. // adding it to the listeners, first emit "newListener".
  12419. if (this._events.newListener)
  12420. this.emit('newListener', type,
  12421. isFunction(listener.listener) ?
  12422. listener.listener : listener);
  12423. if (!this._events[type])
  12424. // Optimize the case of one listener. Don't need the extra array object.
  12425. this._events[type] = listener;
  12426. else if (isObject(this._events[type]))
  12427. // If we've already got an array, just append.
  12428. this._events[type].push(listener);
  12429. else
  12430. // Adding the second element, need to change to array.
  12431. this._events[type] = [this._events[type], listener];
  12432. // Check for listener leak
  12433. if (isObject(this._events[type]) && !this._events[type].warned) {
  12434. var m;
  12435. if (!isUndefined(this._maxListeners)) {
  12436. m = this._maxListeners;
  12437. } else {
  12438. m = EventEmitter.defaultMaxListeners;
  12439. }
  12440. if (m && m > 0 && this._events[type].length > m) {
  12441. this._events[type].warned = true;
  12442. console.error('(node) warning: possible EventEmitter memory ' +
  12443. 'leak detected. %d listeners added. ' +
  12444. 'Use emitter.setMaxListeners() to increase limit.',
  12445. this._events[type].length);
  12446. if (typeof console.trace === 'function') {
  12447. // not supported in IE 10
  12448. console.trace();
  12449. }
  12450. }
  12451. }
  12452. return this;
  12453. };
  12454. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  12455. EventEmitter.prototype.once = function(type, listener) {
  12456. if (!isFunction(listener))
  12457. throw TypeError('listener must be a function');
  12458. var fired = false;
  12459. function g() {
  12460. this.removeListener(type, g);
  12461. if (!fired) {
  12462. fired = true;
  12463. listener.apply(this, arguments);
  12464. }
  12465. }
  12466. g.listener = listener;
  12467. this.on(type, g);
  12468. return this;
  12469. };
  12470. // emits a 'removeListener' event iff the listener was removed
  12471. EventEmitter.prototype.removeListener = function(type, listener) {
  12472. var list, position, length, i;
  12473. if (!isFunction(listener))
  12474. throw TypeError('listener must be a function');
  12475. if (!this._events || !this._events[type])
  12476. return this;
  12477. list = this._events[type];
  12478. length = list.length;
  12479. position = -1;
  12480. if (list === listener ||
  12481. (isFunction(list.listener) && list.listener === listener)) {
  12482. delete this._events[type];
  12483. if (this._events.removeListener)
  12484. this.emit('removeListener', type, listener);
  12485. } else if (isObject(list)) {
  12486. for (i = length; i-- > 0;) {
  12487. if (list[i] === listener ||
  12488. (list[i].listener && list[i].listener === listener)) {
  12489. position = i;
  12490. break;
  12491. }
  12492. }
  12493. if (position < 0)
  12494. return this;
  12495. if (list.length === 1) {
  12496. list.length = 0;
  12497. delete this._events[type];
  12498. } else {
  12499. list.splice(position, 1);
  12500. }
  12501. if (this._events.removeListener)
  12502. this.emit('removeListener', type, listener);
  12503. }
  12504. return this;
  12505. };
  12506. EventEmitter.prototype.removeAllListeners = function(type) {
  12507. var key, listeners;
  12508. if (!this._events)
  12509. return this;
  12510. // not listening for removeListener, no need to emit
  12511. if (!this._events.removeListener) {
  12512. if (arguments.length === 0)
  12513. this._events = {};
  12514. else if (this._events[type])
  12515. delete this._events[type];
  12516. return this;
  12517. }
  12518. // emit removeListener for all listeners on all events
  12519. if (arguments.length === 0) {
  12520. for (key in this._events) {
  12521. if (key === 'removeListener') continue;
  12522. this.removeAllListeners(key);
  12523. }
  12524. this.removeAllListeners('removeListener');
  12525. this._events = {};
  12526. return this;
  12527. }
  12528. listeners = this._events[type];
  12529. if (isFunction(listeners)) {
  12530. this.removeListener(type, listeners);
  12531. } else {
  12532. // LIFO order
  12533. while (listeners.length)
  12534. this.removeListener(type, listeners[listeners.length - 1]);
  12535. }
  12536. delete this._events[type];
  12537. return this;
  12538. };
  12539. EventEmitter.prototype.listeners = function(type) {
  12540. var ret;
  12541. if (!this._events || !this._events[type])
  12542. ret = [];
  12543. else if (isFunction(this._events[type]))
  12544. ret = [this._events[type]];
  12545. else
  12546. ret = this._events[type].slice();
  12547. return ret;
  12548. };
  12549. EventEmitter.listenerCount = function(emitter, type) {
  12550. var ret;
  12551. if (!emitter._events || !emitter._events[type])
  12552. ret = 0;
  12553. else if (isFunction(emitter._events[type]))
  12554. ret = 1;
  12555. else
  12556. ret = emitter._events[type].length;
  12557. return ret;
  12558. };
  12559. function isFunction(arg) {
  12560. return typeof arg === 'function';
  12561. }
  12562. function isNumber(arg) {
  12563. return typeof arg === 'number';
  12564. }
  12565. function isObject(arg) {
  12566. return typeof arg === 'object' && arg !== null;
  12567. }
  12568. function isUndefined(arg) {
  12569. return arg === void 0;
  12570. }
  12571. },{}],45:[function(require,module,exports){
  12572. // shim for using process in browser
  12573. var process = module.exports = {};
  12574. var queue = [];
  12575. var draining = false;
  12576. var currentQueue;
  12577. var queueIndex = -1;
  12578. function cleanUpNextTick() {
  12579. draining = false;
  12580. if (currentQueue.length) {
  12581. queue = currentQueue.concat(queue);
  12582. } else {
  12583. queueIndex = -1;
  12584. }
  12585. if (queue.length) {
  12586. drainQueue();
  12587. }
  12588. }
  12589. function drainQueue() {
  12590. if (draining) {
  12591. return;
  12592. }
  12593. var timeout = setTimeout(cleanUpNextTick);
  12594. draining = true;
  12595. var len = queue.length;
  12596. while(len) {
  12597. currentQueue = queue;
  12598. queue = [];
  12599. while (++queueIndex < len) {
  12600. if (currentQueue) {
  12601. currentQueue[queueIndex].run();
  12602. }
  12603. }
  12604. queueIndex = -1;
  12605. len = queue.length;
  12606. }
  12607. currentQueue = null;
  12608. draining = false;
  12609. clearTimeout(timeout);
  12610. }
  12611. process.nextTick = function (fun) {
  12612. var args = new Array(arguments.length - 1);
  12613. if (arguments.length > 1) {
  12614. for (var i = 1; i < arguments.length; i++) {
  12615. args[i - 1] = arguments[i];
  12616. }
  12617. }
  12618. queue.push(new Item(fun, args));
  12619. if (queue.length === 1 && !draining) {
  12620. setTimeout(drainQueue, 0);
  12621. }
  12622. };
  12623. // v8 likes predictible objects
  12624. function Item(fun, array) {
  12625. this.fun = fun;
  12626. this.array = array;
  12627. }
  12628. Item.prototype.run = function () {
  12629. this.fun.apply(null, this.array);
  12630. };
  12631. process.title = 'browser';
  12632. process.browser = true;
  12633. process.env = {};
  12634. process.argv = [];
  12635. process.version = ''; // empty string to avoid regexp issues
  12636. process.versions = {};
  12637. function noop() {}
  12638. process.on = noop;
  12639. process.addListener = noop;
  12640. process.once = noop;
  12641. process.off = noop;
  12642. process.removeListener = noop;
  12643. process.removeAllListeners = noop;
  12644. process.emit = noop;
  12645. process.binding = function (name) {
  12646. throw new Error('process.binding is not supported');
  12647. };
  12648. process.cwd = function () { return '/' };
  12649. process.chdir = function (dir) {
  12650. throw new Error('process.chdir is not supported');
  12651. };
  12652. process.umask = function() { return 0; };
  12653. },{}],46:[function(require,module,exports){
  12654. (function (process,global){
  12655. /*!
  12656. * @overview es6-promise - a tiny implementation of Promises/A+.
  12657. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  12658. * @license Licensed under MIT license
  12659. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  12660. * @version 3.0.2
  12661. */
  12662. (function() {
  12663. "use strict";
  12664. function lib$es6$promise$utils$$objectOrFunction(x) {
  12665. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  12666. }
  12667. function lib$es6$promise$utils$$isFunction(x) {
  12668. return typeof x === 'function';
  12669. }
  12670. function lib$es6$promise$utils$$isMaybeThenable(x) {
  12671. return typeof x === 'object' && x !== null;
  12672. }
  12673. var lib$es6$promise$utils$$_isArray;
  12674. if (!Array.isArray) {
  12675. lib$es6$promise$utils$$_isArray = function (x) {
  12676. return Object.prototype.toString.call(x) === '[object Array]';
  12677. };
  12678. } else {
  12679. lib$es6$promise$utils$$_isArray = Array.isArray;
  12680. }
  12681. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  12682. var lib$es6$promise$asap$$len = 0;
  12683. var lib$es6$promise$asap$$toString = {}.toString;
  12684. var lib$es6$promise$asap$$vertxNext;
  12685. var lib$es6$promise$asap$$customSchedulerFn;
  12686. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  12687. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  12688. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  12689. lib$es6$promise$asap$$len += 2;
  12690. if (lib$es6$promise$asap$$len === 2) {
  12691. // If len is 2, that means that we need to schedule an async flush.
  12692. // If additional callbacks are queued before the queue is flushed, they
  12693. // will be processed by this flush that we are scheduling.
  12694. if (lib$es6$promise$asap$$customSchedulerFn) {
  12695. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  12696. } else {
  12697. lib$es6$promise$asap$$scheduleFlush();
  12698. }
  12699. }
  12700. }
  12701. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  12702. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  12703. }
  12704. function lib$es6$promise$asap$$setAsap(asapFn) {
  12705. lib$es6$promise$asap$$asap = asapFn;
  12706. }
  12707. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  12708. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  12709. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  12710. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  12711. // test for web worker but not in IE10
  12712. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  12713. typeof importScripts !== 'undefined' &&
  12714. typeof MessageChannel !== 'undefined';
  12715. // node
  12716. function lib$es6$promise$asap$$useNextTick() {
  12717. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  12718. // see https://github.com/cujojs/when/issues/410 for details
  12719. return function() {
  12720. process.nextTick(lib$es6$promise$asap$$flush);
  12721. };
  12722. }
  12723. // vertx
  12724. function lib$es6$promise$asap$$useVertxTimer() {
  12725. return function() {
  12726. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  12727. };
  12728. }
  12729. function lib$es6$promise$asap$$useMutationObserver() {
  12730. var iterations = 0;
  12731. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  12732. var node = document.createTextNode('');
  12733. observer.observe(node, { characterData: true });
  12734. return function() {
  12735. node.data = (iterations = ++iterations % 2);
  12736. };
  12737. }
  12738. // web worker
  12739. function lib$es6$promise$asap$$useMessageChannel() {
  12740. var channel = new MessageChannel();
  12741. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  12742. return function () {
  12743. channel.port2.postMessage(0);
  12744. };
  12745. }
  12746. function lib$es6$promise$asap$$useSetTimeout() {
  12747. return function() {
  12748. setTimeout(lib$es6$promise$asap$$flush, 1);
  12749. };
  12750. }
  12751. var lib$es6$promise$asap$$queue = new Array(1000);
  12752. function lib$es6$promise$asap$$flush() {
  12753. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  12754. var callback = lib$es6$promise$asap$$queue[i];
  12755. var arg = lib$es6$promise$asap$$queue[i+1];
  12756. callback(arg);
  12757. lib$es6$promise$asap$$queue[i] = undefined;
  12758. lib$es6$promise$asap$$queue[i+1] = undefined;
  12759. }
  12760. lib$es6$promise$asap$$len = 0;
  12761. }
  12762. function lib$es6$promise$asap$$attemptVertx() {
  12763. try {
  12764. var r = require;
  12765. var vertx = r('vertx');
  12766. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  12767. return lib$es6$promise$asap$$useVertxTimer();
  12768. } catch(e) {
  12769. return lib$es6$promise$asap$$useSetTimeout();
  12770. }
  12771. }
  12772. var lib$es6$promise$asap$$scheduleFlush;
  12773. // Decide what async method to use to triggering processing of queued callbacks:
  12774. if (lib$es6$promise$asap$$isNode) {
  12775. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  12776. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  12777. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  12778. } else if (lib$es6$promise$asap$$isWorker) {
  12779. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  12780. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  12781. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  12782. } else {
  12783. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  12784. }
  12785. function lib$es6$promise$$internal$$noop() {}
  12786. var lib$es6$promise$$internal$$PENDING = void 0;
  12787. var lib$es6$promise$$internal$$FULFILLED = 1;
  12788. var lib$es6$promise$$internal$$REJECTED = 2;
  12789. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12790. function lib$es6$promise$$internal$$selfFulfillment() {
  12791. return new TypeError("You cannot resolve a promise with itself");
  12792. }
  12793. function lib$es6$promise$$internal$$cannotReturnOwn() {
  12794. return new TypeError('A promises callback cannot return that same promise.');
  12795. }
  12796. function lib$es6$promise$$internal$$getThen(promise) {
  12797. try {
  12798. return promise.then;
  12799. } catch(error) {
  12800. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  12801. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  12802. }
  12803. }
  12804. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  12805. try {
  12806. then.call(value, fulfillmentHandler, rejectionHandler);
  12807. } catch(e) {
  12808. return e;
  12809. }
  12810. }
  12811. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  12812. lib$es6$promise$asap$$asap(function(promise) {
  12813. var sealed = false;
  12814. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  12815. if (sealed) { return; }
  12816. sealed = true;
  12817. if (thenable !== value) {
  12818. lib$es6$promise$$internal$$resolve(promise, value);
  12819. } else {
  12820. lib$es6$promise$$internal$$fulfill(promise, value);
  12821. }
  12822. }, function(reason) {
  12823. if (sealed) { return; }
  12824. sealed = true;
  12825. lib$es6$promise$$internal$$reject(promise, reason);
  12826. }, 'Settle: ' + (promise._label || ' unknown promise'));
  12827. if (!sealed && error) {
  12828. sealed = true;
  12829. lib$es6$promise$$internal$$reject(promise, error);
  12830. }
  12831. }, promise);
  12832. }
  12833. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  12834. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  12835. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  12836. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  12837. lib$es6$promise$$internal$$reject(promise, thenable._result);
  12838. } else {
  12839. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  12840. lib$es6$promise$$internal$$resolve(promise, value);
  12841. }, function(reason) {
  12842. lib$es6$promise$$internal$$reject(promise, reason);
  12843. });
  12844. }
  12845. }
  12846. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12847. if (maybeThenable.constructor === promise.constructor) {
  12848. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12849. } else {
  12850. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12851. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12852. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12853. } else if (then === undefined) {
  12854. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12855. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12856. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12857. } else {
  12858. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12859. }
  12860. }
  12861. }
  12862. function lib$es6$promise$$internal$$resolve(promise, value) {
  12863. if (promise === value) {
  12864. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12865. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12866. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12867. } else {
  12868. lib$es6$promise$$internal$$fulfill(promise, value);
  12869. }
  12870. }
  12871. function lib$es6$promise$$internal$$publishRejection(promise) {
  12872. if (promise._onerror) {
  12873. promise._onerror(promise._result);
  12874. }
  12875. lib$es6$promise$$internal$$publish(promise);
  12876. }
  12877. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12878. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12879. promise._result = value;
  12880. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12881. if (promise._subscribers.length !== 0) {
  12882. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12883. }
  12884. }
  12885. function lib$es6$promise$$internal$$reject(promise, reason) {
  12886. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12887. promise._state = lib$es6$promise$$internal$$REJECTED;
  12888. promise._result = reason;
  12889. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12890. }
  12891. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12892. var subscribers = parent._subscribers;
  12893. var length = subscribers.length;
  12894. parent._onerror = null;
  12895. subscribers[length] = child;
  12896. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12897. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12898. if (length === 0 && parent._state) {
  12899. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12900. }
  12901. }
  12902. function lib$es6$promise$$internal$$publish(promise) {
  12903. var subscribers = promise._subscribers;
  12904. var settled = promise._state;
  12905. if (subscribers.length === 0) { return; }
  12906. var child, callback, detail = promise._result;
  12907. for (var i = 0; i < subscribers.length; i += 3) {
  12908. child = subscribers[i];
  12909. callback = subscribers[i + settled];
  12910. if (child) {
  12911. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12912. } else {
  12913. callback(detail);
  12914. }
  12915. }
  12916. promise._subscribers.length = 0;
  12917. }
  12918. function lib$es6$promise$$internal$$ErrorObject() {
  12919. this.error = null;
  12920. }
  12921. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12922. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12923. try {
  12924. return callback(detail);
  12925. } catch(e) {
  12926. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12927. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12928. }
  12929. }
  12930. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12931. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12932. value, error, succeeded, failed;
  12933. if (hasCallback) {
  12934. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12935. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12936. failed = true;
  12937. error = value.error;
  12938. value = null;
  12939. } else {
  12940. succeeded = true;
  12941. }
  12942. if (promise === value) {
  12943. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12944. return;
  12945. }
  12946. } else {
  12947. value = detail;
  12948. succeeded = true;
  12949. }
  12950. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12951. // noop
  12952. } else if (hasCallback && succeeded) {
  12953. lib$es6$promise$$internal$$resolve(promise, value);
  12954. } else if (failed) {
  12955. lib$es6$promise$$internal$$reject(promise, error);
  12956. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12957. lib$es6$promise$$internal$$fulfill(promise, value);
  12958. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12959. lib$es6$promise$$internal$$reject(promise, value);
  12960. }
  12961. }
  12962. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12963. try {
  12964. resolver(function resolvePromise(value){
  12965. lib$es6$promise$$internal$$resolve(promise, value);
  12966. }, function rejectPromise(reason) {
  12967. lib$es6$promise$$internal$$reject(promise, reason);
  12968. });
  12969. } catch(e) {
  12970. lib$es6$promise$$internal$$reject(promise, e);
  12971. }
  12972. }
  12973. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12974. var enumerator = this;
  12975. enumerator._instanceConstructor = Constructor;
  12976. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12977. if (enumerator._validateInput(input)) {
  12978. enumerator._input = input;
  12979. enumerator.length = input.length;
  12980. enumerator._remaining = input.length;
  12981. enumerator._init();
  12982. if (enumerator.length === 0) {
  12983. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12984. } else {
  12985. enumerator.length = enumerator.length || 0;
  12986. enumerator._enumerate();
  12987. if (enumerator._remaining === 0) {
  12988. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12989. }
  12990. }
  12991. } else {
  12992. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12993. }
  12994. }
  12995. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12996. return lib$es6$promise$utils$$isArray(input);
  12997. };
  12998. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12999. return new Error('Array Methods must be provided an Array');
  13000. };
  13001. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  13002. this._result = new Array(this.length);
  13003. };
  13004. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  13005. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  13006. var enumerator = this;
  13007. var length = enumerator.length;
  13008. var promise = enumerator.promise;
  13009. var input = enumerator._input;
  13010. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13011. enumerator._eachEntry(input[i], i);
  13012. }
  13013. };
  13014. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  13015. var enumerator = this;
  13016. var c = enumerator._instanceConstructor;
  13017. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  13018. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  13019. entry._onerror = null;
  13020. enumerator._settledAt(entry._state, i, entry._result);
  13021. } else {
  13022. enumerator._willSettleAt(c.resolve(entry), i);
  13023. }
  13024. } else {
  13025. enumerator._remaining--;
  13026. enumerator._result[i] = entry;
  13027. }
  13028. };
  13029. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  13030. var enumerator = this;
  13031. var promise = enumerator.promise;
  13032. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  13033. enumerator._remaining--;
  13034. if (state === lib$es6$promise$$internal$$REJECTED) {
  13035. lib$es6$promise$$internal$$reject(promise, value);
  13036. } else {
  13037. enumerator._result[i] = value;
  13038. }
  13039. }
  13040. if (enumerator._remaining === 0) {
  13041. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  13042. }
  13043. };
  13044. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  13045. var enumerator = this;
  13046. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  13047. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  13048. }, function(reason) {
  13049. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  13050. });
  13051. };
  13052. function lib$es6$promise$promise$all$$all(entries) {
  13053. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  13054. }
  13055. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  13056. function lib$es6$promise$promise$race$$race(entries) {
  13057. /*jshint validthis:true */
  13058. var Constructor = this;
  13059. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13060. if (!lib$es6$promise$utils$$isArray(entries)) {
  13061. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  13062. return promise;
  13063. }
  13064. var length = entries.length;
  13065. function onFulfillment(value) {
  13066. lib$es6$promise$$internal$$resolve(promise, value);
  13067. }
  13068. function onRejection(reason) {
  13069. lib$es6$promise$$internal$$reject(promise, reason);
  13070. }
  13071. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13072. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  13073. }
  13074. return promise;
  13075. }
  13076. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  13077. function lib$es6$promise$promise$resolve$$resolve(object) {
  13078. /*jshint validthis:true */
  13079. var Constructor = this;
  13080. if (object && typeof object === 'object' && object.constructor === Constructor) {
  13081. return object;
  13082. }
  13083. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13084. lib$es6$promise$$internal$$resolve(promise, object);
  13085. return promise;
  13086. }
  13087. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  13088. function lib$es6$promise$promise$reject$$reject(reason) {
  13089. /*jshint validthis:true */
  13090. var Constructor = this;
  13091. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13092. lib$es6$promise$$internal$$reject(promise, reason);
  13093. return promise;
  13094. }
  13095. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  13096. var lib$es6$promise$promise$$counter = 0;
  13097. function lib$es6$promise$promise$$needsResolver() {
  13098. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  13099. }
  13100. function lib$es6$promise$promise$$needsNew() {
  13101. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  13102. }
  13103. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  13104. /**
  13105. Promise objects represent the eventual result of an asynchronous operation. The
  13106. primary way of interacting with a promise is through its `then` method, which
  13107. registers callbacks to receive either a promise's eventual value or the reason
  13108. why the promise cannot be fulfilled.
  13109. Terminology
  13110. -----------
  13111. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  13112. - `thenable` is an object or function that defines a `then` method.
  13113. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  13114. - `exception` is a value that is thrown using the throw statement.
  13115. - `reason` is a value that indicates why a promise was rejected.
  13116. - `settled` the final resting state of a promise, fulfilled or rejected.
  13117. A promise can be in one of three states: pending, fulfilled, or rejected.
  13118. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  13119. state. Promises that are rejected have a rejection reason and are in the
  13120. rejected state. A fulfillment value is never a thenable.
  13121. Promises can also be said to *resolve* a value. If this value is also a
  13122. promise, then the original promise's settled state will match the value's
  13123. settled state. So a promise that *resolves* a promise that rejects will
  13124. itself reject, and a promise that *resolves* a promise that fulfills will
  13125. itself fulfill.
  13126. Basic Usage:
  13127. ------------
  13128. ```js
  13129. var promise = new Promise(function(resolve, reject) {
  13130. // on success
  13131. resolve(value);
  13132. // on failure
  13133. reject(reason);
  13134. });
  13135. promise.then(function(value) {
  13136. // on fulfillment
  13137. }, function(reason) {
  13138. // on rejection
  13139. });
  13140. ```
  13141. Advanced Usage:
  13142. ---------------
  13143. Promises shine when abstracting away asynchronous interactions such as
  13144. `XMLHttpRequest`s.
  13145. ```js
  13146. function getJSON(url) {
  13147. return new Promise(function(resolve, reject){
  13148. var xhr = new XMLHttpRequest();
  13149. xhr.open('GET', url);
  13150. xhr.onreadystatechange = handler;
  13151. xhr.responseType = 'json';
  13152. xhr.setRequestHeader('Accept', 'application/json');
  13153. xhr.send();
  13154. function handler() {
  13155. if (this.readyState === this.DONE) {
  13156. if (this.status === 200) {
  13157. resolve(this.response);
  13158. } else {
  13159. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  13160. }
  13161. }
  13162. };
  13163. });
  13164. }
  13165. getJSON('/posts.json').then(function(json) {
  13166. // on fulfillment
  13167. }, function(reason) {
  13168. // on rejection
  13169. });
  13170. ```
  13171. Unlike callbacks, promises are great composable primitives.
  13172. ```js
  13173. Promise.all([
  13174. getJSON('/posts'),
  13175. getJSON('/comments')
  13176. ]).then(function(values){
  13177. values[0] // => postsJSON
  13178. values[1] // => commentsJSON
  13179. return values;
  13180. });
  13181. ```
  13182. @class Promise
  13183. @param {function} resolver
  13184. Useful for tooling.
  13185. @constructor
  13186. */
  13187. function lib$es6$promise$promise$$Promise(resolver) {
  13188. this._id = lib$es6$promise$promise$$counter++;
  13189. this._state = undefined;
  13190. this._result = undefined;
  13191. this._subscribers = [];
  13192. if (lib$es6$promise$$internal$$noop !== resolver) {
  13193. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  13194. lib$es6$promise$promise$$needsResolver();
  13195. }
  13196. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  13197. lib$es6$promise$promise$$needsNew();
  13198. }
  13199. lib$es6$promise$$internal$$initializePromise(this, resolver);
  13200. }
  13201. }
  13202. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  13203. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  13204. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  13205. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  13206. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  13207. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  13208. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  13209. lib$es6$promise$promise$$Promise.prototype = {
  13210. constructor: lib$es6$promise$promise$$Promise,
  13211. /**
  13212. The primary way of interacting with a promise is through its `then` method,
  13213. which registers callbacks to receive either a promise's eventual value or the
  13214. reason why the promise cannot be fulfilled.
  13215. ```js
  13216. findUser().then(function(user){
  13217. // user is available
  13218. }, function(reason){
  13219. // user is unavailable, and you are given the reason why
  13220. });
  13221. ```
  13222. Chaining
  13223. --------
  13224. The return value of `then` is itself a promise. This second, 'downstream'
  13225. promise is resolved with the return value of the first promise's fulfillment
  13226. or rejection handler, or rejected if the handler throws an exception.
  13227. ```js
  13228. findUser().then(function (user) {
  13229. return user.name;
  13230. }, function (reason) {
  13231. return 'default name';
  13232. }).then(function (userName) {
  13233. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  13234. // will be `'default name'`
  13235. });
  13236. findUser().then(function (user) {
  13237. throw new Error('Found user, but still unhappy');
  13238. }, function (reason) {
  13239. throw new Error('`findUser` rejected and we're unhappy');
  13240. }).then(function (value) {
  13241. // never reached
  13242. }, function (reason) {
  13243. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  13244. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  13245. });
  13246. ```
  13247. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  13248. ```js
  13249. findUser().then(function (user) {
  13250. throw new PedagogicalException('Upstream error');
  13251. }).then(function (value) {
  13252. // never reached
  13253. }).then(function (value) {
  13254. // never reached
  13255. }, function (reason) {
  13256. // The `PedgagocialException` is propagated all the way down to here
  13257. });
  13258. ```
  13259. Assimilation
  13260. ------------
  13261. Sometimes the value you want to propagate to a downstream promise can only be
  13262. retrieved asynchronously. This can be achieved by returning a promise in the
  13263. fulfillment or rejection handler. The downstream promise will then be pending
  13264. until the returned promise is settled. This is called *assimilation*.
  13265. ```js
  13266. findUser().then(function (user) {
  13267. return findCommentsByAuthor(user);
  13268. }).then(function (comments) {
  13269. // The user's comments are now available
  13270. });
  13271. ```
  13272. If the assimliated promise rejects, then the downstream promise will also reject.
  13273. ```js
  13274. findUser().then(function (user) {
  13275. return findCommentsByAuthor(user);
  13276. }).then(function (comments) {
  13277. // If `findCommentsByAuthor` fulfills, we'll have the value here
  13278. }, function (reason) {
  13279. // If `findCommentsByAuthor` rejects, we'll have the reason here
  13280. });
  13281. ```
  13282. Simple Example
  13283. --------------
  13284. Synchronous Example
  13285. ```javascript
  13286. var result;
  13287. try {
  13288. result = findResult();
  13289. // success
  13290. } catch(reason) {
  13291. // failure
  13292. }
  13293. ```
  13294. Errback Example
  13295. ```js
  13296. findResult(function(result, err){
  13297. if (err) {
  13298. // failure
  13299. } else {
  13300. // success
  13301. }
  13302. });
  13303. ```
  13304. Promise Example;
  13305. ```javascript
  13306. findResult().then(function(result){
  13307. // success
  13308. }, function(reason){
  13309. // failure
  13310. });
  13311. ```
  13312. Advanced Example
  13313. --------------
  13314. Synchronous Example
  13315. ```javascript
  13316. var author, books;
  13317. try {
  13318. author = findAuthor();
  13319. books = findBooksByAuthor(author);
  13320. // success
  13321. } catch(reason) {
  13322. // failure
  13323. }
  13324. ```
  13325. Errback Example
  13326. ```js
  13327. function foundBooks(books) {
  13328. }
  13329. function failure(reason) {
  13330. }
  13331. findAuthor(function(author, err){
  13332. if (err) {
  13333. failure(err);
  13334. // failure
  13335. } else {
  13336. try {
  13337. findBoooksByAuthor(author, function(books, err) {
  13338. if (err) {
  13339. failure(err);
  13340. } else {
  13341. try {
  13342. foundBooks(books);
  13343. } catch(reason) {
  13344. failure(reason);
  13345. }
  13346. }
  13347. });
  13348. } catch(error) {
  13349. failure(err);
  13350. }
  13351. // success
  13352. }
  13353. });
  13354. ```
  13355. Promise Example;
  13356. ```javascript
  13357. findAuthor().
  13358. then(findBooksByAuthor).
  13359. then(function(books){
  13360. // found books
  13361. }).catch(function(reason){
  13362. // something went wrong
  13363. });
  13364. ```
  13365. @method then
  13366. @param {Function} onFulfilled
  13367. @param {Function} onRejected
  13368. Useful for tooling.
  13369. @return {Promise}
  13370. */
  13371. then: function(onFulfillment, onRejection) {
  13372. var parent = this;
  13373. var state = parent._state;
  13374. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  13375. return this;
  13376. }
  13377. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  13378. var result = parent._result;
  13379. if (state) {
  13380. var callback = arguments[state - 1];
  13381. lib$es6$promise$asap$$asap(function(){
  13382. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  13383. });
  13384. } else {
  13385. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  13386. }
  13387. return child;
  13388. },
  13389. /**
  13390. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  13391. as the catch block of a try/catch statement.
  13392. ```js
  13393. function findAuthor(){
  13394. throw new Error('couldn't find that author');
  13395. }
  13396. // synchronous
  13397. try {
  13398. findAuthor();
  13399. } catch(reason) {
  13400. // something went wrong
  13401. }
  13402. // async with promises
  13403. findAuthor().catch(function(reason){
  13404. // something went wrong
  13405. });
  13406. ```
  13407. @method catch
  13408. @param {Function} onRejection
  13409. Useful for tooling.
  13410. @return {Promise}
  13411. */
  13412. 'catch': function(onRejection) {
  13413. return this.then(null, onRejection);
  13414. }
  13415. };
  13416. function lib$es6$promise$polyfill$$polyfill() {
  13417. var local;
  13418. if (typeof global !== 'undefined') {
  13419. local = global;
  13420. } else if (typeof self !== 'undefined') {
  13421. local = self;
  13422. } else {
  13423. try {
  13424. local = Function('return this')();
  13425. } catch (e) {
  13426. throw new Error('polyfill failed because global object is unavailable in this environment');
  13427. }
  13428. }
  13429. var P = local.Promise;
  13430. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  13431. return;
  13432. }
  13433. local.Promise = lib$es6$promise$promise$$default;
  13434. }
  13435. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  13436. var lib$es6$promise$umd$$ES6Promise = {
  13437. 'Promise': lib$es6$promise$promise$$default,
  13438. 'polyfill': lib$es6$promise$polyfill$$default
  13439. };
  13440. /* global define:true module:true window: true */
  13441. if (typeof define === 'function' && define['amd']) {
  13442. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  13443. } else if (typeof module !== 'undefined' && module['exports']) {
  13444. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  13445. } else if (typeof this !== 'undefined') {
  13446. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  13447. }
  13448. lib$es6$promise$polyfill$$default();
  13449. }).call(this);
  13450. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13451. },{"_process":45}],47:[function(require,module,exports){
  13452. /* Copyright @ 2015 Atlassian Pty Ltd
  13453. *
  13454. * Licensed under the Apache License, Version 2.0 (the "License");
  13455. * you may not use this file except in compliance with the License.
  13456. * You may obtain a copy of the License at
  13457. *
  13458. * http://www.apache.org/licenses/LICENSE-2.0
  13459. *
  13460. * Unless required by applicable law or agreed to in writing, software
  13461. * distributed under the License is distributed on an "AS IS" BASIS,
  13462. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13463. * See the License for the specific language governing permissions and
  13464. * limitations under the License.
  13465. */
  13466. /**
  13467. * Ordered log levels.
  13468. */
  13469. var levels = {
  13470. "trace": 0,
  13471. "debug": 1,
  13472. "info": 2,
  13473. "log": 3,
  13474. "warn": 4,
  13475. "error": 5
  13476. };
  13477. /**
  13478. * Parses Error's object stack trace and extracts information about the last
  13479. * caller before the log method was called.
  13480. * @returns JS object with info about the caller - method name, file location,
  13481. * line and column.
  13482. */
  13483. function getCallerInfo() {
  13484. var callerInfo = {
  13485. methodName: "",
  13486. fileLocation: "",
  13487. line: null,
  13488. column: null
  13489. };
  13490. //gets the part of the stack without the logger wrappers
  13491. var error = new Error();
  13492. var stack = error.stack? error.stack.split("\n") : [];
  13493. if(!stack || stack.length < 1) {
  13494. return callerInfo;
  13495. }
  13496. var m = null;
  13497. if(stack[3]) {
  13498. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  13499. }
  13500. if(!m || m.length <= 4) {
  13501. //Firefox && Safari
  13502. if(stack[2].indexOf("log@") === 0){
  13503. //Safari
  13504. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  13505. } else {
  13506. //Firefox
  13507. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  13508. }
  13509. return callerInfo;
  13510. }
  13511. callerInfo.methodName = m[1];
  13512. callerInfo.fileLocation = m[2];
  13513. callerInfo.line = m[3];
  13514. callerInfo.column = m[4];
  13515. return callerInfo;
  13516. }
  13517. /**
  13518. * Logs messages using the transports and level from the logger.
  13519. * @param logger a logger instance.
  13520. * @param level the log level of the message. See the levels variable.
  13521. * @param arguments array with arguments that will be logged.
  13522. */
  13523. function log() {
  13524. var logger = arguments[0], level = arguments[1],
  13525. args = Array.prototype.slice.call(arguments, 2);
  13526. if(levels[level] <= logger.level) {
  13527. return;
  13528. }
  13529. var callerInfo = getCallerInfo();
  13530. for(var i = 0; i < logger.transports.length; i++) {
  13531. var t = logger.transports[i];
  13532. var l = t[level];
  13533. if(l && typeof(l) === "function") {
  13534. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  13535. .apply(t, args);
  13536. }
  13537. }
  13538. }
  13539. /**
  13540. *
  13541. * Constructs new logger object.
  13542. * @param level the logging level for the new logger
  13543. * @param id optional identifier for the logger instance.
  13544. * @param transports optional list of handlers(objects) for the logs.
  13545. * The handlers must support - log, warn, error, debug, info, trace.
  13546. * @param format optional (NOT implemented) string.
  13547. */
  13548. function Logger(level, id, transports, format) {
  13549. this.id = id;
  13550. this.format = format;
  13551. if(!this.transports) {
  13552. this.transports = [];
  13553. this.transports.push(Logger.consoleTransport);
  13554. }
  13555. this.level = levels[level];
  13556. var methods = Object.keys(levels);
  13557. for(var i = 0; i < methods.length; i++){
  13558. this[methods[i]] =
  13559. log.bind(null, this, methods[i]);
  13560. }
  13561. }
  13562. /**
  13563. * Sets the log level for the logger.
  13564. * @param level the new log level.
  13565. */
  13566. Logger.prototype.setLevel = function (level) {
  13567. this.level = levels[level];
  13568. };
  13569. module.exports = Logger;
  13570. /**
  13571. * The default transport - console
  13572. */
  13573. Logger.consoleTransport = console;
  13574. /**
  13575. * Enum for the supported log levels.
  13576. */
  13577. Logger.levels = {
  13578. TRACE: "trace",
  13579. DEBUG: "debug",
  13580. INFO: "info",
  13581. LOG: "log",
  13582. WARN: "warn",
  13583. ERROR: "error"
  13584. };
  13585. },{}],48:[function(require,module,exports){
  13586. /* Copyright @ 2015 Atlassian Pty Ltd
  13587. *
  13588. * Licensed under the Apache License, Version 2.0 (the "License");
  13589. * you may not use this file except in compliance with the License.
  13590. * You may obtain a copy of the License at
  13591. *
  13592. * http://www.apache.org/licenses/LICENSE-2.0
  13593. *
  13594. * Unless required by applicable law or agreed to in writing, software
  13595. * distributed under the License is distributed on an "AS IS" BASIS,
  13596. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13597. * See the License for the specific language governing permissions and
  13598. * limitations under the License.
  13599. */
  13600. var Logger = require("./Logger");
  13601. /**
  13602. * Map with the created loggers with ID.
  13603. */
  13604. var idLoggers = {};
  13605. /**
  13606. * Array with the loggers without id.
  13607. */
  13608. var loggers = [];
  13609. /**
  13610. * Log level for the lbrary.
  13611. */
  13612. var curLevel = Logger.levels.TRACE;
  13613. module.exports = {
  13614. /**
  13615. * Creates new logger.
  13616. * @arguments the same as Logger constructor
  13617. */
  13618. getLogger: function(id, transports, format) {
  13619. var logger = new Logger(curLevel, id, transports, format);
  13620. if(id) {
  13621. idLoggers[id] = idLoggers[id] || [];
  13622. idLoggers[id].push(logger);
  13623. } else {
  13624. loggers.push(logger);
  13625. }
  13626. return logger;
  13627. },
  13628. /**
  13629. * Changes the log level for the existing loggers by id.
  13630. * @param level the new log level.
  13631. * @param id if specified the level will be changed only for loggers with the
  13632. * same id. Otherwise the operation will affect all loggers that don't
  13633. * have id.
  13634. */
  13635. setLogLevelById: function(level, id) {
  13636. var l = id? (idLoggers[id] || []) : loggers;
  13637. for(var i = 0; i < l.length; i++) {
  13638. l[i].setLevel(level);
  13639. }
  13640. },
  13641. /**
  13642. * Changes the log level for all existing loggers.
  13643. * @param level the new log level.
  13644. */
  13645. setLogLevel: function (level) {
  13646. curLevel = level;
  13647. var i = 0;
  13648. for(; i < loggers.length; i++) {
  13649. loggers[i].setLevel(level);
  13650. }
  13651. for(var id in idLoggers) {
  13652. var l = idLoggers[id] || [];
  13653. for(i = 0; i < l.length; i++) {
  13654. l[i].setLevel(level);
  13655. }
  13656. }
  13657. },
  13658. /**
  13659. * The supported log levels.
  13660. */
  13661. levels: Logger.levels
  13662. };
  13663. },{"./Logger":47}],49:[function(require,module,exports){
  13664. // Top level file is just a mixin of submodules & constants
  13665. 'use strict';
  13666. var assign = require('./lib/utils/common').assign;
  13667. var deflate = require('./lib/deflate');
  13668. var inflate = require('./lib/inflate');
  13669. var constants = require('./lib/zlib/constants');
  13670. var pako = {};
  13671. assign(pako, deflate, inflate, constants);
  13672. module.exports = pako;
  13673. },{"./lib/deflate":50,"./lib/inflate":51,"./lib/utils/common":52,"./lib/zlib/constants":55}],50:[function(require,module,exports){
  13674. 'use strict';
  13675. var zlib_deflate = require('./zlib/deflate.js');
  13676. var utils = require('./utils/common');
  13677. var strings = require('./utils/strings');
  13678. var msg = require('./zlib/messages');
  13679. var zstream = require('./zlib/zstream');
  13680. var toString = Object.prototype.toString;
  13681. /* Public constants ==========================================================*/
  13682. /* ===========================================================================*/
  13683. var Z_NO_FLUSH = 0;
  13684. var Z_FINISH = 4;
  13685. var Z_OK = 0;
  13686. var Z_STREAM_END = 1;
  13687. var Z_SYNC_FLUSH = 2;
  13688. var Z_DEFAULT_COMPRESSION = -1;
  13689. var Z_DEFAULT_STRATEGY = 0;
  13690. var Z_DEFLATED = 8;
  13691. /* ===========================================================================*/
  13692. /**
  13693. * class Deflate
  13694. *
  13695. * Generic JS-style wrapper for zlib calls. If you don't need
  13696. * streaming behaviour - use more simple functions: [[deflate]],
  13697. * [[deflateRaw]] and [[gzip]].
  13698. **/
  13699. /* internal
  13700. * Deflate.chunks -> Array
  13701. *
  13702. * Chunks of output data, if [[Deflate#onData]] not overriden.
  13703. **/
  13704. /**
  13705. * Deflate.result -> Uint8Array|Array
  13706. *
  13707. * Compressed result, generated by default [[Deflate#onData]]
  13708. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  13709. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  13710. * push a chunk with explicit flush (call [[Deflate#push]] with
  13711. * `Z_SYNC_FLUSH` param).
  13712. **/
  13713. /**
  13714. * Deflate.err -> Number
  13715. *
  13716. * Error code after deflate finished. 0 (Z_OK) on success.
  13717. * You will not need it in real life, because deflate errors
  13718. * are possible only on wrong options or bad `onData` / `onEnd`
  13719. * custom handlers.
  13720. **/
  13721. /**
  13722. * Deflate.msg -> String
  13723. *
  13724. * Error message, if [[Deflate.err]] != 0
  13725. **/
  13726. /**
  13727. * new Deflate(options)
  13728. * - options (Object): zlib deflate options.
  13729. *
  13730. * Creates new deflator instance with specified params. Throws exception
  13731. * on bad params. Supported options:
  13732. *
  13733. * - `level`
  13734. * - `windowBits`
  13735. * - `memLevel`
  13736. * - `strategy`
  13737. *
  13738. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13739. * for more information on these.
  13740. *
  13741. * Additional options, for internal needs:
  13742. *
  13743. * - `chunkSize` - size of generated data chunks (16K by default)
  13744. * - `raw` (Boolean) - do raw deflate
  13745. * - `gzip` (Boolean) - create gzip wrapper
  13746. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13747. * (each char code [0..255])
  13748. * - `header` (Object) - custom header for gzip
  13749. * - `text` (Boolean) - true if compressed data believed to be text
  13750. * - `time` (Number) - modification time, unix timestamp
  13751. * - `os` (Number) - operation system code
  13752. * - `extra` (Array) - array of bytes with extra data (max 65536)
  13753. * - `name` (String) - file name (binary string)
  13754. * - `comment` (String) - comment (binary string)
  13755. * - `hcrc` (Boolean) - true if header crc should be added
  13756. *
  13757. * ##### Example:
  13758. *
  13759. * ```javascript
  13760. * var pako = require('pako')
  13761. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13762. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13763. *
  13764. * var deflate = new pako.Deflate({ level: 3});
  13765. *
  13766. * deflate.push(chunk1, false);
  13767. * deflate.push(chunk2, true); // true -> last chunk
  13768. *
  13769. * if (deflate.err) { throw new Error(deflate.err); }
  13770. *
  13771. * console.log(deflate.result);
  13772. * ```
  13773. **/
  13774. var Deflate = function(options) {
  13775. this.options = utils.assign({
  13776. level: Z_DEFAULT_COMPRESSION,
  13777. method: Z_DEFLATED,
  13778. chunkSize: 16384,
  13779. windowBits: 15,
  13780. memLevel: 8,
  13781. strategy: Z_DEFAULT_STRATEGY,
  13782. to: ''
  13783. }, options || {});
  13784. var opt = this.options;
  13785. if (opt.raw && (opt.windowBits > 0)) {
  13786. opt.windowBits = -opt.windowBits;
  13787. }
  13788. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  13789. opt.windowBits += 16;
  13790. }
  13791. this.err = 0; // error code, if happens (0 = Z_OK)
  13792. this.msg = ''; // error message
  13793. this.ended = false; // used to avoid multiple onEnd() calls
  13794. this.chunks = []; // chunks of compressed data
  13795. this.strm = new zstream();
  13796. this.strm.avail_out = 0;
  13797. var status = zlib_deflate.deflateInit2(
  13798. this.strm,
  13799. opt.level,
  13800. opt.method,
  13801. opt.windowBits,
  13802. opt.memLevel,
  13803. opt.strategy
  13804. );
  13805. if (status !== Z_OK) {
  13806. throw new Error(msg[status]);
  13807. }
  13808. if (opt.header) {
  13809. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  13810. }
  13811. };
  13812. /**
  13813. * Deflate#push(data[, mode]) -> Boolean
  13814. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  13815. * converted to utf8 byte sequence.
  13816. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13817. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13818. *
  13819. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  13820. * new compressed chunks. Returns `true` on success. The last data block must have
  13821. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13822. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13823. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  13824. *
  13825. * On fail call [[Deflate#onEnd]] with error code and return false.
  13826. *
  13827. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13828. * array format is detected automatically). Also, don't skip last param and always
  13829. * use the same type in your code (boolean or number). That will improve JS speed.
  13830. *
  13831. * For regular `Array`-s make sure all elements are [0..255].
  13832. *
  13833. * ##### Example
  13834. *
  13835. * ```javascript
  13836. * push(chunk, false); // push one of data chunks
  13837. * ...
  13838. * push(chunk, true); // push last chunk
  13839. * ```
  13840. **/
  13841. Deflate.prototype.push = function(data, mode) {
  13842. var strm = this.strm;
  13843. var chunkSize = this.options.chunkSize;
  13844. var status, _mode;
  13845. if (this.ended) { return false; }
  13846. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13847. // Convert data if needed
  13848. if (typeof data === 'string') {
  13849. // If we need to compress text, change encoding to utf8.
  13850. strm.input = strings.string2buf(data);
  13851. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13852. strm.input = new Uint8Array(data);
  13853. } else {
  13854. strm.input = data;
  13855. }
  13856. strm.next_in = 0;
  13857. strm.avail_in = strm.input.length;
  13858. do {
  13859. if (strm.avail_out === 0) {
  13860. strm.output = new utils.Buf8(chunkSize);
  13861. strm.next_out = 0;
  13862. strm.avail_out = chunkSize;
  13863. }
  13864. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13865. if (status !== Z_STREAM_END && status !== Z_OK) {
  13866. this.onEnd(status);
  13867. this.ended = true;
  13868. return false;
  13869. }
  13870. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13871. if (this.options.to === 'string') {
  13872. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13873. } else {
  13874. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13875. }
  13876. }
  13877. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13878. // Finalize on the last chunk.
  13879. if (_mode === Z_FINISH) {
  13880. status = zlib_deflate.deflateEnd(this.strm);
  13881. this.onEnd(status);
  13882. this.ended = true;
  13883. return status === Z_OK;
  13884. }
  13885. // callback interim results if Z_SYNC_FLUSH.
  13886. if (_mode === Z_SYNC_FLUSH) {
  13887. this.onEnd(Z_OK);
  13888. strm.avail_out = 0;
  13889. return true;
  13890. }
  13891. return true;
  13892. };
  13893. /**
  13894. * Deflate#onData(chunk) -> Void
  13895. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13896. * on js engine support. When string output requested, each chunk
  13897. * will be string.
  13898. *
  13899. * By default, stores data blocks in `chunks[]` property and glue
  13900. * those in `onEnd`. Override this handler, if you need another behaviour.
  13901. **/
  13902. Deflate.prototype.onData = function(chunk) {
  13903. this.chunks.push(chunk);
  13904. };
  13905. /**
  13906. * Deflate#onEnd(status) -> Void
  13907. * - status (Number): deflate status. 0 (Z_OK) on success,
  13908. * other if not.
  13909. *
  13910. * Called once after you tell deflate that the input stream is
  13911. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13912. * or if an error happened. By default - join collected chunks,
  13913. * free memory and fill `results` / `err` properties.
  13914. **/
  13915. Deflate.prototype.onEnd = function(status) {
  13916. // On success - join
  13917. if (status === Z_OK) {
  13918. if (this.options.to === 'string') {
  13919. this.result = this.chunks.join('');
  13920. } else {
  13921. this.result = utils.flattenChunks(this.chunks);
  13922. }
  13923. }
  13924. this.chunks = [];
  13925. this.err = status;
  13926. this.msg = this.strm.msg;
  13927. };
  13928. /**
  13929. * deflate(data[, options]) -> Uint8Array|Array|String
  13930. * - data (Uint8Array|Array|String): input data to compress.
  13931. * - options (Object): zlib deflate options.
  13932. *
  13933. * Compress `data` with deflate alrorythm and `options`.
  13934. *
  13935. * Supported options are:
  13936. *
  13937. * - level
  13938. * - windowBits
  13939. * - memLevel
  13940. * - strategy
  13941. *
  13942. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13943. * for more information on these.
  13944. *
  13945. * Sugar (options):
  13946. *
  13947. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13948. * negative windowBits implicitly.
  13949. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13950. * (each char code [0..255])
  13951. *
  13952. * ##### Example:
  13953. *
  13954. * ```javascript
  13955. * var pako = require('pako')
  13956. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13957. *
  13958. * console.log(pako.deflate(data));
  13959. * ```
  13960. **/
  13961. function deflate(input, options) {
  13962. var deflator = new Deflate(options);
  13963. deflator.push(input, true);
  13964. // That will never happens, if you don't cheat with options :)
  13965. if (deflator.err) { throw deflator.msg; }
  13966. return deflator.result;
  13967. }
  13968. /**
  13969. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13970. * - data (Uint8Array|Array|String): input data to compress.
  13971. * - options (Object): zlib deflate options.
  13972. *
  13973. * The same as [[deflate]], but creates raw data, without wrapper
  13974. * (header and adler32 crc).
  13975. **/
  13976. function deflateRaw(input, options) {
  13977. options = options || {};
  13978. options.raw = true;
  13979. return deflate(input, options);
  13980. }
  13981. /**
  13982. * gzip(data[, options]) -> Uint8Array|Array|String
  13983. * - data (Uint8Array|Array|String): input data to compress.
  13984. * - options (Object): zlib deflate options.
  13985. *
  13986. * The same as [[deflate]], but create gzip wrapper instead of
  13987. * deflate one.
  13988. **/
  13989. function gzip(input, options) {
  13990. options = options || {};
  13991. options.gzip = true;
  13992. return deflate(input, options);
  13993. }
  13994. exports.Deflate = Deflate;
  13995. exports.deflate = deflate;
  13996. exports.deflateRaw = deflateRaw;
  13997. exports.gzip = gzip;
  13998. },{"./utils/common":52,"./utils/strings":53,"./zlib/deflate.js":57,"./zlib/messages":62,"./zlib/zstream":64}],51:[function(require,module,exports){
  13999. 'use strict';
  14000. var zlib_inflate = require('./zlib/inflate.js');
  14001. var utils = require('./utils/common');
  14002. var strings = require('./utils/strings');
  14003. var c = require('./zlib/constants');
  14004. var msg = require('./zlib/messages');
  14005. var zstream = require('./zlib/zstream');
  14006. var gzheader = require('./zlib/gzheader');
  14007. var toString = Object.prototype.toString;
  14008. /**
  14009. * class Inflate
  14010. *
  14011. * Generic JS-style wrapper for zlib calls. If you don't need
  14012. * streaming behaviour - use more simple functions: [[inflate]]
  14013. * and [[inflateRaw]].
  14014. **/
  14015. /* internal
  14016. * inflate.chunks -> Array
  14017. *
  14018. * Chunks of output data, if [[Inflate#onData]] not overriden.
  14019. **/
  14020. /**
  14021. * Inflate.result -> Uint8Array|Array|String
  14022. *
  14023. * Uncompressed result, generated by default [[Inflate#onData]]
  14024. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  14025. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  14026. * push a chunk with explicit flush (call [[Inflate#push]] with
  14027. * `Z_SYNC_FLUSH` param).
  14028. **/
  14029. /**
  14030. * Inflate.err -> Number
  14031. *
  14032. * Error code after inflate finished. 0 (Z_OK) on success.
  14033. * Should be checked if broken data possible.
  14034. **/
  14035. /**
  14036. * Inflate.msg -> String
  14037. *
  14038. * Error message, if [[Inflate.err]] != 0
  14039. **/
  14040. /**
  14041. * new Inflate(options)
  14042. * - options (Object): zlib inflate options.
  14043. *
  14044. * Creates new inflator instance with specified params. Throws exception
  14045. * on bad params. Supported options:
  14046. *
  14047. * - `windowBits`
  14048. *
  14049. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14050. * for more information on these.
  14051. *
  14052. * Additional options, for internal needs:
  14053. *
  14054. * - `chunkSize` - size of generated data chunks (16K by default)
  14055. * - `raw` (Boolean) - do raw inflate
  14056. * - `to` (String) - if equal to 'string', then result will be converted
  14057. * from utf8 to utf16 (javascript) string. When string output requested,
  14058. * chunk length can differ from `chunkSize`, depending on content.
  14059. *
  14060. * By default, when no options set, autodetect deflate/gzip data format via
  14061. * wrapper header.
  14062. *
  14063. * ##### Example:
  14064. *
  14065. * ```javascript
  14066. * var pako = require('pako')
  14067. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14068. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14069. *
  14070. * var inflate = new pako.Inflate({ level: 3});
  14071. *
  14072. * inflate.push(chunk1, false);
  14073. * inflate.push(chunk2, true); // true -> last chunk
  14074. *
  14075. * if (inflate.err) { throw new Error(inflate.err); }
  14076. *
  14077. * console.log(inflate.result);
  14078. * ```
  14079. **/
  14080. var Inflate = function(options) {
  14081. this.options = utils.assign({
  14082. chunkSize: 16384,
  14083. windowBits: 0,
  14084. to: ''
  14085. }, options || {});
  14086. var opt = this.options;
  14087. // Force window size for `raw` data, if not set directly,
  14088. // because we have no header for autodetect.
  14089. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  14090. opt.windowBits = -opt.windowBits;
  14091. if (opt.windowBits === 0) { opt.windowBits = -15; }
  14092. }
  14093. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  14094. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  14095. !(options && options.windowBits)) {
  14096. opt.windowBits += 32;
  14097. }
  14098. // Gzip header has no info about windows size, we can do autodetect only
  14099. // for deflate. So, if window size not set, force it to max when gzip possible
  14100. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  14101. // bit 3 (16) -> gzipped data
  14102. // bit 4 (32) -> autodetect gzip/deflate
  14103. if ((opt.windowBits & 15) === 0) {
  14104. opt.windowBits |= 15;
  14105. }
  14106. }
  14107. this.err = 0; // error code, if happens (0 = Z_OK)
  14108. this.msg = ''; // error message
  14109. this.ended = false; // used to avoid multiple onEnd() calls
  14110. this.chunks = []; // chunks of compressed data
  14111. this.strm = new zstream();
  14112. this.strm.avail_out = 0;
  14113. var status = zlib_inflate.inflateInit2(
  14114. this.strm,
  14115. opt.windowBits
  14116. );
  14117. if (status !== c.Z_OK) {
  14118. throw new Error(msg[status]);
  14119. }
  14120. this.header = new gzheader();
  14121. zlib_inflate.inflateGetHeader(this.strm, this.header);
  14122. };
  14123. /**
  14124. * Inflate#push(data[, mode]) -> Boolean
  14125. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  14126. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14127. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14128. *
  14129. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  14130. * new output chunks. Returns `true` on success. The last data block must have
  14131. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14132. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14133. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  14134. *
  14135. * On fail call [[Inflate#onEnd]] with error code and return false.
  14136. *
  14137. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14138. * format is detected automatically). Also, don't skip last param and always
  14139. * use the same type in your code (boolean or number). That will improve JS speed.
  14140. *
  14141. * For regular `Array`-s make sure all elements are [0..255].
  14142. *
  14143. * ##### Example
  14144. *
  14145. * ```javascript
  14146. * push(chunk, false); // push one of data chunks
  14147. * ...
  14148. * push(chunk, true); // push last chunk
  14149. * ```
  14150. **/
  14151. Inflate.prototype.push = function(data, mode) {
  14152. var strm = this.strm;
  14153. var chunkSize = this.options.chunkSize;
  14154. var status, _mode;
  14155. var next_out_utf8, tail, utf8str;
  14156. // Flag to properly process Z_BUF_ERROR on testing inflate call
  14157. // when we check that all output data was flushed.
  14158. var allowBufError = false;
  14159. if (this.ended) { return false; }
  14160. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  14161. // Convert data if needed
  14162. if (typeof data === 'string') {
  14163. // Only binary strings can be decompressed on practice
  14164. strm.input = strings.binstring2buf(data);
  14165. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14166. strm.input = new Uint8Array(data);
  14167. } else {
  14168. strm.input = data;
  14169. }
  14170. strm.next_in = 0;
  14171. strm.avail_in = strm.input.length;
  14172. do {
  14173. if (strm.avail_out === 0) {
  14174. strm.output = new utils.Buf8(chunkSize);
  14175. strm.next_out = 0;
  14176. strm.avail_out = chunkSize;
  14177. }
  14178. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  14179. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  14180. status = c.Z_OK;
  14181. allowBufError = false;
  14182. }
  14183. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  14184. this.onEnd(status);
  14185. this.ended = true;
  14186. return false;
  14187. }
  14188. if (strm.next_out) {
  14189. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  14190. if (this.options.to === 'string') {
  14191. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  14192. tail = strm.next_out - next_out_utf8;
  14193. utf8str = strings.buf2string(strm.output, next_out_utf8);
  14194. // move tail
  14195. strm.next_out = tail;
  14196. strm.avail_out = chunkSize - tail;
  14197. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  14198. this.onData(utf8str);
  14199. } else {
  14200. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14201. }
  14202. }
  14203. }
  14204. // When no more input data, we should check that internal inflate buffers
  14205. // are flushed. The only way to do it when avail_out = 0 - run one more
  14206. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  14207. // Here we set flag to process this error properly.
  14208. //
  14209. // NOTE. Deflate does not return error in this case and does not needs such
  14210. // logic.
  14211. if (strm.avail_in === 0 && strm.avail_out === 0) {
  14212. allowBufError = true;
  14213. }
  14214. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  14215. if (status === c.Z_STREAM_END) {
  14216. _mode = c.Z_FINISH;
  14217. }
  14218. // Finalize on the last chunk.
  14219. if (_mode === c.Z_FINISH) {
  14220. status = zlib_inflate.inflateEnd(this.strm);
  14221. this.onEnd(status);
  14222. this.ended = true;
  14223. return status === c.Z_OK;
  14224. }
  14225. // callback interim results if Z_SYNC_FLUSH.
  14226. if (_mode === c.Z_SYNC_FLUSH) {
  14227. this.onEnd(c.Z_OK);
  14228. strm.avail_out = 0;
  14229. return true;
  14230. }
  14231. return true;
  14232. };
  14233. /**
  14234. * Inflate#onData(chunk) -> Void
  14235. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14236. * on js engine support. When string output requested, each chunk
  14237. * will be string.
  14238. *
  14239. * By default, stores data blocks in `chunks[]` property and glue
  14240. * those in `onEnd`. Override this handler, if you need another behaviour.
  14241. **/
  14242. Inflate.prototype.onData = function(chunk) {
  14243. this.chunks.push(chunk);
  14244. };
  14245. /**
  14246. * Inflate#onEnd(status) -> Void
  14247. * - status (Number): inflate status. 0 (Z_OK) on success,
  14248. * other if not.
  14249. *
  14250. * Called either after you tell inflate that the input stream is
  14251. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14252. * or if an error happened. By default - join collected chunks,
  14253. * free memory and fill `results` / `err` properties.
  14254. **/
  14255. Inflate.prototype.onEnd = function(status) {
  14256. // On success - join
  14257. if (status === c.Z_OK) {
  14258. if (this.options.to === 'string') {
  14259. // Glue & convert here, until we teach pako to send
  14260. // utf8 alligned strings to onData
  14261. this.result = this.chunks.join('');
  14262. } else {
  14263. this.result = utils.flattenChunks(this.chunks);
  14264. }
  14265. }
  14266. this.chunks = [];
  14267. this.err = status;
  14268. this.msg = this.strm.msg;
  14269. };
  14270. /**
  14271. * inflate(data[, options]) -> Uint8Array|Array|String
  14272. * - data (Uint8Array|Array|String): input data to decompress.
  14273. * - options (Object): zlib inflate options.
  14274. *
  14275. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  14276. * format via wrapper header by default. That's why we don't provide
  14277. * separate `ungzip` method.
  14278. *
  14279. * Supported options are:
  14280. *
  14281. * - windowBits
  14282. *
  14283. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14284. * for more information.
  14285. *
  14286. * Sugar (options):
  14287. *
  14288. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14289. * negative windowBits implicitly.
  14290. * - `to` (String) - if equal to 'string', then result will be converted
  14291. * from utf8 to utf16 (javascript) string. When string output requested,
  14292. * chunk length can differ from `chunkSize`, depending on content.
  14293. *
  14294. *
  14295. * ##### Example:
  14296. *
  14297. * ```javascript
  14298. * var pako = require('pako')
  14299. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  14300. * , output;
  14301. *
  14302. * try {
  14303. * output = pako.inflate(input);
  14304. * } catch (err)
  14305. * console.log(err);
  14306. * }
  14307. * ```
  14308. **/
  14309. function inflate(input, options) {
  14310. var inflator = new Inflate(options);
  14311. inflator.push(input, true);
  14312. // That will never happens, if you don't cheat with options :)
  14313. if (inflator.err) { throw inflator.msg; }
  14314. return inflator.result;
  14315. }
  14316. /**
  14317. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  14318. * - data (Uint8Array|Array|String): input data to decompress.
  14319. * - options (Object): zlib inflate options.
  14320. *
  14321. * The same as [[inflate]], but creates raw data, without wrapper
  14322. * (header and adler32 crc).
  14323. **/
  14324. function inflateRaw(input, options) {
  14325. options = options || {};
  14326. options.raw = true;
  14327. return inflate(input, options);
  14328. }
  14329. /**
  14330. * ungzip(data[, options]) -> Uint8Array|Array|String
  14331. * - data (Uint8Array|Array|String): input data to decompress.
  14332. * - options (Object): zlib inflate options.
  14333. *
  14334. * Just shortcut to [[inflate]], because it autodetects format
  14335. * by header.content. Done for convenience.
  14336. **/
  14337. exports.Inflate = Inflate;
  14338. exports.inflate = inflate;
  14339. exports.inflateRaw = inflateRaw;
  14340. exports.ungzip = inflate;
  14341. },{"./utils/common":52,"./utils/strings":53,"./zlib/constants":55,"./zlib/gzheader":58,"./zlib/inflate.js":60,"./zlib/messages":62,"./zlib/zstream":64}],52:[function(require,module,exports){
  14342. 'use strict';
  14343. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  14344. (typeof Uint16Array !== 'undefined') &&
  14345. (typeof Int32Array !== 'undefined');
  14346. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  14347. var sources = Array.prototype.slice.call(arguments, 1);
  14348. while (sources.length) {
  14349. var source = sources.shift();
  14350. if (!source) { continue; }
  14351. if (typeof source !== 'object') {
  14352. throw new TypeError(source + 'must be non-object');
  14353. }
  14354. for (var p in source) {
  14355. if (source.hasOwnProperty(p)) {
  14356. obj[p] = source[p];
  14357. }
  14358. }
  14359. }
  14360. return obj;
  14361. };
  14362. // reduce buffer size, avoiding mem copy
  14363. exports.shrinkBuf = function (buf, size) {
  14364. if (buf.length === size) { return buf; }
  14365. if (buf.subarray) { return buf.subarray(0, size); }
  14366. buf.length = size;
  14367. return buf;
  14368. };
  14369. var fnTyped = {
  14370. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14371. if (src.subarray && dest.subarray) {
  14372. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  14373. return;
  14374. }
  14375. // Fallback to ordinary array
  14376. for (var i=0; i<len; i++) {
  14377. dest[dest_offs + i] = src[src_offs + i];
  14378. }
  14379. },
  14380. // Join array of chunks to single array.
  14381. flattenChunks: function(chunks) {
  14382. var i, l, len, pos, chunk, result;
  14383. // calculate data length
  14384. len = 0;
  14385. for (i=0, l=chunks.length; i<l; i++) {
  14386. len += chunks[i].length;
  14387. }
  14388. // join chunks
  14389. result = new Uint8Array(len);
  14390. pos = 0;
  14391. for (i=0, l=chunks.length; i<l; i++) {
  14392. chunk = chunks[i];
  14393. result.set(chunk, pos);
  14394. pos += chunk.length;
  14395. }
  14396. return result;
  14397. }
  14398. };
  14399. var fnUntyped = {
  14400. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14401. for (var i=0; i<len; i++) {
  14402. dest[dest_offs + i] = src[src_offs + i];
  14403. }
  14404. },
  14405. // Join array of chunks to single array.
  14406. flattenChunks: function(chunks) {
  14407. return [].concat.apply([], chunks);
  14408. }
  14409. };
  14410. // Enable/Disable typed arrays use, for testing
  14411. //
  14412. exports.setTyped = function (on) {
  14413. if (on) {
  14414. exports.Buf8 = Uint8Array;
  14415. exports.Buf16 = Uint16Array;
  14416. exports.Buf32 = Int32Array;
  14417. exports.assign(exports, fnTyped);
  14418. } else {
  14419. exports.Buf8 = Array;
  14420. exports.Buf16 = Array;
  14421. exports.Buf32 = Array;
  14422. exports.assign(exports, fnUntyped);
  14423. }
  14424. };
  14425. exports.setTyped(TYPED_OK);
  14426. },{}],53:[function(require,module,exports){
  14427. // String encode/decode helpers
  14428. 'use strict';
  14429. var utils = require('./common');
  14430. // Quick check if we can use fast array to bin string conversion
  14431. //
  14432. // - apply(Array) can fail on Android 2.2
  14433. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  14434. //
  14435. var STR_APPLY_OK = true;
  14436. var STR_APPLY_UIA_OK = true;
  14437. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  14438. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  14439. // Table with utf8 lengths (calculated by first byte of sequence)
  14440. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  14441. // because max possible codepoint is 0x10ffff
  14442. var _utf8len = new utils.Buf8(256);
  14443. for (var q=0; q<256; q++) {
  14444. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  14445. }
  14446. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  14447. // convert string to array (typed, when possible)
  14448. exports.string2buf = function (str) {
  14449. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  14450. // count binary size
  14451. for (m_pos = 0; m_pos < str_len; m_pos++) {
  14452. c = str.charCodeAt(m_pos);
  14453. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14454. c2 = str.charCodeAt(m_pos+1);
  14455. if ((c2 & 0xfc00) === 0xdc00) {
  14456. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14457. m_pos++;
  14458. }
  14459. }
  14460. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  14461. }
  14462. // allocate buffer
  14463. buf = new utils.Buf8(buf_len);
  14464. // convert
  14465. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  14466. c = str.charCodeAt(m_pos);
  14467. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14468. c2 = str.charCodeAt(m_pos+1);
  14469. if ((c2 & 0xfc00) === 0xdc00) {
  14470. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14471. m_pos++;
  14472. }
  14473. }
  14474. if (c < 0x80) {
  14475. /* one byte */
  14476. buf[i++] = c;
  14477. } else if (c < 0x800) {
  14478. /* two bytes */
  14479. buf[i++] = 0xC0 | (c >>> 6);
  14480. buf[i++] = 0x80 | (c & 0x3f);
  14481. } else if (c < 0x10000) {
  14482. /* three bytes */
  14483. buf[i++] = 0xE0 | (c >>> 12);
  14484. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14485. buf[i++] = 0x80 | (c & 0x3f);
  14486. } else {
  14487. /* four bytes */
  14488. buf[i++] = 0xf0 | (c >>> 18);
  14489. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  14490. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14491. buf[i++] = 0x80 | (c & 0x3f);
  14492. }
  14493. }
  14494. return buf;
  14495. };
  14496. // Helper (used in 2 places)
  14497. function buf2binstring(buf, len) {
  14498. // use fallback for big arrays to avoid stack overflow
  14499. if (len < 65537) {
  14500. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  14501. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  14502. }
  14503. }
  14504. var result = '';
  14505. for (var i=0; i < len; i++) {
  14506. result += String.fromCharCode(buf[i]);
  14507. }
  14508. return result;
  14509. }
  14510. // Convert byte array to binary string
  14511. exports.buf2binstring = function(buf) {
  14512. return buf2binstring(buf, buf.length);
  14513. };
  14514. // Convert binary string (typed, when possible)
  14515. exports.binstring2buf = function(str) {
  14516. var buf = new utils.Buf8(str.length);
  14517. for (var i=0, len=buf.length; i < len; i++) {
  14518. buf[i] = str.charCodeAt(i);
  14519. }
  14520. return buf;
  14521. };
  14522. // convert array to string
  14523. exports.buf2string = function (buf, max) {
  14524. var i, out, c, c_len;
  14525. var len = max || buf.length;
  14526. // Reserve max possible length (2 words per char)
  14527. // NB: by unknown reasons, Array is significantly faster for
  14528. // String.fromCharCode.apply than Uint16Array.
  14529. var utf16buf = new Array(len*2);
  14530. for (out=0, i=0; i<len;) {
  14531. c = buf[i++];
  14532. // quick process ascii
  14533. if (c < 0x80) { utf16buf[out++] = c; continue; }
  14534. c_len = _utf8len[c];
  14535. // skip 5 & 6 byte codes
  14536. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  14537. // apply mask on first byte
  14538. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  14539. // join the rest
  14540. while (c_len > 1 && i < len) {
  14541. c = (c << 6) | (buf[i++] & 0x3f);
  14542. c_len--;
  14543. }
  14544. // terminated by end of string?
  14545. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  14546. if (c < 0x10000) {
  14547. utf16buf[out++] = c;
  14548. } else {
  14549. c -= 0x10000;
  14550. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  14551. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  14552. }
  14553. }
  14554. return buf2binstring(utf16buf, out);
  14555. };
  14556. // Calculate max possible position in utf8 buffer,
  14557. // that will not break sequence. If that's not possible
  14558. // - (very small limits) return max size as is.
  14559. //
  14560. // buf[] - utf8 bytes array
  14561. // max - length limit (mandatory);
  14562. exports.utf8border = function(buf, max) {
  14563. var pos;
  14564. max = max || buf.length;
  14565. if (max > buf.length) { max = buf.length; }
  14566. // go back from last position, until start of sequence found
  14567. pos = max-1;
  14568. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  14569. // Fuckup - very small and broken sequence,
  14570. // return max, because we should return something anyway.
  14571. if (pos < 0) { return max; }
  14572. // If we came to start of buffer - that means vuffer is too small,
  14573. // return max too.
  14574. if (pos === 0) { return max; }
  14575. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  14576. };
  14577. },{"./common":52}],54:[function(require,module,exports){
  14578. 'use strict';
  14579. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  14580. // It doesn't worth to make additional optimizationa as in original.
  14581. // Small size is preferable.
  14582. function adler32(adler, buf, len, pos) {
  14583. var s1 = (adler & 0xffff) |0,
  14584. s2 = ((adler >>> 16) & 0xffff) |0,
  14585. n = 0;
  14586. while (len !== 0) {
  14587. // Set limit ~ twice less than 5552, to keep
  14588. // s2 in 31-bits, because we force signed ints.
  14589. // in other case %= will fail.
  14590. n = len > 2000 ? 2000 : len;
  14591. len -= n;
  14592. do {
  14593. s1 = (s1 + buf[pos++]) |0;
  14594. s2 = (s2 + s1) |0;
  14595. } while (--n);
  14596. s1 %= 65521;
  14597. s2 %= 65521;
  14598. }
  14599. return (s1 | (s2 << 16)) |0;
  14600. }
  14601. module.exports = adler32;
  14602. },{}],55:[function(require,module,exports){
  14603. module.exports = {
  14604. /* Allowed flush values; see deflate() and inflate() below for details */
  14605. Z_NO_FLUSH: 0,
  14606. Z_PARTIAL_FLUSH: 1,
  14607. Z_SYNC_FLUSH: 2,
  14608. Z_FULL_FLUSH: 3,
  14609. Z_FINISH: 4,
  14610. Z_BLOCK: 5,
  14611. Z_TREES: 6,
  14612. /* Return codes for the compression/decompression functions. Negative values
  14613. * are errors, positive values are used for special but normal events.
  14614. */
  14615. Z_OK: 0,
  14616. Z_STREAM_END: 1,
  14617. Z_NEED_DICT: 2,
  14618. Z_ERRNO: -1,
  14619. Z_STREAM_ERROR: -2,
  14620. Z_DATA_ERROR: -3,
  14621. //Z_MEM_ERROR: -4,
  14622. Z_BUF_ERROR: -5,
  14623. //Z_VERSION_ERROR: -6,
  14624. /* compression levels */
  14625. Z_NO_COMPRESSION: 0,
  14626. Z_BEST_SPEED: 1,
  14627. Z_BEST_COMPRESSION: 9,
  14628. Z_DEFAULT_COMPRESSION: -1,
  14629. Z_FILTERED: 1,
  14630. Z_HUFFMAN_ONLY: 2,
  14631. Z_RLE: 3,
  14632. Z_FIXED: 4,
  14633. Z_DEFAULT_STRATEGY: 0,
  14634. /* Possible values of the data_type field (though see inflate()) */
  14635. Z_BINARY: 0,
  14636. Z_TEXT: 1,
  14637. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  14638. Z_UNKNOWN: 2,
  14639. /* The deflate compression method */
  14640. Z_DEFLATED: 8
  14641. //Z_NULL: null // Use -1 or null inline, depending on var type
  14642. };
  14643. },{}],56:[function(require,module,exports){
  14644. 'use strict';
  14645. // Note: we can't get significant speed boost here.
  14646. // So write code to minimize size - no pregenerated tables
  14647. // and array tools dependencies.
  14648. // Use ordinary array, since untyped makes no boost here
  14649. function makeTable() {
  14650. var c, table = [];
  14651. for (var n =0; n < 256; n++) {
  14652. c = n;
  14653. for (var k =0; k < 8; k++) {
  14654. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  14655. }
  14656. table[n] = c;
  14657. }
  14658. return table;
  14659. }
  14660. // Create table on load. Just 255 signed longs. Not a problem.
  14661. var crcTable = makeTable();
  14662. function crc32(crc, buf, len, pos) {
  14663. var t = crcTable,
  14664. end = pos + len;
  14665. crc = crc ^ (-1);
  14666. for (var i = pos; i < end; i++) {
  14667. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  14668. }
  14669. return (crc ^ (-1)); // >>> 0;
  14670. }
  14671. module.exports = crc32;
  14672. },{}],57:[function(require,module,exports){
  14673. 'use strict';
  14674. var utils = require('../utils/common');
  14675. var trees = require('./trees');
  14676. var adler32 = require('./adler32');
  14677. var crc32 = require('./crc32');
  14678. var msg = require('./messages');
  14679. /* Public constants ==========================================================*/
  14680. /* ===========================================================================*/
  14681. /* Allowed flush values; see deflate() and inflate() below for details */
  14682. var Z_NO_FLUSH = 0;
  14683. var Z_PARTIAL_FLUSH = 1;
  14684. //var Z_SYNC_FLUSH = 2;
  14685. var Z_FULL_FLUSH = 3;
  14686. var Z_FINISH = 4;
  14687. var Z_BLOCK = 5;
  14688. //var Z_TREES = 6;
  14689. /* Return codes for the compression/decompression functions. Negative values
  14690. * are errors, positive values are used for special but normal events.
  14691. */
  14692. var Z_OK = 0;
  14693. var Z_STREAM_END = 1;
  14694. //var Z_NEED_DICT = 2;
  14695. //var Z_ERRNO = -1;
  14696. var Z_STREAM_ERROR = -2;
  14697. var Z_DATA_ERROR = -3;
  14698. //var Z_MEM_ERROR = -4;
  14699. var Z_BUF_ERROR = -5;
  14700. //var Z_VERSION_ERROR = -6;
  14701. /* compression levels */
  14702. //var Z_NO_COMPRESSION = 0;
  14703. //var Z_BEST_SPEED = 1;
  14704. //var Z_BEST_COMPRESSION = 9;
  14705. var Z_DEFAULT_COMPRESSION = -1;
  14706. var Z_FILTERED = 1;
  14707. var Z_HUFFMAN_ONLY = 2;
  14708. var Z_RLE = 3;
  14709. var Z_FIXED = 4;
  14710. var Z_DEFAULT_STRATEGY = 0;
  14711. /* Possible values of the data_type field (though see inflate()) */
  14712. //var Z_BINARY = 0;
  14713. //var Z_TEXT = 1;
  14714. //var Z_ASCII = 1; // = Z_TEXT
  14715. var Z_UNKNOWN = 2;
  14716. /* The deflate compression method */
  14717. var Z_DEFLATED = 8;
  14718. /*============================================================================*/
  14719. var MAX_MEM_LEVEL = 9;
  14720. /* Maximum value for memLevel in deflateInit2 */
  14721. var MAX_WBITS = 15;
  14722. /* 32K LZ77 window */
  14723. var DEF_MEM_LEVEL = 8;
  14724. var LENGTH_CODES = 29;
  14725. /* number of length codes, not counting the special END_BLOCK code */
  14726. var LITERALS = 256;
  14727. /* number of literal bytes 0..255 */
  14728. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14729. /* number of Literal or Length codes, including the END_BLOCK code */
  14730. var D_CODES = 30;
  14731. /* number of distance codes */
  14732. var BL_CODES = 19;
  14733. /* number of codes used to transfer the bit lengths */
  14734. var HEAP_SIZE = 2*L_CODES + 1;
  14735. /* maximum heap size */
  14736. var MAX_BITS = 15;
  14737. /* All codes must not exceed MAX_BITS bits */
  14738. var MIN_MATCH = 3;
  14739. var MAX_MATCH = 258;
  14740. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  14741. var PRESET_DICT = 0x20;
  14742. var INIT_STATE = 42;
  14743. var EXTRA_STATE = 69;
  14744. var NAME_STATE = 73;
  14745. var COMMENT_STATE = 91;
  14746. var HCRC_STATE = 103;
  14747. var BUSY_STATE = 113;
  14748. var FINISH_STATE = 666;
  14749. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  14750. var BS_BLOCK_DONE = 2; /* block flush performed */
  14751. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  14752. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  14753. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  14754. function err(strm, errorCode) {
  14755. strm.msg = msg[errorCode];
  14756. return errorCode;
  14757. }
  14758. function rank(f) {
  14759. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  14760. }
  14761. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14762. /* =========================================================================
  14763. * Flush as much pending output as possible. All deflate() output goes
  14764. * through this function so some applications may wish to modify it
  14765. * to avoid allocating a large strm->output buffer and copying into it.
  14766. * (See also read_buf()).
  14767. */
  14768. function flush_pending(strm) {
  14769. var s = strm.state;
  14770. //_tr_flush_bits(s);
  14771. var len = s.pending;
  14772. if (len > strm.avail_out) {
  14773. len = strm.avail_out;
  14774. }
  14775. if (len === 0) { return; }
  14776. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  14777. strm.next_out += len;
  14778. s.pending_out += len;
  14779. strm.total_out += len;
  14780. strm.avail_out -= len;
  14781. s.pending -= len;
  14782. if (s.pending === 0) {
  14783. s.pending_out = 0;
  14784. }
  14785. }
  14786. function flush_block_only (s, last) {
  14787. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  14788. s.block_start = s.strstart;
  14789. flush_pending(s.strm);
  14790. }
  14791. function put_byte(s, b) {
  14792. s.pending_buf[s.pending++] = b;
  14793. }
  14794. /* =========================================================================
  14795. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  14796. * IN assertion: the stream state is correct and there is enough room in
  14797. * pending_buf.
  14798. */
  14799. function putShortMSB(s, b) {
  14800. // put_byte(s, (Byte)(b >> 8));
  14801. // put_byte(s, (Byte)(b & 0xff));
  14802. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  14803. s.pending_buf[s.pending++] = b & 0xff;
  14804. }
  14805. /* ===========================================================================
  14806. * Read a new buffer from the current input stream, update the adler32
  14807. * and total number of bytes read. All deflate() input goes through
  14808. * this function so some applications may wish to modify it to avoid
  14809. * allocating a large strm->input buffer and copying from it.
  14810. * (See also flush_pending()).
  14811. */
  14812. function read_buf(strm, buf, start, size) {
  14813. var len = strm.avail_in;
  14814. if (len > size) { len = size; }
  14815. if (len === 0) { return 0; }
  14816. strm.avail_in -= len;
  14817. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  14818. if (strm.state.wrap === 1) {
  14819. strm.adler = adler32(strm.adler, buf, len, start);
  14820. }
  14821. else if (strm.state.wrap === 2) {
  14822. strm.adler = crc32(strm.adler, buf, len, start);
  14823. }
  14824. strm.next_in += len;
  14825. strm.total_in += len;
  14826. return len;
  14827. }
  14828. /* ===========================================================================
  14829. * Set match_start to the longest match starting at the given string and
  14830. * return its length. Matches shorter or equal to prev_length are discarded,
  14831. * in which case the result is equal to prev_length and match_start is
  14832. * garbage.
  14833. * IN assertions: cur_match is the head of the hash chain for the current
  14834. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  14835. * OUT assertion: the match length is not greater than s->lookahead.
  14836. */
  14837. function longest_match(s, cur_match) {
  14838. var chain_length = s.max_chain_length; /* max hash chain length */
  14839. var scan = s.strstart; /* current string */
  14840. var match; /* matched string */
  14841. var len; /* length of current match */
  14842. var best_len = s.prev_length; /* best match length so far */
  14843. var nice_match = s.nice_match; /* stop if match long enough */
  14844. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14845. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14846. var _win = s.window; // shortcut
  14847. var wmask = s.w_mask;
  14848. var prev = s.prev;
  14849. /* Stop when cur_match becomes <= limit. To simplify the code,
  14850. * we prevent matches with the string of window index 0.
  14851. */
  14852. var strend = s.strstart + MAX_MATCH;
  14853. var scan_end1 = _win[scan + best_len - 1];
  14854. var scan_end = _win[scan + best_len];
  14855. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14856. * It is easy to get rid of this optimization if necessary.
  14857. */
  14858. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14859. /* Do not waste too much time if we already have a good match: */
  14860. if (s.prev_length >= s.good_match) {
  14861. chain_length >>= 2;
  14862. }
  14863. /* Do not look for matches beyond the end of the input. This is necessary
  14864. * to make deflate deterministic.
  14865. */
  14866. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14867. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14868. do {
  14869. // Assert(cur_match < s->strstart, "no future");
  14870. match = cur_match;
  14871. /* Skip to next match if the match length cannot increase
  14872. * or if the match length is less than 2. Note that the checks below
  14873. * for insufficient lookahead only occur occasionally for performance
  14874. * reasons. Therefore uninitialized memory will be accessed, and
  14875. * conditional jumps will be made that depend on those values.
  14876. * However the length of the match is limited to the lookahead, so
  14877. * the output of deflate is not affected by the uninitialized values.
  14878. */
  14879. if (_win[match + best_len] !== scan_end ||
  14880. _win[match + best_len - 1] !== scan_end1 ||
  14881. _win[match] !== _win[scan] ||
  14882. _win[++match] !== _win[scan + 1]) {
  14883. continue;
  14884. }
  14885. /* The check at best_len-1 can be removed because it will be made
  14886. * again later. (This heuristic is not always a win.)
  14887. * It is not necessary to compare scan[2] and match[2] since they
  14888. * are always equal when the other bytes match, given that
  14889. * the hash keys are equal and that HASH_BITS >= 8.
  14890. */
  14891. scan += 2;
  14892. match++;
  14893. // Assert(*scan == *match, "match[2]?");
  14894. /* We check for insufficient lookahead only every 8th comparison;
  14895. * the 256th check will be made at strstart+258.
  14896. */
  14897. do {
  14898. /*jshint noempty:false*/
  14899. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14900. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14901. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14902. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14903. scan < strend);
  14904. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14905. len = MAX_MATCH - (strend - scan);
  14906. scan = strend - MAX_MATCH;
  14907. if (len > best_len) {
  14908. s.match_start = cur_match;
  14909. best_len = len;
  14910. if (len >= nice_match) {
  14911. break;
  14912. }
  14913. scan_end1 = _win[scan + best_len - 1];
  14914. scan_end = _win[scan + best_len];
  14915. }
  14916. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14917. if (best_len <= s.lookahead) {
  14918. return best_len;
  14919. }
  14920. return s.lookahead;
  14921. }
  14922. /* ===========================================================================
  14923. * Fill the window when the lookahead becomes insufficient.
  14924. * Updates strstart and lookahead.
  14925. *
  14926. * IN assertion: lookahead < MIN_LOOKAHEAD
  14927. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14928. * At least one byte has been read, or avail_in == 0; reads are
  14929. * performed for at least two bytes (required for the zip translate_eol
  14930. * option -- not supported here).
  14931. */
  14932. function fill_window(s) {
  14933. var _w_size = s.w_size;
  14934. var p, n, m, more, str;
  14935. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14936. do {
  14937. more = s.window_size - s.lookahead - s.strstart;
  14938. // JS ints have 32 bit, block below not needed
  14939. /* Deal with !@#$% 64K limit: */
  14940. //if (sizeof(int) <= 2) {
  14941. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14942. // more = wsize;
  14943. //
  14944. // } else if (more == (unsigned)(-1)) {
  14945. // /* Very unlikely, but possible on 16 bit machine if
  14946. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14947. // */
  14948. // more--;
  14949. // }
  14950. //}
  14951. /* If the window is almost full and there is insufficient lookahead,
  14952. * move the upper half to the lower one to make room in the upper half.
  14953. */
  14954. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14955. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14956. s.match_start -= _w_size;
  14957. s.strstart -= _w_size;
  14958. /* we now have strstart >= MAX_DIST */
  14959. s.block_start -= _w_size;
  14960. /* Slide the hash table (could be avoided with 32 bit values
  14961. at the expense of memory usage). We slide even when level == 0
  14962. to keep the hash table consistent if we switch back to level > 0
  14963. later. (Using level 0 permanently is not an optimal usage of
  14964. zlib, so we don't care about this pathological case.)
  14965. */
  14966. n = s.hash_size;
  14967. p = n;
  14968. do {
  14969. m = s.head[--p];
  14970. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14971. } while (--n);
  14972. n = _w_size;
  14973. p = n;
  14974. do {
  14975. m = s.prev[--p];
  14976. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14977. /* If n is not on any hash chain, prev[n] is garbage but
  14978. * its value will never be used.
  14979. */
  14980. } while (--n);
  14981. more += _w_size;
  14982. }
  14983. if (s.strm.avail_in === 0) {
  14984. break;
  14985. }
  14986. /* If there was no sliding:
  14987. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14988. * more == window_size - lookahead - strstart
  14989. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14990. * => more >= window_size - 2*WSIZE + 2
  14991. * In the BIG_MEM or MMAP case (not yet supported),
  14992. * window_size == input_size + MIN_LOOKAHEAD &&
  14993. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14994. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14995. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14996. */
  14997. //Assert(more >= 2, "more < 2");
  14998. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14999. s.lookahead += n;
  15000. /* Initialize the hash value now that we have some input: */
  15001. if (s.lookahead + s.insert >= MIN_MATCH) {
  15002. str = s.strstart - s.insert;
  15003. s.ins_h = s.window[str];
  15004. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  15005. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  15006. //#if MIN_MATCH != 3
  15007. // Call update_hash() MIN_MATCH-3 more times
  15008. //#endif
  15009. while (s.insert) {
  15010. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15011. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  15012. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15013. s.head[s.ins_h] = str;
  15014. str++;
  15015. s.insert--;
  15016. if (s.lookahead + s.insert < MIN_MATCH) {
  15017. break;
  15018. }
  15019. }
  15020. }
  15021. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  15022. * but this is not important since only literal bytes will be emitted.
  15023. */
  15024. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  15025. /* If the WIN_INIT bytes after the end of the current data have never been
  15026. * written, then zero those bytes in order to avoid memory check reports of
  15027. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  15028. * the longest match routines. Update the high water mark for the next
  15029. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  15030. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  15031. */
  15032. // if (s.high_water < s.window_size) {
  15033. // var curr = s.strstart + s.lookahead;
  15034. // var init = 0;
  15035. //
  15036. // if (s.high_water < curr) {
  15037. // /* Previous high water mark below current data -- zero WIN_INIT
  15038. // * bytes or up to end of window, whichever is less.
  15039. // */
  15040. // init = s.window_size - curr;
  15041. // if (init > WIN_INIT)
  15042. // init = WIN_INIT;
  15043. // zmemzero(s->window + curr, (unsigned)init);
  15044. // s->high_water = curr + init;
  15045. // }
  15046. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  15047. // /* High water mark at or above current data, but below current data
  15048. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  15049. // * to end of window, whichever is less.
  15050. // */
  15051. // init = (ulg)curr + WIN_INIT - s->high_water;
  15052. // if (init > s->window_size - s->high_water)
  15053. // init = s->window_size - s->high_water;
  15054. // zmemzero(s->window + s->high_water, (unsigned)init);
  15055. // s->high_water += init;
  15056. // }
  15057. // }
  15058. //
  15059. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15060. // "not enough room for search");
  15061. }
  15062. /* ===========================================================================
  15063. * Copy without compression as much as possible from the input stream, return
  15064. * the current block state.
  15065. * This function does not insert new strings in the dictionary since
  15066. * uncompressible data is probably not useful. This function is used
  15067. * only for the level=0 compression option.
  15068. * NOTE: this function should be optimized to avoid extra copying from
  15069. * window to pending_buf.
  15070. */
  15071. function deflate_stored(s, flush) {
  15072. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15073. * to pending_buf_size, and each stored block has a 5 byte header:
  15074. */
  15075. var max_block_size = 0xffff;
  15076. if (max_block_size > s.pending_buf_size - 5) {
  15077. max_block_size = s.pending_buf_size - 5;
  15078. }
  15079. /* Copy as much as possible from input to output: */
  15080. for (;;) {
  15081. /* Fill the window as much as possible: */
  15082. if (s.lookahead <= 1) {
  15083. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15084. // s->block_start >= (long)s->w_size, "slide too late");
  15085. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15086. // s.block_start >= s.w_size)) {
  15087. // throw new Error("slide too late");
  15088. // }
  15089. fill_window(s);
  15090. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  15091. return BS_NEED_MORE;
  15092. }
  15093. if (s.lookahead === 0) {
  15094. break;
  15095. }
  15096. /* flush the current block */
  15097. }
  15098. //Assert(s->block_start >= 0L, "block gone");
  15099. // if (s.block_start < 0) throw new Error("block gone");
  15100. s.strstart += s.lookahead;
  15101. s.lookahead = 0;
  15102. /* Emit a stored block if pending_buf will be full: */
  15103. var max_start = s.block_start + max_block_size;
  15104. if (s.strstart === 0 || s.strstart >= max_start) {
  15105. /* strstart == 0 is possible when wraparound on 16-bit machine */
  15106. s.lookahead = s.strstart - max_start;
  15107. s.strstart = max_start;
  15108. /*** FLUSH_BLOCK(s, 0); ***/
  15109. flush_block_only(s, false);
  15110. if (s.strm.avail_out === 0) {
  15111. return BS_NEED_MORE;
  15112. }
  15113. /***/
  15114. }
  15115. /* Flush if we may have to slide, otherwise block_start may become
  15116. * negative and the data will be gone:
  15117. */
  15118. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  15119. /*** FLUSH_BLOCK(s, 0); ***/
  15120. flush_block_only(s, false);
  15121. if (s.strm.avail_out === 0) {
  15122. return BS_NEED_MORE;
  15123. }
  15124. /***/
  15125. }
  15126. }
  15127. s.insert = 0;
  15128. if (flush === Z_FINISH) {
  15129. /*** FLUSH_BLOCK(s, 1); ***/
  15130. flush_block_only(s, true);
  15131. if (s.strm.avail_out === 0) {
  15132. return BS_FINISH_STARTED;
  15133. }
  15134. /***/
  15135. return BS_FINISH_DONE;
  15136. }
  15137. if (s.strstart > s.block_start) {
  15138. /*** FLUSH_BLOCK(s, 0); ***/
  15139. flush_block_only(s, false);
  15140. if (s.strm.avail_out === 0) {
  15141. return BS_NEED_MORE;
  15142. }
  15143. /***/
  15144. }
  15145. return BS_NEED_MORE;
  15146. }
  15147. /* ===========================================================================
  15148. * Compress as much as possible from the input stream, return the current
  15149. * block state.
  15150. * This function does not perform lazy evaluation of matches and inserts
  15151. * new strings in the dictionary only for unmatched strings or for short
  15152. * matches. It is used only for the fast compression options.
  15153. */
  15154. function deflate_fast(s, flush) {
  15155. var hash_head; /* head of the hash chain */
  15156. var bflush; /* set if current block must be flushed */
  15157. for (;;) {
  15158. /* Make sure that we always have enough lookahead, except
  15159. * at the end of the input file. We need MAX_MATCH bytes
  15160. * for the next match, plus MIN_MATCH bytes to insert the
  15161. * string following the next match.
  15162. */
  15163. if (s.lookahead < MIN_LOOKAHEAD) {
  15164. fill_window(s);
  15165. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15166. return BS_NEED_MORE;
  15167. }
  15168. if (s.lookahead === 0) {
  15169. break; /* flush the current block */
  15170. }
  15171. }
  15172. /* Insert the string window[strstart .. strstart+2] in the
  15173. * dictionary, and set hash_head to the head of the hash chain:
  15174. */
  15175. hash_head = 0/*NIL*/;
  15176. if (s.lookahead >= MIN_MATCH) {
  15177. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15178. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15179. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15180. s.head[s.ins_h] = s.strstart;
  15181. /***/
  15182. }
  15183. /* Find the longest match, discarding those <= prev_length.
  15184. * At this point we have always match_length < MIN_MATCH
  15185. */
  15186. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  15187. /* To simplify the code, we prevent matches with the string
  15188. * of window index 0 (in particular we have to avoid a match
  15189. * of the string with itself at the start of the input file).
  15190. */
  15191. s.match_length = longest_match(s, hash_head);
  15192. /* longest_match() sets match_start */
  15193. }
  15194. if (s.match_length >= MIN_MATCH) {
  15195. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  15196. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  15197. s.match_length - MIN_MATCH, bflush); ***/
  15198. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  15199. s.lookahead -= s.match_length;
  15200. /* Insert new strings in the hash table only if the match length
  15201. * is not too large. This saves time but degrades compression.
  15202. */
  15203. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  15204. s.match_length--; /* string at strstart already in table */
  15205. do {
  15206. s.strstart++;
  15207. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15208. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15209. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15210. s.head[s.ins_h] = s.strstart;
  15211. /***/
  15212. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  15213. * always MIN_MATCH bytes ahead.
  15214. */
  15215. } while (--s.match_length !== 0);
  15216. s.strstart++;
  15217. } else
  15218. {
  15219. s.strstart += s.match_length;
  15220. s.match_length = 0;
  15221. s.ins_h = s.window[s.strstart];
  15222. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  15223. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  15224. //#if MIN_MATCH != 3
  15225. // Call UPDATE_HASH() MIN_MATCH-3 more times
  15226. //#endif
  15227. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  15228. * matter since it will be recomputed at next deflate call.
  15229. */
  15230. }
  15231. } else {
  15232. /* No match, output a literal byte */
  15233. //Tracevv((stderr,"%c", s.window[s.strstart]));
  15234. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15235. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15236. s.lookahead--;
  15237. s.strstart++;
  15238. }
  15239. if (bflush) {
  15240. /*** FLUSH_BLOCK(s, 0); ***/
  15241. flush_block_only(s, false);
  15242. if (s.strm.avail_out === 0) {
  15243. return BS_NEED_MORE;
  15244. }
  15245. /***/
  15246. }
  15247. }
  15248. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  15249. if (flush === Z_FINISH) {
  15250. /*** FLUSH_BLOCK(s, 1); ***/
  15251. flush_block_only(s, true);
  15252. if (s.strm.avail_out === 0) {
  15253. return BS_FINISH_STARTED;
  15254. }
  15255. /***/
  15256. return BS_FINISH_DONE;
  15257. }
  15258. if (s.last_lit) {
  15259. /*** FLUSH_BLOCK(s, 0); ***/
  15260. flush_block_only(s, false);
  15261. if (s.strm.avail_out === 0) {
  15262. return BS_NEED_MORE;
  15263. }
  15264. /***/
  15265. }
  15266. return BS_BLOCK_DONE;
  15267. }
  15268. /* ===========================================================================
  15269. * Same as above, but achieves better compression. We use a lazy
  15270. * evaluation for matches: a match is finally adopted only if there is
  15271. * no better match at the next window position.
  15272. */
  15273. function deflate_slow(s, flush) {
  15274. var hash_head; /* head of hash chain */
  15275. var bflush; /* set if current block must be flushed */
  15276. var max_insert;
  15277. /* Process the input block. */
  15278. for (;;) {
  15279. /* Make sure that we always have enough lookahead, except
  15280. * at the end of the input file. We need MAX_MATCH bytes
  15281. * for the next match, plus MIN_MATCH bytes to insert the
  15282. * string following the next match.
  15283. */
  15284. if (s.lookahead < MIN_LOOKAHEAD) {
  15285. fill_window(s);
  15286. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15287. return BS_NEED_MORE;
  15288. }
  15289. if (s.lookahead === 0) { break; } /* flush the current block */
  15290. }
  15291. /* Insert the string window[strstart .. strstart+2] in the
  15292. * dictionary, and set hash_head to the head of the hash chain:
  15293. */
  15294. hash_head = 0/*NIL*/;
  15295. if (s.lookahead >= MIN_MATCH) {
  15296. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15297. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15298. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15299. s.head[s.ins_h] = s.strstart;
  15300. /***/
  15301. }
  15302. /* Find the longest match, discarding those <= prev_length.
  15303. */
  15304. s.prev_length = s.match_length;
  15305. s.prev_match = s.match_start;
  15306. s.match_length = MIN_MATCH-1;
  15307. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  15308. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  15309. /* To simplify the code, we prevent matches with the string
  15310. * of window index 0 (in particular we have to avoid a match
  15311. * of the string with itself at the start of the input file).
  15312. */
  15313. s.match_length = longest_match(s, hash_head);
  15314. /* longest_match() sets match_start */
  15315. if (s.match_length <= 5 &&
  15316. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  15317. /* If prev_match is also MIN_MATCH, match_start is garbage
  15318. * but we will ignore the current match anyway.
  15319. */
  15320. s.match_length = MIN_MATCH-1;
  15321. }
  15322. }
  15323. /* If there was a match at the previous step and the current
  15324. * match is not better, output the previous match:
  15325. */
  15326. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  15327. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  15328. /* Do not insert strings in hash table beyond this. */
  15329. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  15330. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  15331. s.prev_length - MIN_MATCH, bflush);***/
  15332. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  15333. /* Insert in hash table all strings up to the end of the match.
  15334. * strstart-1 and strstart are already inserted. If there is not
  15335. * enough lookahead, the last two strings are not inserted in
  15336. * the hash table.
  15337. */
  15338. s.lookahead -= s.prev_length-1;
  15339. s.prev_length -= 2;
  15340. do {
  15341. if (++s.strstart <= max_insert) {
  15342. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15343. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15344. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15345. s.head[s.ins_h] = s.strstart;
  15346. /***/
  15347. }
  15348. } while (--s.prev_length !== 0);
  15349. s.match_available = 0;
  15350. s.match_length = MIN_MATCH-1;
  15351. s.strstart++;
  15352. if (bflush) {
  15353. /*** FLUSH_BLOCK(s, 0); ***/
  15354. flush_block_only(s, false);
  15355. if (s.strm.avail_out === 0) {
  15356. return BS_NEED_MORE;
  15357. }
  15358. /***/
  15359. }
  15360. } else if (s.match_available) {
  15361. /* If there was no match at the previous position, output a
  15362. * single literal. If there was a match but the current match
  15363. * is longer, truncate the previous match to a single literal.
  15364. */
  15365. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15366. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15367. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15368. if (bflush) {
  15369. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  15370. flush_block_only(s, false);
  15371. /***/
  15372. }
  15373. s.strstart++;
  15374. s.lookahead--;
  15375. if (s.strm.avail_out === 0) {
  15376. return BS_NEED_MORE;
  15377. }
  15378. } else {
  15379. /* There is no previous match to compare with, wait for
  15380. * the next step to decide.
  15381. */
  15382. s.match_available = 1;
  15383. s.strstart++;
  15384. s.lookahead--;
  15385. }
  15386. }
  15387. //Assert (flush != Z_NO_FLUSH, "no flush?");
  15388. if (s.match_available) {
  15389. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15390. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15391. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15392. s.match_available = 0;
  15393. }
  15394. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  15395. if (flush === Z_FINISH) {
  15396. /*** FLUSH_BLOCK(s, 1); ***/
  15397. flush_block_only(s, true);
  15398. if (s.strm.avail_out === 0) {
  15399. return BS_FINISH_STARTED;
  15400. }
  15401. /***/
  15402. return BS_FINISH_DONE;
  15403. }
  15404. if (s.last_lit) {
  15405. /*** FLUSH_BLOCK(s, 0); ***/
  15406. flush_block_only(s, false);
  15407. if (s.strm.avail_out === 0) {
  15408. return BS_NEED_MORE;
  15409. }
  15410. /***/
  15411. }
  15412. return BS_BLOCK_DONE;
  15413. }
  15414. /* ===========================================================================
  15415. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  15416. * one. Do not maintain a hash table. (It will be regenerated if this run of
  15417. * deflate switches away from Z_RLE.)
  15418. */
  15419. function deflate_rle(s, flush) {
  15420. var bflush; /* set if current block must be flushed */
  15421. var prev; /* byte at distance one to match */
  15422. var scan, strend; /* scan goes up to strend for length of run */
  15423. var _win = s.window;
  15424. for (;;) {
  15425. /* Make sure that we always have enough lookahead, except
  15426. * at the end of the input file. We need MAX_MATCH bytes
  15427. * for the longest run, plus one for the unrolled loop.
  15428. */
  15429. if (s.lookahead <= MAX_MATCH) {
  15430. fill_window(s);
  15431. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  15432. return BS_NEED_MORE;
  15433. }
  15434. if (s.lookahead === 0) { break; } /* flush the current block */
  15435. }
  15436. /* See how many times the previous byte repeats */
  15437. s.match_length = 0;
  15438. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  15439. scan = s.strstart - 1;
  15440. prev = _win[scan];
  15441. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  15442. strend = s.strstart + MAX_MATCH;
  15443. do {
  15444. /*jshint noempty:false*/
  15445. } while (prev === _win[++scan] && prev === _win[++scan] &&
  15446. prev === _win[++scan] && prev === _win[++scan] &&
  15447. prev === _win[++scan] && prev === _win[++scan] &&
  15448. prev === _win[++scan] && prev === _win[++scan] &&
  15449. scan < strend);
  15450. s.match_length = MAX_MATCH - (strend - scan);
  15451. if (s.match_length > s.lookahead) {
  15452. s.match_length = s.lookahead;
  15453. }
  15454. }
  15455. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  15456. }
  15457. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  15458. if (s.match_length >= MIN_MATCH) {
  15459. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  15460. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  15461. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  15462. s.lookahead -= s.match_length;
  15463. s.strstart += s.match_length;
  15464. s.match_length = 0;
  15465. } else {
  15466. /* No match, output a literal byte */
  15467. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15468. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15469. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15470. s.lookahead--;
  15471. s.strstart++;
  15472. }
  15473. if (bflush) {
  15474. /*** FLUSH_BLOCK(s, 0); ***/
  15475. flush_block_only(s, false);
  15476. if (s.strm.avail_out === 0) {
  15477. return BS_NEED_MORE;
  15478. }
  15479. /***/
  15480. }
  15481. }
  15482. s.insert = 0;
  15483. if (flush === Z_FINISH) {
  15484. /*** FLUSH_BLOCK(s, 1); ***/
  15485. flush_block_only(s, true);
  15486. if (s.strm.avail_out === 0) {
  15487. return BS_FINISH_STARTED;
  15488. }
  15489. /***/
  15490. return BS_FINISH_DONE;
  15491. }
  15492. if (s.last_lit) {
  15493. /*** FLUSH_BLOCK(s, 0); ***/
  15494. flush_block_only(s, false);
  15495. if (s.strm.avail_out === 0) {
  15496. return BS_NEED_MORE;
  15497. }
  15498. /***/
  15499. }
  15500. return BS_BLOCK_DONE;
  15501. }
  15502. /* ===========================================================================
  15503. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  15504. * (It will be regenerated if this run of deflate switches away from Huffman.)
  15505. */
  15506. function deflate_huff(s, flush) {
  15507. var bflush; /* set if current block must be flushed */
  15508. for (;;) {
  15509. /* Make sure that we have a literal to write. */
  15510. if (s.lookahead === 0) {
  15511. fill_window(s);
  15512. if (s.lookahead === 0) {
  15513. if (flush === Z_NO_FLUSH) {
  15514. return BS_NEED_MORE;
  15515. }
  15516. break; /* flush the current block */
  15517. }
  15518. }
  15519. /* Output a literal byte */
  15520. s.match_length = 0;
  15521. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15522. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15523. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15524. s.lookahead--;
  15525. s.strstart++;
  15526. if (bflush) {
  15527. /*** FLUSH_BLOCK(s, 0); ***/
  15528. flush_block_only(s, false);
  15529. if (s.strm.avail_out === 0) {
  15530. return BS_NEED_MORE;
  15531. }
  15532. /***/
  15533. }
  15534. }
  15535. s.insert = 0;
  15536. if (flush === Z_FINISH) {
  15537. /*** FLUSH_BLOCK(s, 1); ***/
  15538. flush_block_only(s, true);
  15539. if (s.strm.avail_out === 0) {
  15540. return BS_FINISH_STARTED;
  15541. }
  15542. /***/
  15543. return BS_FINISH_DONE;
  15544. }
  15545. if (s.last_lit) {
  15546. /*** FLUSH_BLOCK(s, 0); ***/
  15547. flush_block_only(s, false);
  15548. if (s.strm.avail_out === 0) {
  15549. return BS_NEED_MORE;
  15550. }
  15551. /***/
  15552. }
  15553. return BS_BLOCK_DONE;
  15554. }
  15555. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  15556. * the desired pack level (0..9). The values given below have been tuned to
  15557. * exclude worst case performance for pathological files. Better values may be
  15558. * found for specific files.
  15559. */
  15560. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  15561. this.good_length = good_length;
  15562. this.max_lazy = max_lazy;
  15563. this.nice_length = nice_length;
  15564. this.max_chain = max_chain;
  15565. this.func = func;
  15566. };
  15567. var configuration_table;
  15568. configuration_table = [
  15569. /* good lazy nice chain */
  15570. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  15571. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  15572. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  15573. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  15574. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  15575. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  15576. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  15577. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  15578. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  15579. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  15580. ];
  15581. /* ===========================================================================
  15582. * Initialize the "longest match" routines for a new zlib stream
  15583. */
  15584. function lm_init(s) {
  15585. s.window_size = 2 * s.w_size;
  15586. /*** CLEAR_HASH(s); ***/
  15587. zero(s.head); // Fill with NIL (= 0);
  15588. /* Set the default configuration parameters:
  15589. */
  15590. s.max_lazy_match = configuration_table[s.level].max_lazy;
  15591. s.good_match = configuration_table[s.level].good_length;
  15592. s.nice_match = configuration_table[s.level].nice_length;
  15593. s.max_chain_length = configuration_table[s.level].max_chain;
  15594. s.strstart = 0;
  15595. s.block_start = 0;
  15596. s.lookahead = 0;
  15597. s.insert = 0;
  15598. s.match_length = s.prev_length = MIN_MATCH - 1;
  15599. s.match_available = 0;
  15600. s.ins_h = 0;
  15601. }
  15602. function DeflateState() {
  15603. this.strm = null; /* pointer back to this zlib stream */
  15604. this.status = 0; /* as the name implies */
  15605. this.pending_buf = null; /* output still pending */
  15606. this.pending_buf_size = 0; /* size of pending_buf */
  15607. this.pending_out = 0; /* next pending byte to output to the stream */
  15608. this.pending = 0; /* nb of bytes in the pending buffer */
  15609. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15610. this.gzhead = null; /* gzip header information to write */
  15611. this.gzindex = 0; /* where in extra, name, or comment */
  15612. this.method = Z_DEFLATED; /* can only be DEFLATED */
  15613. this.last_flush = -1; /* value of flush param for previous deflate call */
  15614. this.w_size = 0; /* LZ77 window size (32K by default) */
  15615. this.w_bits = 0; /* log2(w_size) (8..16) */
  15616. this.w_mask = 0; /* w_size - 1 */
  15617. this.window = null;
  15618. /* Sliding window. Input bytes are read into the second half of the window,
  15619. * and move to the first half later to keep a dictionary of at least wSize
  15620. * bytes. With this organization, matches are limited to a distance of
  15621. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  15622. * performed with a length multiple of the block size.
  15623. */
  15624. this.window_size = 0;
  15625. /* Actual size of window: 2*wSize, except when the user input buffer
  15626. * is directly used as sliding window.
  15627. */
  15628. this.prev = null;
  15629. /* Link to older string with same hash index. To limit the size of this
  15630. * array to 64K, this link is maintained only for the last 32K strings.
  15631. * An index in this array is thus a window index modulo 32K.
  15632. */
  15633. this.head = null; /* Heads of the hash chains or NIL. */
  15634. this.ins_h = 0; /* hash index of string to be inserted */
  15635. this.hash_size = 0; /* number of elements in hash table */
  15636. this.hash_bits = 0; /* log2(hash_size) */
  15637. this.hash_mask = 0; /* hash_size-1 */
  15638. this.hash_shift = 0;
  15639. /* Number of bits by which ins_h must be shifted at each input
  15640. * step. It must be such that after MIN_MATCH steps, the oldest
  15641. * byte no longer takes part in the hash key, that is:
  15642. * hash_shift * MIN_MATCH >= hash_bits
  15643. */
  15644. this.block_start = 0;
  15645. /* Window position at the beginning of the current output block. Gets
  15646. * negative when the window is moved backwards.
  15647. */
  15648. this.match_length = 0; /* length of best match */
  15649. this.prev_match = 0; /* previous match */
  15650. this.match_available = 0; /* set if previous match exists */
  15651. this.strstart = 0; /* start of string to insert */
  15652. this.match_start = 0; /* start of matching string */
  15653. this.lookahead = 0; /* number of valid bytes ahead in window */
  15654. this.prev_length = 0;
  15655. /* Length of the best match at previous step. Matches not greater than this
  15656. * are discarded. This is used in the lazy match evaluation.
  15657. */
  15658. this.max_chain_length = 0;
  15659. /* To speed up deflation, hash chains are never searched beyond this
  15660. * length. A higher limit improves compression ratio but degrades the
  15661. * speed.
  15662. */
  15663. this.max_lazy_match = 0;
  15664. /* Attempt to find a better match only when the current match is strictly
  15665. * smaller than this value. This mechanism is used only for compression
  15666. * levels >= 4.
  15667. */
  15668. // That's alias to max_lazy_match, don't use directly
  15669. //this.max_insert_length = 0;
  15670. /* Insert new strings in the hash table only if the match length is not
  15671. * greater than this length. This saves time but degrades compression.
  15672. * max_insert_length is used only for compression levels <= 3.
  15673. */
  15674. this.level = 0; /* compression level (1..9) */
  15675. this.strategy = 0; /* favor or force Huffman coding*/
  15676. this.good_match = 0;
  15677. /* Use a faster search when the previous match is longer than this */
  15678. this.nice_match = 0; /* Stop searching when current match exceeds this */
  15679. /* used by trees.c: */
  15680. /* Didn't use ct_data typedef below to suppress compiler warning */
  15681. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  15682. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  15683. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  15684. // Use flat array of DOUBLE size, with interleaved fata,
  15685. // because JS does not support effective
  15686. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  15687. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  15688. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  15689. zero(this.dyn_ltree);
  15690. zero(this.dyn_dtree);
  15691. zero(this.bl_tree);
  15692. this.l_desc = null; /* desc. for literal tree */
  15693. this.d_desc = null; /* desc. for distance tree */
  15694. this.bl_desc = null; /* desc. for bit length tree */
  15695. //ush bl_count[MAX_BITS+1];
  15696. this.bl_count = new utils.Buf16(MAX_BITS+1);
  15697. /* number of codes at each bit length for an optimal tree */
  15698. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  15699. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  15700. zero(this.heap);
  15701. this.heap_len = 0; /* number of elements in the heap */
  15702. this.heap_max = 0; /* element of largest frequency */
  15703. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15704. * The same heap array is used to build all trees.
  15705. */
  15706. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  15707. zero(this.depth);
  15708. /* Depth of each subtree used as tie breaker for trees of equal frequency
  15709. */
  15710. this.l_buf = 0; /* buffer index for literals or lengths */
  15711. this.lit_bufsize = 0;
  15712. /* Size of match buffer for literals/lengths. There are 4 reasons for
  15713. * limiting lit_bufsize to 64K:
  15714. * - frequencies can be kept in 16 bit counters
  15715. * - if compression is not successful for the first block, all input
  15716. * data is still in the window so we can still emit a stored block even
  15717. * when input comes from standard input. (This can also be done for
  15718. * all blocks if lit_bufsize is not greater than 32K.)
  15719. * - if compression is not successful for a file smaller than 64K, we can
  15720. * even emit a stored file instead of a stored block (saving 5 bytes).
  15721. * This is applicable only for zip (not gzip or zlib).
  15722. * - creating new Huffman trees less frequently may not provide fast
  15723. * adaptation to changes in the input data statistics. (Take for
  15724. * example a binary file with poorly compressible code followed by
  15725. * a highly compressible string table.) Smaller buffer sizes give
  15726. * fast adaptation but have of course the overhead of transmitting
  15727. * trees more frequently.
  15728. * - I can't count above 4
  15729. */
  15730. this.last_lit = 0; /* running index in l_buf */
  15731. this.d_buf = 0;
  15732. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  15733. * the same number of elements. To use different lengths, an extra flag
  15734. * array would be necessary.
  15735. */
  15736. this.opt_len = 0; /* bit length of current block with optimal trees */
  15737. this.static_len = 0; /* bit length of current block with static trees */
  15738. this.matches = 0; /* number of string matches in current block */
  15739. this.insert = 0; /* bytes at end of window left to insert */
  15740. this.bi_buf = 0;
  15741. /* Output buffer. bits are inserted starting at the bottom (least
  15742. * significant bits).
  15743. */
  15744. this.bi_valid = 0;
  15745. /* Number of valid bits in bi_buf. All bits above the last valid bit
  15746. * are always zero.
  15747. */
  15748. // Used for window memory init. We safely ignore it for JS. That makes
  15749. // sense only for pointers and memory check tools.
  15750. //this.high_water = 0;
  15751. /* High water mark offset in window for initialized bytes -- bytes above
  15752. * this are set to zero in order to avoid memory check warnings when
  15753. * longest match routines access bytes past the input. This is then
  15754. * updated to the new high water mark.
  15755. */
  15756. }
  15757. function deflateResetKeep(strm) {
  15758. var s;
  15759. if (!strm || !strm.state) {
  15760. return err(strm, Z_STREAM_ERROR);
  15761. }
  15762. strm.total_in = strm.total_out = 0;
  15763. strm.data_type = Z_UNKNOWN;
  15764. s = strm.state;
  15765. s.pending = 0;
  15766. s.pending_out = 0;
  15767. if (s.wrap < 0) {
  15768. s.wrap = -s.wrap;
  15769. /* was made negative by deflate(..., Z_FINISH); */
  15770. }
  15771. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  15772. strm.adler = (s.wrap === 2) ?
  15773. 0 // crc32(0, Z_NULL, 0)
  15774. :
  15775. 1; // adler32(0, Z_NULL, 0)
  15776. s.last_flush = Z_NO_FLUSH;
  15777. trees._tr_init(s);
  15778. return Z_OK;
  15779. }
  15780. function deflateReset(strm) {
  15781. var ret = deflateResetKeep(strm);
  15782. if (ret === Z_OK) {
  15783. lm_init(strm.state);
  15784. }
  15785. return ret;
  15786. }
  15787. function deflateSetHeader(strm, head) {
  15788. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15789. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  15790. strm.state.gzhead = head;
  15791. return Z_OK;
  15792. }
  15793. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  15794. if (!strm) { // === Z_NULL
  15795. return Z_STREAM_ERROR;
  15796. }
  15797. var wrap = 1;
  15798. if (level === Z_DEFAULT_COMPRESSION) {
  15799. level = 6;
  15800. }
  15801. if (windowBits < 0) { /* suppress zlib wrapper */
  15802. wrap = 0;
  15803. windowBits = -windowBits;
  15804. }
  15805. else if (windowBits > 15) {
  15806. wrap = 2; /* write gzip wrapper instead */
  15807. windowBits -= 16;
  15808. }
  15809. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  15810. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  15811. strategy < 0 || strategy > Z_FIXED) {
  15812. return err(strm, Z_STREAM_ERROR);
  15813. }
  15814. if (windowBits === 8) {
  15815. windowBits = 9;
  15816. }
  15817. /* until 256-byte window bug fixed */
  15818. var s = new DeflateState();
  15819. strm.state = s;
  15820. s.strm = strm;
  15821. s.wrap = wrap;
  15822. s.gzhead = null;
  15823. s.w_bits = windowBits;
  15824. s.w_size = 1 << s.w_bits;
  15825. s.w_mask = s.w_size - 1;
  15826. s.hash_bits = memLevel + 7;
  15827. s.hash_size = 1 << s.hash_bits;
  15828. s.hash_mask = s.hash_size - 1;
  15829. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15830. s.window = new utils.Buf8(s.w_size * 2);
  15831. s.head = new utils.Buf16(s.hash_size);
  15832. s.prev = new utils.Buf16(s.w_size);
  15833. // Don't need mem init magic for JS.
  15834. //s.high_water = 0; /* nothing written to s->window yet */
  15835. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  15836. s.pending_buf_size = s.lit_bufsize * 4;
  15837. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  15838. s.d_buf = s.lit_bufsize >> 1;
  15839. s.l_buf = (1 + 2) * s.lit_bufsize;
  15840. s.level = level;
  15841. s.strategy = strategy;
  15842. s.method = method;
  15843. return deflateReset(strm);
  15844. }
  15845. function deflateInit(strm, level) {
  15846. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15847. }
  15848. function deflate(strm, flush) {
  15849. var old_flush, s;
  15850. var beg, val; // for gzip header write only
  15851. if (!strm || !strm.state ||
  15852. flush > Z_BLOCK || flush < 0) {
  15853. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15854. }
  15855. s = strm.state;
  15856. if (!strm.output ||
  15857. (!strm.input && strm.avail_in !== 0) ||
  15858. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15859. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15860. }
  15861. s.strm = strm; /* just in case */
  15862. old_flush = s.last_flush;
  15863. s.last_flush = flush;
  15864. /* Write the header */
  15865. if (s.status === INIT_STATE) {
  15866. if (s.wrap === 2) { // GZIP header
  15867. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15868. put_byte(s, 31);
  15869. put_byte(s, 139);
  15870. put_byte(s, 8);
  15871. if (!s.gzhead) { // s->gzhead == Z_NULL
  15872. put_byte(s, 0);
  15873. put_byte(s, 0);
  15874. put_byte(s, 0);
  15875. put_byte(s, 0);
  15876. put_byte(s, 0);
  15877. put_byte(s, s.level === 9 ? 2 :
  15878. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15879. 4 : 0));
  15880. put_byte(s, OS_CODE);
  15881. s.status = BUSY_STATE;
  15882. }
  15883. else {
  15884. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15885. (s.gzhead.hcrc ? 2 : 0) +
  15886. (!s.gzhead.extra ? 0 : 4) +
  15887. (!s.gzhead.name ? 0 : 8) +
  15888. (!s.gzhead.comment ? 0 : 16)
  15889. );
  15890. put_byte(s, s.gzhead.time & 0xff);
  15891. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15892. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15893. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15894. put_byte(s, s.level === 9 ? 2 :
  15895. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15896. 4 : 0));
  15897. put_byte(s, s.gzhead.os & 0xff);
  15898. if (s.gzhead.extra && s.gzhead.extra.length) {
  15899. put_byte(s, s.gzhead.extra.length & 0xff);
  15900. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15901. }
  15902. if (s.gzhead.hcrc) {
  15903. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15904. }
  15905. s.gzindex = 0;
  15906. s.status = EXTRA_STATE;
  15907. }
  15908. }
  15909. else // DEFLATE header
  15910. {
  15911. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15912. var level_flags = -1;
  15913. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15914. level_flags = 0;
  15915. } else if (s.level < 6) {
  15916. level_flags = 1;
  15917. } else if (s.level === 6) {
  15918. level_flags = 2;
  15919. } else {
  15920. level_flags = 3;
  15921. }
  15922. header |= (level_flags << 6);
  15923. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15924. header += 31 - (header % 31);
  15925. s.status = BUSY_STATE;
  15926. putShortMSB(s, header);
  15927. /* Save the adler32 of the preset dictionary: */
  15928. if (s.strstart !== 0) {
  15929. putShortMSB(s, strm.adler >>> 16);
  15930. putShortMSB(s, strm.adler & 0xffff);
  15931. }
  15932. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15933. }
  15934. }
  15935. //#ifdef GZIP
  15936. if (s.status === EXTRA_STATE) {
  15937. if (s.gzhead.extra/* != Z_NULL*/) {
  15938. beg = s.pending; /* start of bytes to update crc */
  15939. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15940. if (s.pending === s.pending_buf_size) {
  15941. if (s.gzhead.hcrc && s.pending > beg) {
  15942. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15943. }
  15944. flush_pending(strm);
  15945. beg = s.pending;
  15946. if (s.pending === s.pending_buf_size) {
  15947. break;
  15948. }
  15949. }
  15950. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15951. s.gzindex++;
  15952. }
  15953. if (s.gzhead.hcrc && s.pending > beg) {
  15954. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15955. }
  15956. if (s.gzindex === s.gzhead.extra.length) {
  15957. s.gzindex = 0;
  15958. s.status = NAME_STATE;
  15959. }
  15960. }
  15961. else {
  15962. s.status = NAME_STATE;
  15963. }
  15964. }
  15965. if (s.status === NAME_STATE) {
  15966. if (s.gzhead.name/* != Z_NULL*/) {
  15967. beg = s.pending; /* start of bytes to update crc */
  15968. //int val;
  15969. do {
  15970. if (s.pending === s.pending_buf_size) {
  15971. if (s.gzhead.hcrc && s.pending > beg) {
  15972. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15973. }
  15974. flush_pending(strm);
  15975. beg = s.pending;
  15976. if (s.pending === s.pending_buf_size) {
  15977. val = 1;
  15978. break;
  15979. }
  15980. }
  15981. // JS specific: little magic to add zero terminator to end of string
  15982. if (s.gzindex < s.gzhead.name.length) {
  15983. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15984. } else {
  15985. val = 0;
  15986. }
  15987. put_byte(s, val);
  15988. } while (val !== 0);
  15989. if (s.gzhead.hcrc && s.pending > beg) {
  15990. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15991. }
  15992. if (val === 0) {
  15993. s.gzindex = 0;
  15994. s.status = COMMENT_STATE;
  15995. }
  15996. }
  15997. else {
  15998. s.status = COMMENT_STATE;
  15999. }
  16000. }
  16001. if (s.status === COMMENT_STATE) {
  16002. if (s.gzhead.comment/* != Z_NULL*/) {
  16003. beg = s.pending; /* start of bytes to update crc */
  16004. //int val;
  16005. do {
  16006. if (s.pending === s.pending_buf_size) {
  16007. if (s.gzhead.hcrc && s.pending > beg) {
  16008. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16009. }
  16010. flush_pending(strm);
  16011. beg = s.pending;
  16012. if (s.pending === s.pending_buf_size) {
  16013. val = 1;
  16014. break;
  16015. }
  16016. }
  16017. // JS specific: little magic to add zero terminator to end of string
  16018. if (s.gzindex < s.gzhead.comment.length) {
  16019. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  16020. } else {
  16021. val = 0;
  16022. }
  16023. put_byte(s, val);
  16024. } while (val !== 0);
  16025. if (s.gzhead.hcrc && s.pending > beg) {
  16026. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16027. }
  16028. if (val === 0) {
  16029. s.status = HCRC_STATE;
  16030. }
  16031. }
  16032. else {
  16033. s.status = HCRC_STATE;
  16034. }
  16035. }
  16036. if (s.status === HCRC_STATE) {
  16037. if (s.gzhead.hcrc) {
  16038. if (s.pending + 2 > s.pending_buf_size) {
  16039. flush_pending(strm);
  16040. }
  16041. if (s.pending + 2 <= s.pending_buf_size) {
  16042. put_byte(s, strm.adler & 0xff);
  16043. put_byte(s, (strm.adler >> 8) & 0xff);
  16044. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16045. s.status = BUSY_STATE;
  16046. }
  16047. }
  16048. else {
  16049. s.status = BUSY_STATE;
  16050. }
  16051. }
  16052. //#endif
  16053. /* Flush as much pending output as possible */
  16054. if (s.pending !== 0) {
  16055. flush_pending(strm);
  16056. if (strm.avail_out === 0) {
  16057. /* Since avail_out is 0, deflate will be called again with
  16058. * more output space, but possibly with both pending and
  16059. * avail_in equal to zero. There won't be anything to do,
  16060. * but this is not an error situation so make sure we
  16061. * return OK instead of BUF_ERROR at next call of deflate:
  16062. */
  16063. s.last_flush = -1;
  16064. return Z_OK;
  16065. }
  16066. /* Make sure there is something to do and avoid duplicate consecutive
  16067. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16068. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16069. */
  16070. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16071. flush !== Z_FINISH) {
  16072. return err(strm, Z_BUF_ERROR);
  16073. }
  16074. /* User must not provide more input after the first FINISH: */
  16075. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16076. return err(strm, Z_BUF_ERROR);
  16077. }
  16078. /* Start a new block or continue the current one.
  16079. */
  16080. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16081. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16082. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16083. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16084. configuration_table[s.level].func(s, flush));
  16085. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16086. s.status = FINISH_STATE;
  16087. }
  16088. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  16089. if (strm.avail_out === 0) {
  16090. s.last_flush = -1;
  16091. /* avoid BUF_ERROR next call, see above */
  16092. }
  16093. return Z_OK;
  16094. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  16095. * of deflate should use the same flush parameter to make sure
  16096. * that the flush is complete. So we don't have to output an
  16097. * empty block here, this will be done at next call. This also
  16098. * ensures that for a very small output buffer, we emit at most
  16099. * one empty block.
  16100. */
  16101. }
  16102. if (bstate === BS_BLOCK_DONE) {
  16103. if (flush === Z_PARTIAL_FLUSH) {
  16104. trees._tr_align(s);
  16105. }
  16106. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  16107. trees._tr_stored_block(s, 0, 0, false);
  16108. /* For a full flush, this empty block will be recognized
  16109. * as a special marker by inflate_sync().
  16110. */
  16111. if (flush === Z_FULL_FLUSH) {
  16112. /*** CLEAR_HASH(s); ***/ /* forget history */
  16113. zero(s.head); // Fill with NIL (= 0);
  16114. if (s.lookahead === 0) {
  16115. s.strstart = 0;
  16116. s.block_start = 0;
  16117. s.insert = 0;
  16118. }
  16119. }
  16120. }
  16121. flush_pending(strm);
  16122. if (strm.avail_out === 0) {
  16123. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  16124. return Z_OK;
  16125. }
  16126. }
  16127. }
  16128. //Assert(strm->avail_out > 0, "bug2");
  16129. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  16130. if (flush !== Z_FINISH) { return Z_OK; }
  16131. if (s.wrap <= 0) { return Z_STREAM_END; }
  16132. /* Write the trailer */
  16133. if (s.wrap === 2) {
  16134. put_byte(s, strm.adler & 0xff);
  16135. put_byte(s, (strm.adler >> 8) & 0xff);
  16136. put_byte(s, (strm.adler >> 16) & 0xff);
  16137. put_byte(s, (strm.adler >> 24) & 0xff);
  16138. put_byte(s, strm.total_in & 0xff);
  16139. put_byte(s, (strm.total_in >> 8) & 0xff);
  16140. put_byte(s, (strm.total_in >> 16) & 0xff);
  16141. put_byte(s, (strm.total_in >> 24) & 0xff);
  16142. }
  16143. else
  16144. {
  16145. putShortMSB(s, strm.adler >>> 16);
  16146. putShortMSB(s, strm.adler & 0xffff);
  16147. }
  16148. flush_pending(strm);
  16149. /* If avail_out is zero, the application will call deflate again
  16150. * to flush the rest.
  16151. */
  16152. if (s.wrap > 0) { s.wrap = -s.wrap; }
  16153. /* write the trailer only once! */
  16154. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  16155. }
  16156. function deflateEnd(strm) {
  16157. var status;
  16158. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  16159. return Z_STREAM_ERROR;
  16160. }
  16161. status = strm.state.status;
  16162. if (status !== INIT_STATE &&
  16163. status !== EXTRA_STATE &&
  16164. status !== NAME_STATE &&
  16165. status !== COMMENT_STATE &&
  16166. status !== HCRC_STATE &&
  16167. status !== BUSY_STATE &&
  16168. status !== FINISH_STATE
  16169. ) {
  16170. return err(strm, Z_STREAM_ERROR);
  16171. }
  16172. strm.state = null;
  16173. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  16174. }
  16175. /* =========================================================================
  16176. * Copy the source state to the destination state
  16177. */
  16178. //function deflateCopy(dest, source) {
  16179. //
  16180. //}
  16181. exports.deflateInit = deflateInit;
  16182. exports.deflateInit2 = deflateInit2;
  16183. exports.deflateReset = deflateReset;
  16184. exports.deflateResetKeep = deflateResetKeep;
  16185. exports.deflateSetHeader = deflateSetHeader;
  16186. exports.deflate = deflate;
  16187. exports.deflateEnd = deflateEnd;
  16188. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  16189. /* Not implemented
  16190. exports.deflateBound = deflateBound;
  16191. exports.deflateCopy = deflateCopy;
  16192. exports.deflateSetDictionary = deflateSetDictionary;
  16193. exports.deflateParams = deflateParams;
  16194. exports.deflatePending = deflatePending;
  16195. exports.deflatePrime = deflatePrime;
  16196. exports.deflateTune = deflateTune;
  16197. */
  16198. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./messages":62,"./trees":63}],58:[function(require,module,exports){
  16199. 'use strict';
  16200. function GZheader() {
  16201. /* true if compressed data believed to be text */
  16202. this.text = 0;
  16203. /* modification time */
  16204. this.time = 0;
  16205. /* extra flags (not used when writing a gzip file) */
  16206. this.xflags = 0;
  16207. /* operating system */
  16208. this.os = 0;
  16209. /* pointer to extra field or Z_NULL if none */
  16210. this.extra = null;
  16211. /* extra field length (valid if extra != Z_NULL) */
  16212. this.extra_len = 0; // Actually, we don't need it in JS,
  16213. // but leave for few code modifications
  16214. //
  16215. // Setup limits is not necessary because in js we should not preallocate memory
  16216. // for inflate use constant limit in 65536 bytes
  16217. //
  16218. /* space at extra (only when reading header) */
  16219. // this.extra_max = 0;
  16220. /* pointer to zero-terminated file name or Z_NULL */
  16221. this.name = '';
  16222. /* space at name (only when reading header) */
  16223. // this.name_max = 0;
  16224. /* pointer to zero-terminated comment or Z_NULL */
  16225. this.comment = '';
  16226. /* space at comment (only when reading header) */
  16227. // this.comm_max = 0;
  16228. /* true if there was or will be a header crc */
  16229. this.hcrc = 0;
  16230. /* true when done reading gzip header (not used when writing a gzip file) */
  16231. this.done = false;
  16232. }
  16233. module.exports = GZheader;
  16234. },{}],59:[function(require,module,exports){
  16235. 'use strict';
  16236. // See state defs from inflate.js
  16237. var BAD = 30; /* got a data error -- remain here until reset */
  16238. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16239. /*
  16240. Decode literal, length, and distance codes and write out the resulting
  16241. literal and match bytes until either not enough input or output is
  16242. available, an end-of-block is encountered, or a data error is encountered.
  16243. When large enough input and output buffers are supplied to inflate(), for
  16244. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  16245. inflate execution time is spent in this routine.
  16246. Entry assumptions:
  16247. state.mode === LEN
  16248. strm.avail_in >= 6
  16249. strm.avail_out >= 258
  16250. start >= strm.avail_out
  16251. state.bits < 8
  16252. On return, state.mode is one of:
  16253. LEN -- ran out of enough output space or enough available input
  16254. TYPE -- reached end of block code, inflate() to interpret next block
  16255. BAD -- error in block data
  16256. Notes:
  16257. - The maximum input bits used by a length/distance pair is 15 bits for the
  16258. length code, 5 bits for the length extra, 15 bits for the distance code,
  16259. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  16260. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  16261. checking for available input while decoding.
  16262. - The maximum bytes that a single length/distance pair can output is 258
  16263. bytes, which is the maximum length that can be coded. inflate_fast()
  16264. requires strm.avail_out >= 258 for each loop to avoid checking for
  16265. output space.
  16266. */
  16267. module.exports = function inflate_fast(strm, start) {
  16268. var state;
  16269. var _in; /* local strm.input */
  16270. var last; /* have enough input while in < last */
  16271. var _out; /* local strm.output */
  16272. var beg; /* inflate()'s initial strm.output */
  16273. var end; /* while out < end, enough space available */
  16274. //#ifdef INFLATE_STRICT
  16275. var dmax; /* maximum distance from zlib header */
  16276. //#endif
  16277. var wsize; /* window size or zero if not using window */
  16278. var whave; /* valid bytes in the window */
  16279. var wnext; /* window write index */
  16280. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  16281. var s_window; /* allocated sliding window, if wsize != 0 */
  16282. var hold; /* local strm.hold */
  16283. var bits; /* local strm.bits */
  16284. var lcode; /* local strm.lencode */
  16285. var dcode; /* local strm.distcode */
  16286. var lmask; /* mask for first level of length codes */
  16287. var dmask; /* mask for first level of distance codes */
  16288. var here; /* retrieved table entry */
  16289. var op; /* code bits, operation, extra bits, or */
  16290. /* window position, window bytes to copy */
  16291. var len; /* match length, unused bytes */
  16292. var dist; /* match distance */
  16293. var from; /* where to copy match from */
  16294. var from_source;
  16295. var input, output; // JS specific, because we have no pointers
  16296. /* copy state to local variables */
  16297. state = strm.state;
  16298. //here = state.here;
  16299. _in = strm.next_in;
  16300. input = strm.input;
  16301. last = _in + (strm.avail_in - 5);
  16302. _out = strm.next_out;
  16303. output = strm.output;
  16304. beg = _out - (start - strm.avail_out);
  16305. end = _out + (strm.avail_out - 257);
  16306. //#ifdef INFLATE_STRICT
  16307. dmax = state.dmax;
  16308. //#endif
  16309. wsize = state.wsize;
  16310. whave = state.whave;
  16311. wnext = state.wnext;
  16312. s_window = state.window;
  16313. hold = state.hold;
  16314. bits = state.bits;
  16315. lcode = state.lencode;
  16316. dcode = state.distcode;
  16317. lmask = (1 << state.lenbits) - 1;
  16318. dmask = (1 << state.distbits) - 1;
  16319. /* decode literals and length/distances until end-of-block or not enough
  16320. input data or output space */
  16321. top:
  16322. do {
  16323. if (bits < 15) {
  16324. hold += input[_in++] << bits;
  16325. bits += 8;
  16326. hold += input[_in++] << bits;
  16327. bits += 8;
  16328. }
  16329. here = lcode[hold & lmask];
  16330. dolen:
  16331. for (;;) { // Goto emulation
  16332. op = here >>> 24/*here.bits*/;
  16333. hold >>>= op;
  16334. bits -= op;
  16335. op = (here >>> 16) & 0xff/*here.op*/;
  16336. if (op === 0) { /* literal */
  16337. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16338. // "inflate: literal '%c'\n" :
  16339. // "inflate: literal 0x%02x\n", here.val));
  16340. output[_out++] = here & 0xffff/*here.val*/;
  16341. }
  16342. else if (op & 16) { /* length base */
  16343. len = here & 0xffff/*here.val*/;
  16344. op &= 15; /* number of extra bits */
  16345. if (op) {
  16346. if (bits < op) {
  16347. hold += input[_in++] << bits;
  16348. bits += 8;
  16349. }
  16350. len += hold & ((1 << op) - 1);
  16351. hold >>>= op;
  16352. bits -= op;
  16353. }
  16354. //Tracevv((stderr, "inflate: length %u\n", len));
  16355. if (bits < 15) {
  16356. hold += input[_in++] << bits;
  16357. bits += 8;
  16358. hold += input[_in++] << bits;
  16359. bits += 8;
  16360. }
  16361. here = dcode[hold & dmask];
  16362. dodist:
  16363. for (;;) { // goto emulation
  16364. op = here >>> 24/*here.bits*/;
  16365. hold >>>= op;
  16366. bits -= op;
  16367. op = (here >>> 16) & 0xff/*here.op*/;
  16368. if (op & 16) { /* distance base */
  16369. dist = here & 0xffff/*here.val*/;
  16370. op &= 15; /* number of extra bits */
  16371. if (bits < op) {
  16372. hold += input[_in++] << bits;
  16373. bits += 8;
  16374. if (bits < op) {
  16375. hold += input[_in++] << bits;
  16376. bits += 8;
  16377. }
  16378. }
  16379. dist += hold & ((1 << op) - 1);
  16380. //#ifdef INFLATE_STRICT
  16381. if (dist > dmax) {
  16382. strm.msg = 'invalid distance too far back';
  16383. state.mode = BAD;
  16384. break top;
  16385. }
  16386. //#endif
  16387. hold >>>= op;
  16388. bits -= op;
  16389. //Tracevv((stderr, "inflate: distance %u\n", dist));
  16390. op = _out - beg; /* max distance in output */
  16391. if (dist > op) { /* see if copy from window */
  16392. op = dist - op; /* distance back in window */
  16393. if (op > whave) {
  16394. if (state.sane) {
  16395. strm.msg = 'invalid distance too far back';
  16396. state.mode = BAD;
  16397. break top;
  16398. }
  16399. // (!) This block is disabled in zlib defailts,
  16400. // don't enable it for binary compatibility
  16401. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16402. // if (len <= op - whave) {
  16403. // do {
  16404. // output[_out++] = 0;
  16405. // } while (--len);
  16406. // continue top;
  16407. // }
  16408. // len -= op - whave;
  16409. // do {
  16410. // output[_out++] = 0;
  16411. // } while (--op > whave);
  16412. // if (op === 0) {
  16413. // from = _out - dist;
  16414. // do {
  16415. // output[_out++] = output[from++];
  16416. // } while (--len);
  16417. // continue top;
  16418. // }
  16419. //#endif
  16420. }
  16421. from = 0; // window index
  16422. from_source = s_window;
  16423. if (wnext === 0) { /* very common case */
  16424. from += wsize - op;
  16425. if (op < len) { /* some from window */
  16426. len -= op;
  16427. do {
  16428. output[_out++] = s_window[from++];
  16429. } while (--op);
  16430. from = _out - dist; /* rest from output */
  16431. from_source = output;
  16432. }
  16433. }
  16434. else if (wnext < op) { /* wrap around window */
  16435. from += wsize + wnext - op;
  16436. op -= wnext;
  16437. if (op < len) { /* some from end of window */
  16438. len -= op;
  16439. do {
  16440. output[_out++] = s_window[from++];
  16441. } while (--op);
  16442. from = 0;
  16443. if (wnext < len) { /* some from start of window */
  16444. op = wnext;
  16445. len -= op;
  16446. do {
  16447. output[_out++] = s_window[from++];
  16448. } while (--op);
  16449. from = _out - dist; /* rest from output */
  16450. from_source = output;
  16451. }
  16452. }
  16453. }
  16454. else { /* contiguous in window */
  16455. from += wnext - op;
  16456. if (op < len) { /* some from window */
  16457. len -= op;
  16458. do {
  16459. output[_out++] = s_window[from++];
  16460. } while (--op);
  16461. from = _out - dist; /* rest from output */
  16462. from_source = output;
  16463. }
  16464. }
  16465. while (len > 2) {
  16466. output[_out++] = from_source[from++];
  16467. output[_out++] = from_source[from++];
  16468. output[_out++] = from_source[from++];
  16469. len -= 3;
  16470. }
  16471. if (len) {
  16472. output[_out++] = from_source[from++];
  16473. if (len > 1) {
  16474. output[_out++] = from_source[from++];
  16475. }
  16476. }
  16477. }
  16478. else {
  16479. from = _out - dist; /* copy direct from output */
  16480. do { /* minimum length is three */
  16481. output[_out++] = output[from++];
  16482. output[_out++] = output[from++];
  16483. output[_out++] = output[from++];
  16484. len -= 3;
  16485. } while (len > 2);
  16486. if (len) {
  16487. output[_out++] = output[from++];
  16488. if (len > 1) {
  16489. output[_out++] = output[from++];
  16490. }
  16491. }
  16492. }
  16493. }
  16494. else if ((op & 64) === 0) { /* 2nd level distance code */
  16495. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16496. continue dodist;
  16497. }
  16498. else {
  16499. strm.msg = 'invalid distance code';
  16500. state.mode = BAD;
  16501. break top;
  16502. }
  16503. break; // need to emulate goto via "continue"
  16504. }
  16505. }
  16506. else if ((op & 64) === 0) { /* 2nd level length code */
  16507. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16508. continue dolen;
  16509. }
  16510. else if (op & 32) { /* end-of-block */
  16511. //Tracevv((stderr, "inflate: end of block\n"));
  16512. state.mode = TYPE;
  16513. break top;
  16514. }
  16515. else {
  16516. strm.msg = 'invalid literal/length code';
  16517. state.mode = BAD;
  16518. break top;
  16519. }
  16520. break; // need to emulate goto via "continue"
  16521. }
  16522. } while (_in < last && _out < end);
  16523. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  16524. len = bits >> 3;
  16525. _in -= len;
  16526. bits -= len << 3;
  16527. hold &= (1 << bits) - 1;
  16528. /* update state and return */
  16529. strm.next_in = _in;
  16530. strm.next_out = _out;
  16531. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  16532. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  16533. state.hold = hold;
  16534. state.bits = bits;
  16535. return;
  16536. };
  16537. },{}],60:[function(require,module,exports){
  16538. 'use strict';
  16539. var utils = require('../utils/common');
  16540. var adler32 = require('./adler32');
  16541. var crc32 = require('./crc32');
  16542. var inflate_fast = require('./inffast');
  16543. var inflate_table = require('./inftrees');
  16544. var CODES = 0;
  16545. var LENS = 1;
  16546. var DISTS = 2;
  16547. /* Public constants ==========================================================*/
  16548. /* ===========================================================================*/
  16549. /* Allowed flush values; see deflate() and inflate() below for details */
  16550. //var Z_NO_FLUSH = 0;
  16551. //var Z_PARTIAL_FLUSH = 1;
  16552. //var Z_SYNC_FLUSH = 2;
  16553. //var Z_FULL_FLUSH = 3;
  16554. var Z_FINISH = 4;
  16555. var Z_BLOCK = 5;
  16556. var Z_TREES = 6;
  16557. /* Return codes for the compression/decompression functions. Negative values
  16558. * are errors, positive values are used for special but normal events.
  16559. */
  16560. var Z_OK = 0;
  16561. var Z_STREAM_END = 1;
  16562. var Z_NEED_DICT = 2;
  16563. //var Z_ERRNO = -1;
  16564. var Z_STREAM_ERROR = -2;
  16565. var Z_DATA_ERROR = -3;
  16566. var Z_MEM_ERROR = -4;
  16567. var Z_BUF_ERROR = -5;
  16568. //var Z_VERSION_ERROR = -6;
  16569. /* The deflate compression method */
  16570. var Z_DEFLATED = 8;
  16571. /* STATES ====================================================================*/
  16572. /* ===========================================================================*/
  16573. var HEAD = 1; /* i: waiting for magic header */
  16574. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  16575. var TIME = 3; /* i: waiting for modification time (gzip) */
  16576. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  16577. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  16578. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  16579. var NAME = 7; /* i: waiting for end of file name (gzip) */
  16580. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  16581. var HCRC = 9; /* i: waiting for header crc (gzip) */
  16582. var DICTID = 10; /* i: waiting for dictionary check value */
  16583. var DICT = 11; /* waiting for inflateSetDictionary() call */
  16584. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16585. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  16586. var STORED = 14; /* i: waiting for stored size (length and complement) */
  16587. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  16588. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  16589. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  16590. var LENLENS = 18; /* i: waiting for code length code lengths */
  16591. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  16592. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  16593. var LEN = 21; /* i: waiting for length/lit/eob code */
  16594. var LENEXT = 22; /* i: waiting for length extra bits */
  16595. var DIST = 23; /* i: waiting for distance code */
  16596. var DISTEXT = 24; /* i: waiting for distance extra bits */
  16597. var MATCH = 25; /* o: waiting for output space to copy string */
  16598. var LIT = 26; /* o: waiting for output space to write literal */
  16599. var CHECK = 27; /* i: waiting for 32-bit check value */
  16600. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  16601. var DONE = 29; /* finished check, done -- remain here until reset */
  16602. var BAD = 30; /* got a data error -- remain here until reset */
  16603. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  16604. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  16605. /* ===========================================================================*/
  16606. var ENOUGH_LENS = 852;
  16607. var ENOUGH_DISTS = 592;
  16608. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16609. var MAX_WBITS = 15;
  16610. /* 32K LZ77 window */
  16611. var DEF_WBITS = MAX_WBITS;
  16612. function ZSWAP32(q) {
  16613. return (((q >>> 24) & 0xff) +
  16614. ((q >>> 8) & 0xff00) +
  16615. ((q & 0xff00) << 8) +
  16616. ((q & 0xff) << 24));
  16617. }
  16618. function InflateState() {
  16619. this.mode = 0; /* current inflate mode */
  16620. this.last = false; /* true if processing last block */
  16621. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16622. this.havedict = false; /* true if dictionary provided */
  16623. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  16624. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  16625. this.check = 0; /* protected copy of check value */
  16626. this.total = 0; /* protected copy of output count */
  16627. // TODO: may be {}
  16628. this.head = null; /* where to save gzip header information */
  16629. /* sliding window */
  16630. this.wbits = 0; /* log base 2 of requested window size */
  16631. this.wsize = 0; /* window size or zero if not using window */
  16632. this.whave = 0; /* valid bytes in the window */
  16633. this.wnext = 0; /* window write index */
  16634. this.window = null; /* allocated sliding window, if needed */
  16635. /* bit accumulator */
  16636. this.hold = 0; /* input bit accumulator */
  16637. this.bits = 0; /* number of bits in "in" */
  16638. /* for string and stored block copying */
  16639. this.length = 0; /* literal or length of data to copy */
  16640. this.offset = 0; /* distance back to copy string from */
  16641. /* for table and code decoding */
  16642. this.extra = 0; /* extra bits needed */
  16643. /* fixed and dynamic code tables */
  16644. this.lencode = null; /* starting table for length/literal codes */
  16645. this.distcode = null; /* starting table for distance codes */
  16646. this.lenbits = 0; /* index bits for lencode */
  16647. this.distbits = 0; /* index bits for distcode */
  16648. /* dynamic table building */
  16649. this.ncode = 0; /* number of code length code lengths */
  16650. this.nlen = 0; /* number of length code lengths */
  16651. this.ndist = 0; /* number of distance code lengths */
  16652. this.have = 0; /* number of code lengths in lens[] */
  16653. this.next = null; /* next available space in codes[] */
  16654. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  16655. this.work = new utils.Buf16(288); /* work area for code table building */
  16656. /*
  16657. because we don't have pointers in js, we use lencode and distcode directly
  16658. as buffers so we don't need codes
  16659. */
  16660. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  16661. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  16662. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  16663. this.sane = 0; /* if false, allow invalid distance too far */
  16664. this.back = 0; /* bits back of last unprocessed length/lit */
  16665. this.was = 0; /* initial length of match */
  16666. }
  16667. function inflateResetKeep(strm) {
  16668. var state;
  16669. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16670. state = strm.state;
  16671. strm.total_in = strm.total_out = state.total = 0;
  16672. strm.msg = ''; /*Z_NULL*/
  16673. if (state.wrap) { /* to support ill-conceived Java test suite */
  16674. strm.adler = state.wrap & 1;
  16675. }
  16676. state.mode = HEAD;
  16677. state.last = 0;
  16678. state.havedict = 0;
  16679. state.dmax = 32768;
  16680. state.head = null/*Z_NULL*/;
  16681. state.hold = 0;
  16682. state.bits = 0;
  16683. //state.lencode = state.distcode = state.next = state.codes;
  16684. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  16685. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  16686. state.sane = 1;
  16687. state.back = -1;
  16688. //Tracev((stderr, "inflate: reset\n"));
  16689. return Z_OK;
  16690. }
  16691. function inflateReset(strm) {
  16692. var state;
  16693. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16694. state = strm.state;
  16695. state.wsize = 0;
  16696. state.whave = 0;
  16697. state.wnext = 0;
  16698. return inflateResetKeep(strm);
  16699. }
  16700. function inflateReset2(strm, windowBits) {
  16701. var wrap;
  16702. var state;
  16703. /* get the state */
  16704. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16705. state = strm.state;
  16706. /* extract wrap request from windowBits parameter */
  16707. if (windowBits < 0) {
  16708. wrap = 0;
  16709. windowBits = -windowBits;
  16710. }
  16711. else {
  16712. wrap = (windowBits >> 4) + 1;
  16713. if (windowBits < 48) {
  16714. windowBits &= 15;
  16715. }
  16716. }
  16717. /* set number of window bits, free window if different */
  16718. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  16719. return Z_STREAM_ERROR;
  16720. }
  16721. if (state.window !== null && state.wbits !== windowBits) {
  16722. state.window = null;
  16723. }
  16724. /* update state and reset the rest of it */
  16725. state.wrap = wrap;
  16726. state.wbits = windowBits;
  16727. return inflateReset(strm);
  16728. }
  16729. function inflateInit2(strm, windowBits) {
  16730. var ret;
  16731. var state;
  16732. if (!strm) { return Z_STREAM_ERROR; }
  16733. //strm.msg = Z_NULL; /* in case we return an error */
  16734. state = new InflateState();
  16735. //if (state === Z_NULL) return Z_MEM_ERROR;
  16736. //Tracev((stderr, "inflate: allocated\n"));
  16737. strm.state = state;
  16738. state.window = null/*Z_NULL*/;
  16739. ret = inflateReset2(strm, windowBits);
  16740. if (ret !== Z_OK) {
  16741. strm.state = null/*Z_NULL*/;
  16742. }
  16743. return ret;
  16744. }
  16745. function inflateInit(strm) {
  16746. return inflateInit2(strm, DEF_WBITS);
  16747. }
  16748. /*
  16749. Return state with length and distance decoding tables and index sizes set to
  16750. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  16751. If BUILDFIXED is defined, then instead this routine builds the tables the
  16752. first time it's called, and returns those tables the first time and
  16753. thereafter. This reduces the size of the code by about 2K bytes, in
  16754. exchange for a little execution time. However, BUILDFIXED should not be
  16755. used for threaded applications, since the rewriting of the tables and virgin
  16756. may not be thread-safe.
  16757. */
  16758. var virgin = true;
  16759. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  16760. function fixedtables(state) {
  16761. /* build fixed huffman tables if first call (may not be thread safe) */
  16762. if (virgin) {
  16763. var sym;
  16764. lenfix = new utils.Buf32(512);
  16765. distfix = new utils.Buf32(32);
  16766. /* literal/length table */
  16767. sym = 0;
  16768. while (sym < 144) { state.lens[sym++] = 8; }
  16769. while (sym < 256) { state.lens[sym++] = 9; }
  16770. while (sym < 280) { state.lens[sym++] = 7; }
  16771. while (sym < 288) { state.lens[sym++] = 8; }
  16772. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  16773. /* distance table */
  16774. sym = 0;
  16775. while (sym < 32) { state.lens[sym++] = 5; }
  16776. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  16777. /* do this just once */
  16778. virgin = false;
  16779. }
  16780. state.lencode = lenfix;
  16781. state.lenbits = 9;
  16782. state.distcode = distfix;
  16783. state.distbits = 5;
  16784. }
  16785. /*
  16786. Update the window with the last wsize (normally 32K) bytes written before
  16787. returning. If window does not exist yet, create it. This is only called
  16788. when a window is already in use, or when output has been written during this
  16789. inflate call, but the end of the deflate stream has not been reached yet.
  16790. It is also called to create a window for dictionary data when a dictionary
  16791. is loaded.
  16792. Providing output buffers larger than 32K to inflate() should provide a speed
  16793. advantage, since only the last 32K of output is copied to the sliding window
  16794. upon return from inflate(), and since all distances after the first 32K of
  16795. output will fall in the output data, making match copies simpler and faster.
  16796. The advantage may be dependent on the size of the processor's data caches.
  16797. */
  16798. function updatewindow(strm, src, end, copy) {
  16799. var dist;
  16800. var state = strm.state;
  16801. /* if it hasn't been done already, allocate space for the window */
  16802. if (state.window === null) {
  16803. state.wsize = 1 << state.wbits;
  16804. state.wnext = 0;
  16805. state.whave = 0;
  16806. state.window = new utils.Buf8(state.wsize);
  16807. }
  16808. /* copy state->wsize or less output bytes into the circular window */
  16809. if (copy >= state.wsize) {
  16810. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  16811. state.wnext = 0;
  16812. state.whave = state.wsize;
  16813. }
  16814. else {
  16815. dist = state.wsize - state.wnext;
  16816. if (dist > copy) {
  16817. dist = copy;
  16818. }
  16819. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16820. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  16821. copy -= dist;
  16822. if (copy) {
  16823. //zmemcpy(state->window, end - copy, copy);
  16824. utils.arraySet(state.window,src, end - copy, copy, 0);
  16825. state.wnext = copy;
  16826. state.whave = state.wsize;
  16827. }
  16828. else {
  16829. state.wnext += dist;
  16830. if (state.wnext === state.wsize) { state.wnext = 0; }
  16831. if (state.whave < state.wsize) { state.whave += dist; }
  16832. }
  16833. }
  16834. return 0;
  16835. }
  16836. function inflate(strm, flush) {
  16837. var state;
  16838. var input, output; // input/output buffers
  16839. var next; /* next input INDEX */
  16840. var put; /* next output INDEX */
  16841. var have, left; /* available input and output */
  16842. var hold; /* bit buffer */
  16843. var bits; /* bits in bit buffer */
  16844. var _in, _out; /* save starting available input and output */
  16845. var copy; /* number of stored or match bytes to copy */
  16846. var from; /* where to copy match bytes from */
  16847. var from_source;
  16848. var here = 0; /* current decoding table entry */
  16849. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16850. //var last; /* parent table entry */
  16851. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16852. var len; /* length to copy for repeats, bits to drop */
  16853. var ret; /* return code */
  16854. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16855. var opts;
  16856. var n; // temporary var for NEED_BITS
  16857. var order = /* permutation of code lengths */
  16858. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16859. if (!strm || !strm.state || !strm.output ||
  16860. (!strm.input && strm.avail_in !== 0)) {
  16861. return Z_STREAM_ERROR;
  16862. }
  16863. state = strm.state;
  16864. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16865. //--- LOAD() ---
  16866. put = strm.next_out;
  16867. output = strm.output;
  16868. left = strm.avail_out;
  16869. next = strm.next_in;
  16870. input = strm.input;
  16871. have = strm.avail_in;
  16872. hold = state.hold;
  16873. bits = state.bits;
  16874. //---
  16875. _in = have;
  16876. _out = left;
  16877. ret = Z_OK;
  16878. inf_leave: // goto emulation
  16879. for (;;) {
  16880. switch (state.mode) {
  16881. case HEAD:
  16882. if (state.wrap === 0) {
  16883. state.mode = TYPEDO;
  16884. break;
  16885. }
  16886. //=== NEEDBITS(16);
  16887. while (bits < 16) {
  16888. if (have === 0) { break inf_leave; }
  16889. have--;
  16890. hold += input[next++] << bits;
  16891. bits += 8;
  16892. }
  16893. //===//
  16894. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16895. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16896. //=== CRC2(state.check, hold);
  16897. hbuf[0] = hold & 0xff;
  16898. hbuf[1] = (hold >>> 8) & 0xff;
  16899. state.check = crc32(state.check, hbuf, 2, 0);
  16900. //===//
  16901. //=== INITBITS();
  16902. hold = 0;
  16903. bits = 0;
  16904. //===//
  16905. state.mode = FLAGS;
  16906. break;
  16907. }
  16908. state.flags = 0; /* expect zlib header */
  16909. if (state.head) {
  16910. state.head.done = false;
  16911. }
  16912. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16913. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16914. strm.msg = 'incorrect header check';
  16915. state.mode = BAD;
  16916. break;
  16917. }
  16918. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16919. strm.msg = 'unknown compression method';
  16920. state.mode = BAD;
  16921. break;
  16922. }
  16923. //--- DROPBITS(4) ---//
  16924. hold >>>= 4;
  16925. bits -= 4;
  16926. //---//
  16927. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16928. if (state.wbits === 0) {
  16929. state.wbits = len;
  16930. }
  16931. else if (len > state.wbits) {
  16932. strm.msg = 'invalid window size';
  16933. state.mode = BAD;
  16934. break;
  16935. }
  16936. state.dmax = 1 << len;
  16937. //Tracev((stderr, "inflate: zlib header ok\n"));
  16938. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16939. state.mode = hold & 0x200 ? DICTID : TYPE;
  16940. //=== INITBITS();
  16941. hold = 0;
  16942. bits = 0;
  16943. //===//
  16944. break;
  16945. case FLAGS:
  16946. //=== NEEDBITS(16); */
  16947. while (bits < 16) {
  16948. if (have === 0) { break inf_leave; }
  16949. have--;
  16950. hold += input[next++] << bits;
  16951. bits += 8;
  16952. }
  16953. //===//
  16954. state.flags = hold;
  16955. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16956. strm.msg = 'unknown compression method';
  16957. state.mode = BAD;
  16958. break;
  16959. }
  16960. if (state.flags & 0xe000) {
  16961. strm.msg = 'unknown header flags set';
  16962. state.mode = BAD;
  16963. break;
  16964. }
  16965. if (state.head) {
  16966. state.head.text = ((hold >> 8) & 1);
  16967. }
  16968. if (state.flags & 0x0200) {
  16969. //=== CRC2(state.check, hold);
  16970. hbuf[0] = hold & 0xff;
  16971. hbuf[1] = (hold >>> 8) & 0xff;
  16972. state.check = crc32(state.check, hbuf, 2, 0);
  16973. //===//
  16974. }
  16975. //=== INITBITS();
  16976. hold = 0;
  16977. bits = 0;
  16978. //===//
  16979. state.mode = TIME;
  16980. /* falls through */
  16981. case TIME:
  16982. //=== NEEDBITS(32); */
  16983. while (bits < 32) {
  16984. if (have === 0) { break inf_leave; }
  16985. have--;
  16986. hold += input[next++] << bits;
  16987. bits += 8;
  16988. }
  16989. //===//
  16990. if (state.head) {
  16991. state.head.time = hold;
  16992. }
  16993. if (state.flags & 0x0200) {
  16994. //=== CRC4(state.check, hold)
  16995. hbuf[0] = hold & 0xff;
  16996. hbuf[1] = (hold >>> 8) & 0xff;
  16997. hbuf[2] = (hold >>> 16) & 0xff;
  16998. hbuf[3] = (hold >>> 24) & 0xff;
  16999. state.check = crc32(state.check, hbuf, 4, 0);
  17000. //===
  17001. }
  17002. //=== INITBITS();
  17003. hold = 0;
  17004. bits = 0;
  17005. //===//
  17006. state.mode = OS;
  17007. /* falls through */
  17008. case OS:
  17009. //=== NEEDBITS(16); */
  17010. while (bits < 16) {
  17011. if (have === 0) { break inf_leave; }
  17012. have--;
  17013. hold += input[next++] << bits;
  17014. bits += 8;
  17015. }
  17016. //===//
  17017. if (state.head) {
  17018. state.head.xflags = (hold & 0xff);
  17019. state.head.os = (hold >> 8);
  17020. }
  17021. if (state.flags & 0x0200) {
  17022. //=== CRC2(state.check, hold);
  17023. hbuf[0] = hold & 0xff;
  17024. hbuf[1] = (hold >>> 8) & 0xff;
  17025. state.check = crc32(state.check, hbuf, 2, 0);
  17026. //===//
  17027. }
  17028. //=== INITBITS();
  17029. hold = 0;
  17030. bits = 0;
  17031. //===//
  17032. state.mode = EXLEN;
  17033. /* falls through */
  17034. case EXLEN:
  17035. if (state.flags & 0x0400) {
  17036. //=== NEEDBITS(16); */
  17037. while (bits < 16) {
  17038. if (have === 0) { break inf_leave; }
  17039. have--;
  17040. hold += input[next++] << bits;
  17041. bits += 8;
  17042. }
  17043. //===//
  17044. state.length = hold;
  17045. if (state.head) {
  17046. state.head.extra_len = hold;
  17047. }
  17048. if (state.flags & 0x0200) {
  17049. //=== CRC2(state.check, hold);
  17050. hbuf[0] = hold & 0xff;
  17051. hbuf[1] = (hold >>> 8) & 0xff;
  17052. state.check = crc32(state.check, hbuf, 2, 0);
  17053. //===//
  17054. }
  17055. //=== INITBITS();
  17056. hold = 0;
  17057. bits = 0;
  17058. //===//
  17059. }
  17060. else if (state.head) {
  17061. state.head.extra = null/*Z_NULL*/;
  17062. }
  17063. state.mode = EXTRA;
  17064. /* falls through */
  17065. case EXTRA:
  17066. if (state.flags & 0x0400) {
  17067. copy = state.length;
  17068. if (copy > have) { copy = have; }
  17069. if (copy) {
  17070. if (state.head) {
  17071. len = state.head.extra_len - state.length;
  17072. if (!state.head.extra) {
  17073. // Use untyped array for more conveniend processing later
  17074. state.head.extra = new Array(state.head.extra_len);
  17075. }
  17076. utils.arraySet(
  17077. state.head.extra,
  17078. input,
  17079. next,
  17080. // extra field is limited to 65536 bytes
  17081. // - no need for additional size check
  17082. copy,
  17083. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17084. len
  17085. );
  17086. //zmemcpy(state.head.extra + len, next,
  17087. // len + copy > state.head.extra_max ?
  17088. // state.head.extra_max - len : copy);
  17089. }
  17090. if (state.flags & 0x0200) {
  17091. state.check = crc32(state.check, input, copy, next);
  17092. }
  17093. have -= copy;
  17094. next += copy;
  17095. state.length -= copy;
  17096. }
  17097. if (state.length) { break inf_leave; }
  17098. }
  17099. state.length = 0;
  17100. state.mode = NAME;
  17101. /* falls through */
  17102. case NAME:
  17103. if (state.flags & 0x0800) {
  17104. if (have === 0) { break inf_leave; }
  17105. copy = 0;
  17106. do {
  17107. // TODO: 2 or 1 bytes?
  17108. len = input[next + copy++];
  17109. /* use constant limit because in js we should not preallocate memory */
  17110. if (state.head && len &&
  17111. (state.length < 65536 /*state.head.name_max*/)) {
  17112. state.head.name += String.fromCharCode(len);
  17113. }
  17114. } while (len && copy < have);
  17115. if (state.flags & 0x0200) {
  17116. state.check = crc32(state.check, input, copy, next);
  17117. }
  17118. have -= copy;
  17119. next += copy;
  17120. if (len) { break inf_leave; }
  17121. }
  17122. else if (state.head) {
  17123. state.head.name = null;
  17124. }
  17125. state.length = 0;
  17126. state.mode = COMMENT;
  17127. /* falls through */
  17128. case COMMENT:
  17129. if (state.flags & 0x1000) {
  17130. if (have === 0) { break inf_leave; }
  17131. copy = 0;
  17132. do {
  17133. len = input[next + copy++];
  17134. /* use constant limit because in js we should not preallocate memory */
  17135. if (state.head && len &&
  17136. (state.length < 65536 /*state.head.comm_max*/)) {
  17137. state.head.comment += String.fromCharCode(len);
  17138. }
  17139. } while (len && copy < have);
  17140. if (state.flags & 0x0200) {
  17141. state.check = crc32(state.check, input, copy, next);
  17142. }
  17143. have -= copy;
  17144. next += copy;
  17145. if (len) { break inf_leave; }
  17146. }
  17147. else if (state.head) {
  17148. state.head.comment = null;
  17149. }
  17150. state.mode = HCRC;
  17151. /* falls through */
  17152. case HCRC:
  17153. if (state.flags & 0x0200) {
  17154. //=== NEEDBITS(16); */
  17155. while (bits < 16) {
  17156. if (have === 0) { break inf_leave; }
  17157. have--;
  17158. hold += input[next++] << bits;
  17159. bits += 8;
  17160. }
  17161. //===//
  17162. if (hold !== (state.check & 0xffff)) {
  17163. strm.msg = 'header crc mismatch';
  17164. state.mode = BAD;
  17165. break;
  17166. }
  17167. //=== INITBITS();
  17168. hold = 0;
  17169. bits = 0;
  17170. //===//
  17171. }
  17172. if (state.head) {
  17173. state.head.hcrc = ((state.flags >> 9) & 1);
  17174. state.head.done = true;
  17175. }
  17176. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  17177. state.mode = TYPE;
  17178. break;
  17179. case DICTID:
  17180. //=== NEEDBITS(32); */
  17181. while (bits < 32) {
  17182. if (have === 0) { break inf_leave; }
  17183. have--;
  17184. hold += input[next++] << bits;
  17185. bits += 8;
  17186. }
  17187. //===//
  17188. strm.adler = state.check = ZSWAP32(hold);
  17189. //=== INITBITS();
  17190. hold = 0;
  17191. bits = 0;
  17192. //===//
  17193. state.mode = DICT;
  17194. /* falls through */
  17195. case DICT:
  17196. if (state.havedict === 0) {
  17197. //--- RESTORE() ---
  17198. strm.next_out = put;
  17199. strm.avail_out = left;
  17200. strm.next_in = next;
  17201. strm.avail_in = have;
  17202. state.hold = hold;
  17203. state.bits = bits;
  17204. //---
  17205. return Z_NEED_DICT;
  17206. }
  17207. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17208. state.mode = TYPE;
  17209. /* falls through */
  17210. case TYPE:
  17211. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  17212. /* falls through */
  17213. case TYPEDO:
  17214. if (state.last) {
  17215. //--- BYTEBITS() ---//
  17216. hold >>>= bits & 7;
  17217. bits -= bits & 7;
  17218. //---//
  17219. state.mode = CHECK;
  17220. break;
  17221. }
  17222. //=== NEEDBITS(3); */
  17223. while (bits < 3) {
  17224. if (have === 0) { break inf_leave; }
  17225. have--;
  17226. hold += input[next++] << bits;
  17227. bits += 8;
  17228. }
  17229. //===//
  17230. state.last = (hold & 0x01)/*BITS(1)*/;
  17231. //--- DROPBITS(1) ---//
  17232. hold >>>= 1;
  17233. bits -= 1;
  17234. //---//
  17235. switch ((hold & 0x03)/*BITS(2)*/) {
  17236. case 0: /* stored block */
  17237. //Tracev((stderr, "inflate: stored block%s\n",
  17238. // state.last ? " (last)" : ""));
  17239. state.mode = STORED;
  17240. break;
  17241. case 1: /* fixed block */
  17242. fixedtables(state);
  17243. //Tracev((stderr, "inflate: fixed codes block%s\n",
  17244. // state.last ? " (last)" : ""));
  17245. state.mode = LEN_; /* decode codes */
  17246. if (flush === Z_TREES) {
  17247. //--- DROPBITS(2) ---//
  17248. hold >>>= 2;
  17249. bits -= 2;
  17250. //---//
  17251. break inf_leave;
  17252. }
  17253. break;
  17254. case 2: /* dynamic block */
  17255. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  17256. // state.last ? " (last)" : ""));
  17257. state.mode = TABLE;
  17258. break;
  17259. case 3:
  17260. strm.msg = 'invalid block type';
  17261. state.mode = BAD;
  17262. }
  17263. //--- DROPBITS(2) ---//
  17264. hold >>>= 2;
  17265. bits -= 2;
  17266. //---//
  17267. break;
  17268. case STORED:
  17269. //--- BYTEBITS() ---// /* go to byte boundary */
  17270. hold >>>= bits & 7;
  17271. bits -= bits & 7;
  17272. //---//
  17273. //=== NEEDBITS(32); */
  17274. while (bits < 32) {
  17275. if (have === 0) { break inf_leave; }
  17276. have--;
  17277. hold += input[next++] << bits;
  17278. bits += 8;
  17279. }
  17280. //===//
  17281. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  17282. strm.msg = 'invalid stored block lengths';
  17283. state.mode = BAD;
  17284. break;
  17285. }
  17286. state.length = hold & 0xffff;
  17287. //Tracev((stderr, "inflate: stored length %u\n",
  17288. // state.length));
  17289. //=== INITBITS();
  17290. hold = 0;
  17291. bits = 0;
  17292. //===//
  17293. state.mode = COPY_;
  17294. if (flush === Z_TREES) { break inf_leave; }
  17295. /* falls through */
  17296. case COPY_:
  17297. state.mode = COPY;
  17298. /* falls through */
  17299. case COPY:
  17300. copy = state.length;
  17301. if (copy) {
  17302. if (copy > have) { copy = have; }
  17303. if (copy > left) { copy = left; }
  17304. if (copy === 0) { break inf_leave; }
  17305. //--- zmemcpy(put, next, copy); ---
  17306. utils.arraySet(output, input, next, copy, put);
  17307. //---//
  17308. have -= copy;
  17309. next += copy;
  17310. left -= copy;
  17311. put += copy;
  17312. state.length -= copy;
  17313. break;
  17314. }
  17315. //Tracev((stderr, "inflate: stored end\n"));
  17316. state.mode = TYPE;
  17317. break;
  17318. case TABLE:
  17319. //=== NEEDBITS(14); */
  17320. while (bits < 14) {
  17321. if (have === 0) { break inf_leave; }
  17322. have--;
  17323. hold += input[next++] << bits;
  17324. bits += 8;
  17325. }
  17326. //===//
  17327. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  17328. //--- DROPBITS(5) ---//
  17329. hold >>>= 5;
  17330. bits -= 5;
  17331. //---//
  17332. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  17333. //--- DROPBITS(5) ---//
  17334. hold >>>= 5;
  17335. bits -= 5;
  17336. //---//
  17337. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  17338. //--- DROPBITS(4) ---//
  17339. hold >>>= 4;
  17340. bits -= 4;
  17341. //---//
  17342. //#ifndef PKZIP_BUG_WORKAROUND
  17343. if (state.nlen > 286 || state.ndist > 30) {
  17344. strm.msg = 'too many length or distance symbols';
  17345. state.mode = BAD;
  17346. break;
  17347. }
  17348. //#endif
  17349. //Tracev((stderr, "inflate: table sizes ok\n"));
  17350. state.have = 0;
  17351. state.mode = LENLENS;
  17352. /* falls through */
  17353. case LENLENS:
  17354. while (state.have < state.ncode) {
  17355. //=== NEEDBITS(3);
  17356. while (bits < 3) {
  17357. if (have === 0) { break inf_leave; }
  17358. have--;
  17359. hold += input[next++] << bits;
  17360. bits += 8;
  17361. }
  17362. //===//
  17363. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  17364. //--- DROPBITS(3) ---//
  17365. hold >>>= 3;
  17366. bits -= 3;
  17367. //---//
  17368. }
  17369. while (state.have < 19) {
  17370. state.lens[order[state.have++]] = 0;
  17371. }
  17372. // We have separate tables & no pointers. 2 commented lines below not needed.
  17373. //state.next = state.codes;
  17374. //state.lencode = state.next;
  17375. // Switch to use dynamic table
  17376. state.lencode = state.lendyn;
  17377. state.lenbits = 7;
  17378. opts = {bits: state.lenbits};
  17379. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  17380. state.lenbits = opts.bits;
  17381. if (ret) {
  17382. strm.msg = 'invalid code lengths set';
  17383. state.mode = BAD;
  17384. break;
  17385. }
  17386. //Tracev((stderr, "inflate: code lengths ok\n"));
  17387. state.have = 0;
  17388. state.mode = CODELENS;
  17389. /* falls through */
  17390. case CODELENS:
  17391. while (state.have < state.nlen + state.ndist) {
  17392. for (;;) {
  17393. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  17394. here_bits = here >>> 24;
  17395. here_op = (here >>> 16) & 0xff;
  17396. here_val = here & 0xffff;
  17397. if ((here_bits) <= bits) { break; }
  17398. //--- PULLBYTE() ---//
  17399. if (have === 0) { break inf_leave; }
  17400. have--;
  17401. hold += input[next++] << bits;
  17402. bits += 8;
  17403. //---//
  17404. }
  17405. if (here_val < 16) {
  17406. //--- DROPBITS(here.bits) ---//
  17407. hold >>>= here_bits;
  17408. bits -= here_bits;
  17409. //---//
  17410. state.lens[state.have++] = here_val;
  17411. }
  17412. else {
  17413. if (here_val === 16) {
  17414. //=== NEEDBITS(here.bits + 2);
  17415. n = here_bits + 2;
  17416. while (bits < n) {
  17417. if (have === 0) { break inf_leave; }
  17418. have--;
  17419. hold += input[next++] << bits;
  17420. bits += 8;
  17421. }
  17422. //===//
  17423. //--- DROPBITS(here.bits) ---//
  17424. hold >>>= here_bits;
  17425. bits -= here_bits;
  17426. //---//
  17427. if (state.have === 0) {
  17428. strm.msg = 'invalid bit length repeat';
  17429. state.mode = BAD;
  17430. break;
  17431. }
  17432. len = state.lens[state.have - 1];
  17433. copy = 3 + (hold & 0x03);//BITS(2);
  17434. //--- DROPBITS(2) ---//
  17435. hold >>>= 2;
  17436. bits -= 2;
  17437. //---//
  17438. }
  17439. else if (here_val === 17) {
  17440. //=== NEEDBITS(here.bits + 3);
  17441. n = here_bits + 3;
  17442. while (bits < n) {
  17443. if (have === 0) { break inf_leave; }
  17444. have--;
  17445. hold += input[next++] << bits;
  17446. bits += 8;
  17447. }
  17448. //===//
  17449. //--- DROPBITS(here.bits) ---//
  17450. hold >>>= here_bits;
  17451. bits -= here_bits;
  17452. //---//
  17453. len = 0;
  17454. copy = 3 + (hold & 0x07);//BITS(3);
  17455. //--- DROPBITS(3) ---//
  17456. hold >>>= 3;
  17457. bits -= 3;
  17458. //---//
  17459. }
  17460. else {
  17461. //=== NEEDBITS(here.bits + 7);
  17462. n = here_bits + 7;
  17463. while (bits < n) {
  17464. if (have === 0) { break inf_leave; }
  17465. have--;
  17466. hold += input[next++] << bits;
  17467. bits += 8;
  17468. }
  17469. //===//
  17470. //--- DROPBITS(here.bits) ---//
  17471. hold >>>= here_bits;
  17472. bits -= here_bits;
  17473. //---//
  17474. len = 0;
  17475. copy = 11 + (hold & 0x7f);//BITS(7);
  17476. //--- DROPBITS(7) ---//
  17477. hold >>>= 7;
  17478. bits -= 7;
  17479. //---//
  17480. }
  17481. if (state.have + copy > state.nlen + state.ndist) {
  17482. strm.msg = 'invalid bit length repeat';
  17483. state.mode = BAD;
  17484. break;
  17485. }
  17486. while (copy--) {
  17487. state.lens[state.have++] = len;
  17488. }
  17489. }
  17490. }
  17491. /* handle error breaks in while */
  17492. if (state.mode === BAD) { break; }
  17493. /* check for end-of-block code (better have one) */
  17494. if (state.lens[256] === 0) {
  17495. strm.msg = 'invalid code -- missing end-of-block';
  17496. state.mode = BAD;
  17497. break;
  17498. }
  17499. /* build code tables -- note: do not change the lenbits or distbits
  17500. values here (9 and 6) without reading the comments in inftrees.h
  17501. concerning the ENOUGH constants, which depend on those values */
  17502. state.lenbits = 9;
  17503. opts = {bits: state.lenbits};
  17504. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  17505. // We have separate tables & no pointers. 2 commented lines below not needed.
  17506. // state.next_index = opts.table_index;
  17507. state.lenbits = opts.bits;
  17508. // state.lencode = state.next;
  17509. if (ret) {
  17510. strm.msg = 'invalid literal/lengths set';
  17511. state.mode = BAD;
  17512. break;
  17513. }
  17514. state.distbits = 6;
  17515. //state.distcode.copy(state.codes);
  17516. // Switch to use dynamic table
  17517. state.distcode = state.distdyn;
  17518. opts = {bits: state.distbits};
  17519. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  17520. // We have separate tables & no pointers. 2 commented lines below not needed.
  17521. // state.next_index = opts.table_index;
  17522. state.distbits = opts.bits;
  17523. // state.distcode = state.next;
  17524. if (ret) {
  17525. strm.msg = 'invalid distances set';
  17526. state.mode = BAD;
  17527. break;
  17528. }
  17529. //Tracev((stderr, 'inflate: codes ok\n'));
  17530. state.mode = LEN_;
  17531. if (flush === Z_TREES) { break inf_leave; }
  17532. /* falls through */
  17533. case LEN_:
  17534. state.mode = LEN;
  17535. /* falls through */
  17536. case LEN:
  17537. if (have >= 6 && left >= 258) {
  17538. //--- RESTORE() ---
  17539. strm.next_out = put;
  17540. strm.avail_out = left;
  17541. strm.next_in = next;
  17542. strm.avail_in = have;
  17543. state.hold = hold;
  17544. state.bits = bits;
  17545. //---
  17546. inflate_fast(strm, _out);
  17547. //--- LOAD() ---
  17548. put = strm.next_out;
  17549. output = strm.output;
  17550. left = strm.avail_out;
  17551. next = strm.next_in;
  17552. input = strm.input;
  17553. have = strm.avail_in;
  17554. hold = state.hold;
  17555. bits = state.bits;
  17556. //---
  17557. if (state.mode === TYPE) {
  17558. state.back = -1;
  17559. }
  17560. break;
  17561. }
  17562. state.back = 0;
  17563. for (;;) {
  17564. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  17565. here_bits = here >>> 24;
  17566. here_op = (here >>> 16) & 0xff;
  17567. here_val = here & 0xffff;
  17568. if (here_bits <= bits) { break; }
  17569. //--- PULLBYTE() ---//
  17570. if (have === 0) { break inf_leave; }
  17571. have--;
  17572. hold += input[next++] << bits;
  17573. bits += 8;
  17574. //---//
  17575. }
  17576. if (here_op && (here_op & 0xf0) === 0) {
  17577. last_bits = here_bits;
  17578. last_op = here_op;
  17579. last_val = here_val;
  17580. for (;;) {
  17581. here = state.lencode[last_val +
  17582. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17583. here_bits = here >>> 24;
  17584. here_op = (here >>> 16) & 0xff;
  17585. here_val = here & 0xffff;
  17586. if ((last_bits + here_bits) <= bits) { break; }
  17587. //--- PULLBYTE() ---//
  17588. if (have === 0) { break inf_leave; }
  17589. have--;
  17590. hold += input[next++] << bits;
  17591. bits += 8;
  17592. //---//
  17593. }
  17594. //--- DROPBITS(last.bits) ---//
  17595. hold >>>= last_bits;
  17596. bits -= last_bits;
  17597. //---//
  17598. state.back += last_bits;
  17599. }
  17600. //--- DROPBITS(here.bits) ---//
  17601. hold >>>= here_bits;
  17602. bits -= here_bits;
  17603. //---//
  17604. state.back += here_bits;
  17605. state.length = here_val;
  17606. if (here_op === 0) {
  17607. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17608. // "inflate: literal '%c'\n" :
  17609. // "inflate: literal 0x%02x\n", here.val));
  17610. state.mode = LIT;
  17611. break;
  17612. }
  17613. if (here_op & 32) {
  17614. //Tracevv((stderr, "inflate: end of block\n"));
  17615. state.back = -1;
  17616. state.mode = TYPE;
  17617. break;
  17618. }
  17619. if (here_op & 64) {
  17620. strm.msg = 'invalid literal/length code';
  17621. state.mode = BAD;
  17622. break;
  17623. }
  17624. state.extra = here_op & 15;
  17625. state.mode = LENEXT;
  17626. /* falls through */
  17627. case LENEXT:
  17628. if (state.extra) {
  17629. //=== NEEDBITS(state.extra);
  17630. n = state.extra;
  17631. while (bits < n) {
  17632. if (have === 0) { break inf_leave; }
  17633. have--;
  17634. hold += input[next++] << bits;
  17635. bits += 8;
  17636. }
  17637. //===//
  17638. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17639. //--- DROPBITS(state.extra) ---//
  17640. hold >>>= state.extra;
  17641. bits -= state.extra;
  17642. //---//
  17643. state.back += state.extra;
  17644. }
  17645. //Tracevv((stderr, "inflate: length %u\n", state.length));
  17646. state.was = state.length;
  17647. state.mode = DIST;
  17648. /* falls through */
  17649. case DIST:
  17650. for (;;) {
  17651. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  17652. here_bits = here >>> 24;
  17653. here_op = (here >>> 16) & 0xff;
  17654. here_val = here & 0xffff;
  17655. if ((here_bits) <= bits) { break; }
  17656. //--- PULLBYTE() ---//
  17657. if (have === 0) { break inf_leave; }
  17658. have--;
  17659. hold += input[next++] << bits;
  17660. bits += 8;
  17661. //---//
  17662. }
  17663. if ((here_op & 0xf0) === 0) {
  17664. last_bits = here_bits;
  17665. last_op = here_op;
  17666. last_val = here_val;
  17667. for (;;) {
  17668. here = state.distcode[last_val +
  17669. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17670. here_bits = here >>> 24;
  17671. here_op = (here >>> 16) & 0xff;
  17672. here_val = here & 0xffff;
  17673. if ((last_bits + here_bits) <= bits) { break; }
  17674. //--- PULLBYTE() ---//
  17675. if (have === 0) { break inf_leave; }
  17676. have--;
  17677. hold += input[next++] << bits;
  17678. bits += 8;
  17679. //---//
  17680. }
  17681. //--- DROPBITS(last.bits) ---//
  17682. hold >>>= last_bits;
  17683. bits -= last_bits;
  17684. //---//
  17685. state.back += last_bits;
  17686. }
  17687. //--- DROPBITS(here.bits) ---//
  17688. hold >>>= here_bits;
  17689. bits -= here_bits;
  17690. //---//
  17691. state.back += here_bits;
  17692. if (here_op & 64) {
  17693. strm.msg = 'invalid distance code';
  17694. state.mode = BAD;
  17695. break;
  17696. }
  17697. state.offset = here_val;
  17698. state.extra = (here_op) & 15;
  17699. state.mode = DISTEXT;
  17700. /* falls through */
  17701. case DISTEXT:
  17702. if (state.extra) {
  17703. //=== NEEDBITS(state.extra);
  17704. n = state.extra;
  17705. while (bits < n) {
  17706. if (have === 0) { break inf_leave; }
  17707. have--;
  17708. hold += input[next++] << bits;
  17709. bits += 8;
  17710. }
  17711. //===//
  17712. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17713. //--- DROPBITS(state.extra) ---//
  17714. hold >>>= state.extra;
  17715. bits -= state.extra;
  17716. //---//
  17717. state.back += state.extra;
  17718. }
  17719. //#ifdef INFLATE_STRICT
  17720. if (state.offset > state.dmax) {
  17721. strm.msg = 'invalid distance too far back';
  17722. state.mode = BAD;
  17723. break;
  17724. }
  17725. //#endif
  17726. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  17727. state.mode = MATCH;
  17728. /* falls through */
  17729. case MATCH:
  17730. if (left === 0) { break inf_leave; }
  17731. copy = _out - left;
  17732. if (state.offset > copy) { /* copy from window */
  17733. copy = state.offset - copy;
  17734. if (copy > state.whave) {
  17735. if (state.sane) {
  17736. strm.msg = 'invalid distance too far back';
  17737. state.mode = BAD;
  17738. break;
  17739. }
  17740. // (!) This block is disabled in zlib defailts,
  17741. // don't enable it for binary compatibility
  17742. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17743. // Trace((stderr, "inflate.c too far\n"));
  17744. // copy -= state.whave;
  17745. // if (copy > state.length) { copy = state.length; }
  17746. // if (copy > left) { copy = left; }
  17747. // left -= copy;
  17748. // state.length -= copy;
  17749. // do {
  17750. // output[put++] = 0;
  17751. // } while (--copy);
  17752. // if (state.length === 0) { state.mode = LEN; }
  17753. // break;
  17754. //#endif
  17755. }
  17756. if (copy > state.wnext) {
  17757. copy -= state.wnext;
  17758. from = state.wsize - copy;
  17759. }
  17760. else {
  17761. from = state.wnext - copy;
  17762. }
  17763. if (copy > state.length) { copy = state.length; }
  17764. from_source = state.window;
  17765. }
  17766. else { /* copy from output */
  17767. from_source = output;
  17768. from = put - state.offset;
  17769. copy = state.length;
  17770. }
  17771. if (copy > left) { copy = left; }
  17772. left -= copy;
  17773. state.length -= copy;
  17774. do {
  17775. output[put++] = from_source[from++];
  17776. } while (--copy);
  17777. if (state.length === 0) { state.mode = LEN; }
  17778. break;
  17779. case LIT:
  17780. if (left === 0) { break inf_leave; }
  17781. output[put++] = state.length;
  17782. left--;
  17783. state.mode = LEN;
  17784. break;
  17785. case CHECK:
  17786. if (state.wrap) {
  17787. //=== NEEDBITS(32);
  17788. while (bits < 32) {
  17789. if (have === 0) { break inf_leave; }
  17790. have--;
  17791. // Use '|' insdead of '+' to make sure that result is signed
  17792. hold |= input[next++] << bits;
  17793. bits += 8;
  17794. }
  17795. //===//
  17796. _out -= left;
  17797. strm.total_out += _out;
  17798. state.total += _out;
  17799. if (_out) {
  17800. strm.adler = state.check =
  17801. /*UPDATE(state.check, put - _out, _out);*/
  17802. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17803. }
  17804. _out = left;
  17805. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  17806. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  17807. strm.msg = 'incorrect data check';
  17808. state.mode = BAD;
  17809. break;
  17810. }
  17811. //=== INITBITS();
  17812. hold = 0;
  17813. bits = 0;
  17814. //===//
  17815. //Tracev((stderr, "inflate: check matches trailer\n"));
  17816. }
  17817. state.mode = LENGTH;
  17818. /* falls through */
  17819. case LENGTH:
  17820. if (state.wrap && state.flags) {
  17821. //=== NEEDBITS(32);
  17822. while (bits < 32) {
  17823. if (have === 0) { break inf_leave; }
  17824. have--;
  17825. hold += input[next++] << bits;
  17826. bits += 8;
  17827. }
  17828. //===//
  17829. if (hold !== (state.total & 0xffffffff)) {
  17830. strm.msg = 'incorrect length check';
  17831. state.mode = BAD;
  17832. break;
  17833. }
  17834. //=== INITBITS();
  17835. hold = 0;
  17836. bits = 0;
  17837. //===//
  17838. //Tracev((stderr, "inflate: length matches trailer\n"));
  17839. }
  17840. state.mode = DONE;
  17841. /* falls through */
  17842. case DONE:
  17843. ret = Z_STREAM_END;
  17844. break inf_leave;
  17845. case BAD:
  17846. ret = Z_DATA_ERROR;
  17847. break inf_leave;
  17848. case MEM:
  17849. return Z_MEM_ERROR;
  17850. case SYNC:
  17851. /* falls through */
  17852. default:
  17853. return Z_STREAM_ERROR;
  17854. }
  17855. }
  17856. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17857. /*
  17858. Return from inflate(), updating the total counts and the check value.
  17859. If there was no progress during the inflate() call, return a buffer
  17860. error. Call updatewindow() to create and/or update the window state.
  17861. Note: a memory error from inflate() is non-recoverable.
  17862. */
  17863. //--- RESTORE() ---
  17864. strm.next_out = put;
  17865. strm.avail_out = left;
  17866. strm.next_in = next;
  17867. strm.avail_in = have;
  17868. state.hold = hold;
  17869. state.bits = bits;
  17870. //---
  17871. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17872. (state.mode < CHECK || flush !== Z_FINISH))) {
  17873. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17874. state.mode = MEM;
  17875. return Z_MEM_ERROR;
  17876. }
  17877. }
  17878. _in -= strm.avail_in;
  17879. _out -= strm.avail_out;
  17880. strm.total_in += _in;
  17881. strm.total_out += _out;
  17882. state.total += _out;
  17883. if (state.wrap && _out) {
  17884. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17885. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17886. }
  17887. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17888. (state.mode === TYPE ? 128 : 0) +
  17889. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17890. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17891. ret = Z_BUF_ERROR;
  17892. }
  17893. return ret;
  17894. }
  17895. function inflateEnd(strm) {
  17896. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17897. return Z_STREAM_ERROR;
  17898. }
  17899. var state = strm.state;
  17900. if (state.window) {
  17901. state.window = null;
  17902. }
  17903. strm.state = null;
  17904. return Z_OK;
  17905. }
  17906. function inflateGetHeader(strm, head) {
  17907. var state;
  17908. /* check state */
  17909. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17910. state = strm.state;
  17911. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17912. /* save header structure */
  17913. state.head = head;
  17914. head.done = false;
  17915. return Z_OK;
  17916. }
  17917. exports.inflateReset = inflateReset;
  17918. exports.inflateReset2 = inflateReset2;
  17919. exports.inflateResetKeep = inflateResetKeep;
  17920. exports.inflateInit = inflateInit;
  17921. exports.inflateInit2 = inflateInit2;
  17922. exports.inflate = inflate;
  17923. exports.inflateEnd = inflateEnd;
  17924. exports.inflateGetHeader = inflateGetHeader;
  17925. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17926. /* Not implemented
  17927. exports.inflateCopy = inflateCopy;
  17928. exports.inflateGetDictionary = inflateGetDictionary;
  17929. exports.inflateMark = inflateMark;
  17930. exports.inflatePrime = inflatePrime;
  17931. exports.inflateSetDictionary = inflateSetDictionary;
  17932. exports.inflateSync = inflateSync;
  17933. exports.inflateSyncPoint = inflateSyncPoint;
  17934. exports.inflateUndermine = inflateUndermine;
  17935. */
  17936. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./inffast":59,"./inftrees":61}],61:[function(require,module,exports){
  17937. 'use strict';
  17938. var utils = require('../utils/common');
  17939. var MAXBITS = 15;
  17940. var ENOUGH_LENS = 852;
  17941. var ENOUGH_DISTS = 592;
  17942. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17943. var CODES = 0;
  17944. var LENS = 1;
  17945. var DISTS = 2;
  17946. var lbase = [ /* Length codes 257..285 base */
  17947. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17948. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17949. ];
  17950. var lext = [ /* Length codes 257..285 extra */
  17951. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17952. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17953. ];
  17954. var dbase = [ /* Distance codes 0..29 base */
  17955. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17956. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17957. 8193, 12289, 16385, 24577, 0, 0
  17958. ];
  17959. var dext = [ /* Distance codes 0..29 extra */
  17960. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17961. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17962. 28, 28, 29, 29, 64, 64
  17963. ];
  17964. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17965. {
  17966. var bits = opts.bits;
  17967. //here = opts.here; /* table entry for duplication */
  17968. var len = 0; /* a code's length in bits */
  17969. var sym = 0; /* index of code symbols */
  17970. var min = 0, max = 0; /* minimum and maximum code lengths */
  17971. var root = 0; /* number of index bits for root table */
  17972. var curr = 0; /* number of index bits for current table */
  17973. var drop = 0; /* code bits to drop for sub-table */
  17974. var left = 0; /* number of prefix codes available */
  17975. var used = 0; /* code entries in table used */
  17976. var huff = 0; /* Huffman code */
  17977. var incr; /* for incrementing code, index */
  17978. var fill; /* index for replicating entries */
  17979. var low; /* low bits for current root entry */
  17980. var mask; /* mask for low root bits */
  17981. var next; /* next available space in table */
  17982. var base = null; /* base value table to use */
  17983. var base_index = 0;
  17984. // var shoextra; /* extra bits table to use */
  17985. var end; /* use base and extra for symbol > end */
  17986. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17987. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17988. var extra = null;
  17989. var extra_index = 0;
  17990. var here_bits, here_op, here_val;
  17991. /*
  17992. Process a set of code lengths to create a canonical Huffman code. The
  17993. code lengths are lens[0..codes-1]. Each length corresponds to the
  17994. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17995. symbols by length from short to long, and retaining the symbol order
  17996. for codes with equal lengths. Then the code starts with all zero bits
  17997. for the first code of the shortest length, and the codes are integer
  17998. increments for the same length, and zeros are appended as the length
  17999. increases. For the deflate format, these bits are stored backwards
  18000. from their more natural integer increment ordering, and so when the
  18001. decoding tables are built in the large loop below, the integer codes
  18002. are incremented backwards.
  18003. This routine assumes, but does not check, that all of the entries in
  18004. lens[] are in the range 0..MAXBITS. The caller must assure this.
  18005. 1..MAXBITS is interpreted as that code length. zero means that that
  18006. symbol does not occur in this code.
  18007. The codes are sorted by computing a count of codes for each length,
  18008. creating from that a table of starting indices for each length in the
  18009. sorted table, and then entering the symbols in order in the sorted
  18010. table. The sorted table is work[], with that space being provided by
  18011. the caller.
  18012. The length counts are used for other purposes as well, i.e. finding
  18013. the minimum and maximum length codes, determining if there are any
  18014. codes at all, checking for a valid set of lengths, and looking ahead
  18015. at length counts to determine sub-table sizes when building the
  18016. decoding tables.
  18017. */
  18018. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  18019. for (len = 0; len <= MAXBITS; len++) {
  18020. count[len] = 0;
  18021. }
  18022. for (sym = 0; sym < codes; sym++) {
  18023. count[lens[lens_index + sym]]++;
  18024. }
  18025. /* bound code lengths, force root to be within code lengths */
  18026. root = bits;
  18027. for (max = MAXBITS; max >= 1; max--) {
  18028. if (count[max] !== 0) { break; }
  18029. }
  18030. if (root > max) {
  18031. root = max;
  18032. }
  18033. if (max === 0) { /* no symbols to code at all */
  18034. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  18035. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  18036. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  18037. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18038. //table.op[opts.table_index] = 64;
  18039. //table.bits[opts.table_index] = 1;
  18040. //table.val[opts.table_index++] = 0;
  18041. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18042. opts.bits = 1;
  18043. return 0; /* no symbols, but wait for decoding to report error */
  18044. }
  18045. for (min = 1; min < max; min++) {
  18046. if (count[min] !== 0) { break; }
  18047. }
  18048. if (root < min) {
  18049. root = min;
  18050. }
  18051. /* check for an over-subscribed or incomplete set of lengths */
  18052. left = 1;
  18053. for (len = 1; len <= MAXBITS; len++) {
  18054. left <<= 1;
  18055. left -= count[len];
  18056. if (left < 0) {
  18057. return -1;
  18058. } /* over-subscribed */
  18059. }
  18060. if (left > 0 && (type === CODES || max !== 1)) {
  18061. return -1; /* incomplete set */
  18062. }
  18063. /* generate offsets into symbol table for each length for sorting */
  18064. offs[1] = 0;
  18065. for (len = 1; len < MAXBITS; len++) {
  18066. offs[len + 1] = offs[len] + count[len];
  18067. }
  18068. /* sort symbols by length, by symbol order within each length */
  18069. for (sym = 0; sym < codes; sym++) {
  18070. if (lens[lens_index + sym] !== 0) {
  18071. work[offs[lens[lens_index + sym]]++] = sym;
  18072. }
  18073. }
  18074. /*
  18075. Create and fill in decoding tables. In this loop, the table being
  18076. filled is at next and has curr index bits. The code being used is huff
  18077. with length len. That code is converted to an index by dropping drop
  18078. bits off of the bottom. For codes where len is less than drop + curr,
  18079. those top drop + curr - len bits are incremented through all values to
  18080. fill the table with replicated entries.
  18081. root is the number of index bits for the root table. When len exceeds
  18082. root, sub-tables are created pointed to by the root entry with an index
  18083. of the low root bits of huff. This is saved in low to check for when a
  18084. new sub-table should be started. drop is zero when the root table is
  18085. being filled, and drop is root when sub-tables are being filled.
  18086. When a new sub-table is needed, it is necessary to look ahead in the
  18087. code lengths to determine what size sub-table is needed. The length
  18088. counts are used for this, and so count[] is decremented as codes are
  18089. entered in the tables.
  18090. used keeps track of how many table entries have been allocated from the
  18091. provided *table space. It is checked for LENS and DIST tables against
  18092. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  18093. the initial root table size constants. See the comments in inftrees.h
  18094. for more information.
  18095. sym increments through all symbols, and the loop terminates when
  18096. all codes of length max, i.e. all codes, have been processed. This
  18097. routine permits incomplete codes, so another loop after this one fills
  18098. in the rest of the decoding tables with invalid code markers.
  18099. */
  18100. /* set up for code type */
  18101. // poor man optimization - use if-else instead of switch,
  18102. // to avoid deopts in old v8
  18103. if (type === CODES) {
  18104. base = extra = work; /* dummy value--not used */
  18105. end = 19;
  18106. } else if (type === LENS) {
  18107. base = lbase;
  18108. base_index -= 257;
  18109. extra = lext;
  18110. extra_index -= 257;
  18111. end = 256;
  18112. } else { /* DISTS */
  18113. base = dbase;
  18114. extra = dext;
  18115. end = -1;
  18116. }
  18117. /* initialize opts for loop */
  18118. huff = 0; /* starting code */
  18119. sym = 0; /* starting code symbol */
  18120. len = min; /* starting code length */
  18121. next = table_index; /* current table to fill in */
  18122. curr = root; /* current table index bits */
  18123. drop = 0; /* current bits to drop from code for index */
  18124. low = -1; /* trigger new sub-table when len > root */
  18125. used = 1 << root; /* use root table entries */
  18126. mask = used - 1; /* mask for comparing low */
  18127. /* check available table space */
  18128. if ((type === LENS && used > ENOUGH_LENS) ||
  18129. (type === DISTS && used > ENOUGH_DISTS)) {
  18130. return 1;
  18131. }
  18132. var i=0;
  18133. /* process all codes and make table entries */
  18134. for (;;) {
  18135. i++;
  18136. /* create table entry */
  18137. here_bits = len - drop;
  18138. if (work[sym] < end) {
  18139. here_op = 0;
  18140. here_val = work[sym];
  18141. }
  18142. else if (work[sym] > end) {
  18143. here_op = extra[extra_index + work[sym]];
  18144. here_val = base[base_index + work[sym]];
  18145. }
  18146. else {
  18147. here_op = 32 + 64; /* end of block */
  18148. here_val = 0;
  18149. }
  18150. /* replicate for those indices with low len bits equal to huff */
  18151. incr = 1 << (len - drop);
  18152. fill = 1 << curr;
  18153. min = fill; /* save offset to next table */
  18154. do {
  18155. fill -= incr;
  18156. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  18157. } while (fill !== 0);
  18158. /* backwards increment the len-bit code huff */
  18159. incr = 1 << (len - 1);
  18160. while (huff & incr) {
  18161. incr >>= 1;
  18162. }
  18163. if (incr !== 0) {
  18164. huff &= incr - 1;
  18165. huff += incr;
  18166. } else {
  18167. huff = 0;
  18168. }
  18169. /* go to next symbol, update count, len */
  18170. sym++;
  18171. if (--count[len] === 0) {
  18172. if (len === max) { break; }
  18173. len = lens[lens_index + work[sym]];
  18174. }
  18175. /* create new sub-table if needed */
  18176. if (len > root && (huff & mask) !== low) {
  18177. /* if first time, transition to sub-tables */
  18178. if (drop === 0) {
  18179. drop = root;
  18180. }
  18181. /* increment past last table */
  18182. next += min; /* here min is 1 << curr */
  18183. /* determine length of next table */
  18184. curr = len - drop;
  18185. left = 1 << curr;
  18186. while (curr + drop < max) {
  18187. left -= count[curr + drop];
  18188. if (left <= 0) { break; }
  18189. curr++;
  18190. left <<= 1;
  18191. }
  18192. /* check for enough space */
  18193. used += 1 << curr;
  18194. if ((type === LENS && used > ENOUGH_LENS) ||
  18195. (type === DISTS && used > ENOUGH_DISTS)) {
  18196. return 1;
  18197. }
  18198. /* point entry in root table to sub-table */
  18199. low = huff & mask;
  18200. /*table.op[low] = curr;
  18201. table.bits[low] = root;
  18202. table.val[low] = next - opts.table_index;*/
  18203. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  18204. }
  18205. }
  18206. /* fill in remaining table entry if code is incomplete (guaranteed to have
  18207. at most one remaining entry, since if the code is incomplete, the
  18208. maximum code length that was allowed to get this far is one bit) */
  18209. if (huff !== 0) {
  18210. //table.op[next + huff] = 64; /* invalid code marker */
  18211. //table.bits[next + huff] = len - drop;
  18212. //table.val[next + huff] = 0;
  18213. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  18214. }
  18215. /* set return parameters */
  18216. //opts.table_index += used;
  18217. opts.bits = root;
  18218. return 0;
  18219. };
  18220. },{"../utils/common":52}],62:[function(require,module,exports){
  18221. 'use strict';
  18222. module.exports = {
  18223. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  18224. '1': 'stream end', /* Z_STREAM_END 1 */
  18225. '0': '', /* Z_OK 0 */
  18226. '-1': 'file error', /* Z_ERRNO (-1) */
  18227. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  18228. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  18229. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  18230. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  18231. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  18232. };
  18233. },{}],63:[function(require,module,exports){
  18234. 'use strict';
  18235. var utils = require('../utils/common');
  18236. /* Public constants ==========================================================*/
  18237. /* ===========================================================================*/
  18238. //var Z_FILTERED = 1;
  18239. //var Z_HUFFMAN_ONLY = 2;
  18240. //var Z_RLE = 3;
  18241. var Z_FIXED = 4;
  18242. //var Z_DEFAULT_STRATEGY = 0;
  18243. /* Possible values of the data_type field (though see inflate()) */
  18244. var Z_BINARY = 0;
  18245. var Z_TEXT = 1;
  18246. //var Z_ASCII = 1; // = Z_TEXT
  18247. var Z_UNKNOWN = 2;
  18248. /*============================================================================*/
  18249. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18250. // From zutil.h
  18251. var STORED_BLOCK = 0;
  18252. var STATIC_TREES = 1;
  18253. var DYN_TREES = 2;
  18254. /* The three kinds of block type */
  18255. var MIN_MATCH = 3;
  18256. var MAX_MATCH = 258;
  18257. /* The minimum and maximum match lengths */
  18258. // From deflate.h
  18259. /* ===========================================================================
  18260. * Internal compression state.
  18261. */
  18262. var LENGTH_CODES = 29;
  18263. /* number of length codes, not counting the special END_BLOCK code */
  18264. var LITERALS = 256;
  18265. /* number of literal bytes 0..255 */
  18266. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18267. /* number of Literal or Length codes, including the END_BLOCK code */
  18268. var D_CODES = 30;
  18269. /* number of distance codes */
  18270. var BL_CODES = 19;
  18271. /* number of codes used to transfer the bit lengths */
  18272. var HEAP_SIZE = 2*L_CODES + 1;
  18273. /* maximum heap size */
  18274. var MAX_BITS = 15;
  18275. /* All codes must not exceed MAX_BITS bits */
  18276. var Buf_size = 16;
  18277. /* size of bit buffer in bi_buf */
  18278. /* ===========================================================================
  18279. * Constants
  18280. */
  18281. var MAX_BL_BITS = 7;
  18282. /* Bit length codes must not exceed MAX_BL_BITS bits */
  18283. var END_BLOCK = 256;
  18284. /* end of block literal code */
  18285. var REP_3_6 = 16;
  18286. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  18287. var REPZ_3_10 = 17;
  18288. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  18289. var REPZ_11_138 = 18;
  18290. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  18291. var extra_lbits = /* extra bits for each length code */
  18292. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  18293. var extra_dbits = /* extra bits for each distance code */
  18294. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  18295. var extra_blbits = /* extra bits for each bit length code */
  18296. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  18297. var bl_order =
  18298. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  18299. /* The lengths of the bit length codes are sent in order of decreasing
  18300. * probability, to avoid transmitting the lengths for unused bit length codes.
  18301. */
  18302. /* ===========================================================================
  18303. * Local data. These are initialized only once.
  18304. */
  18305. // We pre-fill arrays with 0 to avoid uninitialized gaps
  18306. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  18307. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  18308. var static_ltree = new Array((L_CODES+2) * 2);
  18309. zero(static_ltree);
  18310. /* The static literal tree. Since the bit lengths are imposed, there is no
  18311. * need for the L_CODES extra codes used during heap construction. However
  18312. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  18313. * below).
  18314. */
  18315. var static_dtree = new Array(D_CODES * 2);
  18316. zero(static_dtree);
  18317. /* The static distance tree. (Actually a trivial tree since all codes use
  18318. * 5 bits.)
  18319. */
  18320. var _dist_code = new Array(DIST_CODE_LEN);
  18321. zero(_dist_code);
  18322. /* Distance codes. The first 256 values correspond to the distances
  18323. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  18324. * the 15 bit distances.
  18325. */
  18326. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  18327. zero(_length_code);
  18328. /* length code for each normalized match length (0 == MIN_MATCH) */
  18329. var base_length = new Array(LENGTH_CODES);
  18330. zero(base_length);
  18331. /* First normalized length for each code (0 = MIN_MATCH) */
  18332. var base_dist = new Array(D_CODES);
  18333. zero(base_dist);
  18334. /* First normalized distance for each code (0 = distance of 1) */
  18335. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  18336. this.static_tree = static_tree; /* static tree or NULL */
  18337. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  18338. this.extra_base = extra_base; /* base index for extra_bits */
  18339. this.elems = elems; /* max number of elements in the tree */
  18340. this.max_length = max_length; /* max bit length for the codes */
  18341. // show if `static_tree` has data or dummy - needed for monomorphic objects
  18342. this.has_stree = static_tree && static_tree.length;
  18343. };
  18344. var static_l_desc;
  18345. var static_d_desc;
  18346. var static_bl_desc;
  18347. var TreeDesc = function(dyn_tree, stat_desc) {
  18348. this.dyn_tree = dyn_tree; /* the dynamic tree */
  18349. this.max_code = 0; /* largest code with non zero frequency */
  18350. this.stat_desc = stat_desc; /* the corresponding static tree */
  18351. };
  18352. function d_code(dist) {
  18353. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  18354. }
  18355. /* ===========================================================================
  18356. * Output a short LSB first on the stream.
  18357. * IN assertion: there is enough room in pendingBuf.
  18358. */
  18359. function put_short (s, w) {
  18360. // put_byte(s, (uch)((w) & 0xff));
  18361. // put_byte(s, (uch)((ush)(w) >> 8));
  18362. s.pending_buf[s.pending++] = (w) & 0xff;
  18363. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  18364. }
  18365. /* ===========================================================================
  18366. * Send a value on a given number of bits.
  18367. * IN assertion: length <= 16 and value fits in length bits.
  18368. */
  18369. function send_bits(s, value, length) {
  18370. if (s.bi_valid > (Buf_size - length)) {
  18371. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18372. put_short(s, s.bi_buf);
  18373. s.bi_buf = value >> (Buf_size - s.bi_valid);
  18374. s.bi_valid += length - Buf_size;
  18375. } else {
  18376. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18377. s.bi_valid += length;
  18378. }
  18379. }
  18380. function send_code(s, c, tree) {
  18381. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  18382. }
  18383. /* ===========================================================================
  18384. * Reverse the first len bits of a code, using straightforward code (a faster
  18385. * method would use a table)
  18386. * IN assertion: 1 <= len <= 15
  18387. */
  18388. function bi_reverse(code, len) {
  18389. var res = 0;
  18390. do {
  18391. res |= code & 1;
  18392. code >>>= 1;
  18393. res <<= 1;
  18394. } while (--len > 0);
  18395. return res >>> 1;
  18396. }
  18397. /* ===========================================================================
  18398. * Flush the bit buffer, keeping at most 7 bits in it.
  18399. */
  18400. function bi_flush(s) {
  18401. if (s.bi_valid === 16) {
  18402. put_short(s, s.bi_buf);
  18403. s.bi_buf = 0;
  18404. s.bi_valid = 0;
  18405. } else if (s.bi_valid >= 8) {
  18406. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  18407. s.bi_buf >>= 8;
  18408. s.bi_valid -= 8;
  18409. }
  18410. }
  18411. /* ===========================================================================
  18412. * Compute the optimal bit lengths for a tree and update the total bit length
  18413. * for the current block.
  18414. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  18415. * above are the tree nodes sorted by increasing frequency.
  18416. * OUT assertions: the field len is set to the optimal bit length, the
  18417. * array bl_count contains the frequencies for each bit length.
  18418. * The length opt_len is updated; static_len is also updated if stree is
  18419. * not null.
  18420. */
  18421. function gen_bitlen(s, desc)
  18422. // deflate_state *s;
  18423. // tree_desc *desc; /* the tree descriptor */
  18424. {
  18425. var tree = desc.dyn_tree;
  18426. var max_code = desc.max_code;
  18427. var stree = desc.stat_desc.static_tree;
  18428. var has_stree = desc.stat_desc.has_stree;
  18429. var extra = desc.stat_desc.extra_bits;
  18430. var base = desc.stat_desc.extra_base;
  18431. var max_length = desc.stat_desc.max_length;
  18432. var h; /* heap index */
  18433. var n, m; /* iterate over the tree elements */
  18434. var bits; /* bit length */
  18435. var xbits; /* extra bits */
  18436. var f; /* frequency */
  18437. var overflow = 0; /* number of elements with bit length too large */
  18438. for (bits = 0; bits <= MAX_BITS; bits++) {
  18439. s.bl_count[bits] = 0;
  18440. }
  18441. /* In a first pass, compute the optimal bit lengths (which may
  18442. * overflow in the case of the bit length tree).
  18443. */
  18444. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  18445. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  18446. n = s.heap[h];
  18447. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  18448. if (bits > max_length) {
  18449. bits = max_length;
  18450. overflow++;
  18451. }
  18452. tree[n*2 + 1]/*.Len*/ = bits;
  18453. /* We overwrite tree[n].Dad which is no longer needed */
  18454. if (n > max_code) { continue; } /* not a leaf node */
  18455. s.bl_count[bits]++;
  18456. xbits = 0;
  18457. if (n >= base) {
  18458. xbits = extra[n-base];
  18459. }
  18460. f = tree[n * 2]/*.Freq*/;
  18461. s.opt_len += f * (bits + xbits);
  18462. if (has_stree) {
  18463. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  18464. }
  18465. }
  18466. if (overflow === 0) { return; }
  18467. // Trace((stderr,"\nbit length overflow\n"));
  18468. /* This happens for example on obj2 and pic of the Calgary corpus */
  18469. /* Find the first bit length which could increase: */
  18470. do {
  18471. bits = max_length-1;
  18472. while (s.bl_count[bits] === 0) { bits--; }
  18473. s.bl_count[bits]--; /* move one leaf down the tree */
  18474. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  18475. s.bl_count[max_length]--;
  18476. /* The brother of the overflow item also moves one step up,
  18477. * but this does not affect bl_count[max_length]
  18478. */
  18479. overflow -= 2;
  18480. } while (overflow > 0);
  18481. /* Now recompute all bit lengths, scanning in increasing frequency.
  18482. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  18483. * lengths instead of fixing only the wrong ones. This idea is taken
  18484. * from 'ar' written by Haruhiko Okumura.)
  18485. */
  18486. for (bits = max_length; bits !== 0; bits--) {
  18487. n = s.bl_count[bits];
  18488. while (n !== 0) {
  18489. m = s.heap[--h];
  18490. if (m > max_code) { continue; }
  18491. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  18492. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  18493. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  18494. tree[m*2 + 1]/*.Len*/ = bits;
  18495. }
  18496. n--;
  18497. }
  18498. }
  18499. }
  18500. /* ===========================================================================
  18501. * Generate the codes for a given tree and bit counts (which need not be
  18502. * optimal).
  18503. * IN assertion: the array bl_count contains the bit length statistics for
  18504. * the given tree and the field len is set for all tree elements.
  18505. * OUT assertion: the field code is set for all tree elements of non
  18506. * zero code length.
  18507. */
  18508. function gen_codes(tree, max_code, bl_count)
  18509. // ct_data *tree; /* the tree to decorate */
  18510. // int max_code; /* largest code with non zero frequency */
  18511. // ushf *bl_count; /* number of codes at each bit length */
  18512. {
  18513. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  18514. var code = 0; /* running code value */
  18515. var bits; /* bit index */
  18516. var n; /* code index */
  18517. /* The distribution counts are first used to generate the code values
  18518. * without bit reversal.
  18519. */
  18520. for (bits = 1; bits <= MAX_BITS; bits++) {
  18521. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  18522. }
  18523. /* Check that the bit counts in bl_count are consistent. The last code
  18524. * must be all ones.
  18525. */
  18526. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  18527. // "inconsistent bit counts");
  18528. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  18529. for (n = 0; n <= max_code; n++) {
  18530. var len = tree[n*2 + 1]/*.Len*/;
  18531. if (len === 0) { continue; }
  18532. /* Now reverse the bits */
  18533. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  18534. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  18535. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  18536. }
  18537. }
  18538. /* ===========================================================================
  18539. * Initialize the various 'constant' tables.
  18540. */
  18541. function tr_static_init() {
  18542. var n; /* iterates over tree elements */
  18543. var bits; /* bit counter */
  18544. var length; /* length value */
  18545. var code; /* code value */
  18546. var dist; /* distance index */
  18547. var bl_count = new Array(MAX_BITS+1);
  18548. /* number of codes at each bit length for an optimal tree */
  18549. // do check in _tr_init()
  18550. //if (static_init_done) return;
  18551. /* For some embedded targets, global variables are not initialized: */
  18552. /*#ifdef NO_INIT_GLOBAL_POINTERS
  18553. static_l_desc.static_tree = static_ltree;
  18554. static_l_desc.extra_bits = extra_lbits;
  18555. static_d_desc.static_tree = static_dtree;
  18556. static_d_desc.extra_bits = extra_dbits;
  18557. static_bl_desc.extra_bits = extra_blbits;
  18558. #endif*/
  18559. /* Initialize the mapping length (0..255) -> length code (0..28) */
  18560. length = 0;
  18561. for (code = 0; code < LENGTH_CODES-1; code++) {
  18562. base_length[code] = length;
  18563. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  18564. _length_code[length++] = code;
  18565. }
  18566. }
  18567. //Assert (length == 256, "tr_static_init: length != 256");
  18568. /* Note that the length 255 (match length 258) can be represented
  18569. * in two different ways: code 284 + 5 bits or code 285, so we
  18570. * overwrite length_code[255] to use the best encoding:
  18571. */
  18572. _length_code[length-1] = code;
  18573. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  18574. dist = 0;
  18575. for (code = 0 ; code < 16; code++) {
  18576. base_dist[code] = dist;
  18577. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  18578. _dist_code[dist++] = code;
  18579. }
  18580. }
  18581. //Assert (dist == 256, "tr_static_init: dist != 256");
  18582. dist >>= 7; /* from now on, all distances are divided by 128 */
  18583. for (; code < D_CODES; code++) {
  18584. base_dist[code] = dist << 7;
  18585. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  18586. _dist_code[256 + dist++] = code;
  18587. }
  18588. }
  18589. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  18590. /* Construct the codes of the static literal tree */
  18591. for (bits = 0; bits <= MAX_BITS; bits++) {
  18592. bl_count[bits] = 0;
  18593. }
  18594. n = 0;
  18595. while (n <= 143) {
  18596. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18597. n++;
  18598. bl_count[8]++;
  18599. }
  18600. while (n <= 255) {
  18601. static_ltree[n*2 + 1]/*.Len*/ = 9;
  18602. n++;
  18603. bl_count[9]++;
  18604. }
  18605. while (n <= 279) {
  18606. static_ltree[n*2 + 1]/*.Len*/ = 7;
  18607. n++;
  18608. bl_count[7]++;
  18609. }
  18610. while (n <= 287) {
  18611. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18612. n++;
  18613. bl_count[8]++;
  18614. }
  18615. /* Codes 286 and 287 do not exist, but we must include them in the
  18616. * tree construction to get a canonical Huffman tree (longest code
  18617. * all ones)
  18618. */
  18619. gen_codes(static_ltree, L_CODES+1, bl_count);
  18620. /* The static distance tree is trivial: */
  18621. for (n = 0; n < D_CODES; n++) {
  18622. static_dtree[n*2 + 1]/*.Len*/ = 5;
  18623. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  18624. }
  18625. // Now data ready and we can init static trees
  18626. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  18627. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  18628. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  18629. //static_init_done = true;
  18630. }
  18631. /* ===========================================================================
  18632. * Initialize a new block.
  18633. */
  18634. function init_block(s) {
  18635. var n; /* iterates over tree elements */
  18636. /* Initialize the trees. */
  18637. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  18638. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  18639. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  18640. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  18641. s.opt_len = s.static_len = 0;
  18642. s.last_lit = s.matches = 0;
  18643. }
  18644. /* ===========================================================================
  18645. * Flush the bit buffer and align the output on a byte boundary
  18646. */
  18647. function bi_windup(s)
  18648. {
  18649. if (s.bi_valid > 8) {
  18650. put_short(s, s.bi_buf);
  18651. } else if (s.bi_valid > 0) {
  18652. //put_byte(s, (Byte)s->bi_buf);
  18653. s.pending_buf[s.pending++] = s.bi_buf;
  18654. }
  18655. s.bi_buf = 0;
  18656. s.bi_valid = 0;
  18657. }
  18658. /* ===========================================================================
  18659. * Copy a stored block, storing first the length and its
  18660. * one's complement if requested.
  18661. */
  18662. function copy_block(s, buf, len, header)
  18663. //DeflateState *s;
  18664. //charf *buf; /* the input data */
  18665. //unsigned len; /* its length */
  18666. //int header; /* true if block header must be written */
  18667. {
  18668. bi_windup(s); /* align on byte boundary */
  18669. if (header) {
  18670. put_short(s, len);
  18671. put_short(s, ~len);
  18672. }
  18673. // while (len--) {
  18674. // put_byte(s, *buf++);
  18675. // }
  18676. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  18677. s.pending += len;
  18678. }
  18679. /* ===========================================================================
  18680. * Compares to subtrees, using the tree depth as tie breaker when
  18681. * the subtrees have equal frequency. This minimizes the worst case length.
  18682. */
  18683. function smaller(tree, n, m, depth) {
  18684. var _n2 = n*2;
  18685. var _m2 = m*2;
  18686. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  18687. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  18688. }
  18689. /* ===========================================================================
  18690. * Restore the heap property by moving down the tree starting at node k,
  18691. * exchanging a node with the smallest of its two sons if necessary, stopping
  18692. * when the heap property is re-established (each father smaller than its
  18693. * two sons).
  18694. */
  18695. function pqdownheap(s, tree, k)
  18696. // deflate_state *s;
  18697. // ct_data *tree; /* the tree to restore */
  18698. // int k; /* node to move down */
  18699. {
  18700. var v = s.heap[k];
  18701. var j = k << 1; /* left son of k */
  18702. while (j <= s.heap_len) {
  18703. /* Set j to the smallest of the two sons: */
  18704. if (j < s.heap_len &&
  18705. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  18706. j++;
  18707. }
  18708. /* Exit if v is smaller than both sons */
  18709. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  18710. /* Exchange v with the smallest son */
  18711. s.heap[k] = s.heap[j];
  18712. k = j;
  18713. /* And continue down the tree, setting j to the left son of k */
  18714. j <<= 1;
  18715. }
  18716. s.heap[k] = v;
  18717. }
  18718. // inlined manually
  18719. // var SMALLEST = 1;
  18720. /* ===========================================================================
  18721. * Send the block data compressed using the given Huffman trees
  18722. */
  18723. function compress_block(s, ltree, dtree)
  18724. // deflate_state *s;
  18725. // const ct_data *ltree; /* literal tree */
  18726. // const ct_data *dtree; /* distance tree */
  18727. {
  18728. var dist; /* distance of matched string */
  18729. var lc; /* match length or unmatched char (if dist == 0) */
  18730. var lx = 0; /* running index in l_buf */
  18731. var code; /* the code to send */
  18732. var extra; /* number of extra bits to send */
  18733. if (s.last_lit !== 0) {
  18734. do {
  18735. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  18736. lc = s.pending_buf[s.l_buf + lx];
  18737. lx++;
  18738. if (dist === 0) {
  18739. send_code(s, lc, ltree); /* send a literal byte */
  18740. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18741. } else {
  18742. /* Here, lc is the match length - MIN_MATCH */
  18743. code = _length_code[lc];
  18744. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  18745. extra = extra_lbits[code];
  18746. if (extra !== 0) {
  18747. lc -= base_length[code];
  18748. send_bits(s, lc, extra); /* send the extra length bits */
  18749. }
  18750. dist--; /* dist is now the match distance - 1 */
  18751. code = d_code(dist);
  18752. //Assert (code < D_CODES, "bad d_code");
  18753. send_code(s, code, dtree); /* send the distance code */
  18754. extra = extra_dbits[code];
  18755. if (extra !== 0) {
  18756. dist -= base_dist[code];
  18757. send_bits(s, dist, extra); /* send the extra distance bits */
  18758. }
  18759. } /* literal or match pair ? */
  18760. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18761. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18762. // "pendingBuf overflow");
  18763. } while (lx < s.last_lit);
  18764. }
  18765. send_code(s, END_BLOCK, ltree);
  18766. }
  18767. /* ===========================================================================
  18768. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18769. * Update the total bit length for the current block.
  18770. * IN assertion: the field freq is set for all tree elements.
  18771. * OUT assertions: the fields len and code are set to the optimal bit length
  18772. * and corresponding code. The length opt_len is updated; static_len is
  18773. * also updated if stree is not null. The field max_code is set.
  18774. */
  18775. function build_tree(s, desc)
  18776. // deflate_state *s;
  18777. // tree_desc *desc; /* the tree descriptor */
  18778. {
  18779. var tree = desc.dyn_tree;
  18780. var stree = desc.stat_desc.static_tree;
  18781. var has_stree = desc.stat_desc.has_stree;
  18782. var elems = desc.stat_desc.elems;
  18783. var n, m; /* iterate over heap elements */
  18784. var max_code = -1; /* largest code with non zero frequency */
  18785. var node; /* new node being created */
  18786. /* Construct the initial heap, with least frequent element in
  18787. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18788. * heap[0] is not used.
  18789. */
  18790. s.heap_len = 0;
  18791. s.heap_max = HEAP_SIZE;
  18792. for (n = 0; n < elems; n++) {
  18793. if (tree[n * 2]/*.Freq*/ !== 0) {
  18794. s.heap[++s.heap_len] = max_code = n;
  18795. s.depth[n] = 0;
  18796. } else {
  18797. tree[n*2 + 1]/*.Len*/ = 0;
  18798. }
  18799. }
  18800. /* The pkzip format requires that at least one distance code exists,
  18801. * and that at least one bit should be sent even if there is only one
  18802. * possible code. So to avoid special checks later on we force at least
  18803. * two codes of non zero frequency.
  18804. */
  18805. while (s.heap_len < 2) {
  18806. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18807. tree[node * 2]/*.Freq*/ = 1;
  18808. s.depth[node] = 0;
  18809. s.opt_len--;
  18810. if (has_stree) {
  18811. s.static_len -= stree[node*2 + 1]/*.Len*/;
  18812. }
  18813. /* node is 0 or 1 so it does not have extra bits */
  18814. }
  18815. desc.max_code = max_code;
  18816. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18817. * establish sub-heaps of increasing lengths:
  18818. */
  18819. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18820. /* Construct the Huffman tree by repeatedly combining the least two
  18821. * frequent nodes.
  18822. */
  18823. node = elems; /* next internal node of the tree */
  18824. do {
  18825. //pqremove(s, tree, n); /* n = node of least frequency */
  18826. /*** pqremove ***/
  18827. n = s.heap[1/*SMALLEST*/];
  18828. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18829. pqdownheap(s, tree, 1/*SMALLEST*/);
  18830. /***/
  18831. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18832. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18833. s.heap[--s.heap_max] = m;
  18834. /* Create a new node father of n and m */
  18835. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18836. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18837. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  18838. /* and insert the new node in the heap */
  18839. s.heap[1/*SMALLEST*/] = node++;
  18840. pqdownheap(s, tree, 1/*SMALLEST*/);
  18841. } while (s.heap_len >= 2);
  18842. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18843. /* At this point, the fields freq and dad are set. We can now
  18844. * generate the bit lengths.
  18845. */
  18846. gen_bitlen(s, desc);
  18847. /* The field len is now set, we can generate the bit codes */
  18848. gen_codes(tree, max_code, s.bl_count);
  18849. }
  18850. /* ===========================================================================
  18851. * Scan a literal or distance tree to determine the frequencies of the codes
  18852. * in the bit length tree.
  18853. */
  18854. function scan_tree(s, tree, max_code)
  18855. // deflate_state *s;
  18856. // ct_data *tree; /* the tree to be scanned */
  18857. // int max_code; /* and its largest code of non zero frequency */
  18858. {
  18859. var n; /* iterates over all tree elements */
  18860. var prevlen = -1; /* last emitted length */
  18861. var curlen; /* length of current code */
  18862. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18863. var count = 0; /* repeat count of the current code */
  18864. var max_count = 7; /* max repeat count */
  18865. var min_count = 4; /* min repeat count */
  18866. if (nextlen === 0) {
  18867. max_count = 138;
  18868. min_count = 3;
  18869. }
  18870. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18871. for (n = 0; n <= max_code; n++) {
  18872. curlen = nextlen;
  18873. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18874. if (++count < max_count && curlen === nextlen) {
  18875. continue;
  18876. } else if (count < min_count) {
  18877. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18878. } else if (curlen !== 0) {
  18879. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18880. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18881. } else if (count <= 10) {
  18882. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18883. } else {
  18884. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18885. }
  18886. count = 0;
  18887. prevlen = curlen;
  18888. if (nextlen === 0) {
  18889. max_count = 138;
  18890. min_count = 3;
  18891. } else if (curlen === nextlen) {
  18892. max_count = 6;
  18893. min_count = 3;
  18894. } else {
  18895. max_count = 7;
  18896. min_count = 4;
  18897. }
  18898. }
  18899. }
  18900. /* ===========================================================================
  18901. * Send a literal or distance tree in compressed form, using the codes in
  18902. * bl_tree.
  18903. */
  18904. function send_tree(s, tree, max_code)
  18905. // deflate_state *s;
  18906. // ct_data *tree; /* the tree to be scanned */
  18907. // int max_code; /* and its largest code of non zero frequency */
  18908. {
  18909. var n; /* iterates over all tree elements */
  18910. var prevlen = -1; /* last emitted length */
  18911. var curlen; /* length of current code */
  18912. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18913. var count = 0; /* repeat count of the current code */
  18914. var max_count = 7; /* max repeat count */
  18915. var min_count = 4; /* min repeat count */
  18916. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18917. if (nextlen === 0) {
  18918. max_count = 138;
  18919. min_count = 3;
  18920. }
  18921. for (n = 0; n <= max_code; n++) {
  18922. curlen = nextlen;
  18923. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18924. if (++count < max_count && curlen === nextlen) {
  18925. continue;
  18926. } else if (count < min_count) {
  18927. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18928. } else if (curlen !== 0) {
  18929. if (curlen !== prevlen) {
  18930. send_code(s, curlen, s.bl_tree);
  18931. count--;
  18932. }
  18933. //Assert(count >= 3 && count <= 6, " 3_6?");
  18934. send_code(s, REP_3_6, s.bl_tree);
  18935. send_bits(s, count-3, 2);
  18936. } else if (count <= 10) {
  18937. send_code(s, REPZ_3_10, s.bl_tree);
  18938. send_bits(s, count-3, 3);
  18939. } else {
  18940. send_code(s, REPZ_11_138, s.bl_tree);
  18941. send_bits(s, count-11, 7);
  18942. }
  18943. count = 0;
  18944. prevlen = curlen;
  18945. if (nextlen === 0) {
  18946. max_count = 138;
  18947. min_count = 3;
  18948. } else if (curlen === nextlen) {
  18949. max_count = 6;
  18950. min_count = 3;
  18951. } else {
  18952. max_count = 7;
  18953. min_count = 4;
  18954. }
  18955. }
  18956. }
  18957. /* ===========================================================================
  18958. * Construct the Huffman tree for the bit lengths and return the index in
  18959. * bl_order of the last bit length code to send.
  18960. */
  18961. function build_bl_tree(s) {
  18962. var max_blindex; /* index of last bit length code of non zero freq */
  18963. /* Determine the bit length frequencies for literal and distance trees */
  18964. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18965. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18966. /* Build the bit length tree: */
  18967. build_tree(s, s.bl_desc);
  18968. /* opt_len now includes the length of the tree representations, except
  18969. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18970. */
  18971. /* Determine the number of bit length codes to send. The pkzip format
  18972. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18973. * 3 but the actual value used is 4.)
  18974. */
  18975. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18976. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18977. break;
  18978. }
  18979. }
  18980. /* Update opt_len to include the bit length tree and counts */
  18981. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18982. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18983. // s->opt_len, s->static_len));
  18984. return max_blindex;
  18985. }
  18986. /* ===========================================================================
  18987. * Send the header for a block using dynamic Huffman trees: the counts, the
  18988. * lengths of the bit length codes, the literal tree and the distance tree.
  18989. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18990. */
  18991. function send_all_trees(s, lcodes, dcodes, blcodes)
  18992. // deflate_state *s;
  18993. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18994. {
  18995. var rank; /* index in bl_order */
  18996. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18997. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18998. // "too many codes");
  18999. //Tracev((stderr, "\nbl counts: "));
  19000. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  19001. send_bits(s, dcodes-1, 5);
  19002. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  19003. for (rank = 0; rank < blcodes; rank++) {
  19004. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  19005. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  19006. }
  19007. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  19008. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  19009. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  19010. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  19011. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  19012. }
  19013. /* ===========================================================================
  19014. * Check if the data type is TEXT or BINARY, using the following algorithm:
  19015. * - TEXT if the two conditions below are satisfied:
  19016. * a) There are no non-portable control characters belonging to the
  19017. * "black list" (0..6, 14..25, 28..31).
  19018. * b) There is at least one printable character belonging to the
  19019. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  19020. * - BINARY otherwise.
  19021. * - The following partially-portable control characters form a
  19022. * "gray list" that is ignored in this detection algorithm:
  19023. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  19024. * IN assertion: the fields Freq of dyn_ltree are set.
  19025. */
  19026. function detect_data_type(s) {
  19027. /* black_mask is the bit mask of black-listed bytes
  19028. * set bits 0..6, 14..25, and 28..31
  19029. * 0xf3ffc07f = binary 11110011111111111100000001111111
  19030. */
  19031. var black_mask = 0xf3ffc07f;
  19032. var n;
  19033. /* Check for non-textual ("black-listed") bytes. */
  19034. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  19035. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  19036. return Z_BINARY;
  19037. }
  19038. }
  19039. /* Check for textual ("white-listed") bytes. */
  19040. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  19041. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  19042. return Z_TEXT;
  19043. }
  19044. for (n = 32; n < LITERALS; n++) {
  19045. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  19046. return Z_TEXT;
  19047. }
  19048. }
  19049. /* There are no "black-listed" or "white-listed" bytes:
  19050. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  19051. */
  19052. return Z_BINARY;
  19053. }
  19054. var static_init_done = false;
  19055. /* ===========================================================================
  19056. * Initialize the tree data structures for a new zlib stream.
  19057. */
  19058. function _tr_init(s)
  19059. {
  19060. if (!static_init_done) {
  19061. tr_static_init();
  19062. static_init_done = true;
  19063. }
  19064. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19065. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19066. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19067. s.bi_buf = 0;
  19068. s.bi_valid = 0;
  19069. /* Initialize the first block of the first file: */
  19070. init_block(s);
  19071. }
  19072. /* ===========================================================================
  19073. * Send a stored block
  19074. */
  19075. function _tr_stored_block(s, buf, stored_len, last)
  19076. //DeflateState *s;
  19077. //charf *buf; /* input block */
  19078. //ulg stored_len; /* length of input block */
  19079. //int last; /* one if this is the last block for a file */
  19080. {
  19081. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19082. copy_block(s, buf, stored_len, true); /* with header */
  19083. }
  19084. /* ===========================================================================
  19085. * Send one empty static block to give enough lookahead for inflate.
  19086. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19087. */
  19088. function _tr_align(s) {
  19089. send_bits(s, STATIC_TREES<<1, 3);
  19090. send_code(s, END_BLOCK, static_ltree);
  19091. bi_flush(s);
  19092. }
  19093. /* ===========================================================================
  19094. * Determine the best encoding for the current block: dynamic trees, static
  19095. * trees or store, and output the encoded block to the zip file.
  19096. */
  19097. function _tr_flush_block(s, buf, stored_len, last)
  19098. //DeflateState *s;
  19099. //charf *buf; /* input block, or NULL if too old */
  19100. //ulg stored_len; /* length of input block */
  19101. //int last; /* one if this is the last block for a file */
  19102. {
  19103. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  19104. var max_blindex = 0; /* index of last bit length code of non zero freq */
  19105. /* Build the Huffman trees unless a stored block is forced */
  19106. if (s.level > 0) {
  19107. /* Check if the file is binary or text */
  19108. if (s.strm.data_type === Z_UNKNOWN) {
  19109. s.strm.data_type = detect_data_type(s);
  19110. }
  19111. /* Construct the literal and distance trees */
  19112. build_tree(s, s.l_desc);
  19113. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  19114. // s->static_len));
  19115. build_tree(s, s.d_desc);
  19116. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  19117. // s->static_len));
  19118. /* At this point, opt_len and static_len are the total bit lengths of
  19119. * the compressed block data, excluding the tree representations.
  19120. */
  19121. /* Build the bit length tree for the above two trees, and get the index
  19122. * in bl_order of the last bit length code to send.
  19123. */
  19124. max_blindex = build_bl_tree(s);
  19125. /* Determine the best encoding. Compute the block lengths in bytes. */
  19126. opt_lenb = (s.opt_len+3+7) >>> 3;
  19127. static_lenb = (s.static_len+3+7) >>> 3;
  19128. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  19129. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  19130. // s->last_lit));
  19131. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  19132. } else {
  19133. // Assert(buf != (char*)0, "lost buf");
  19134. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  19135. }
  19136. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  19137. /* 4: two words for the lengths */
  19138. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  19139. * Otherwise we can't have processed more than WSIZE input bytes since
  19140. * the last block flush, because compression would have been
  19141. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  19142. * transform a block into a stored block.
  19143. */
  19144. _tr_stored_block(s, buf, stored_len, last);
  19145. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  19146. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  19147. compress_block(s, static_ltree, static_dtree);
  19148. } else {
  19149. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  19150. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  19151. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  19152. }
  19153. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  19154. /* The above check is made mod 2^32, for files larger than 512 MB
  19155. * and uLong implemented on 32 bits.
  19156. */
  19157. init_block(s);
  19158. if (last) {
  19159. bi_windup(s);
  19160. }
  19161. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  19162. // s->compressed_len-7*last));
  19163. }
  19164. /* ===========================================================================
  19165. * Save the match info and tally the frequency counts. Return true if
  19166. * the current block must be flushed.
  19167. */
  19168. function _tr_tally(s, dist, lc)
  19169. // deflate_state *s;
  19170. // unsigned dist; /* distance of matched string */
  19171. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  19172. {
  19173. //var out_length, in_length, dcode;
  19174. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  19175. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  19176. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  19177. s.last_lit++;
  19178. if (dist === 0) {
  19179. /* lc is the unmatched char */
  19180. s.dyn_ltree[lc*2]/*.Freq*/++;
  19181. } else {
  19182. s.matches++;
  19183. /* Here, lc is the match length - MIN_MATCH */
  19184. dist--; /* dist = match distance - 1 */
  19185. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  19186. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  19187. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  19188. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  19189. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  19190. }
  19191. // (!) This block is disabled in zlib defailts,
  19192. // don't enable it for binary compatibility
  19193. //#ifdef TRUNCATE_BLOCK
  19194. // /* Try to guess if it is profitable to stop the current block here */
  19195. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  19196. // /* Compute an upper bound for the compressed length */
  19197. // out_length = s.last_lit*8;
  19198. // in_length = s.strstart - s.block_start;
  19199. //
  19200. // for (dcode = 0; dcode < D_CODES; dcode++) {
  19201. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  19202. // }
  19203. // out_length >>>= 3;
  19204. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  19205. // // s->last_lit, in_length, out_length,
  19206. // // 100L - out_length*100L/in_length));
  19207. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  19208. // return true;
  19209. // }
  19210. // }
  19211. //#endif
  19212. return (s.last_lit === s.lit_bufsize-1);
  19213. /* We avoid equality with lit_bufsize because of wraparound at 64K
  19214. * on 16 bit machines and because stored blocks are restricted to
  19215. * 64K-1 bytes.
  19216. */
  19217. }
  19218. exports._tr_init = _tr_init;
  19219. exports._tr_stored_block = _tr_stored_block;
  19220. exports._tr_flush_block = _tr_flush_block;
  19221. exports._tr_tally = _tr_tally;
  19222. exports._tr_align = _tr_align;
  19223. },{"../utils/common":52}],64:[function(require,module,exports){
  19224. 'use strict';
  19225. function ZStream() {
  19226. /* next input byte */
  19227. this.input = null; // JS specific, because we have no pointers
  19228. this.next_in = 0;
  19229. /* number of bytes available at input */
  19230. this.avail_in = 0;
  19231. /* total number of input bytes read so far */
  19232. this.total_in = 0;
  19233. /* next output byte should be put there */
  19234. this.output = null; // JS specific, because we have no pointers
  19235. this.next_out = 0;
  19236. /* remaining free space at output */
  19237. this.avail_out = 0;
  19238. /* total number of bytes output so far */
  19239. this.total_out = 0;
  19240. /* last error message, NULL if no error */
  19241. this.msg = ''/*Z_NULL*/;
  19242. /* not visible by applications */
  19243. this.state = null;
  19244. /* best guess about the data type: binary or text */
  19245. this.data_type = 2/*Z_UNKNOWN*/;
  19246. /* adler32 value of the uncompressed data */
  19247. this.adler = 0;
  19248. }
  19249. module.exports = ZStream;
  19250. },{}],65:[function(require,module,exports){
  19251. /* Copyright @ 2015 Atlassian Pty Ltd
  19252. *
  19253. * Licensed under the Apache License, Version 2.0 (the "License");
  19254. * you may not use this file except in compliance with the License.
  19255. * You may obtain a copy of the License at
  19256. *
  19257. * http://www.apache.org/licenses/LICENSE-2.0
  19258. *
  19259. * Unless required by applicable law or agreed to in writing, software
  19260. * distributed under the License is distributed on an "AS IS" BASIS,
  19261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19262. * See the License for the specific language governing permissions and
  19263. * limitations under the License.
  19264. */
  19265. module.exports = function arrayEquals(array) {
  19266. // if the other array is a falsy value, return
  19267. if (!array)
  19268. return false;
  19269. // compare lengths - can save a lot of time
  19270. if (this.length != array.length)
  19271. return false;
  19272. for (var i = 0, l = this.length; i < l; i++) {
  19273. // Check if we have nested arrays
  19274. if (this[i] instanceof Array && array[i] instanceof Array) {
  19275. // recurse into the nested arrays
  19276. if (!arrayEquals.apply(this[i], [array[i]]))
  19277. return false;
  19278. } else if (this[i] != array[i]) {
  19279. // Warning - two different object instances will never be equal:
  19280. // {x:20} != {x:20}
  19281. return false;
  19282. }
  19283. }
  19284. return true;
  19285. };
  19286. },{}],66:[function(require,module,exports){
  19287. /* Copyright @ 2015 Atlassian Pty Ltd
  19288. *
  19289. * Licensed under the Apache License, Version 2.0 (the "License");
  19290. * you may not use this file except in compliance with the License.
  19291. * You may obtain a copy of the License at
  19292. *
  19293. * http://www.apache.org/licenses/LICENSE-2.0
  19294. *
  19295. * Unless required by applicable law or agreed to in writing, software
  19296. * distributed under the License is distributed on an "AS IS" BASIS,
  19297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19298. * See the License for the specific language governing permissions and
  19299. * limitations under the License.
  19300. */
  19301. exports.Interop = require('./interop');
  19302. },{"./interop":67}],67:[function(require,module,exports){
  19303. /* Copyright @ 2015 Atlassian Pty Ltd
  19304. *
  19305. * Licensed under the Apache License, Version 2.0 (the "License");
  19306. * you may not use this file except in compliance with the License.
  19307. * You may obtain a copy of the License at
  19308. *
  19309. * http://www.apache.org/licenses/LICENSE-2.0
  19310. *
  19311. * Unless required by applicable law or agreed to in writing, software
  19312. * distributed under the License is distributed on an "AS IS" BASIS,
  19313. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19314. * See the License for the specific language governing permissions and
  19315. * limitations under the License.
  19316. */
  19317. /* global RTCSessionDescription */
  19318. /* jshint -W097 */
  19319. "use strict";
  19320. var transform = require('./transform');
  19321. var arrayEquals = require('./array-equals');
  19322. function Interop() {
  19323. /**
  19324. * This map holds the most recent Unified Plan offer/answer SDP that was
  19325. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  19326. * the SDP string as values.
  19327. *
  19328. * @type {{}}
  19329. */
  19330. this.cache = {};
  19331. }
  19332. module.exports = Interop;
  19333. /**
  19334. * Returns the index of the first m-line with the given media type and with a
  19335. * direction which allows sending, in the last Unified Plan description with
  19336. * type "answer" converted to Plan B. Returns {null} if there is no saved
  19337. * answer, or if none of its m-lines with the given type allow sending.
  19338. * @param type the media type ("audio" or "video").
  19339. * @returns {*}
  19340. */
  19341. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  19342. if (!this.cache.answer) {
  19343. return null;
  19344. }
  19345. var session = transform.parse(this.cache.answer);
  19346. if (session && session.media && Array.isArray(session.media)){
  19347. for (var i = 0; i < session.media.length; i++) {
  19348. if (session.media[i].type == type &&
  19349. (!session.media[i].direction /* default to sendrecv */ ||
  19350. session.media[i].direction === 'sendrecv' ||
  19351. session.media[i].direction === 'sendonly')){
  19352. return i;
  19353. }
  19354. }
  19355. }
  19356. return null;
  19357. };
  19358. /**
  19359. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  19360. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  19361. * application.
  19362. *
  19363. * @param desc
  19364. * @returns {*}
  19365. */
  19366. Interop.prototype.toPlanB = function(desc) {
  19367. var self = this;
  19368. //#region Preliminary input validation.
  19369. if (typeof desc !== 'object' || desc === null ||
  19370. typeof desc.sdp !== 'string') {
  19371. console.warn('An empty description was passed as an argument.');
  19372. return desc;
  19373. }
  19374. // Objectify the SDP for easier manipulation.
  19375. var session = transform.parse(desc.sdp);
  19376. // If the SDP contains no media, there's nothing to transform.
  19377. if (typeof session.media === 'undefined' ||
  19378. !Array.isArray(session.media) || session.media.length === 0) {
  19379. console.warn('The description has no media.');
  19380. return desc;
  19381. }
  19382. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  19383. // SDP has a video, an audio and a data "channel" at most.
  19384. if (session.media.length <= 3 && session.media.every(function(m) {
  19385. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19386. })) {
  19387. console.warn('This description does not look like Unified Plan.');
  19388. return desc;
  19389. }
  19390. //#endregion
  19391. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  19392. var sdp = desc.sdp;
  19393. var rewrite = false;
  19394. for (var i = 0; i < session.media.length; i++) {
  19395. var uLine = session.media[i];
  19396. uLine.rtp.forEach(function(rtp) {
  19397. if (rtp.codec === 'NULL')
  19398. {
  19399. rewrite = true;
  19400. var offer = transform.parse(self.cache['offer']);
  19401. rtp.codec = offer.media[i].rtp[0].codec;
  19402. }
  19403. });
  19404. };
  19405. if (rewrite) {
  19406. sdp = transform.write(session);
  19407. }
  19408. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  19409. // -> Unified Plan transformation.
  19410. this.cache[desc.type] = sdp;
  19411. //#region Convert from Unified Plan to Plan B.
  19412. // We rebuild the session.media array.
  19413. var media = session.media;
  19414. session.media = [];
  19415. // Associative array that maps channel types to channel objects for fast
  19416. // access to channel objects by their type, e.g. type2bl['audio']->channel
  19417. // obj.
  19418. var type2bl = {};
  19419. // Used to build the group:BUNDLE value after the channels construction
  19420. // loop.
  19421. var types = [];
  19422. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  19423. media.forEach(function(uLine) {
  19424. // rtcp-mux is required in the Plan B SDP.
  19425. if ((typeof uLine.rtcpMux !== 'string' ||
  19426. uLine.rtcpMux !== 'rtcp-mux') &&
  19427. uLine.direction !== 'inactive') {
  19428. throw new Error('Cannot convert to Plan B because m-lines ' +
  19429. 'without the rtcp-mux attribute were found.');
  19430. }
  19431. if (uLine.type === 'application') {
  19432. session.media.push(uLine);
  19433. types.push(uLine.mid);
  19434. return;
  19435. }
  19436. // If we don't have a channel for this uLine.type, then use this
  19437. // uLine as the channel basis.
  19438. if (typeof type2bl[uLine.type] === 'undefined') {
  19439. type2bl[uLine.type] = uLine;
  19440. }
  19441. // Add sources to the channel and handle a=msid.
  19442. if (typeof uLine.sources === 'object') {
  19443. Object.keys(uLine.sources).forEach(function(ssrc) {
  19444. if (typeof type2bl[uLine.type].sources !== 'object')
  19445. type2bl[uLine.type].sources = {};
  19446. // Assign the sources to the channel.
  19447. type2bl[uLine.type].sources[ssrc] =
  19448. uLine.sources[ssrc];
  19449. if (typeof uLine.msid !== 'undefined') {
  19450. // In Plan B the msid is an SSRC attribute. Also, we don't
  19451. // care about the obsolete label and mslabel attributes.
  19452. //
  19453. // Note that it is not guaranteed that the uLine will
  19454. // have an msid. recvonly channels in particular don't have
  19455. // one.
  19456. type2bl[uLine.type].sources[ssrc].msid =
  19457. uLine.msid;
  19458. }
  19459. // NOTE ssrcs in ssrc groups will share msids, as
  19460. // draft-uberti-rtcweb-plan-00 mandates.
  19461. });
  19462. }
  19463. // Add ssrc groups to the channel.
  19464. if (typeof uLine.ssrcGroups !== 'undefined' &&
  19465. Array.isArray(uLine.ssrcGroups)) {
  19466. // Create the ssrcGroups array, if it's not defined.
  19467. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  19468. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  19469. type2bl[uLine.type].ssrcGroups = [];
  19470. }
  19471. type2bl[uLine.type].ssrcGroups =
  19472. type2bl[uLine.type].ssrcGroups.concat(
  19473. uLine.ssrcGroups);
  19474. }
  19475. if (type2bl[uLine.type] === uLine) {
  19476. // Copy ICE related stuff from the principal media line.
  19477. uLine.candidates = media[0].candidates;
  19478. uLine.iceUfrag = media[0].iceUfrag;
  19479. uLine.icePwd = media[0].icePwd;
  19480. uLine.fingerprint = media[0].fingerprint;
  19481. // Plan B mids are in ['audio', 'video', 'data']
  19482. uLine.mid = uLine.type;
  19483. // Plan B doesn't support/need the bundle-only attribute.
  19484. delete uLine.bundleOnly;
  19485. // In Plan B the msid is an SSRC attribute.
  19486. delete uLine.msid;
  19487. // Used to build the group:BUNDLE value after this loop.
  19488. types.push(uLine.type);
  19489. // Add the channel to the new media array.
  19490. session.media.push(uLine);
  19491. }
  19492. });
  19493. // We regenerate the BUNDLE group with the new mids.
  19494. session.groups.some(function(group) {
  19495. if (group.type === 'BUNDLE') {
  19496. group.mids = types.join(' ');
  19497. return true;
  19498. }
  19499. });
  19500. // msid semantic
  19501. session.msidSemantic = {
  19502. semantic: 'WMS',
  19503. token: '*'
  19504. };
  19505. var resStr = transform.write(session);
  19506. return new RTCSessionDescription({
  19507. type: desc.type,
  19508. sdp: resStr
  19509. });
  19510. //#endregion
  19511. };
  19512. /**
  19513. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  19514. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  19515. * to FF.
  19516. *
  19517. * @param desc
  19518. * @returns {*}
  19519. */
  19520. Interop.prototype.toUnifiedPlan = function(desc) {
  19521. var self = this;
  19522. //#region Preliminary input validation.
  19523. if (typeof desc !== 'object' || desc === null ||
  19524. typeof desc.sdp !== 'string') {
  19525. console.warn('An empty description was passed as an argument.');
  19526. return desc;
  19527. }
  19528. var session = transform.parse(desc.sdp);
  19529. // If the SDP contains no media, there's nothing to transform.
  19530. if (typeof session.media === 'undefined' ||
  19531. !Array.isArray(session.media) || session.media.length === 0) {
  19532. console.warn('The description has no media.');
  19533. return desc;
  19534. }
  19535. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  19536. // a video, an audio and a data "channel" at most.
  19537. if (session.media.length > 3 || !session.media.every(function(m) {
  19538. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19539. })) {
  19540. console.warn('This description does not look like Plan B.');
  19541. return desc;
  19542. }
  19543. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  19544. var mids = [];
  19545. session.media.forEach(function(m) {
  19546. mids.push(m.mid);
  19547. });
  19548. var hasBundle = false;
  19549. if (typeof session.groups !== 'undefined' &&
  19550. Array.isArray(session.groups)) {
  19551. hasBundle = session.groups.every(function(g) {
  19552. return g.type !== 'BUNDLE' ||
  19553. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  19554. });
  19555. }
  19556. if (!hasBundle) {
  19557. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  19558. " are not bundled were found.");
  19559. }
  19560. //#endregion
  19561. //#region Convert from Plan B to Unified Plan.
  19562. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  19563. // rebuild an equivalent Unified Plan offer/answer.
  19564. //
  19565. // For example, if this is a local answer (in Unified Plan style) that we
  19566. // convert to Plan B prior to handing it over to the application (the
  19567. // PeerConnection wrapper called us, for instance, after a successful
  19568. // createAnswer), we want to remember the m-line at which we've seen the
  19569. // (local) SSRC. That's because when the application wants to do call the
  19570. // SLD method, forcing us to do the inverse transformation (from Plan B to
  19571. // Unified Plan), we need to know to which m-line to assign the (local)
  19572. // SSRC. We also need to know all the other m-lines that the original
  19573. // answer had and include them in the transformed answer as well.
  19574. //
  19575. // Another example is if this is a remote offer that we convert to Plan B
  19576. // prior to giving it to the application, we want to remember the mid at
  19577. // which we've seen the (remote) SSRC.
  19578. //
  19579. // In the iteration that follows, we use the cached Unified Plan (if it
  19580. // exists) to assign mids to ssrcs.
  19581. var cached;
  19582. if (typeof this.cache[desc.type] !== 'undefined') {
  19583. cached = transform.parse(this.cache[desc.type]);
  19584. }
  19585. var recvonlySsrcs = {
  19586. audio: {},
  19587. video: {}
  19588. };
  19589. // A helper map that sends mids to m-line objects. We use it later to
  19590. // rebuild the Unified Plan style session.media array.
  19591. var mid2ul = {};
  19592. session.media.forEach(function(bLine) {
  19593. if ((typeof bLine.rtcpMux !== 'string' ||
  19594. bLine.rtcpMux !== 'rtcp-mux') &&
  19595. bLine.direction !== 'inactive') {
  19596. throw new Error("Cannot convert to Unified Plan because m-lines " +
  19597. "without the rtcp-mux attribute were found.");
  19598. }
  19599. if (bLine.type === 'application') {
  19600. mid2ul[bLine.mid] = bLine;
  19601. return;
  19602. }
  19603. // With rtcp-mux and bundle all the channels should have the same ICE
  19604. // stuff.
  19605. var sources = bLine.sources;
  19606. var ssrcGroups = bLine.ssrcGroups;
  19607. var candidates = bLine.candidates;
  19608. var iceUfrag = bLine.iceUfrag;
  19609. var icePwd = bLine.icePwd;
  19610. var fingerprint = bLine.fingerprint;
  19611. var port = bLine.port;
  19612. // We'll use the "bLine" object as a prototype for each new "mLine"
  19613. // that we create, but first we need to clean it up a bit.
  19614. delete bLine.sources;
  19615. delete bLine.ssrcGroups;
  19616. delete bLine.candidates;
  19617. delete bLine.iceUfrag;
  19618. delete bLine.icePwd;
  19619. delete bLine.fingerprint;
  19620. delete bLine.port;
  19621. delete bLine.mid;
  19622. // inverted ssrc group map
  19623. var ssrc2group = {};
  19624. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  19625. ssrcGroups.forEach(function (ssrcGroup) {
  19626. // TODO(gp) find out how to receive simulcast with FF. For the
  19627. // time being, hide it.
  19628. if (ssrcGroup.semantics === 'SIM') {
  19629. return;
  19630. }
  19631. // XXX This might brake if an SSRC is in more than one group
  19632. // for some reason.
  19633. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19634. Array.isArray(ssrcGroup.ssrcs)) {
  19635. ssrcGroup.ssrcs.forEach(function (ssrc) {
  19636. if (typeof ssrc2group[ssrc] === 'undefined') {
  19637. ssrc2group[ssrc] = [];
  19638. }
  19639. ssrc2group[ssrc].push(ssrcGroup);
  19640. });
  19641. }
  19642. });
  19643. }
  19644. // ssrc to m-line index.
  19645. var ssrc2ml = {};
  19646. if (typeof sources === 'object') {
  19647. // Explode the Plan B channel sources with one m-line per source.
  19648. Object.keys(sources).forEach(function(ssrc) {
  19649. // The (unified) m-line for this SSRC. We either create it from
  19650. // scratch or, if it's a grouped SSRC, we re-use a related
  19651. // mline. In other words, if the source is grouped with another
  19652. // source, put the two together in the same m-line.
  19653. var uLine;
  19654. // We assume here that we are the answerer in the O/A, so any
  19655. // offers which we translate come from the remote side, while
  19656. // answers are local. So the check below is to make that we
  19657. // handle receive-only SSRCs in a special way only if they come
  19658. // from the remote side.
  19659. if (desc.type==='offer') {
  19660. // We want to detect SSRCs which are used by a remote peer
  19661. // in an m-line with direction=recvonly (i.e. they are
  19662. // being used for RTCP only).
  19663. // This information would have gotten lost if the remote
  19664. // peer used Unified Plan and their local description was
  19665. // translated to Plan B. So we use the lack of an MSID
  19666. // attribute to deduce a "receive only" SSRC.
  19667. if (!sources[ssrc].msid) {
  19668. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  19669. // Receive-only SSRCs must not create new m-lines. We
  19670. // will assign them to an existing m-line later.
  19671. return;
  19672. }
  19673. }
  19674. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  19675. Array.isArray(ssrc2group[ssrc])) {
  19676. ssrc2group[ssrc].some(function (ssrcGroup) {
  19677. // ssrcGroup.ssrcs *is* an Array, no need to check
  19678. // again here.
  19679. return ssrcGroup.ssrcs.some(function (related) {
  19680. if (typeof ssrc2ml[related] === 'object') {
  19681. uLine = ssrc2ml[related];
  19682. return true;
  19683. }
  19684. });
  19685. });
  19686. }
  19687. if (typeof uLine === 'object') {
  19688. // the m-line already exists. Just add the source.
  19689. uLine.sources[ssrc] = sources[ssrc];
  19690. delete sources[ssrc].msid;
  19691. } else {
  19692. // Use the "bLine" as a prototype for the "uLine".
  19693. uLine = Object.create(bLine);
  19694. ssrc2ml[ssrc] = uLine;
  19695. if (typeof sources[ssrc].msid !== 'undefined') {
  19696. // Assign the msid of the source to the m-line. Note
  19697. // that it is not guaranteed that the source will have
  19698. // msid. In particular "recvonly" sources don't have an
  19699. // msid. Note that "recvonly" is a term only defined
  19700. // for m-lines.
  19701. uLine.msid = sources[ssrc].msid;
  19702. uLine.direction = 'sendrecv';
  19703. delete sources[ssrc].msid;
  19704. }
  19705. // We assign one SSRC per media line.
  19706. uLine.sources = {};
  19707. uLine.sources[ssrc] = sources[ssrc];
  19708. uLine.ssrcGroups = ssrc2group[ssrc];
  19709. // Use the cached Unified Plan SDP (if it exists) to assign
  19710. // SSRCs to mids.
  19711. if (typeof cached !== 'undefined' &&
  19712. typeof cached.media !== 'undefined' &&
  19713. Array.isArray(cached.media)) {
  19714. cached.media.forEach(function (m) {
  19715. if (typeof m.sources === 'object') {
  19716. Object.keys(m.sources).forEach(function (s) {
  19717. if (s === ssrc) {
  19718. uLine.mid = m.mid;
  19719. }
  19720. });
  19721. }
  19722. });
  19723. }
  19724. if (typeof uLine.mid === 'undefined') {
  19725. // If this is an SSRC that we see for the first time
  19726. // assign it a new mid. This is typically the case when
  19727. // this method is called to transform a remote
  19728. // description for the first time or when there is a
  19729. // new SSRC in the remote description because a new
  19730. // peer has joined the conference. Local SSRCs should
  19731. // have already been added to the map in the toPlanB
  19732. // method.
  19733. //
  19734. // Because FF generates answers in Unified Plan style,
  19735. // we MUST already have a cached answer with all the
  19736. // local SSRCs mapped to some m-line/mid.
  19737. if (desc.type === 'answer') {
  19738. throw new Error("An unmapped SSRC was found.");
  19739. }
  19740. uLine.mid = [bLine.type, '-', ssrc].join('');
  19741. }
  19742. // Include the candidates in the 1st media line.
  19743. uLine.candidates = candidates;
  19744. uLine.iceUfrag = iceUfrag;
  19745. uLine.icePwd = icePwd;
  19746. uLine.fingerprint = fingerprint;
  19747. uLine.port = port;
  19748. mid2ul[uLine.mid] = uLine;
  19749. }
  19750. });
  19751. }
  19752. });
  19753. // Rebuild the media array in the right order and add the missing mLines
  19754. // (missing from the Plan B SDP).
  19755. session.media = [];
  19756. mids = []; // reuse
  19757. if (desc.type === 'answer') {
  19758. // The media lines in the answer must match the media lines in the
  19759. // offer. The order is important too. Here we assume that Firefox is
  19760. // the answerer, so we merely have to use the reconstructed (unified)
  19761. // answer to update the cached (unified) answer accordingly.
  19762. //
  19763. // In the general case, one would have to use the cached (unified)
  19764. // offer to find the m-lines that are missing from the reconstructed
  19765. // answer, potentially grabbing them from the cached (unified) answer.
  19766. // One has to be careful with this approach because inactive m-lines do
  19767. // not always have an mid, making it tricky (impossible?) to find where
  19768. // exactly and which m-lines are missing from the reconstructed answer.
  19769. for (var i = 0; i < cached.media.length; i++) {
  19770. var uLine = cached.media[i];
  19771. if (typeof mid2ul[uLine.mid] === 'undefined') {
  19772. // The mid isn't in the reconstructed (unified) answer.
  19773. // This is either a (unified) m-line containing a remote
  19774. // track only, or a (unified) m-line containing a remote
  19775. // track and a local track that has been removed.
  19776. // In either case, it MUST exist in the cached
  19777. // (unified) answer.
  19778. //
  19779. // In case this is a removed local track, clean-up
  19780. // the (unified) m-line and make sure it's 'recvonly' or
  19781. // 'inactive'.
  19782. delete uLine.msid;
  19783. delete uLine.sources;
  19784. delete uLine.ssrcGroups;
  19785. if (!uLine.direction
  19786. || uLine.direction === 'sendrecv')
  19787. uLine.direction = 'recvonly';
  19788. else if (uLine.direction === 'sendonly')
  19789. uLine.direction = 'inactive';
  19790. } else {
  19791. // This is an (unified) m-line/channel that contains a local
  19792. // track (sendrecv or sendonly channel) or it's a unified
  19793. // recvonly m-line/channel. In either case, since we're
  19794. // going from PlanB -> Unified Plan this m-line MUST
  19795. // exist in the cached answer.
  19796. }
  19797. session.media.push(uLine);
  19798. if (typeof uLine.mid === 'string') {
  19799. // inactive lines don't/may not have an mid.
  19800. mids.push(uLine.mid);
  19801. }
  19802. }
  19803. } else {
  19804. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  19805. // under any circumstances. If we are no longer interested in sending a
  19806. // track, we just remove the msid and ssrc attributes and set it to
  19807. // either a=recvonly (as the reofferer, we must use recvonly if the
  19808. // other side was previously sending on the m-section, but we can also
  19809. // leave the possibility open if it wasn't previously in use), or
  19810. // a=inactive.
  19811. if (typeof cached !== 'undefined' &&
  19812. typeof cached.media !== 'undefined' &&
  19813. Array.isArray(cached.media)) {
  19814. cached.media.forEach(function(uLine) {
  19815. mids.push(uLine.mid);
  19816. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  19817. session.media.push(mid2ul[uLine.mid]);
  19818. } else {
  19819. delete uLine.msid;
  19820. delete uLine.sources;
  19821. delete uLine.ssrcGroups;
  19822. if (!uLine.direction
  19823. || uLine.direction === 'sendrecv')
  19824. uLine.direction = 'recvonly';
  19825. if (!uLine.direction
  19826. || uLine.direction === 'sendonly')
  19827. uLine.direction = 'inactive';
  19828. session.media.push(uLine);
  19829. }
  19830. });
  19831. }
  19832. // Add all the remaining (new) m-lines of the transformed SDP.
  19833. Object.keys(mid2ul).forEach(function(mid) {
  19834. if (mids.indexOf(mid) === -1) {
  19835. mids.push(mid);
  19836. if (mid2ul[mid].direction === 'recvonly') {
  19837. // This is a remote recvonly channel. Add its SSRC to the
  19838. // appropriate sendrecv or sendonly channel.
  19839. // TODO(gp) what if we don't have sendrecv/sendonly
  19840. // channel?
  19841. session.media.some(function (uLine) {
  19842. if ((uLine.direction === 'sendrecv' ||
  19843. uLine.direction === 'sendonly') &&
  19844. uLine.type === mid2ul[mid].type) {
  19845. // mid2ul[mid] shouldn't have any ssrc-groups
  19846. Object.keys(mid2ul[mid].sources).forEach(
  19847. function (ssrc) {
  19848. uLine.sources[ssrc] =
  19849. mid2ul[mid].sources[ssrc];
  19850. });
  19851. return true;
  19852. }
  19853. });
  19854. } else {
  19855. session.media.push(mid2ul[mid]);
  19856. }
  19857. }
  19858. });
  19859. }
  19860. // After we have constructed the Plan Unified m-lines we can figure out
  19861. // where (in which m-line) to place the 'recvonly SSRCs'.
  19862. // Note: we assume here that we are the answerer in the O/A, so any offers
  19863. // which we translate come from the remote side, while answers are local
  19864. // (and so our last local description is cached as an 'answer').
  19865. ["audio", "video"].forEach(function (type) {
  19866. if (!session || !session.media || !Array.isArray(session.media))
  19867. return;
  19868. var idx = null;
  19869. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19870. idx = self.getFirstSendingIndexFromAnswer(type);
  19871. if (idx === null){
  19872. // If this is the first offer we receive, we don't have a
  19873. // cached answer. Assume that we will be sending media using
  19874. // the first m-line for each media type.
  19875. for (var i = 0; i < session.media.length; i++) {
  19876. if (session.media[i].type === type) {
  19877. idx = i;
  19878. break;
  19879. }
  19880. }
  19881. }
  19882. }
  19883. if (idx && session.media.length > idx) {
  19884. var mLine = session.media[idx];
  19885. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19886. if (mLine.sources && mLine.sources[ssrc]) {
  19887. console.warn("Replacing an existing SSRC.");
  19888. }
  19889. if (!mLine.sources) {
  19890. mLine.sources = {};
  19891. }
  19892. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19893. });
  19894. }
  19895. });
  19896. // We regenerate the BUNDLE group (since we regenerated the mids)
  19897. session.groups.some(function(group) {
  19898. if (group.type === 'BUNDLE') {
  19899. group.mids = mids.join(' ');
  19900. return true;
  19901. }
  19902. });
  19903. // msid semantic
  19904. session.msidSemantic = {
  19905. semantic: 'WMS',
  19906. token: '*'
  19907. };
  19908. var resStr = transform.write(session);
  19909. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19910. // function.
  19911. this.cache[desc.type] = resStr;
  19912. return new RTCSessionDescription({
  19913. type: desc.type,
  19914. sdp: resStr
  19915. });
  19916. //#endregion
  19917. };
  19918. },{"./array-equals":65,"./transform":68}],68:[function(require,module,exports){
  19919. /* Copyright @ 2015 Atlassian Pty Ltd
  19920. *
  19921. * Licensed under the Apache License, Version 2.0 (the "License");
  19922. * you may not use this file except in compliance with the License.
  19923. * You may obtain a copy of the License at
  19924. *
  19925. * http://www.apache.org/licenses/LICENSE-2.0
  19926. *
  19927. * Unless required by applicable law or agreed to in writing, software
  19928. * distributed under the License is distributed on an "AS IS" BASIS,
  19929. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19930. * See the License for the specific language governing permissions and
  19931. * limitations under the License.
  19932. */
  19933. var transform = require('sdp-transform');
  19934. exports.write = function(session, opts) {
  19935. if (typeof session !== 'undefined' &&
  19936. typeof session.media !== 'undefined' &&
  19937. Array.isArray(session.media)) {
  19938. session.media.forEach(function (mLine) {
  19939. // expand sources to ssrcs
  19940. if (typeof mLine.sources !== 'undefined' &&
  19941. Object.keys(mLine.sources).length !== 0) {
  19942. mLine.ssrcs = [];
  19943. Object.keys(mLine.sources).forEach(function (ssrc) {
  19944. var source = mLine.sources[ssrc];
  19945. Object.keys(source).forEach(function (attribute) {
  19946. mLine.ssrcs.push({
  19947. id: ssrc,
  19948. attribute: attribute,
  19949. value: source[attribute]
  19950. });
  19951. });
  19952. });
  19953. delete mLine.sources;
  19954. }
  19955. // join ssrcs in ssrc groups
  19956. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19957. Array.isArray(mLine.ssrcGroups)) {
  19958. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19959. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19960. Array.isArray(ssrcGroup.ssrcs)) {
  19961. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19962. }
  19963. });
  19964. }
  19965. });
  19966. }
  19967. // join group mids
  19968. if (typeof session !== 'undefined' &&
  19969. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19970. session.groups.forEach(function (g) {
  19971. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19972. g.mids = g.mids.join(' ');
  19973. }
  19974. });
  19975. }
  19976. return transform.write(session, opts);
  19977. };
  19978. exports.parse = function(sdp) {
  19979. var session = transform.parse(sdp);
  19980. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19981. Array.isArray(session.media)) {
  19982. session.media.forEach(function (mLine) {
  19983. // group sources attributes by ssrc
  19984. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19985. mLine.sources = {};
  19986. mLine.ssrcs.forEach(function (ssrc) {
  19987. if (!mLine.sources[ssrc.id])
  19988. mLine.sources[ssrc.id] = {};
  19989. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19990. });
  19991. delete mLine.ssrcs;
  19992. }
  19993. // split ssrcs in ssrc groups
  19994. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19995. Array.isArray(mLine.ssrcGroups)) {
  19996. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19997. if (typeof ssrcGroup.ssrcs === 'string') {
  19998. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19999. }
  20000. });
  20001. }
  20002. });
  20003. }
  20004. // split group mids
  20005. if (typeof session !== 'undefined' &&
  20006. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20007. session.groups.forEach(function (g) {
  20008. if (typeof g.mids === 'string') {
  20009. g.mids = g.mids.split(' ');
  20010. }
  20011. });
  20012. }
  20013. return session;
  20014. };
  20015. },{"sdp-transform":76}],69:[function(require,module,exports){
  20016. /* Copyright @ 2015 Atlassian Pty Ltd
  20017. *
  20018. * Licensed under the Apache License, Version 2.0 (the "License");
  20019. * you may not use this file except in compliance with the License.
  20020. * You may obtain a copy of the License at
  20021. *
  20022. * http://www.apache.org/licenses/LICENSE-2.0
  20023. *
  20024. * Unless required by applicable law or agreed to in writing, software
  20025. * distributed under the License is distributed on an "AS IS" BASIS,
  20026. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20027. * See the License for the specific language governing permissions and
  20028. * limitations under the License.
  20029. */
  20030. var transform = require('sdp-transform');
  20031. var transformUtils = require('./transform-utils');
  20032. var parseSsrcs = transformUtils.parseSsrcs;
  20033. var writeSsrcs = transformUtils.writeSsrcs;
  20034. //region Constants
  20035. var DEFAULT_NUM_OF_LAYERS = 3;
  20036. //endregion
  20037. //region Ctor
  20038. function Simulcast(options) {
  20039. this.options = options ? options : {};
  20040. if (!this.options.numOfLayers) {
  20041. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  20042. }
  20043. this.layers = [];
  20044. }
  20045. //endregion
  20046. //region Stateless private utility functions
  20047. /**
  20048. * Returns a random integer between min (included) and max (excluded)
  20049. * Using Math.round() gives a non-uniform distribution!
  20050. * @returns {number}
  20051. */
  20052. function generateSSRC() {
  20053. var min = 0, max = 0xffffffff;
  20054. return Math.floor(Math.random() * (max - min)) + min;
  20055. };
  20056. function processVideo(session, action) {
  20057. if (session == null || !Array.isArray(session.media)) {
  20058. return;
  20059. }
  20060. session.media.forEach(function (mLine) {
  20061. if (mLine.type === 'video') {
  20062. action(mLine);
  20063. }
  20064. });
  20065. }
  20066. function validateDescription(desc)
  20067. {
  20068. return desc && desc != null
  20069. && desc.type && desc.type != ''
  20070. && desc.sdp && desc.sdp != '';
  20071. }
  20072. function explodeRemoteSimulcast(mLine) {
  20073. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20074. return;
  20075. }
  20076. var sources = parseSsrcs(mLine);
  20077. var order = [];
  20078. // Find the SIM group and explode its sources.
  20079. var j = mLine.ssrcGroups.length;
  20080. while (j--) {
  20081. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  20082. continue;
  20083. }
  20084. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  20085. for (var i = 0; i < simulcastSsrcs.length; i++) {
  20086. var ssrc = simulcastSsrcs[i];
  20087. order.push(ssrc);
  20088. var parts = sources[ssrc].msid.split(' ');
  20089. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  20090. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  20091. // Remove all the groups that this SSRC participates in.
  20092. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20093. if (relatedGroup.semantics === 'SIM') {
  20094. return;
  20095. }
  20096. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20097. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20098. return;
  20099. }
  20100. // Nuke all the related SSRCs.
  20101. relatedSsrcs.forEach(function (relatedSSRC) {
  20102. sources[relatedSSRC].msid = sources[ssrc].msid;
  20103. sources[relatedSSRC].cname = sources[ssrc].cname;
  20104. if (relatedSSRC !== ssrc) {
  20105. order.push(relatedSSRC);
  20106. }
  20107. });
  20108. // Schedule the related group for nuking.
  20109. })
  20110. }
  20111. mLine.ssrcs = writeSsrcs(sources, order);
  20112. mLine.ssrcGroups.splice(j, 1);
  20113. };
  20114. }
  20115. function implodeRemoteSimulcast(mLine) {
  20116. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20117. console.debug('Halt: There are no SSRC groups in the remote ' +
  20118. 'description.');
  20119. return;
  20120. }
  20121. var sources = parseSsrcs(mLine);
  20122. // Find the SIM group and nuke it.
  20123. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  20124. if (simulcastGroup.semantics !== 'SIM') {
  20125. return;
  20126. }
  20127. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  20128. // Schedule the SIM group for nuking.
  20129. simulcastGroup.nuke = true;
  20130. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  20131. // Nuke all the higher layer SSRCs.
  20132. for (var i = 1; i < simulcastSsrcs.length; i++) {
  20133. var ssrc = simulcastSsrcs[i];
  20134. delete sources[ssrc];
  20135. // Remove all the groups that this SSRC participates in.
  20136. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20137. if (relatedGroup.semantics === 'SIM') {
  20138. return;
  20139. }
  20140. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20141. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20142. return;
  20143. }
  20144. // Nuke all the related SSRCs.
  20145. relatedSsrcs.forEach(function (relatedSSRC) {
  20146. delete sources[relatedSSRC];
  20147. });
  20148. // Schedule the related group for nuking.
  20149. relatedGroup.nuke = true;
  20150. })
  20151. }
  20152. return;
  20153. });
  20154. mLine.ssrcs = writeSsrcs(sources);
  20155. // Nuke all the scheduled groups.
  20156. var i = mLine.ssrcGroups.length;
  20157. while (i--) {
  20158. if (mLine.ssrcGroups[i].nuke) {
  20159. mLine.ssrcGroups.splice(i, 1);
  20160. }
  20161. }
  20162. }
  20163. function removeGoogConference(mLine) {
  20164. if (!mLine || !Array.isArray(mLine.invalid)) {
  20165. return;
  20166. }
  20167. var i = mLine.invalid.length;
  20168. while (i--) {
  20169. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  20170. mLine.invalid.splice(i, 1);
  20171. }
  20172. }
  20173. }
  20174. function assertGoogConference(mLine) {
  20175. if (!mLine) {
  20176. return;
  20177. }
  20178. if (!Array.isArray(mLine.invalid)) {
  20179. mLine.invalid = [];
  20180. }
  20181. if (!mLine.invalid.some(
  20182. function (i) { return i.value === 'x-google-flag:conference' })) {
  20183. mLine.invalid.push({'value': 'x-google-flag:conference'});
  20184. }
  20185. }
  20186. //endregion
  20187. //region "Private" functions
  20188. /**
  20189. *
  20190. * @param mLine
  20191. * @private
  20192. */
  20193. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  20194. if (!mLine || mLine.type !== 'video') {
  20195. return;
  20196. }
  20197. var sources = parseSsrcs(mLine);
  20198. if (Object.keys(sources).length === 0) {
  20199. // no sources, disable simulcast.
  20200. if (this.layers.length !== 0) {
  20201. this.layers = [];
  20202. }
  20203. return;
  20204. }
  20205. // find the base layer (we'll reuse its msid and cname).
  20206. var baseLayerSSRC = Object.keys(sources)[0];
  20207. var baseLayer = sources[baseLayerSSRC];
  20208. // todo(gp) handle screen sharing.
  20209. // check if base CNAME has changed and reinitialise layers.
  20210. if (this.layers.length > 0
  20211. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  20212. this.layers = [];
  20213. }
  20214. // (re)initialise layers
  20215. if (this.layers.length < 1) {
  20216. // first push the base layer.
  20217. this.layers.push({
  20218. ssrc: baseLayerSSRC,
  20219. msid: baseLayer.msid,
  20220. cname: baseLayer.cname
  20221. });
  20222. var rtx = false; // RFC 4588
  20223. if (Array.isArray(mLine.rtp)) {
  20224. rtx = mLine.rtp.some(
  20225. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  20226. }
  20227. if (rtx) {
  20228. this.layers[0].rtx = generateSSRC();
  20229. }
  20230. // now push additional layers.
  20231. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  20232. var layer = { ssrc: generateSSRC() };
  20233. if (rtx) {
  20234. layer.rtx = generateSSRC();
  20235. }
  20236. this.layers.push(layer);
  20237. }
  20238. }
  20239. };
  20240. /**
  20241. *
  20242. * @param mLine
  20243. * @private
  20244. */
  20245. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  20246. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  20247. var sources = {};
  20248. var msid = this.layers[0].msid;
  20249. var cname = this.layers[0].cname;
  20250. var simulcastSsrcs = [];
  20251. var ssrcGroups = [];
  20252. for (var i = 0; i < this.layers.length; i++) {
  20253. var layer = this.layers[i];
  20254. sources[layer.ssrc] = { msid: msid, cname: cname };
  20255. simulcastSsrcs.push(layer.ssrc);
  20256. if (layer.rtx) {
  20257. sources[layer.rtx] = {
  20258. msid: msid,
  20259. cname: cname
  20260. }
  20261. ssrcGroups.push({
  20262. semantics: 'FID',
  20263. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  20264. });
  20265. }
  20266. }
  20267. ssrcGroups.push({
  20268. semantics: 'SIM',
  20269. ssrcs: simulcastSsrcs.join(' ')
  20270. });
  20271. mLine.ssrcGroups = ssrcGroups;
  20272. mLine.ssrcs = writeSsrcs(sources);
  20273. }
  20274. }
  20275. //endregion
  20276. //region "Public" functions
  20277. Simulcast.prototype.isSupported = function () {
  20278. return window.chrome;
  20279. // TODO this needs improvements. For example I doubt that Chrome in Android
  20280. // has simulcast support. Also, only recent versions of Chromium have native
  20281. // simulcast support.
  20282. }
  20283. /**
  20284. *
  20285. * @param desc
  20286. * @returns {RTCSessionDescription}
  20287. */
  20288. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  20289. if (!validateDescription(desc)) {
  20290. return desc;
  20291. }
  20292. var session = transform.parse(desc.sdp);
  20293. var self = this;
  20294. processVideo(session, function (mLine) {
  20295. // Handle simulcast reception.
  20296. if (self.options.explodeRemoteSimulcast) {
  20297. explodeRemoteSimulcast(mLine);
  20298. } else {
  20299. implodeRemoteSimulcast(mLine);
  20300. }
  20301. // If native simulcast is enabled, we must append the x-goog-conference
  20302. // attribute to the SDP.
  20303. if (self.layers.length < 1) {
  20304. removeGoogConference(mLine);
  20305. } else {
  20306. assertGoogConference(mLine);
  20307. }
  20308. });
  20309. return new RTCSessionDescription({
  20310. type: desc.type,
  20311. sdp: transform.write(session)
  20312. });
  20313. };
  20314. /**
  20315. *
  20316. * @param desc
  20317. * @returns {RTCSessionDescription}
  20318. */
  20319. Simulcast.prototype.mungeLocalDescription = function (desc) {
  20320. if (!validateDescription(desc) || !this.isSupported()) {
  20321. return desc;
  20322. }
  20323. var session = transform.parse(desc.sdp);
  20324. var self = this;
  20325. processVideo(session, function (mLine) {
  20326. // Initialize native simulcast layers, if not already done.
  20327. self._maybeInitializeLayers(mLine);
  20328. // Update the SDP with the simulcast layers.
  20329. self._restoreSimulcastView(mLine);
  20330. });
  20331. return new RTCSessionDescription({
  20332. type: desc.type,
  20333. sdp: transform.write(session)
  20334. });
  20335. };
  20336. //endregion
  20337. module.exports = Simulcast;
  20338. },{"./transform-utils":70,"sdp-transform":72}],70:[function(require,module,exports){
  20339. /* Copyright @ 2015 Atlassian Pty Ltd
  20340. *
  20341. * Licensed under the Apache License, Version 2.0 (the "License");
  20342. * you may not use this file except in compliance with the License.
  20343. * You may obtain a copy of the License at
  20344. *
  20345. * http://www.apache.org/licenses/LICENSE-2.0
  20346. *
  20347. * Unless required by applicable law or agreed to in writing, software
  20348. * distributed under the License is distributed on an "AS IS" BASIS,
  20349. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20350. * See the License for the specific language governing permissions and
  20351. * limitations under the License.
  20352. */
  20353. exports.writeSsrcs = function(sources, order) {
  20354. var ssrcs = [];
  20355. // expand sources to ssrcs
  20356. if (typeof sources !== 'undefined' &&
  20357. Object.keys(sources).length !== 0) {
  20358. if (Array.isArray(order)) {
  20359. for (var i = 0; i < order.length; i++) {
  20360. var ssrc = order[i];
  20361. var source = sources[ssrc];
  20362. Object.keys(source).forEach(function (attribute) {
  20363. ssrcs.push({
  20364. id: ssrc,
  20365. attribute: attribute,
  20366. value: source[attribute]
  20367. });
  20368. });
  20369. }
  20370. } else {
  20371. Object.keys(sources).forEach(function (ssrc) {
  20372. var source = sources[ssrc];
  20373. Object.keys(source).forEach(function (attribute) {
  20374. ssrcs.push({
  20375. id: ssrc,
  20376. attribute: attribute,
  20377. value: source[attribute]
  20378. });
  20379. });
  20380. });
  20381. }
  20382. }
  20383. return ssrcs;
  20384. };
  20385. exports.parseSsrcs = function (mLine) {
  20386. var sources = {};
  20387. // group sources attributes by ssrc.
  20388. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20389. mLine.ssrcs.forEach(function (ssrc) {
  20390. if (!sources[ssrc.id])
  20391. sources[ssrc.id] = {};
  20392. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20393. });
  20394. }
  20395. return sources;
  20396. };
  20397. },{}],71:[function(require,module,exports){
  20398. var grammar = module.exports = {
  20399. v: [{
  20400. name: 'version',
  20401. reg: /^(\d*)$/
  20402. }],
  20403. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20404. // NB: sessionId will be a String in most cases because it is huge
  20405. name: 'origin',
  20406. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20407. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20408. format: "%s %s %d %s IP%d %s"
  20409. }],
  20410. // default parsing of these only (though some of these feel outdated)
  20411. s: [{ name: 'name' }],
  20412. i: [{ name: 'description' }],
  20413. u: [{ name: 'uri' }],
  20414. e: [{ name: 'email' }],
  20415. p: [{ name: 'phone' }],
  20416. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20417. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20418. //k: [{}], // outdated thing ignored
  20419. t: [{ //t=0 0
  20420. name: 'timing',
  20421. reg: /^(\d*) (\d*)/,
  20422. names: ['start', 'stop'],
  20423. format: "%d %d"
  20424. }],
  20425. c: [{ //c=IN IP4 10.47.197.26
  20426. name: 'connection',
  20427. reg: /^IN IP(\d) (\S*)/,
  20428. names: ['version', 'ip'],
  20429. format: "IN IP%d %s"
  20430. }],
  20431. b: [{ //b=AS:4000
  20432. push: 'bandwidth',
  20433. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20434. names: ['type', 'limit'],
  20435. format: "%s:%s"
  20436. }],
  20437. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20438. // NB: special - pushes to session
  20439. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20440. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20441. names: ['type', 'port', 'protocol', 'payloads'],
  20442. format: "%s %d %s %s"
  20443. }],
  20444. a: [
  20445. { //a=rtpmap:110 opus/48000/2
  20446. push: 'rtp',
  20447. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  20448. names: ['payload', 'codec', 'rate', 'encoding'],
  20449. format: function (o) {
  20450. return (o.encoding) ?
  20451. "rtpmap:%d %s/%s/%s":
  20452. "rtpmap:%d %s/%s";
  20453. }
  20454. },
  20455. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20456. push: 'fmtp',
  20457. reg: /^fmtp:(\d*) (\S*)/,
  20458. names: ['payload', 'config'],
  20459. format: "fmtp:%d %s"
  20460. },
  20461. { //a=control:streamid=0
  20462. name: 'control',
  20463. reg: /^control:(.*)/,
  20464. format: "control:%s"
  20465. },
  20466. { //a=rtcp:65179 IN IP4 193.84.77.194
  20467. name: 'rtcp',
  20468. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20469. names: ['port', 'netType', 'ipVer', 'address'],
  20470. format: function (o) {
  20471. return (o.address != null) ?
  20472. "rtcp:%d %s IP%d %s":
  20473. "rtcp:%d";
  20474. }
  20475. },
  20476. { //a=rtcp-fb:98 trr-int 100
  20477. push: 'rtcpFbTrrInt',
  20478. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20479. names: ['payload', 'value'],
  20480. format: "rtcp-fb:%d trr-int %d"
  20481. },
  20482. { //a=rtcp-fb:98 nack rpsi
  20483. push: 'rtcpFb',
  20484. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20485. names: ['payload', 'type', 'subtype'],
  20486. format: function (o) {
  20487. return (o.subtype != null) ?
  20488. "rtcp-fb:%s %s %s":
  20489. "rtcp-fb:%s %s";
  20490. }
  20491. },
  20492. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20493. //a=extmap:1/recvonly URI-gps-string
  20494. push: 'ext',
  20495. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20496. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20497. format: function (o) {
  20498. return (o.config != null) ?
  20499. "extmap:%s %s %s":
  20500. "extmap:%s %s";
  20501. }
  20502. },
  20503. {
  20504. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20505. push: 'crypto',
  20506. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20507. names: ['id', 'suite', 'config', 'sessionConfig'],
  20508. format: function (o) {
  20509. return (o.sessionConfig != null) ?
  20510. "crypto:%d %s %s %s":
  20511. "crypto:%d %s %s";
  20512. }
  20513. },
  20514. { //a=setup:actpass
  20515. name: 'setup',
  20516. reg: /^setup:(\w*)/,
  20517. format: "setup:%s"
  20518. },
  20519. { //a=mid:1
  20520. name: 'mid',
  20521. reg: /^mid:([^\s]*)/,
  20522. format: "mid:%s"
  20523. },
  20524. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20525. name: 'msid',
  20526. reg: /^msid:(.*)/,
  20527. format: "msid:%s"
  20528. },
  20529. { //a=ptime:20
  20530. name: 'ptime',
  20531. reg: /^ptime:(\d*)/,
  20532. format: "ptime:%d"
  20533. },
  20534. { //a=maxptime:60
  20535. name: 'maxptime',
  20536. reg: /^maxptime:(\d*)/,
  20537. format: "maxptime:%d"
  20538. },
  20539. { //a=sendrecv
  20540. name: 'direction',
  20541. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20542. },
  20543. { //a=ice-lite
  20544. name: 'icelite',
  20545. reg: /^(ice-lite)/
  20546. },
  20547. { //a=ice-ufrag:F7gI
  20548. name: 'iceUfrag',
  20549. reg: /^ice-ufrag:(\S*)/,
  20550. format: "ice-ufrag:%s"
  20551. },
  20552. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20553. name: 'icePwd',
  20554. reg: /^ice-pwd:(\S*)/,
  20555. format: "ice-pwd:%s"
  20556. },
  20557. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20558. name: 'fingerprint',
  20559. reg: /^fingerprint:(\S*) (\S*)/,
  20560. names: ['type', 'hash'],
  20561. format: "fingerprint:%s %s"
  20562. },
  20563. {
  20564. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20565. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20566. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20567. push:'candidates',
  20568. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  20569. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  20570. format: function (o) {
  20571. var str = "candidate:%s %d %s %d %s %d typ %s";
  20572. // NB: candidate has two optional chunks, so %void middle one if it's missing
  20573. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20574. if (o.generation != null) {
  20575. str += " generation %d";
  20576. }
  20577. return str;
  20578. }
  20579. },
  20580. { //a=end-of-candidates (keep after the candidates line for readability)
  20581. name: 'endOfCandidates',
  20582. reg: /^(end-of-candidates)/
  20583. },
  20584. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20585. name: 'remoteCandidates',
  20586. reg: /^remote-candidates:(.*)/,
  20587. format: "remote-candidates:%s"
  20588. },
  20589. { //a=ice-options:google-ice
  20590. name: 'iceOptions',
  20591. reg: /^ice-options:(\S*)/,
  20592. format: "ice-options:%s"
  20593. },
  20594. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20595. push: "ssrcs",
  20596. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20597. names: ['id', 'attribute', 'value'],
  20598. format: "ssrc:%d %s:%s"
  20599. },
  20600. { //a=ssrc-group:FEC 1 2
  20601. push: "ssrcGroups",
  20602. reg: /^ssrc-group:(\w*) (.*)/,
  20603. names: ['semantics', 'ssrcs'],
  20604. format: "ssrc-group:%s %s"
  20605. },
  20606. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20607. name: "msidSemantic",
  20608. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20609. names: ['semantic', 'token'],
  20610. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20611. },
  20612. { //a=group:BUNDLE audio video
  20613. push: 'groups',
  20614. reg: /^group:(\w*) (.*)/,
  20615. names: ['type', 'mids'],
  20616. format: "group:%s %s"
  20617. },
  20618. { //a=rtcp-mux
  20619. name: 'rtcpMux',
  20620. reg: /^(rtcp-mux)/
  20621. },
  20622. { //a=rtcp-rsize
  20623. name: 'rtcpRsize',
  20624. reg: /^(rtcp-rsize)/
  20625. },
  20626. { // any a= that we don't understand is kepts verbatim on media.invalid
  20627. push: 'invalid',
  20628. names: ["value"]
  20629. }
  20630. ]
  20631. };
  20632. // set sensible defaults to avoid polluting the grammar with boring details
  20633. Object.keys(grammar).forEach(function (key) {
  20634. var objs = grammar[key];
  20635. objs.forEach(function (obj) {
  20636. if (!obj.reg) {
  20637. obj.reg = /(.*)/;
  20638. }
  20639. if (!obj.format) {
  20640. obj.format = "%s";
  20641. }
  20642. });
  20643. });
  20644. },{}],72:[function(require,module,exports){
  20645. var parser = require('./parser');
  20646. var writer = require('./writer');
  20647. exports.write = writer;
  20648. exports.parse = parser.parse;
  20649. exports.parseFmtpConfig = parser.parseFmtpConfig;
  20650. exports.parsePayloads = parser.parsePayloads;
  20651. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  20652. },{"./parser":73,"./writer":74}],73:[function(require,module,exports){
  20653. var toIntIfInt = function (v) {
  20654. return String(Number(v)) === v ? Number(v) : v;
  20655. };
  20656. var attachProperties = function (match, location, names, rawName) {
  20657. if (rawName && !names) {
  20658. location[rawName] = toIntIfInt(match[1]);
  20659. }
  20660. else {
  20661. for (var i = 0; i < names.length; i += 1) {
  20662. if (match[i+1] != null) {
  20663. location[names[i]] = toIntIfInt(match[i+1]);
  20664. }
  20665. }
  20666. }
  20667. };
  20668. var parseReg = function (obj, location, content) {
  20669. var needsBlank = obj.name && obj.names;
  20670. if (obj.push && !location[obj.push]) {
  20671. location[obj.push] = [];
  20672. }
  20673. else if (needsBlank && !location[obj.name]) {
  20674. location[obj.name] = {};
  20675. }
  20676. var keyLocation = obj.push ?
  20677. {} : // blank object that will be pushed
  20678. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20679. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20680. if (obj.push) {
  20681. location[obj.push].push(keyLocation);
  20682. }
  20683. };
  20684. var grammar = require('./grammar');
  20685. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20686. exports.parse = function (sdp) {
  20687. var session = {}
  20688. , media = []
  20689. , location = session; // points at where properties go under (one of the above)
  20690. // parse lines we understand
  20691. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20692. var type = l[0];
  20693. var content = l.slice(2);
  20694. if (type === 'm') {
  20695. media.push({rtp: [], fmtp: []});
  20696. location = media[media.length-1]; // point at latest media line
  20697. }
  20698. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20699. var obj = grammar[type][j];
  20700. if (obj.reg.test(content)) {
  20701. return parseReg(obj, location, content);
  20702. }
  20703. }
  20704. });
  20705. session.media = media; // link it up
  20706. return session;
  20707. };
  20708. var fmtpReducer = function (acc, expr) {
  20709. var s = expr.split('=');
  20710. if (s.length === 2) {
  20711. acc[s[0]] = toIntIfInt(s[1]);
  20712. }
  20713. return acc;
  20714. };
  20715. exports.parseFmtpConfig = function (str) {
  20716. return str.split(';').reduce(fmtpReducer, {});
  20717. };
  20718. exports.parsePayloads = function (str) {
  20719. return str.split(' ').map(Number);
  20720. };
  20721. exports.parseRemoteCandidates = function (str) {
  20722. var candidates = [];
  20723. var parts = str.split(' ').map(toIntIfInt);
  20724. for (var i = 0; i < parts.length; i += 3) {
  20725. candidates.push({
  20726. component: parts[i],
  20727. ip: parts[i + 1],
  20728. port: parts[i + 2]
  20729. });
  20730. }
  20731. return candidates;
  20732. };
  20733. },{"./grammar":71}],74:[function(require,module,exports){
  20734. var grammar = require('./grammar');
  20735. // customized util.format - discards excess arguments and can void middle ones
  20736. var formatRegExp = /%[sdv%]/g;
  20737. var format = function (formatStr) {
  20738. var i = 1;
  20739. var args = arguments;
  20740. var len = args.length;
  20741. return formatStr.replace(formatRegExp, function (x) {
  20742. if (i >= len) {
  20743. return x; // missing argument
  20744. }
  20745. var arg = args[i];
  20746. i += 1;
  20747. switch (x) {
  20748. case '%%':
  20749. return '%';
  20750. case '%s':
  20751. return String(arg);
  20752. case '%d':
  20753. return Number(arg);
  20754. case '%v':
  20755. return '';
  20756. }
  20757. });
  20758. // NB: we discard excess arguments - they are typically undefined from makeLine
  20759. };
  20760. var makeLine = function (type, obj, location) {
  20761. var str = obj.format instanceof Function ?
  20762. (obj.format(obj.push ? location : location[obj.name])) :
  20763. obj.format;
  20764. var args = [type + '=' + str];
  20765. if (obj.names) {
  20766. for (var i = 0; i < obj.names.length; i += 1) {
  20767. var n = obj.names[i];
  20768. if (obj.name) {
  20769. args.push(location[obj.name][n]);
  20770. }
  20771. else { // for mLine and push attributes
  20772. args.push(location[obj.names[i]]);
  20773. }
  20774. }
  20775. }
  20776. else {
  20777. args.push(location[obj.name]);
  20778. }
  20779. return format.apply(null, args);
  20780. };
  20781. // RFC specified order
  20782. // TODO: extend this with all the rest
  20783. var defaultOuterOrder = [
  20784. 'v', 'o', 's', 'i',
  20785. 'u', 'e', 'p', 'c',
  20786. 'b', 't', 'r', 'z', 'a'
  20787. ];
  20788. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  20789. module.exports = function (session, opts) {
  20790. opts = opts || {};
  20791. // ensure certain properties exist
  20792. if (session.version == null) {
  20793. session.version = 0; // "v=0" must be there (only defined version atm)
  20794. }
  20795. if (session.name == null) {
  20796. session.name = " "; // "s= " must be there if no meaningful name set
  20797. }
  20798. session.media.forEach(function (mLine) {
  20799. if (mLine.payloads == null) {
  20800. mLine.payloads = "";
  20801. }
  20802. });
  20803. var outerOrder = opts.outerOrder || defaultOuterOrder;
  20804. var innerOrder = opts.innerOrder || defaultInnerOrder;
  20805. var sdp = [];
  20806. // loop through outerOrder for matching properties on session
  20807. outerOrder.forEach(function (type) {
  20808. grammar[type].forEach(function (obj) {
  20809. if (obj.name in session && session[obj.name] != null) {
  20810. sdp.push(makeLine(type, obj, session));
  20811. }
  20812. else if (obj.push in session && session[obj.push] != null) {
  20813. session[obj.push].forEach(function (el) {
  20814. sdp.push(makeLine(type, obj, el));
  20815. });
  20816. }
  20817. });
  20818. });
  20819. // then for each media line, follow the innerOrder
  20820. session.media.forEach(function (mLine) {
  20821. sdp.push(makeLine('m', grammar.m[0], mLine));
  20822. innerOrder.forEach(function (type) {
  20823. grammar[type].forEach(function (obj) {
  20824. if (obj.name in mLine && mLine[obj.name] != null) {
  20825. sdp.push(makeLine(type, obj, mLine));
  20826. }
  20827. else if (obj.push in mLine && mLine[obj.push] != null) {
  20828. mLine[obj.push].forEach(function (el) {
  20829. sdp.push(makeLine(type, obj, el));
  20830. });
  20831. }
  20832. });
  20833. });
  20834. });
  20835. return sdp.join('\r\n') + '\r\n';
  20836. };
  20837. },{"./grammar":71}],75:[function(require,module,exports){
  20838. var grammar = module.exports = {
  20839. v: [{
  20840. name: 'version',
  20841. reg: /^(\d*)$/
  20842. }],
  20843. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20844. // NB: sessionId will be a String in most cases because it is huge
  20845. name: 'origin',
  20846. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20847. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20848. format: "%s %s %d %s IP%d %s"
  20849. }],
  20850. // default parsing of these only (though some of these feel outdated)
  20851. s: [{ name: 'name' }],
  20852. i: [{ name: 'description' }],
  20853. u: [{ name: 'uri' }],
  20854. e: [{ name: 'email' }],
  20855. p: [{ name: 'phone' }],
  20856. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20857. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20858. //k: [{}], // outdated thing ignored
  20859. t: [{ //t=0 0
  20860. name: 'timing',
  20861. reg: /^(\d*) (\d*)/,
  20862. names: ['start', 'stop'],
  20863. format: "%d %d"
  20864. }],
  20865. c: [{ //c=IN IP4 10.47.197.26
  20866. name: 'connection',
  20867. reg: /^IN IP(\d) (\S*)/,
  20868. names: ['version', 'ip'],
  20869. format: "IN IP%d %s"
  20870. }],
  20871. b: [{ //b=AS:4000
  20872. push: 'bandwidth',
  20873. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20874. names: ['type', 'limit'],
  20875. format: "%s:%s"
  20876. }],
  20877. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20878. // NB: special - pushes to session
  20879. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20880. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20881. names: ['type', 'port', 'protocol', 'payloads'],
  20882. format: "%s %d %s %s"
  20883. }],
  20884. a: [
  20885. { //a=rtpmap:110 opus/48000/2
  20886. push: 'rtp',
  20887. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  20888. names: ['payload', 'codec', 'rate', 'encoding'],
  20889. format: function (o) {
  20890. return (o.encoding) ?
  20891. "rtpmap:%d %s/%s/%s":
  20892. "rtpmap:%d %s/%s";
  20893. }
  20894. },
  20895. {
  20896. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20897. //a=fmtp:111 minptime=10; useinbandfec=1
  20898. push: 'fmtp',
  20899. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20900. names: ['payload', 'config'],
  20901. format: "fmtp:%d %s"
  20902. },
  20903. { //a=control:streamid=0
  20904. name: 'control',
  20905. reg: /^control:(.*)/,
  20906. format: "control:%s"
  20907. },
  20908. { //a=rtcp:65179 IN IP4 193.84.77.194
  20909. name: 'rtcp',
  20910. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20911. names: ['port', 'netType', 'ipVer', 'address'],
  20912. format: function (o) {
  20913. return (o.address != null) ?
  20914. "rtcp:%d %s IP%d %s":
  20915. "rtcp:%d";
  20916. }
  20917. },
  20918. { //a=rtcp-fb:98 trr-int 100
  20919. push: 'rtcpFbTrrInt',
  20920. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20921. names: ['payload', 'value'],
  20922. format: "rtcp-fb:%d trr-int %d"
  20923. },
  20924. { //a=rtcp-fb:98 nack rpsi
  20925. push: 'rtcpFb',
  20926. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20927. names: ['payload', 'type', 'subtype'],
  20928. format: function (o) {
  20929. return (o.subtype != null) ?
  20930. "rtcp-fb:%s %s %s":
  20931. "rtcp-fb:%s %s";
  20932. }
  20933. },
  20934. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20935. //a=extmap:1/recvonly URI-gps-string
  20936. push: 'ext',
  20937. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20938. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20939. format: function (o) {
  20940. return (o.config != null) ?
  20941. "extmap:%s %s %s":
  20942. "extmap:%s %s";
  20943. }
  20944. },
  20945. {
  20946. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20947. push: 'crypto',
  20948. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20949. names: ['id', 'suite', 'config', 'sessionConfig'],
  20950. format: function (o) {
  20951. return (o.sessionConfig != null) ?
  20952. "crypto:%d %s %s %s":
  20953. "crypto:%d %s %s";
  20954. }
  20955. },
  20956. { //a=setup:actpass
  20957. name: 'setup',
  20958. reg: /^setup:(\w*)/,
  20959. format: "setup:%s"
  20960. },
  20961. { //a=mid:1
  20962. name: 'mid',
  20963. reg: /^mid:([^\s]*)/,
  20964. format: "mid:%s"
  20965. },
  20966. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20967. name: 'msid',
  20968. reg: /^msid:(.*)/,
  20969. format: "msid:%s"
  20970. },
  20971. { //a=ptime:20
  20972. name: 'ptime',
  20973. reg: /^ptime:(\d*)/,
  20974. format: "ptime:%d"
  20975. },
  20976. { //a=maxptime:60
  20977. name: 'maxptime',
  20978. reg: /^maxptime:(\d*)/,
  20979. format: "maxptime:%d"
  20980. },
  20981. { //a=sendrecv
  20982. name: 'direction',
  20983. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20984. },
  20985. { //a=ice-lite
  20986. name: 'icelite',
  20987. reg: /^(ice-lite)/
  20988. },
  20989. { //a=ice-ufrag:F7gI
  20990. name: 'iceUfrag',
  20991. reg: /^ice-ufrag:(\S*)/,
  20992. format: "ice-ufrag:%s"
  20993. },
  20994. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20995. name: 'icePwd',
  20996. reg: /^ice-pwd:(\S*)/,
  20997. format: "ice-pwd:%s"
  20998. },
  20999. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  21000. name: 'fingerprint',
  21001. reg: /^fingerprint:(\S*) (\S*)/,
  21002. names: ['type', 'hash'],
  21003. format: "fingerprint:%s %s"
  21004. },
  21005. {
  21006. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  21007. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  21008. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  21009. push:'candidates',
  21010. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  21011. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  21012. format: function (o) {
  21013. var str = "candidate:%s %d %s %d %s %d typ %s";
  21014. // NB: candidate has two optional chunks, so %void middle one if it's missing
  21015. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  21016. if (o.generation != null) {
  21017. str += " generation %d";
  21018. }
  21019. return str;
  21020. }
  21021. },
  21022. { //a=end-of-candidates (keep after the candidates line for readability)
  21023. name: 'endOfCandidates',
  21024. reg: /^(end-of-candidates)/
  21025. },
  21026. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  21027. name: 'remoteCandidates',
  21028. reg: /^remote-candidates:(.*)/,
  21029. format: "remote-candidates:%s"
  21030. },
  21031. { //a=ice-options:google-ice
  21032. name: 'iceOptions',
  21033. reg: /^ice-options:(\S*)/,
  21034. format: "ice-options:%s"
  21035. },
  21036. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  21037. push: "ssrcs",
  21038. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  21039. names: ['id', 'attribute', 'value'],
  21040. format: "ssrc:%d %s:%s"
  21041. },
  21042. { //a=ssrc-group:FEC 1 2
  21043. push: "ssrcGroups",
  21044. reg: /^ssrc-group:(\w*) (.*)/,
  21045. names: ['semantics', 'ssrcs'],
  21046. format: "ssrc-group:%s %s"
  21047. },
  21048. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  21049. name: "msidSemantic",
  21050. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  21051. names: ['semantic', 'token'],
  21052. format: "msid-semantic: %s %s" // space after ":" is not accidental
  21053. },
  21054. { //a=group:BUNDLE audio video
  21055. push: 'groups',
  21056. reg: /^group:(\w*) (.*)/,
  21057. names: ['type', 'mids'],
  21058. format: "group:%s %s"
  21059. },
  21060. { //a=rtcp-mux
  21061. name: 'rtcpMux',
  21062. reg: /^(rtcp-mux)/
  21063. },
  21064. { //a=rtcp-rsize
  21065. name: 'rtcpRsize',
  21066. reg: /^(rtcp-rsize)/
  21067. },
  21068. { // any a= that we don't understand is kepts verbatim on media.invalid
  21069. push: 'invalid',
  21070. names: ["value"]
  21071. }
  21072. ]
  21073. };
  21074. // set sensible defaults to avoid polluting the grammar with boring details
  21075. Object.keys(grammar).forEach(function (key) {
  21076. var objs = grammar[key];
  21077. objs.forEach(function (obj) {
  21078. if (!obj.reg) {
  21079. obj.reg = /(.*)/;
  21080. }
  21081. if (!obj.format) {
  21082. obj.format = "%s";
  21083. }
  21084. });
  21085. });
  21086. },{}],76:[function(require,module,exports){
  21087. arguments[4][72][0].apply(exports,arguments)
  21088. },{"./parser":77,"./writer":78,"dup":72}],77:[function(require,module,exports){
  21089. var toIntIfInt = function (v) {
  21090. return String(Number(v)) === v ? Number(v) : v;
  21091. };
  21092. var attachProperties = function (match, location, names, rawName) {
  21093. if (rawName && !names) {
  21094. location[rawName] = toIntIfInt(match[1]);
  21095. }
  21096. else {
  21097. for (var i = 0; i < names.length; i += 1) {
  21098. if (match[i+1] != null) {
  21099. location[names[i]] = toIntIfInt(match[i+1]);
  21100. }
  21101. }
  21102. }
  21103. };
  21104. var parseReg = function (obj, location, content) {
  21105. var needsBlank = obj.name && obj.names;
  21106. if (obj.push && !location[obj.push]) {
  21107. location[obj.push] = [];
  21108. }
  21109. else if (needsBlank && !location[obj.name]) {
  21110. location[obj.name] = {};
  21111. }
  21112. var keyLocation = obj.push ?
  21113. {} : // blank object that will be pushed
  21114. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  21115. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  21116. if (obj.push) {
  21117. location[obj.push].push(keyLocation);
  21118. }
  21119. };
  21120. var grammar = require('./grammar');
  21121. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  21122. exports.parse = function (sdp) {
  21123. var session = {}
  21124. , media = []
  21125. , location = session; // points at where properties go under (one of the above)
  21126. // parse lines we understand
  21127. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  21128. var type = l[0];
  21129. var content = l.slice(2);
  21130. if (type === 'm') {
  21131. media.push({rtp: [], fmtp: []});
  21132. location = media[media.length-1]; // point at latest media line
  21133. }
  21134. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  21135. var obj = grammar[type][j];
  21136. if (obj.reg.test(content)) {
  21137. return parseReg(obj, location, content);
  21138. }
  21139. }
  21140. });
  21141. session.media = media; // link it up
  21142. return session;
  21143. };
  21144. var fmtpReducer = function (acc, expr) {
  21145. var s = expr.split('=');
  21146. if (s.length === 2) {
  21147. acc[s[0]] = toIntIfInt(s[1]);
  21148. }
  21149. return acc;
  21150. };
  21151. exports.parseFmtpConfig = function (str) {
  21152. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  21153. };
  21154. exports.parsePayloads = function (str) {
  21155. return str.split(' ').map(Number);
  21156. };
  21157. exports.parseRemoteCandidates = function (str) {
  21158. var candidates = [];
  21159. var parts = str.split(' ').map(toIntIfInt);
  21160. for (var i = 0; i < parts.length; i += 3) {
  21161. candidates.push({
  21162. component: parts[i],
  21163. ip: parts[i + 1],
  21164. port: parts[i + 2]
  21165. });
  21166. }
  21167. return candidates;
  21168. };
  21169. },{"./grammar":75}],78:[function(require,module,exports){
  21170. arguments[4][74][0].apply(exports,arguments)
  21171. },{"./grammar":75,"dup":74}],79:[function(require,module,exports){
  21172. var MediaStreamType = {
  21173. VIDEO_TYPE: "Video",
  21174. AUDIO_TYPE: "Audio"
  21175. };
  21176. module.exports = MediaStreamType;
  21177. },{}],80:[function(require,module,exports){
  21178. var RTCEvents = {
  21179. RTC_READY: "rtc.ready",
  21180. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  21181. LASTN_CHANGED: "rtc.lastn_changed",
  21182. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  21183. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  21184. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  21185. };
  21186. module.exports = RTCEvents;
  21187. },{}],81:[function(require,module,exports){
  21188. var Resolutions = {
  21189. "1080": {
  21190. width: 1920,
  21191. height: 1080,
  21192. order: 7
  21193. },
  21194. "fullhd": {
  21195. width: 1920,
  21196. height: 1080,
  21197. order: 7
  21198. },
  21199. "720": {
  21200. width: 1280,
  21201. height: 720,
  21202. order: 6
  21203. },
  21204. "hd": {
  21205. width: 1280,
  21206. height: 720,
  21207. order: 6
  21208. },
  21209. "960": {
  21210. width: 960,
  21211. height: 720,
  21212. order: 5
  21213. },
  21214. "640": {
  21215. width: 640,
  21216. height: 480,
  21217. order: 4
  21218. },
  21219. "vga": {
  21220. width: 640,
  21221. height: 480,
  21222. order: 4
  21223. },
  21224. "360": {
  21225. width: 640,
  21226. height: 360,
  21227. order: 3
  21228. },
  21229. "320": {
  21230. width: 320,
  21231. height: 240,
  21232. order: 2
  21233. },
  21234. "180": {
  21235. width: 320,
  21236. height: 180,
  21237. order: 1
  21238. }
  21239. };
  21240. module.exports = Resolutions;
  21241. },{}],82:[function(require,module,exports){
  21242. var XMPPEvents = {
  21243. // Designates an event indicating that the connection to the XMPP server
  21244. // failed.
  21245. CONNECTION_FAILED: "xmpp.connection.failed",
  21246. // Designates an event indicating that the media (ICE) connection was
  21247. // interrupted. This should go to the RTC module.
  21248. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  21249. // Designates an event indicating that the media (ICE) connection was
  21250. // restored. This should go to the RTC module.
  21251. CONNECTION_RESTORED: "xmpp.connection.restored",
  21252. // Designates an event indicating that an offer (e.g. Jingle
  21253. // session-initiate) was received.
  21254. CALL_INCOMING: "xmpp.callincoming.jingle",
  21255. // Designates an event indicating that we were kicked from the XMPP MUC.
  21256. KICKED: "xmpp.kicked",
  21257. // Designates an event indicating that the userID for a specific JID has
  21258. // changed.
  21259. // Note: currently this event fires every time we receive presence from
  21260. // someone (regardless of whether or not the "userID" changed).
  21261. USER_ID_CHANGED: "xmpp.user_id_changed",
  21262. // Designates an event indicating that we have joined the XMPP MUC.
  21263. MUC_JOINED: "xmpp.muc_joined",
  21264. // Designates an event indicating that a participant joined the XMPP MUC.
  21265. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  21266. // Designates an event indicating that a participant left the XMPP MUC.
  21267. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  21268. // Designates an event indicating that the MUC role of a participant has
  21269. // changed.
  21270. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  21271. // Designates an event indicating that the XMPP MUC was destroyed.
  21272. MUC_DESTROYED: "xmpp.muc_destroyed",
  21273. // Designates an event indicating that the display name of a participant
  21274. // has changed.
  21275. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  21276. // Designates an event indicating that we received statistics from a
  21277. // participant in the MUC.
  21278. REMOTE_STATS: "xmpp.remote_stats",
  21279. // Designates an event indicating that our role in the XMPP MUC has changed.
  21280. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  21281. // Designates an event indicating that the subject of the XMPP MUC has
  21282. // changed.
  21283. SUBJECT_CHANGED: "xmpp.subject_changed",
  21284. // Designates an event indicating that an XMPP message in the MUC was
  21285. // received.
  21286. MESSAGE_RECEIVED: "xmpp.message_received",
  21287. // Designates an event indicating that we sent an XMPP message to the MUC.
  21288. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  21289. // Designates an event indicating that the video type (e.g. 'camera' or
  21290. // 'screen') for a participant has changed.
  21291. // Note: currently this event fires every time we receive presence from
  21292. // someone (regardless of whether or not the "video type" changed).
  21293. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  21294. // Designates an event indicating that a participant in the XMPP MUC has
  21295. // advertised that they have audio muted (or unmuted).
  21296. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  21297. // Designates an event indicating that a participant in the XMPP MUC has
  21298. // advertised that they have video muted (or unmuted).
  21299. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  21300. // Designates an event indicating that the focus has asked us to mute our
  21301. // audio.
  21302. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  21303. // Designates an event indicating that we should join the conference with
  21304. // audio and/or video muted.
  21305. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  21306. // Designates an event indicating that a remote participant's available
  21307. // devices (whether he supports a audio and/or video) changed.
  21308. // Note: currently this event fires every time we receive presence from
  21309. // someone (regardless of whether or not the devices changed).
  21310. DEVICE_AVAILABLE: "xmpp.device_available",
  21311. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  21312. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  21313. PASSWORD_REQUIRED: "xmpp.password_required",
  21314. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  21315. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  21316. ETHERPAD: "xmpp.etherpad",
  21317. BRIDGE_DOWN: "xmpp.bridge_down",
  21318. PRESENCE_STATUS: "xmpp.presence_status",
  21319. RESERVATION_ERROR: "xmpp.room_reservation_error",
  21320. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  21321. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  21322. // TODO: only used in a hack, should probably be removed.
  21323. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  21324. // TODO: only used in a hack, should probably be removed.
  21325. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  21326. // TODO: only used in a hack, should probably be removed.
  21327. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  21328. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  21329. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  21330. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  21331. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  21332. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  21333. // xmpp is connected and obtained user media
  21334. READY_TO_JOIN: 'xmpp.ready_to_join',
  21335. FOCUS_LEFT: "xmpp.focus_left",
  21336. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  21337. /**
  21338. * Indicates that recording state changed.
  21339. */
  21340. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  21341. /**
  21342. * Indicates that phone number changed.
  21343. */
  21344. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  21345. };
  21346. module.exports = XMPPEvents;
  21347. },{}],83:[function(require,module,exports){
  21348. var AuthenticationEvents = {
  21349. /**
  21350. * Event callback arguments:
  21351. * function(authenticationEnabled, userIdentity)
  21352. * authenticationEnabled - indicates whether authentication has been enabled
  21353. * in this session
  21354. * userIdentity - if user has been logged in then it contains user name. If
  21355. * contains 'null' or 'undefined' then user is not logged in.
  21356. */
  21357. IDENTITY_UPDATED: "authentication.identity_updated"
  21358. };
  21359. module.exports = AuthenticationEvents;
  21360. },{}],84:[function(require,module,exports){
  21361. var DesktopSharingEventTypes = {
  21362. /**
  21363. * An event which indicates that the jidesha extension for Firefox is
  21364. * needed to proceed with screen sharing, and that it is not installed.
  21365. */
  21366. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  21367. };
  21368. module.exports = DesktopSharingEventTypes;
  21369. },{}],85:[function(require,module,exports){
  21370. module.exports = {
  21371. /**
  21372. * An event carrying connection statistics.
  21373. */
  21374. CONNECTION_STATS: "statistics.connectionstats",
  21375. /**
  21376. * FIXME: needs documentation.
  21377. */
  21378. AUDIO_LEVEL: "statistics.audioLevel",
  21379. /**
  21380. * FIXME: needs documentation.
  21381. */
  21382. STOP: "statistics.stop"
  21383. };
  21384. },{}],86:[function(require,module,exports){
  21385. var Constants = {
  21386. LOCAL_JID: 'local'
  21387. };
  21388. module.exports = Constants;
  21389. },{}],87:[function(require,module,exports){
  21390. arguments[4][82][0].apply(exports,arguments)
  21391. },{"dup":82}]},{},[7])(7)
  21392. });