You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.bundle.js 746KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(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. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.simulcast = require("./modules/simulcast/simulcast");
  13. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  14. this.xmpp = require("./modules/xmpp/xmpp");
  15. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  16. }
  17. };
  18. function init() {
  19. APP.RTC.start();
  20. APP.xmpp.start(APP.UI.getCreadentials);
  21. APP.statistics.start();
  22. APP.connectionquality.init();
  23. // Set default desktop sharing method
  24. APP.desktopsharing.init();
  25. APP.keyboardshortcut.init();
  26. }
  27. $(document).ready(function () {
  28. APP.init();
  29. if(APP.API.isEnabled())
  30. APP.API.init();
  31. APP.UI.start(init);
  32. });
  33. $(window).bind('beforeunload', function () {
  34. if(APP.API.isEnabled())
  35. APP.API.dispose();
  36. });
  37. module.exports = APP;
  38. },{"./modules/API/API":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":35,"./modules/desktopsharing/desktopsharing":36,"./modules/keyboardshortcut/keyboardshortcut":37,"./modules/simulcast/simulcast":42,"./modules/statistics/statistics":45,"./modules/xmpp/xmpp":59}],2:[function(require,module,exports){
  39. /**
  40. * Implements API class that communicates with external api class
  41. * and provides interface to access Jitsi Meet features by external
  42. * applications that embed Jitsi Meet
  43. */
  44. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  45. /**
  46. * List of the available commands.
  47. * @type {{
  48. * displayName: inputDisplayNameHandler,
  49. * muteAudio: toggleAudio,
  50. * muteVideo: toggleVideo,
  51. * filmStrip: toggleFilmStrip
  52. * }}
  53. */
  54. var commands =
  55. {
  56. displayName: APP.UI.inputDisplayNameHandler,
  57. muteAudio: APP.UI.toggleAudio,
  58. muteVideo: APP.UI.toggleVideo,
  59. toggleFilmStrip: APP.UI.toggleFilmStrip,
  60. toggleChat: APP.UI.toggleChat,
  61. toggleContactList: APP.UI.toggleContactList
  62. };
  63. /**
  64. * Maps the supported events and their status
  65. * (true it the event is enabled and false if it is disabled)
  66. * @type {{
  67. * incomingMessage: boolean,
  68. * outgoingMessage: boolean,
  69. * displayNameChange: boolean,
  70. * participantJoined: boolean,
  71. * participantLeft: boolean
  72. * }}
  73. */
  74. var events =
  75. {
  76. incomingMessage: false,
  77. outgoingMessage:false,
  78. displayNameChange: false,
  79. participantJoined: false,
  80. participantLeft: false
  81. };
  82. var displayName = {};
  83. /**
  84. * Processes commands from external applicaiton.
  85. * @param message the object with the command
  86. */
  87. function processCommand(message)
  88. {
  89. if(message.action != "execute")
  90. {
  91. console.error("Unknown action of the message");
  92. return;
  93. }
  94. for(var key in message)
  95. {
  96. if(commands[key])
  97. commands[key].apply(null, message[key]);
  98. }
  99. }
  100. /**
  101. * Processes events objects from external applications
  102. * @param event the event
  103. */
  104. function processEvent(event) {
  105. if(!event.action)
  106. {
  107. console.error("Event with no action is received.");
  108. return;
  109. }
  110. var i = 0;
  111. switch(event.action)
  112. {
  113. case "add":
  114. for(; i < event.events.length; i++)
  115. {
  116. events[event.events[i]] = true;
  117. }
  118. break;
  119. case "remove":
  120. for(; i < event.events.length; i++)
  121. {
  122. events[event.events[i]] = false;
  123. }
  124. break;
  125. default:
  126. console.error("Unknown action for event.");
  127. }
  128. }
  129. /**
  130. * Sends message to the external application.
  131. * @param object
  132. */
  133. function sendMessage(object) {
  134. window.parent.postMessage(JSON.stringify(object), "*");
  135. }
  136. /**
  137. * Processes a message event from the external application
  138. * @param event the message event
  139. */
  140. function processMessage(event)
  141. {
  142. var message;
  143. try {
  144. message = JSON.parse(event.data);
  145. } catch (e) {}
  146. if(!message.type)
  147. return;
  148. switch (message.type)
  149. {
  150. case "command":
  151. processCommand(message);
  152. break;
  153. case "event":
  154. processEvent(message);
  155. break;
  156. default:
  157. console.error("Unknown type of the message");
  158. return;
  159. }
  160. }
  161. function setupListeners() {
  162. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  163. API.triggerEvent("participantJoined", {jid: from});
  164. });
  165. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  166. if (from != myjid)
  167. API.triggerEvent("incomingMessage",
  168. {"from": from, "nick": nick, "message": txt});
  169. });
  170. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  171. API.triggerEvent("participantLeft", {jid: jid});
  172. });
  173. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  174. name = displayName[jid];
  175. if(!name || name != newDisplayName) {
  176. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  177. displayName[jid] = newDisplayName;
  178. }
  179. });
  180. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  181. APP.API.triggerEvent("outgoingMessage", {"message": body});
  182. });
  183. }
  184. var API = {
  185. /**
  186. * Check whether the API should be enabled or not.
  187. * @returns {boolean}
  188. */
  189. isEnabled: function () {
  190. var hash = location.hash;
  191. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  192. return true;
  193. return false;
  194. },
  195. /**
  196. * Initializes the APIConnector. Setups message event listeners that will
  197. * receive information from external applications that embed Jitsi Meet.
  198. * It also sends a message to the external application that APIConnector
  199. * is initialized.
  200. */
  201. init: function () {
  202. if (window.addEventListener)
  203. {
  204. window.addEventListener('message',
  205. processMessage, false);
  206. }
  207. else
  208. {
  209. window.attachEvent('onmessage', processMessage);
  210. }
  211. sendMessage({type: "system", loaded: true});
  212. setupListeners();
  213. },
  214. /**
  215. * Checks whether the event is enabled ot not.
  216. * @param name the name of the event.
  217. * @returns {*}
  218. */
  219. isEventEnabled: function (name) {
  220. return events[name];
  221. },
  222. /**
  223. * Sends event object to the external application that has been subscribed
  224. * for that event.
  225. * @param name the name event
  226. * @param object data associated with the event
  227. */
  228. triggerEvent: function (name, object) {
  229. if(this.isEnabled() && this.isEventEnabled(name))
  230. sendMessage({
  231. type: "event", action: "result", event: name, result: object});
  232. },
  233. /**
  234. * Removes the listeners.
  235. */
  236. dispose: function () {
  237. if(window.removeEventListener)
  238. {
  239. window.removeEventListener("message",
  240. processMessage, false);
  241. }
  242. else
  243. {
  244. window.detachEvent('onmessage', processMessage);
  245. }
  246. }
  247. };
  248. module.exports = API;
  249. },{"../../service/xmpp/XMPPEvents":83}],3:[function(require,module,exports){
  250. /* global Strophe, updateLargeVideo, focusedVideoSrc*/
  251. // cache datachannels to avoid garbage collection
  252. // https://code.google.com/p/chromium/issues/detail?id=405545
  253. var RTCEvents = require("../../service/RTC/RTCEvents");
  254. var _dataChannels = [];
  255. var eventEmitter = null;
  256. var DataChannels =
  257. {
  258. /**
  259. * Callback triggered by PeerConnection when new data channel is opened
  260. * on the bridge.
  261. * @param event the event info object.
  262. */
  263. onDataChannel: function (event)
  264. {
  265. var dataChannel = event.channel;
  266. dataChannel.onopen = function () {
  267. console.info("Data channel opened by the Videobridge!", dataChannel);
  268. // Code sample for sending string and/or binary data
  269. // Sends String message to the bridge
  270. //dataChannel.send("Hello bridge!");
  271. // Sends 12 bytes binary message to the bridge
  272. //dataChannel.send(new ArrayBuffer(12));
  273. // when the data channel becomes available, tell the bridge about video
  274. // selections so that it can do adaptive simulcast,
  275. // we want the notification to trigger even if userJid is undefined,
  276. // or null.
  277. var userJid = APP.UI.getLargeVideoState().userJid;
  278. // we want the notification to trigger even if userJid is undefined,
  279. // or null.
  280. onSelectedEndpointChanged(userJid);
  281. };
  282. dataChannel.onerror = function (error) {
  283. console.error("Data Channel Error:", error, dataChannel);
  284. };
  285. dataChannel.onmessage = function (event) {
  286. var data = event.data;
  287. // JSON
  288. var obj;
  289. try {
  290. obj = JSON.parse(data);
  291. }
  292. catch (e) {
  293. console.error(
  294. "Failed to parse data channel message as JSON: ",
  295. data,
  296. dataChannel);
  297. }
  298. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  299. var colibriClass = obj.colibriClass;
  300. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  301. // Endpoint ID from the Videobridge.
  302. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  303. console.info(
  304. "Data channel new dominant speaker event: ",
  305. dominantSpeakerEndpoint);
  306. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  307. }
  308. else if ("InLastNChangeEvent" === colibriClass)
  309. {
  310. var oldValue = obj.oldValue;
  311. var newValue = obj.newValue;
  312. // Make sure that oldValue and newValue are of type boolean.
  313. var type;
  314. if ((type = typeof oldValue) !== 'boolean') {
  315. if (type === 'string') {
  316. oldValue = (oldValue == "true");
  317. } else {
  318. oldValue = new Boolean(oldValue).valueOf();
  319. }
  320. }
  321. if ((type = typeof newValue) !== 'boolean') {
  322. if (type === 'string') {
  323. newValue = (newValue == "true");
  324. } else {
  325. newValue = new Boolean(newValue).valueOf();
  326. }
  327. }
  328. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  329. }
  330. else if ("LastNEndpointsChangeEvent" === colibriClass)
  331. {
  332. // The new/latest list of last-n endpoint IDs.
  333. var lastNEndpoints = obj.lastNEndpoints;
  334. // The list of endpoint IDs which are entering the list of
  335. // last-n at this time i.e. were not in the old list of last-n
  336. // endpoint IDs.
  337. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  338. var stream = obj.stream;
  339. console.log(
  340. "Data channel new last-n event: ",
  341. lastNEndpoints, endpointsEnteringLastN, obj);
  342. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  343. lastNEndpoints, endpointsEnteringLastN, obj);
  344. }
  345. else if ("SimulcastLayersChangedEvent" === colibriClass)
  346. {
  347. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  348. obj.endpointSimulcastLayers);
  349. }
  350. else if ("SimulcastLayersChangingEvent" === colibriClass)
  351. {
  352. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  353. obj.endpointSimulcastLayers);
  354. }
  355. else if ("StartSimulcastLayerEvent" === colibriClass)
  356. {
  357. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  358. }
  359. else if ("StopSimulcastLayerEvent" === colibriClass)
  360. {
  361. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  362. }
  363. else
  364. {
  365. console.debug("Data channel JSON-formatted message: ", obj);
  366. }
  367. }
  368. };
  369. dataChannel.onclose = function ()
  370. {
  371. console.info("The Data Channel closed", dataChannel);
  372. var idx = _dataChannels.indexOf(dataChannel);
  373. if (idx > -1)
  374. _dataChannels = _dataChannels.splice(idx, 1);
  375. };
  376. _dataChannels.push(dataChannel);
  377. },
  378. /**
  379. * Binds "ondatachannel" event listener to given PeerConnection instance.
  380. * @param peerConnection WebRTC peer connection instance.
  381. */
  382. init: function (peerConnection, emitter) {
  383. if(!config.openSctp)
  384. return;
  385. peerConnection.ondatachannel = this.onDataChannel;
  386. eventEmitter = emitter;
  387. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  388. // Although it's not a requirement to open separate channels from both bridge
  389. // and peer as single channel can be used for sending and receiving data.
  390. // So either channel opened by the bridge or the one opened here is enough
  391. // for communication with the bridge.
  392. /*var dataChannelOptions =
  393. {
  394. reliable: true
  395. };
  396. var dataChannel
  397. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  398. // Can be used only when is in open state
  399. dataChannel.onopen = function ()
  400. {
  401. dataChannel.send("My channel !!!");
  402. };
  403. dataChannel.onmessage = function (event)
  404. {
  405. var msgData = event.data;
  406. console.info("Got My Data Channel Message:", msgData, dataChannel);
  407. };*/
  408. },
  409. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  410. handlePinnedEndpointEvent: onPinnedEndpointChanged
  411. };
  412. function onSelectedEndpointChanged(userResource)
  413. {
  414. console.log('selected endpoint changed: ', userResource);
  415. if (_dataChannels && _dataChannels.length != 0)
  416. {
  417. _dataChannels.some(function (dataChannel) {
  418. if (dataChannel.readyState == 'open')
  419. {
  420. dataChannel.send(JSON.stringify({
  421. 'colibriClass': 'SelectedEndpointChangedEvent',
  422. 'selectedEndpoint':
  423. (!userResource || userResource === null)?
  424. null : userResource
  425. }));
  426. return true;
  427. }
  428. });
  429. }
  430. }
  431. function onPinnedEndpointChanged(userResource)
  432. {
  433. console.log('pinned endpoint changed: ', userResource);
  434. if (_dataChannels && _dataChannels.length != 0)
  435. {
  436. _dataChannels.some(function (dataChannel) {
  437. if (dataChannel.readyState == 'open')
  438. {
  439. dataChannel.send(JSON.stringify({
  440. 'colibriClass': 'PinnedEndpointChangedEvent',
  441. 'pinnedEndpoint':
  442. (!userResource || userResource == null)?
  443. null : userResource
  444. }));
  445. return true;
  446. }
  447. });
  448. }
  449. }
  450. module.exports = DataChannels;
  451. },{"../../service/RTC/RTCEvents":78}],4:[function(require,module,exports){
  452. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  453. function LocalStream(stream, type, eventEmitter, videoType)
  454. {
  455. this.stream = stream;
  456. this.eventEmitter = eventEmitter;
  457. this.type = type;
  458. this.videoType = videoType;
  459. var self = this;
  460. if(type == "audio")
  461. {
  462. this.getTracks = function () {
  463. return self.stream.getAudioTracks();
  464. };
  465. }
  466. else
  467. {
  468. this.getTracks = function () {
  469. return self.stream.getVideoTracks();
  470. };
  471. }
  472. this.stream.onended = function()
  473. {
  474. self.streamEnded();
  475. };
  476. }
  477. LocalStream.prototype.streamEnded = function () {
  478. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  479. }
  480. LocalStream.prototype.getOriginalStream = function()
  481. {
  482. return this.stream;
  483. }
  484. LocalStream.prototype.isAudioStream = function () {
  485. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  486. };
  487. LocalStream.prototype.mute = function()
  488. {
  489. var ismuted = false;
  490. var tracks = this.getTracks();
  491. for (var idx = 0; idx < tracks.length; idx++) {
  492. ismuted = !tracks[idx].enabled;
  493. tracks[idx].enabled = ismuted;
  494. }
  495. return ismuted;
  496. };
  497. LocalStream.prototype.setMute = function(mute)
  498. {
  499. var tracks = this.getTracks();
  500. for (var idx = 0; idx < tracks.length; idx++) {
  501. tracks[idx].enabled = mute;
  502. }
  503. };
  504. LocalStream.prototype.isMuted = function () {
  505. var tracks = [];
  506. if(this.type == "audio")
  507. {
  508. tracks = this.stream.getAudioTracks();
  509. }
  510. else
  511. {
  512. tracks = this.stream.getVideoTracks();
  513. }
  514. for (var idx = 0; idx < tracks.length; idx++) {
  515. if(tracks[idx].enabled)
  516. return false;
  517. }
  518. return true;
  519. }
  520. LocalStream.prototype.getId = function () {
  521. return this.stream.getTracks()[0].id;
  522. }
  523. module.exports = LocalStream;
  524. },{"../../service/RTC/StreamEventTypes.js":79}],5:[function(require,module,exports){
  525. ////These lines should be uncommented when require works in app.js
  526. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  527. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  528. /**
  529. * Creates a MediaStream object for the given data, session id and ssrc.
  530. * It is a wrapper class for the MediaStream.
  531. *
  532. * @param data the data object from which we obtain the stream,
  533. * the peerjid, etc.
  534. * @param sid the session id
  535. * @param ssrc the ssrc corresponding to this MediaStream
  536. *
  537. * @constructor
  538. */
  539. function MediaStream(data, sid, ssrc, browser) {
  540. // XXX(gp) to minimize headaches in the future, we should build our
  541. // abstractions around tracks and not streams. ORTC is track based API.
  542. // Mozilla expects m-lines to represent media tracks.
  543. //
  544. // Practically, what I'm saying is that we should have a MediaTrack class
  545. // and not a MediaStream class.
  546. //
  547. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  548. // a track might have an associated RTX and FEC sources.
  549. this.sid = sid;
  550. this.stream = data.stream;
  551. this.peerjid = data.peerjid;
  552. this.ssrc = ssrc;
  553. this.type = (this.stream.getVideoTracks().length > 0)?
  554. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  555. this.videoType = null;
  556. this.muted = false;
  557. if(browser == RTCBrowserType.RTC_BROWSER_FIREFOX)
  558. {
  559. if (!this.getVideoTracks)
  560. this.getVideoTracks = function () { return []; };
  561. if (!this.getAudioTracks)
  562. this.getAudioTracks = function () { return []; };
  563. }
  564. }
  565. MediaStream.prototype.getOriginalStream = function()
  566. {
  567. return this.stream;
  568. }
  569. MediaStream.prototype.setMute = function (value)
  570. {
  571. this.stream.muted = value;
  572. this.muted = value;
  573. }
  574. module.exports = MediaStream;
  575. },{"../../service/RTC/MediaStreamTypes":76,"../../service/RTC/RTCBrowserType.js":77}],6:[function(require,module,exports){
  576. var EventEmitter = require("events");
  577. var RTCUtils = require("./RTCUtils.js");
  578. var LocalStream = require("./LocalStream.js");
  579. var DataChannels = require("./DataChannels");
  580. var MediaStream = require("./MediaStream.js");
  581. var DesktopSharingEventTypes
  582. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  583. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  584. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  585. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  586. var UIEvents = require("../../service/UI/UIEvents");
  587. var eventEmitter = new EventEmitter();
  588. var RTC = {
  589. rtcUtils: null,
  590. localStreams: [],
  591. remoteStreams: {},
  592. localAudio: null,
  593. localVideo: null,
  594. addStreamListener: function (listener, eventType) {
  595. eventEmitter.on(eventType, listener);
  596. },
  597. addListener: function (type, listener) {
  598. eventEmitter.on(type, listener);
  599. },
  600. removeStreamListener: function (listener, eventType) {
  601. if(!(eventType instanceof StreamEventTypes))
  602. throw "Illegal argument";
  603. eventEmitter.removeListener(eventType, listener);
  604. },
  605. createLocalStream: function (stream, type, change) {
  606. var localStream = new LocalStream(stream, type, eventEmitter);
  607. //in firefox we have only one stream object
  608. if(this.localStreams.length == 0 ||
  609. this.localStreams[0].getOriginalStream() != stream)
  610. this.localStreams.push(localStream);
  611. if(type == "audio")
  612. {
  613. this.localAudio = localStream;
  614. }
  615. else
  616. {
  617. this.localVideo = localStream;
  618. }
  619. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  620. if(change)
  621. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  622. eventEmitter.emit(eventType, localStream);
  623. return localStream;
  624. },
  625. removeLocalStream: function (stream) {
  626. for(var i = 0; i < this.localStreams.length; i++)
  627. {
  628. if(this.localStreams[i].getOriginalStream() === stream) {
  629. delete this.localStreams[i];
  630. return;
  631. }
  632. }
  633. },
  634. createRemoteStream: function (data, sid, thessrc) {
  635. var remoteStream = new MediaStream(data, sid, thessrc,
  636. this.getBrowserType());
  637. var jid = data.peerjid || APP.xmpp.myJid();
  638. if(!this.remoteStreams[jid]) {
  639. this.remoteStreams[jid] = {};
  640. }
  641. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  642. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  643. console.debug("ADD remote stream ", remoteStream.type, " ", jid, " ", thessrc);
  644. return remoteStream;
  645. },
  646. getBrowserType: function () {
  647. return this.rtcUtils.browser;
  648. },
  649. getPCConstraints: function () {
  650. return this.rtcUtils.pc_constraints;
  651. },
  652. getUserMediaWithConstraints:function(um, success_callback,
  653. failure_callback, resolution,
  654. bandwidth, fps, desktopStream)
  655. {
  656. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  657. failure_callback, resolution, bandwidth, fps, desktopStream);
  658. },
  659. attachMediaStream: function (element, stream) {
  660. this.rtcUtils.attachMediaStream(element, stream);
  661. },
  662. getStreamID: function (stream) {
  663. return this.rtcUtils.getStreamID(stream);
  664. },
  665. getVideoSrc: function (element) {
  666. return this.rtcUtils.getVideoSrc(element);
  667. },
  668. setVideoSrc: function (element, src) {
  669. this.rtcUtils.setVideoSrc(element, src);
  670. },
  671. dispose: function() {
  672. if (this.rtcUtils) {
  673. this.rtcUtils = null;
  674. }
  675. },
  676. stop: function () {
  677. this.dispose();
  678. },
  679. start: function () {
  680. var self = this;
  681. APP.desktopsharing.addListener(
  682. function (stream, isUsingScreenStream, callback) {
  683. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  684. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  685. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  686. for(var i = 0; i < changedStreams.length; i++) {
  687. var type = changedStreams[i].type;
  688. if (type != "audio") {
  689. var peerStreams = self.remoteStreams[jid];
  690. if(!peerStreams)
  691. continue;
  692. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  693. if(!videoStream)
  694. continue;
  695. videoStream.videoType = changedStreams[i].type;
  696. }
  697. }
  698. });
  699. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  700. DataChannels.init(event.peerconnection, eventEmitter);
  701. });
  702. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  703. DataChannels.handleSelectedEndpointEvent);
  704. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  705. DataChannels.handlePinnedEndpointEvent);
  706. this.rtcUtils = new RTCUtils(this);
  707. this.rtcUtils.obtainAudioAndVideoPermissions();
  708. },
  709. muteRemoteVideoStream: function (jid, value) {
  710. var stream;
  711. if(this.remoteStreams[jid] &&
  712. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  713. {
  714. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  715. }
  716. if(!stream)
  717. return false;
  718. if (value != stream.muted) {
  719. stream.setMute(value);
  720. return true;
  721. }
  722. return false;
  723. },
  724. switchVideoStreams: function (new_stream) {
  725. this.localVideo.stream = new_stream;
  726. this.localStreams = [];
  727. //in firefox we have only one stream object
  728. if (this.localAudio.getOriginalStream() != new_stream)
  729. this.localStreams.push(this.localAudio);
  730. this.localStreams.push(this.localVideo);
  731. },
  732. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  733. var oldStream = this.localVideo.getOriginalStream();
  734. var type = (isUsingScreenStream? "screen" : "video");
  735. this.localVideo = this.createLocalStream(stream, "video", true, type);
  736. // Stop the stream to trigger onended event for old stream
  737. oldStream.stop();
  738. APP.xmpp.switchStreams(stream, oldStream,callback);
  739. },
  740. /**
  741. * Checks if video identified by given src is desktop stream.
  742. * @param videoSrc eg.
  743. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  744. * @returns {boolean}
  745. */
  746. isVideoSrcDesktop: function (jid) {
  747. if(!jid)
  748. return false;
  749. var isDesktop = false;
  750. var stream = null;
  751. if (APP.xmpp.myJid() &&
  752. APP.xmpp.myResource() === jid) {
  753. // local video
  754. stream = this.localVideo;
  755. } else {
  756. var peerStreams = this.remoteStreams[jid];
  757. if(!peerStreams)
  758. return false;
  759. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  760. }
  761. if(stream)
  762. isDesktop = (stream.videoType === "screen");
  763. return isDesktop;
  764. }
  765. };
  766. module.exports = RTC;
  767. },{"../../service/RTC/MediaStreamTypes":76,"../../service/RTC/StreamEventTypes.js":79,"../../service/UI/UIEvents":80,"../../service/desktopsharing/DesktopSharingEventTypes":82,"../../service/xmpp/XMPPEvents":83,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":84}],7:[function(require,module,exports){
  768. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  769. function setResolutionConstraints(constraints, resolution, isAndroid)
  770. {
  771. if (resolution && !constraints.video || isAndroid) {
  772. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  773. }
  774. // see https://code.google.com/p/chromium/issues/detail?id=143631#c9 for list of supported resolutions
  775. switch (resolution) {
  776. // 16:9 first
  777. case '1080':
  778. case 'fullhd':
  779. constraints.video.mandatory.minWidth = 1920;
  780. constraints.video.mandatory.minHeight = 1080;
  781. break;
  782. case '720':
  783. case 'hd':
  784. constraints.video.mandatory.minWidth = 1280;
  785. constraints.video.mandatory.minHeight = 720;
  786. break;
  787. case '360':
  788. constraints.video.mandatory.minWidth = 640;
  789. constraints.video.mandatory.minHeight = 360;
  790. break;
  791. case '180':
  792. constraints.video.mandatory.minWidth = 320;
  793. constraints.video.mandatory.minHeight = 180;
  794. break;
  795. // 4:3
  796. case '960':
  797. constraints.video.mandatory.minWidth = 960;
  798. constraints.video.mandatory.minHeight = 720;
  799. break;
  800. case '640':
  801. case 'vga':
  802. constraints.video.mandatory.minWidth = 640;
  803. constraints.video.mandatory.minHeight = 480;
  804. break;
  805. case '320':
  806. constraints.video.mandatory.minWidth = 320;
  807. constraints.video.mandatory.minHeight = 240;
  808. break;
  809. default:
  810. if (isAndroid) {
  811. constraints.video.mandatory.minWidth = 320;
  812. constraints.video.mandatory.minHeight = 240;
  813. constraints.video.mandatory.maxFrameRate = 15;
  814. }
  815. break;
  816. }
  817. if (constraints.video.mandatory.minWidth)
  818. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  819. if (constraints.video.mandatory.minHeight)
  820. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  821. }
  822. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  823. {
  824. var constraints = {audio: false, video: false};
  825. if (um.indexOf('video') >= 0) {
  826. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  827. }
  828. if (um.indexOf('audio') >= 0) {
  829. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  830. }
  831. if (um.indexOf('screen') >= 0) {
  832. constraints.video = {
  833. mandatory: {
  834. chromeMediaSource: "screen",
  835. googLeakyBucket: true,
  836. maxWidth: window.screen.width,
  837. maxHeight: window.screen.height,
  838. maxFrameRate: 3
  839. },
  840. optional: []
  841. };
  842. }
  843. if (um.indexOf('desktop') >= 0) {
  844. constraints.video = {
  845. mandatory: {
  846. chromeMediaSource: "desktop",
  847. chromeMediaSourceId: desktopStream,
  848. googLeakyBucket: true,
  849. maxWidth: window.screen.width,
  850. maxHeight: window.screen.height,
  851. maxFrameRate: 3
  852. },
  853. optional: []
  854. };
  855. }
  856. if (constraints.audio) {
  857. // if it is good enough for hangouts...
  858. constraints.audio.optional.push(
  859. {googEchoCancellation: true},
  860. {googAutoGainControl: true},
  861. {googNoiseSupression: true},
  862. {googHighpassFilter: true},
  863. {googNoisesuppression2: true},
  864. {googEchoCancellation2: true},
  865. {googAutoGainControl2: true}
  866. );
  867. }
  868. if (constraints.video) {
  869. constraints.video.optional.push(
  870. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  871. );
  872. if (um.indexOf('video') >= 0) {
  873. constraints.video.optional.push(
  874. {googLeakyBucket: true}
  875. );
  876. }
  877. }
  878. if (um.indexOf('video') >= 0) {
  879. setResolutionConstraints(constraints, resolution, isAndroid);
  880. }
  881. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  882. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  883. constraints.video.optional.push({bandwidth: bandwidth});
  884. }
  885. if (fps) { // for some cameras it might be necessary to request 30fps
  886. // so they choose 30fps mjpg over 10fps yuy2
  887. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  888. constraints.video.mandatory.minFrameRate = fps;
  889. }
  890. return constraints;
  891. }
  892. function RTCUtils(RTCService)
  893. {
  894. this.service = RTCService;
  895. if (navigator.mozGetUserMedia) {
  896. console.log('This appears to be Firefox');
  897. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  898. if (version >= 22) {
  899. this.peerconnection = mozRTCPeerConnection;
  900. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  901. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  902. this.pc_constraints = {};
  903. this.attachMediaStream = function (element, stream) {
  904. element[0].mozSrcObject = stream;
  905. element[0].play();
  906. };
  907. this.getStreamID = function (stream) {
  908. var tracks = stream.getVideoTracks();
  909. if(!tracks || tracks.length == 0)
  910. {
  911. tracks = stream.getAudioTracks();
  912. }
  913. return tracks[0].id.replace(/[\{,\}]/g,"");
  914. };
  915. this.getVideoSrc = function (element) {
  916. return element.mozSrcObject;
  917. };
  918. this.setVideoSrc = function (element, src) {
  919. element.mozSrcObject = src;
  920. };
  921. RTCSessionDescription = mozRTCSessionDescription;
  922. RTCIceCandidate = mozRTCIceCandidate;
  923. }
  924. } else if (navigator.webkitGetUserMedia) {
  925. console.log('This appears to be Chrome');
  926. this.peerconnection = webkitRTCPeerConnection;
  927. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  928. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  929. this.attachMediaStream = function (element, stream) {
  930. element.attr('src', webkitURL.createObjectURL(stream));
  931. };
  932. this.getStreamID = function (stream) {
  933. // streams from FF endpoints have the characters '{' and '}'
  934. // that make jQuery choke.
  935. return stream.id.replace(/[\{,\}]/g,"");
  936. };
  937. this.getVideoSrc = function (element) {
  938. return element.getAttribute("src");
  939. };
  940. this.setVideoSrc = function (element, src) {
  941. element.setAttribute("src", src);
  942. };
  943. // DTLS should now be enabled by default but..
  944. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  945. if (navigator.userAgent.indexOf('Android') != -1) {
  946. this.pc_constraints = {}; // disable DTLS on Android
  947. }
  948. if (!webkitMediaStream.prototype.getVideoTracks) {
  949. webkitMediaStream.prototype.getVideoTracks = function () {
  950. return this.videoTracks;
  951. };
  952. }
  953. if (!webkitMediaStream.prototype.getAudioTracks) {
  954. webkitMediaStream.prototype.getAudioTracks = function () {
  955. return this.audioTracks;
  956. };
  957. }
  958. }
  959. else
  960. {
  961. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  962. window.location.href = 'webrtcrequired.html';
  963. return;
  964. }
  965. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  966. config.enableFirefoxSupport !== true) {
  967. window.location.href = 'chromeonly.html';
  968. return;
  969. }
  970. }
  971. RTCUtils.prototype.getUserMediaWithConstraints = function(
  972. um, success_callback, failure_callback, resolution,bandwidth, fps,
  973. desktopStream)
  974. {
  975. // Check if we are running on Android device
  976. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  977. var constraints = getConstraints(
  978. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  979. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  980. try {
  981. if (config.enableSimulcast
  982. && constraints.video
  983. && constraints.video.chromeMediaSource !== 'screen'
  984. && constraints.video.chromeMediaSource !== 'desktop'
  985. && !isAndroid
  986. // We currently do not support FF, as it doesn't have multistream support.
  987. && !isFF) {
  988. APP.simulcast.getUserMedia(constraints, function (stream) {
  989. console.log('onUserMediaSuccess');
  990. success_callback(stream);
  991. },
  992. function (error) {
  993. console.warn('Failed to get access to local media. Error ', error);
  994. if (failure_callback) {
  995. failure_callback(error);
  996. }
  997. });
  998. } else {
  999. this.getUserMedia(constraints,
  1000. function (stream) {
  1001. console.log('onUserMediaSuccess');
  1002. success_callback(stream);
  1003. },
  1004. function (error) {
  1005. console.warn('Failed to get access to local media. Error ',
  1006. error, constraints);
  1007. if (failure_callback) {
  1008. failure_callback(error);
  1009. }
  1010. });
  1011. }
  1012. } catch (e) {
  1013. console.error('GUM failed: ', e);
  1014. if(failure_callback) {
  1015. failure_callback(e);
  1016. }
  1017. }
  1018. };
  1019. /**
  1020. * We ask for audio and video combined stream in order to get permissions and
  1021. * not to ask twice.
  1022. */
  1023. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1024. var self = this;
  1025. // Get AV
  1026. var cb = function (stream) {
  1027. console.log('got', stream, stream.getAudioTracks().length, stream.getVideoTracks().length);
  1028. self.handleLocalStream(stream);
  1029. };
  1030. var self = this;
  1031. this.getUserMediaWithConstraints(
  1032. ['audio', 'video'],
  1033. cb,
  1034. function (error) {
  1035. console.error('failed to obtain audio/video stream - trying audio only', error);
  1036. self.getUserMediaWithConstraints(
  1037. ['audio'],
  1038. cb,
  1039. function (error) {
  1040. console.error('failed to obtain audio/video stream - stop', error);
  1041. APP.UI.messageHandler.showError("Error",
  1042. "Failed to obtain permissions to use the local microphone" +
  1043. "and/or camera.");
  1044. }
  1045. );
  1046. },
  1047. config.resolution || '360');
  1048. }
  1049. RTCUtils.prototype.handleLocalStream = function(stream)
  1050. {
  1051. if(window.webkitMediaStream)
  1052. {
  1053. var audioStream = new webkitMediaStream();
  1054. var videoStream = new webkitMediaStream();
  1055. var audioTracks = stream.getAudioTracks();
  1056. var videoTracks = stream.getVideoTracks();
  1057. for (var i = 0; i < audioTracks.length; i++) {
  1058. audioStream.addTrack(audioTracks[i]);
  1059. }
  1060. this.service.createLocalStream(audioStream, "audio");
  1061. for (i = 0; i < videoTracks.length; i++) {
  1062. videoStream.addTrack(videoTracks[i]);
  1063. }
  1064. this.service.createLocalStream(videoStream, "video");
  1065. }
  1066. else
  1067. {//firefox
  1068. this.service.createLocalStream(stream, "stream");
  1069. }
  1070. };
  1071. module.exports = RTCUtils;
  1072. },{"../../service/RTC/RTCBrowserType.js":77}],8:[function(require,module,exports){
  1073. var UI = {};
  1074. var VideoLayout = require("./videolayout/VideoLayout.js");
  1075. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1076. var Prezi = require("./prezi/Prezi.js");
  1077. var Etherpad = require("./etherpad/Etherpad.js");
  1078. var Chat = require("./side_pannels/chat/Chat.js");
  1079. var Toolbar = require("./toolbars/Toolbar");
  1080. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1081. var BottomToolbar = require("./toolbars/BottomToolbar");
  1082. var ContactList = require("./side_pannels/contactlist/ContactList");
  1083. var Avatar = require("./avatar/Avatar");
  1084. var EventEmitter = require("events");
  1085. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1086. var Settings = require("./side_pannels/settings/Settings");
  1087. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1088. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1089. UI.messageHandler = require("./util/MessageHandler");
  1090. var messageHandler = UI.messageHandler;
  1091. var Authentication = require("./authentication/Authentication");
  1092. var UIUtil = require("./util/UIUtil");
  1093. var NicknameHandler = require("./util/NicknameHandler");
  1094. var CQEvents = require("../../service/connectionquality/CQEvents");
  1095. var DesktopSharingEventTypes
  1096. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1097. var RTCEvents = require("../../service/RTC/RTCEvents");
  1098. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1099. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1100. var eventEmitter = new EventEmitter();
  1101. var roomName = null;
  1102. function setupPrezi()
  1103. {
  1104. $("#reloadPresentationLink").click(function()
  1105. {
  1106. Prezi.reloadPresentation();
  1107. });
  1108. }
  1109. function setupChat()
  1110. {
  1111. Chat.init();
  1112. $("#toggle_smileys").click(function() {
  1113. Chat.toggleSmileys();
  1114. });
  1115. }
  1116. function setupToolbars() {
  1117. Toolbar.init(UI);
  1118. Toolbar.setupButtonsFromConfig();
  1119. BottomToolbar.init();
  1120. }
  1121. function streamHandler(stream) {
  1122. switch (stream.type)
  1123. {
  1124. case "audio":
  1125. VideoLayout.changeLocalAudio(stream);
  1126. break;
  1127. case "video":
  1128. VideoLayout.changeLocalVideo(stream);
  1129. break;
  1130. case "stream":
  1131. VideoLayout.changeLocalStream(stream);
  1132. break;
  1133. }
  1134. }
  1135. function onDisposeConference(unload) {
  1136. Toolbar.showAuthenticateButton(false);
  1137. };
  1138. function onDisplayNameChanged(jid, displayName) {
  1139. ContactList.onDisplayNameChange(jid, displayName);
  1140. SettingsMenu.onDisplayNameChange(jid, displayName);
  1141. VideoLayout.onDisplayNameChanged(jid, displayName);
  1142. }
  1143. function registerListeners() {
  1144. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1145. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1146. APP.RTC.addStreamListener(function (stream) {
  1147. VideoLayout.onRemoteStreamAdded(stream);
  1148. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1149. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1150. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1151. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1152. });
  1153. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1154. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1155. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1156. endpointsEnteringLastN, stream);
  1157. });
  1158. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1159. function (endpointSimulcastLayers) {
  1160. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1161. });
  1162. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1163. function (endpointSimulcastLayers) {
  1164. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1165. });
  1166. VideoLayout.init(eventEmitter);
  1167. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1168. {
  1169. var resourceJid;
  1170. if(jid === APP.statistics.LOCAL_JID)
  1171. {
  1172. resourceJid = AudioLevels.LOCAL_LEVEL;
  1173. if(APP.RTC.localAudio.isMuted())
  1174. {
  1175. audioLevel = 0;
  1176. }
  1177. }
  1178. else
  1179. {
  1180. resourceJid = Strophe.getResourceFromJid(jid);
  1181. }
  1182. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1183. UI.getLargeVideoState().userResourceJid);
  1184. });
  1185. APP.desktopsharing.addListener(function () {
  1186. ToolbarToggler.showDesktopSharingButton();
  1187. }, DesktopSharingEventTypes.INIT);
  1188. APP.desktopsharing.addListener(
  1189. Toolbar.changeDesktopSharingButtonState,
  1190. DesktopSharingEventTypes.SWITCHING_DONE);
  1191. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1192. VideoLayout.updateLocalConnectionStats);
  1193. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1194. VideoLayout.updateConnectionStats);
  1195. APP.connectionquality.addListener(CQEvents.STOP,
  1196. VideoLayout.onStatsStop);
  1197. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1198. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1199. messageHandler.openMessageDialog("Session Terminated",
  1200. "Ouch! You have been kicked out of the meet!");
  1201. });
  1202. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1203. messageHandler.showError("Error",
  1204. "Jitsi Videobridge is currently unavailable. Please try again later!");
  1205. });
  1206. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1207. Avatar.setUserAvatar(from, id);
  1208. });
  1209. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1210. for(stream in changedStreams)
  1211. {
  1212. // might need to update the direction if participant just went from sendrecv to recvonly
  1213. if (stream.type === 'video' || stream.type === 'screen') {
  1214. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1215. switch (stream.direction) {
  1216. case 'sendrecv':
  1217. el.show();
  1218. break;
  1219. case 'recvonly':
  1220. el.hide();
  1221. // FIXME: Check if we have to change large video
  1222. //VideoLayout.updateLargeVideo(el);
  1223. break;
  1224. }
  1225. }
  1226. }
  1227. });
  1228. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1229. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1230. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1231. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1232. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1233. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1234. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1235. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1236. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1237. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1238. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1239. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1240. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1241. }
  1242. /**
  1243. * Mutes/unmutes the local video.
  1244. *
  1245. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1246. * @param options an object which specifies optional arguments such as the
  1247. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1248. * specifies whether the method was initiated in response to a user command (in
  1249. * contrast to an automatic decision taken by the application logic)
  1250. */
  1251. function setVideoMute(mute, options) {
  1252. APP.xmpp.setVideoMute(
  1253. mute,
  1254. function (mute) {
  1255. var video = $('#video');
  1256. var communicativeClass = "icon-camera";
  1257. var muteClass = "icon-camera icon-camera-disabled";
  1258. if (mute) {
  1259. video.removeClass(communicativeClass);
  1260. video.addClass(muteClass);
  1261. } else {
  1262. video.removeClass(muteClass);
  1263. video.addClass(communicativeClass);
  1264. }
  1265. },
  1266. options);
  1267. }
  1268. function bindEvents()
  1269. {
  1270. /**
  1271. * Resizes and repositions videos in full screen mode.
  1272. */
  1273. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1274. function () {
  1275. VideoLayout.resizeLargeVideoContainer();
  1276. VideoLayout.positionLarge();
  1277. }
  1278. );
  1279. $(window).resize(function () {
  1280. VideoLayout.resizeLargeVideoContainer();
  1281. VideoLayout.positionLarge();
  1282. });
  1283. }
  1284. UI.start = function (init) {
  1285. document.title = interfaceConfig.APP_NAME;
  1286. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1287. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1288. {
  1289. $("#videoconference_page").hide();
  1290. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1291. setupWelcomePage();
  1292. return;
  1293. }
  1294. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1295. var leftWatermarkDiv
  1296. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1297. leftWatermarkDiv.css({display: 'block'});
  1298. leftWatermarkDiv.parent().get(0).href
  1299. = interfaceConfig.JITSI_WATERMARK_LINK;
  1300. }
  1301. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1302. var rightWatermarkDiv
  1303. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1304. rightWatermarkDiv.css({display: 'block'});
  1305. rightWatermarkDiv.parent().get(0).href
  1306. = interfaceConfig.BRAND_WATERMARK_LINK;
  1307. rightWatermarkDiv.get(0).style.backgroundImage
  1308. = "url(images/rightwatermark.png)";
  1309. }
  1310. if (interfaceConfig.SHOW_POWERED_BY) {
  1311. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1312. }
  1313. $("#welcome_page").hide();
  1314. VideoLayout.resizeLargeVideoContainer();
  1315. $("#videospace").mousemove(function () {
  1316. return ToolbarToggler.showToolbar();
  1317. });
  1318. // Set the defaults for prompt dialogs.
  1319. jQuery.prompt.setDefaults({persistent: false});
  1320. NicknameHandler.init(eventEmitter);
  1321. registerListeners();
  1322. bindEvents();
  1323. setupPrezi();
  1324. setupToolbars();
  1325. setupChat();
  1326. document.title = interfaceConfig.APP_NAME;
  1327. $("#downloadlog").click(function (event) {
  1328. dump(event.target);
  1329. });
  1330. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1331. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1332. {
  1333. $("#videoconference_page").hide();
  1334. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1335. setupWelcomePage();
  1336. return;
  1337. }
  1338. $("#welcome_page").hide();
  1339. document.getElementById('largeVideo').volume = 0;
  1340. if (!$('#settings').is(':visible')) {
  1341. console.log('init');
  1342. init();
  1343. } else {
  1344. loginInfo.onsubmit = function (e) {
  1345. if (e.preventDefault) e.preventDefault();
  1346. $('#settings').hide();
  1347. init();
  1348. };
  1349. }
  1350. toastr.options = {
  1351. "closeButton": true,
  1352. "debug": false,
  1353. "positionClass": "notification-bottom-right",
  1354. "onclick": null,
  1355. "showDuration": "300",
  1356. "hideDuration": "1000",
  1357. "timeOut": "2000",
  1358. "extendedTimeOut": "1000",
  1359. "showEasing": "swing",
  1360. "hideEasing": "linear",
  1361. "showMethod": "fadeIn",
  1362. "hideMethod": "fadeOut",
  1363. "reposition": function() {
  1364. if(PanelToggler.isVisible()) {
  1365. $("#toast-container").addClass("notification-bottom-right-center");
  1366. } else {
  1367. $("#toast-container").removeClass("notification-bottom-right-center");
  1368. }
  1369. },
  1370. "newestOnTop": false
  1371. };
  1372. $('#settingsmenu>input').keyup(function(event){
  1373. if(event.keyCode === 13) {//enter
  1374. SettingsMenu.update();
  1375. }
  1376. });
  1377. $("#updateSettings").click(function () {
  1378. SettingsMenu.update();
  1379. });
  1380. };
  1381. function chatAddError(errorMessage, originalText)
  1382. {
  1383. return Chat.chatAddError(errorMessage, originalText);
  1384. };
  1385. function chatSetSubject(text)
  1386. {
  1387. return Chat.chatSetSubject(text);
  1388. };
  1389. function updateChatConversation(from, displayName, message) {
  1390. return Chat.updateChatConversation(from, displayName, message);
  1391. };
  1392. function onMucJoined(jid, info) {
  1393. Toolbar.updateRoomUrl(window.location.href);
  1394. document.getElementById('localNick').appendChild(
  1395. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  1396. );
  1397. var settings = Settings.getSettings();
  1398. // Add myself to the contact list.
  1399. ContactList.addContact(jid, settings.email || settings.uid);
  1400. // Once we've joined the muc show the toolbar
  1401. ToolbarToggler.showToolbar();
  1402. // Show authenticate button if needed
  1403. Toolbar.showAuthenticateButton(
  1404. APP.xmpp.isExternalAuthEnabled() && !APP.xmpp.isModerator());
  1405. var displayName = !config.displayJids
  1406. ? info.displayName : Strophe.getResourceFromJid(jid);
  1407. if (displayName)
  1408. onDisplayNameChanged('localVideoContainer', displayName + ' (me)');
  1409. }
  1410. function initEtherpad(name) {
  1411. Etherpad.init(name);
  1412. };
  1413. function onMucLeft(jid) {
  1414. console.log('left.muc', jid);
  1415. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1416. '>.displayname').html();
  1417. messageHandler.notify(displayName || 'Somebody',
  1418. 'disconnected',
  1419. 'disconnected');
  1420. // Need to call this with a slight delay, otherwise the element couldn't be
  1421. // found for some reason.
  1422. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1423. window.setTimeout(function () {
  1424. var container = document.getElementById(
  1425. 'participant_' + Strophe.getResourceFromJid(jid));
  1426. if (container) {
  1427. ContactList.removeContact(jid);
  1428. VideoLayout.removeConnectionIndicator(jid);
  1429. // hide here, wait for video to close before removing
  1430. $(container).hide();
  1431. VideoLayout.resizeThumbnails();
  1432. }
  1433. }, 10);
  1434. VideoLayout.participantLeft(jid);
  1435. };
  1436. function onLocalRoleChange(jid, info, pres, isModerator, isExternalAuthEnabled)
  1437. {
  1438. console.info("My role changed, new role: " + info.role);
  1439. onModeratorStatusChanged(isModerator);
  1440. VideoLayout.showModeratorIndicator();
  1441. Toolbar.showAuthenticateButton(
  1442. isExternalAuthEnabled && !isModerator);
  1443. if (isModerator) {
  1444. Authentication.closeAuthenticationWindow();
  1445. messageHandler.notify(
  1446. 'Me', 'connected', 'Moderator rights granted !');
  1447. }
  1448. }
  1449. function onModeratorStatusChanged(isModerator) {
  1450. Toolbar.showSipCallButton(isModerator);
  1451. Toolbar.showRecordingButton(
  1452. isModerator); //&&
  1453. // FIXME:
  1454. // Recording visible if
  1455. // there are at least 2(+ 1 focus) participants
  1456. //Object.keys(connection.emuc.members).length >= 3);
  1457. if (isModerator && config.etherpad_base) {
  1458. Etherpad.init();
  1459. }
  1460. };
  1461. function onPasswordReqiured(callback) {
  1462. // password is required
  1463. Toolbar.lockLockButton();
  1464. messageHandler.openTwoButtonDialog(null,
  1465. '<h2>Password required</h2>' +
  1466. '<input id="lockKey" type="text" placeholder="password" autofocus>',
  1467. true,
  1468. "Ok",
  1469. function (e, v, m, f) {},
  1470. function (event) {
  1471. document.getElementById('lockKey').focus();
  1472. },
  1473. function (e, v, m, f) {
  1474. if (v) {
  1475. var lockKey = document.getElementById('lockKey');
  1476. if (lockKey.value !== null) {
  1477. Toolbar.setSharedKey(lockKey.value);
  1478. callback(lockKey.value);
  1479. }
  1480. }
  1481. }
  1482. );
  1483. }
  1484. function onMucEntered(jid, id, displayName) {
  1485. messageHandler.notify(displayName || 'Somebody',
  1486. 'connected',
  1487. 'connected');
  1488. // Add Peer's container
  1489. VideoLayout.ensurePeerContainerExists(jid,id);
  1490. }
  1491. function onMucPresenceStatus( jid, info) {
  1492. VideoLayout.setPresenceStatus(
  1493. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1494. }
  1495. function onMucRoleChanged(role, displayName) {
  1496. VideoLayout.showModeratorIndicator();
  1497. if (role === 'moderator') {
  1498. var displayName = displayName;
  1499. if (!displayName) {
  1500. displayName = 'Somebody';
  1501. }
  1502. messageHandler.notify(
  1503. displayName,
  1504. 'connected',
  1505. 'Moderator rights granted to ' + displayName + '!');
  1506. }
  1507. }
  1508. function onAuthenticationRequired(intervalCallback) {
  1509. Authentication.openAuthenticationDialog(
  1510. roomName, intervalCallback, function () {
  1511. Toolbar.authenticateClicked();
  1512. });
  1513. };
  1514. function onLastNChanged(oldValue, newValue) {
  1515. if (config.muteLocalVideoIfNotInLastN) {
  1516. setVideoMute(!newValue, { 'byUser': false });
  1517. }
  1518. }
  1519. UI.toggleSmileys = function () {
  1520. Chat.toggleSmileys();
  1521. };
  1522. UI.getSettings = function () {
  1523. return Settings.getSettings();
  1524. };
  1525. UI.toggleFilmStrip = function () {
  1526. return BottomToolbar.toggleFilmStrip();
  1527. };
  1528. UI.toggleChat = function () {
  1529. return BottomToolbar.toggleChat();
  1530. };
  1531. UI.toggleContactList = function () {
  1532. return BottomToolbar.toggleContactList();
  1533. };
  1534. UI.inputDisplayNameHandler = function (value) {
  1535. VideoLayout.inputDisplayNameHandler(value);
  1536. };
  1537. UI.getLargeVideoState = function()
  1538. {
  1539. return VideoLayout.getLargeVideoState();
  1540. };
  1541. UI.generateRoomName = function() {
  1542. if(roomName)
  1543. return roomName;
  1544. var roomnode = null;
  1545. var path = window.location.pathname;
  1546. // determinde the room node from the url
  1547. // TODO: just the roomnode or the whole bare jid?
  1548. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1549. // custom function might be responsible for doing the pushstate
  1550. roomnode = config.getroomnode(path);
  1551. } else {
  1552. /* fall back to default strategy
  1553. * this is making assumptions about how the URL->room mapping happens.
  1554. * It currently assumes deployment at root, with a rewrite like the
  1555. * following one (for nginx):
  1556. location ~ ^/([a-zA-Z0-9]+)$ {
  1557. rewrite ^/(.*)$ / break;
  1558. }
  1559. */
  1560. if (path.length > 1) {
  1561. roomnode = path.substr(1).toLowerCase();
  1562. } else {
  1563. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1564. roomnode = word.toLowerCase();
  1565. window.history.pushState('VideoChat',
  1566. 'Room: ' + word, window.location.pathname + word);
  1567. }
  1568. }
  1569. roomName = roomnode + '@' + config.hosts.muc;
  1570. return roomName;
  1571. };
  1572. UI.connectionIndicatorShowMore = function(id)
  1573. {
  1574. return VideoLayout.connectionIndicators[id].showMore();
  1575. };
  1576. UI.getCreadentials = function () {
  1577. var settings = this.getSettings();
  1578. return {
  1579. bosh: document.getElementById('boshURL').value,
  1580. password: document.getElementById('password').value,
  1581. jid: document.getElementById('jid').value,
  1582. email: settings.email,
  1583. displayName: settings.displayName,
  1584. uid: settings.uid
  1585. };
  1586. };
  1587. UI.disableConnect = function () {
  1588. document.getElementById('connect').disabled = true;
  1589. };
  1590. UI.showLoginPopup = function(callback)
  1591. {
  1592. console.log('password is required');
  1593. UI.messageHandler.openTwoButtonDialog(null,
  1594. '<h2>Password required</h2>' +
  1595. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  1596. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  1597. true,
  1598. "Ok",
  1599. function (e, v, m, f) {
  1600. if (v) {
  1601. var username = document.getElementById('passwordrequired.username');
  1602. var password = document.getElementById('passwordrequired.password');
  1603. if (username.value !== null && password.value != null) {
  1604. callback(username.value, password.value);
  1605. }
  1606. }
  1607. },
  1608. function (event) {
  1609. document.getElementById('passwordrequired.username').focus();
  1610. }
  1611. );
  1612. }
  1613. UI.checkForNicknameAndJoin = function () {
  1614. Authentication.closeAuthenticationDialog();
  1615. Authentication.stopInterval();
  1616. var nick = null;
  1617. if (config.useNicks) {
  1618. nick = window.prompt('Your nickname (optional)');
  1619. }
  1620. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1621. };
  1622. function dump(elem, filename) {
  1623. elem = elem.parentNode;
  1624. elem.download = filename || 'meetlog.json';
  1625. elem.href = 'data:application/json;charset=utf-8,\n';
  1626. var data = APP.xmpp.populateData();
  1627. var metadata = {};
  1628. metadata.time = new Date();
  1629. metadata.url = window.location.href;
  1630. metadata.ua = navigator.userAgent;
  1631. var log = APP.xmpp.getLogger();
  1632. if (log) {
  1633. metadata.xmpp = log;
  1634. }
  1635. data.metadata = metadata;
  1636. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1637. return false;
  1638. }
  1639. UI.getRoomName = function () {
  1640. return roomName;
  1641. };
  1642. /**
  1643. * Mutes/unmutes the local video.
  1644. */
  1645. UI.toggleVideo = function () {
  1646. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1647. setVideoMute(!APP.RTC.localVideo.isMuted());
  1648. };
  1649. /**
  1650. * Mutes / unmutes audio for the local participant.
  1651. */
  1652. UI.toggleAudio = function() {
  1653. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1654. };
  1655. /**
  1656. * Sets muted audio state for the local participant.
  1657. */
  1658. UI.setAudioMuted = function (mute) {
  1659. if(!APP.xmpp.setAudioMute(mute, function () {
  1660. VideoLayout.showLocalAudioIndicator(mute);
  1661. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1662. }))
  1663. {
  1664. // We still click the button.
  1665. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1666. return;
  1667. }
  1668. }
  1669. UI.addListener = function (type, listener) {
  1670. eventEmitter.on(type, listener);
  1671. }
  1672. UI.clickOnVideo = function (videoNumber) {
  1673. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1674. if (remoteVideos.length > videoNumber) {
  1675. remoteVideos[videoNumber].click();
  1676. }
  1677. }
  1678. module.exports = UI;
  1679. },{"../../service/RTC/RTCEvents":78,"../../service/RTC/StreamEventTypes":79,"../../service/connectionquality/CQEvents":81,"../../service/desktopsharing/DesktopSharingEventTypes":82,"../../service/xmpp/XMPPEvents":83,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":12,"./etherpad/Etherpad.js":13,"./prezi/Prezi.js":14,"./side_pannels/SidePanelToggler":16,"./side_pannels/chat/Chat.js":17,"./side_pannels/contactlist/ContactList":21,"./side_pannels/settings/Settings":22,"./side_pannels/settings/SettingsMenu":23,"./toolbars/BottomToolbar":24,"./toolbars/Toolbar":25,"./toolbars/ToolbarToggler":26,"./util/MessageHandler":28,"./util/NicknameHandler":29,"./util/UIUtil":30,"./videolayout/VideoLayout.js":32,"./welcome_page/RoomnameGenerator":33,"./welcome_page/WelcomePage":34,"events":84}],9:[function(require,module,exports){
  1680. var CanvasUtil = require("./CanvasUtils");
  1681. /**
  1682. * The audio Levels plugin.
  1683. */
  1684. var AudioLevels = (function(my) {
  1685. var audioLevelCanvasCache = {};
  1686. my.LOCAL_LEVEL = 'local';
  1687. /**
  1688. * Updates the audio level canvas for the given peerJid. If the canvas
  1689. * didn't exist we create it.
  1690. */
  1691. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1692. var resourceJid = null;
  1693. var videoSpanId = null;
  1694. if (!peerJid)
  1695. videoSpanId = 'localVideoContainer';
  1696. else {
  1697. resourceJid = Strophe.getResourceFromJid(peerJid);
  1698. videoSpanId = 'participant_' + resourceJid;
  1699. }
  1700. var videoSpan = document.getElementById(videoSpanId);
  1701. if (!videoSpan) {
  1702. if (resourceJid)
  1703. console.error("No video element for jid", resourceJid);
  1704. else
  1705. console.error("No video element for local video.");
  1706. return;
  1707. }
  1708. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1709. var videoSpaceWidth = $('#remoteVideos').width();
  1710. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1711. var thumbnailWidth = thumbnailSize[0];
  1712. var thumbnailHeight = thumbnailSize[1];
  1713. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1714. audioLevelCanvas = document.createElement('canvas');
  1715. audioLevelCanvas.className = "audiolevel";
  1716. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1717. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1718. resizeAudioLevelCanvas( audioLevelCanvas,
  1719. thumbnailWidth,
  1720. thumbnailHeight);
  1721. videoSpan.appendChild(audioLevelCanvas);
  1722. } else {
  1723. audioLevelCanvas = audioLevelCanvas.get(0);
  1724. resizeAudioLevelCanvas( audioLevelCanvas,
  1725. thumbnailWidth,
  1726. thumbnailHeight);
  1727. }
  1728. };
  1729. /**
  1730. * Updates the audio level UI for the given resourceJid.
  1731. *
  1732. * @param resourceJid the resource jid indicating the video element for
  1733. * which we draw the audio level
  1734. * @param audioLevel the newAudio level to render
  1735. */
  1736. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1737. drawAudioLevelCanvas(resourceJid, audioLevel);
  1738. var videoSpanId = getVideoSpanId(resourceJid);
  1739. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1740. if (!audioLevelCanvas)
  1741. return;
  1742. var drawContext = audioLevelCanvas.getContext('2d');
  1743. var canvasCache = audioLevelCanvasCache[resourceJid];
  1744. drawContext.clearRect (0, 0,
  1745. audioLevelCanvas.width, audioLevelCanvas.height);
  1746. drawContext.drawImage(canvasCache, 0, 0);
  1747. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1748. if(!APP.xmpp.myJid()) {
  1749. return;
  1750. }
  1751. resourceJid = APP.xmpp.myResource();
  1752. }
  1753. if(resourceJid === largeVideoResourceJid) {
  1754. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1755. }
  1756. };
  1757. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1758. var drawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1759. var r = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1760. var center = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + r) / 2;
  1761. // Save the previous state of the context.
  1762. drawContext.save();
  1763. drawContext.clearRect(0, 0, 300, 300);
  1764. // Draw a circle.
  1765. drawContext.arc(center, center, r, 0, 2 * Math.PI);
  1766. // Add a shadow around the circle
  1767. drawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1768. drawContext.shadowBlur = getShadowLevel(audioLevel);
  1769. drawContext.shadowOffsetX = 0;
  1770. drawContext.shadowOffsetY = 0;
  1771. // Fill the shape.
  1772. drawContext.fill();
  1773. drawContext.save();
  1774. drawContext.restore();
  1775. drawContext.arc(center, center, r, 0, 2 * Math.PI);
  1776. drawContext.clip();
  1777. drawContext.clearRect(0, 0, 277, 200);
  1778. // Restore the previous context state.
  1779. drawContext.restore();
  1780. };
  1781. /**
  1782. * Resizes the given audio level canvas to match the given thumbnail size.
  1783. */
  1784. function resizeAudioLevelCanvas(audioLevelCanvas,
  1785. thumbnailWidth,
  1786. thumbnailHeight) {
  1787. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1788. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1789. }
  1790. /**
  1791. * Draws the audio level canvas into the cached canvas object.
  1792. *
  1793. * @param resourceJid the resource jid indicating the video element for
  1794. * which we draw the audio level
  1795. * @param audioLevel the newAudio level to render
  1796. */
  1797. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1798. if (!audioLevelCanvasCache[resourceJid]) {
  1799. var videoSpanId = getVideoSpanId(resourceJid);
  1800. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1801. /*
  1802. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1803. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1804. * error. Since audio levels are frequently updated, the errors have
  1805. * been observed to pile into the console, strain the CPU.
  1806. */
  1807. if (audioLevelCanvasOrig)
  1808. {
  1809. audioLevelCanvasCache[resourceJid]
  1810. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1811. }
  1812. }
  1813. var canvas = audioLevelCanvasCache[resourceJid];
  1814. if (!canvas)
  1815. return;
  1816. var drawContext = canvas.getContext('2d');
  1817. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1818. var shadowLevel = getShadowLevel(audioLevel);
  1819. if (shadowLevel > 0)
  1820. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1821. CanvasUtil.drawRoundRectGlow( drawContext,
  1822. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1823. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1824. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1825. interfaceConfig.CANVAS_RADIUS,
  1826. interfaceConfig.SHADOW_COLOR,
  1827. shadowLevel);
  1828. }
  1829. /**
  1830. * Returns the shadow/glow level for the given audio level.
  1831. *
  1832. * @param audioLevel the audio level from which we determine the shadow
  1833. * level
  1834. */
  1835. function getShadowLevel (audioLevel) {
  1836. var shadowLevel = 0;
  1837. if (audioLevel <= 0.3) {
  1838. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1839. }
  1840. else if (audioLevel <= 0.6) {
  1841. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1842. }
  1843. else {
  1844. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1845. }
  1846. return shadowLevel;
  1847. }
  1848. /**
  1849. * Returns the video span id corresponding to the given resourceJid or local
  1850. * user.
  1851. */
  1852. function getVideoSpanId(resourceJid) {
  1853. var videoSpanId = null;
  1854. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1855. || (APP.xmpp.myResource() && resourceJid
  1856. === APP.xmpp.myResource()))
  1857. videoSpanId = 'localVideoContainer';
  1858. else
  1859. videoSpanId = 'participant_' + resourceJid;
  1860. return videoSpanId;
  1861. }
  1862. /**
  1863. * Indicates that the remote video has been resized.
  1864. */
  1865. $(document).bind('remotevideo.resized', function (event, width, height) {
  1866. var resized = false;
  1867. $('#remoteVideos>span>canvas').each(function() {
  1868. var canvas = $(this).get(0);
  1869. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  1870. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  1871. resized = true;
  1872. }
  1873. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  1874. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  1875. resized = true;
  1876. }
  1877. });
  1878. if (resized)
  1879. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  1880. audioLevelCanvasCache[resourceJid].width
  1881. = width + interfaceConfig.CANVAS_EXTRA;
  1882. audioLevelCanvasCache[resourceJid].height
  1883. = height + interfaceConfig.CANVAS_EXTRA;
  1884. });
  1885. });
  1886. return my;
  1887. })(AudioLevels || {});
  1888. module.exports = AudioLevels;
  1889. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  1890. /**
  1891. * Utility class for drawing canvas shapes.
  1892. */
  1893. var CanvasUtil = (function(my) {
  1894. /**
  1895. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  1896. * of the glow.
  1897. *
  1898. * @param drawContext the context of the canvas to draw to
  1899. * @param x the x coordinate of the round rectangle
  1900. * @param y the y coordinate of the round rectangle
  1901. * @param w the width of the round rectangle
  1902. * @param h the height of the round rectangle
  1903. * @param glowColor the color of the glow
  1904. * @param glowWidth the width of the glow
  1905. */
  1906. my.drawRoundRectGlow
  1907. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  1908. // Save the previous state of the context.
  1909. drawContext.save();
  1910. if (w < 2 * r) r = w / 2;
  1911. if (h < 2 * r) r = h / 2;
  1912. // Draw a round rectangle.
  1913. drawContext.beginPath();
  1914. drawContext.moveTo(x+r, y);
  1915. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1916. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1917. drawContext.arcTo(x, y+h, x, y, r);
  1918. drawContext.arcTo(x, y, x+w, y, r);
  1919. drawContext.closePath();
  1920. // Add a shadow around the rectangle
  1921. drawContext.shadowColor = glowColor;
  1922. drawContext.shadowBlur = glowWidth;
  1923. drawContext.shadowOffsetX = 0;
  1924. drawContext.shadowOffsetY = 0;
  1925. // Fill the shape.
  1926. drawContext.fill();
  1927. drawContext.save();
  1928. drawContext.restore();
  1929. // 1) Uncomment this line to use Composite Operation, which is doing the
  1930. // same as the clip function below and is also antialiasing the round
  1931. // border, but is said to be less fast performance wise.
  1932. // drawContext.globalCompositeOperation='destination-out';
  1933. drawContext.beginPath();
  1934. drawContext.moveTo(x+r, y);
  1935. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1936. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1937. drawContext.arcTo(x, y+h, x, y, r);
  1938. drawContext.arcTo(x, y, x+w, y, r);
  1939. drawContext.closePath();
  1940. // 2) Uncomment this line to use Composite Operation, which is doing the
  1941. // same as the clip function below and is also antialiasing the round
  1942. // border, but is said to be less fast performance wise.
  1943. // drawContext.fill();
  1944. // Comment these two lines if choosing to do the same with composite
  1945. // operation above 1 and 2.
  1946. drawContext.clip();
  1947. drawContext.clearRect(0, 0, 277, 200);
  1948. // Restore the previous context state.
  1949. drawContext.restore();
  1950. };
  1951. /**
  1952. * Clones the given canvas.
  1953. *
  1954. * @return the new cloned canvas.
  1955. */
  1956. my.cloneCanvas = function (oldCanvas) {
  1957. /*
  1958. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  1959. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  1960. * levels are frequently updated, the errors have been observed to pile
  1961. * into the console, strain the CPU.
  1962. */
  1963. if (!oldCanvas)
  1964. return oldCanvas;
  1965. //create a new canvas
  1966. var newCanvas = document.createElement('canvas');
  1967. var context = newCanvas.getContext('2d');
  1968. //set dimensions
  1969. newCanvas.width = oldCanvas.width;
  1970. newCanvas.height = oldCanvas.height;
  1971. //apply the old canvas to the new one
  1972. context.drawImage(oldCanvas, 0, 0);
  1973. //return the new canvas
  1974. return newCanvas;
  1975. };
  1976. return my;
  1977. })(CanvasUtil || {});
  1978. module.exports = CanvasUtil;
  1979. },{}],11:[function(require,module,exports){
  1980. /* Initial "authentication required" dialog */
  1981. var authDialog = null;
  1982. /* Loop retry ID that wits for other user to create the room */
  1983. var authRetryId = null;
  1984. var authenticationWindow = null;
  1985. var Authentication = {
  1986. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  1987. // This is the loop that will wait for the room to be created by
  1988. // someone else. 'auth_required.moderator' will bring us back here.
  1989. authRetryId = window.setTimeout(intervalCallback , 5000);
  1990. // Show prompt only if it's not open
  1991. if (authDialog !== null) {
  1992. return;
  1993. }
  1994. // extract room name from 'room@muc.server.net'
  1995. var room = roomName.substr(0, roomName.indexOf('@'));
  1996. authDialog = messageHandler.openDialog(
  1997. 'Stop',
  1998. 'Authentication is required to create room:<br/><b>' + room +
  1999. '</b></br> You can either authenticate to create the room or ' +
  2000. 'just wait for someone else to do so.',
  2001. true,
  2002. {
  2003. Authenticate: 'authNow'
  2004. },
  2005. function (onSubmitEvent, submitValue) {
  2006. // Do not close the dialog yet
  2007. onSubmitEvent.preventDefault();
  2008. // Open login popup
  2009. if (submitValue === 'authNow') {
  2010. callback();
  2011. }
  2012. }
  2013. );
  2014. },
  2015. closeAuthenticationWindow:function () {
  2016. if (authenticationWindow) {
  2017. authenticationWindow.close();
  2018. authenticationWindow = null;
  2019. }
  2020. },
  2021. focusAuthenticationWindow: function () {
  2022. // If auth window exists just bring it to the front
  2023. if (authenticationWindow) {
  2024. authenticationWindow.focus();
  2025. return;
  2026. }
  2027. },
  2028. closeAuthenticationDialog: function () {
  2029. // Close authentication dialog if opened
  2030. if (authDialog) {
  2031. APP.UI.messageHandler.closeDialog();
  2032. authDialog = null;
  2033. }
  2034. },
  2035. createAuthenticationWindow: function (callback, url) {
  2036. authenticationWindow = messageHandler.openCenteredPopup(
  2037. url, 910, 660,
  2038. // On closed
  2039. function () {
  2040. // Close authentication dialog if opened
  2041. if (authDialog) {
  2042. messageHandler.closeDialog();
  2043. authDialog = null;
  2044. }
  2045. callback();
  2046. authenticationWindow = null;
  2047. });
  2048. return authenticationWindow;
  2049. },
  2050. stopInterval: function () {
  2051. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2052. if (authRetryId) {
  2053. window.clearTimeout(authRetryId);
  2054. authRetryId = null;
  2055. }
  2056. }
  2057. };
  2058. module.exports = Authentication;
  2059. },{}],12:[function(require,module,exports){
  2060. var Settings = require("../side_pannels/settings/Settings");
  2061. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2062. var users = {};
  2063. var activeSpeakerJid;
  2064. function setVisibility(selector, show) {
  2065. if (selector && selector.length > 0) {
  2066. selector.css("visibility", show ? "visible" : "hidden");
  2067. }
  2068. }
  2069. function isUserMuted(jid) {
  2070. // XXX(gp) we may want to rename this method to something like
  2071. // isUserStreaming, for example.
  2072. if (jid && jid != APP.xmpp.myJid()) {
  2073. var resource = Strophe.getResourceFromJid(jid);
  2074. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2075. return true;
  2076. }
  2077. }
  2078. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2079. return null;
  2080. }
  2081. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2082. }
  2083. function getGravatarUrl(id, size) {
  2084. if(id === APP.xmpp.myJid() || !id) {
  2085. id = Settings.getSettings().uid;
  2086. }
  2087. return 'https://www.gravatar.com/avatar/' +
  2088. MD5.hexdigest(id.trim().toLowerCase()) +
  2089. "?d=wavatar&size=" + (size || "30");
  2090. }
  2091. var Avatar = {
  2092. /**
  2093. * Sets the user's avatar in the settings menu(if local user), contact list
  2094. * and thumbnail
  2095. * @param jid jid of the user
  2096. * @param id email or userID to be used as a hash
  2097. */
  2098. setUserAvatar: function (jid, id) {
  2099. if (id) {
  2100. if (users[jid] === id) {
  2101. return;
  2102. }
  2103. users[jid] = id;
  2104. }
  2105. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2106. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2107. var resourceJid = Strophe.getResourceFromJid(jid);
  2108. var thumbnail = $('#participant_' + resourceJid);
  2109. var avatar = $('#avatar_' + resourceJid);
  2110. // set the avatar in the settings menu if it is local user and get the
  2111. // local video container
  2112. if (jid === APP.xmpp.myJid()) {
  2113. $('#avatar').get(0).src = thumbUrl;
  2114. thumbnail = $('#localVideoContainer');
  2115. }
  2116. // set the avatar in the contact list
  2117. var contact = $('#' + resourceJid + '>img');
  2118. if (contact && contact.length > 0) {
  2119. contact.get(0).src = contactListUrl;
  2120. }
  2121. // set the avatar in the thumbnail
  2122. if (avatar && avatar.length > 0) {
  2123. avatar[0].src = thumbUrl;
  2124. } else {
  2125. if (thumbnail && thumbnail.length > 0) {
  2126. avatar = document.createElement('img');
  2127. avatar.id = 'avatar_' + resourceJid;
  2128. avatar.className = 'userAvatar';
  2129. avatar.src = thumbUrl;
  2130. thumbnail.append(avatar);
  2131. }
  2132. }
  2133. //if the user is the current active speaker - update the active speaker
  2134. // avatar
  2135. if (jid === activeSpeakerJid) {
  2136. this.updateActiveSpeakerAvatarSrc(jid);
  2137. }
  2138. },
  2139. /**
  2140. * Hides or shows the user's avatar
  2141. * @param jid jid of the user
  2142. * @param show whether we should show the avatar or not
  2143. * video because there is no dominant speaker and no focused speaker
  2144. */
  2145. showUserAvatar: function (jid, show) {
  2146. if (users[jid]) {
  2147. var resourceJid = Strophe.getResourceFromJid(jid);
  2148. var video = $('#participant_' + resourceJid + '>video');
  2149. var avatar = $('#avatar_' + resourceJid);
  2150. if (jid === APP.xmpp.myJid()) {
  2151. video = $('#localVideoWrapper>video');
  2152. }
  2153. if (show === undefined || show === null) {
  2154. show = isUserMuted(jid);
  2155. }
  2156. //if the user is the currently focused, the dominant speaker or if
  2157. //there is no focused and no dominant speaker and the large video is
  2158. //currently shown
  2159. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2160. setVisibility($("#largeVideo"), !show);
  2161. setVisibility($('#activeSpeaker'), show);
  2162. setVisibility(avatar, false);
  2163. setVisibility(video, false);
  2164. } else {
  2165. if (video && video.length > 0) {
  2166. setVisibility(video, !show);
  2167. setVisibility(avatar, show);
  2168. }
  2169. }
  2170. }
  2171. },
  2172. /**
  2173. * Updates the src of the active speaker avatar
  2174. * @param jid of the current active speaker
  2175. */
  2176. updateActiveSpeakerAvatarSrc: function (jid) {
  2177. if (!jid) {
  2178. jid = APP.xmpp.findJidFromResource(
  2179. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2180. }
  2181. var avatar = $("#activeSpeakerAvatar")[0];
  2182. var url = getGravatarUrl(users[jid],
  2183. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2184. if (jid === activeSpeakerJid && avatar.src === url) {
  2185. return;
  2186. }
  2187. activeSpeakerJid = jid;
  2188. var isMuted = isUserMuted(jid);
  2189. if (jid && isMuted !== null) {
  2190. avatar.src = url;
  2191. setVisibility($("#largeVideo"), !isMuted);
  2192. Avatar.showUserAvatar(jid, isMuted);
  2193. }
  2194. }
  2195. };
  2196. module.exports = Avatar;
  2197. },{"../../../service/RTC/MediaStreamTypes":76,"../side_pannels/settings/Settings":22,"../videolayout/VideoLayout":32}],13:[function(require,module,exports){
  2198. /* global $, config,
  2199. setLargeVideoVisible, Util */
  2200. var VideoLayout = require("../videolayout/VideoLayout");
  2201. var Prezi = require("../prezi/Prezi");
  2202. var UIUtil = require("../util/UIUtil");
  2203. var etherpadName = null;
  2204. var etherpadIFrame = null;
  2205. var domain = null;
  2206. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2207. /**
  2208. * Resizes the etherpad.
  2209. */
  2210. function resize() {
  2211. if ($('#etherpad>iframe').length) {
  2212. var remoteVideos = $('#remoteVideos');
  2213. var availableHeight
  2214. = window.innerHeight - remoteVideos.outerHeight();
  2215. var availableWidth = UIUtil.getAvailableVideoWidth();
  2216. $('#etherpad>iframe').width(availableWidth);
  2217. $('#etherpad>iframe').height(availableHeight);
  2218. }
  2219. }
  2220. /**
  2221. * Shares the Etherpad name with other participants.
  2222. */
  2223. function shareEtherpad() {
  2224. APP.xmpp.addToPresence("etherpad", etherpadName);
  2225. }
  2226. /**
  2227. * Creates the Etherpad button and adds it to the toolbar.
  2228. */
  2229. function enableEtherpadButton() {
  2230. if (!$('#etherpadButton').is(":visible"))
  2231. $('#etherpadButton').css({display: 'inline-block'});
  2232. }
  2233. /**
  2234. * Creates the IFrame for the etherpad.
  2235. */
  2236. function createIFrame() {
  2237. etherpadIFrame = document.createElement('iframe');
  2238. etherpadIFrame.src = domain + etherpadName + options;
  2239. etherpadIFrame.frameBorder = 0;
  2240. etherpadIFrame.scrolling = "no";
  2241. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2242. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2243. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2244. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2245. etherpadIFrame.onload = function() {
  2246. document.domain = document.domain;
  2247. bubbleIframeMouseMove(etherpadIFrame);
  2248. setTimeout(function() {
  2249. // the iframes inside of the etherpad are
  2250. // not yet loaded when the etherpad iframe is loaded
  2251. var outer = etherpadIFrame.
  2252. contentDocument.getElementsByName("ace_outer")[0];
  2253. bubbleIframeMouseMove(outer);
  2254. var inner = outer.
  2255. contentDocument.getElementsByName("ace_inner")[0];
  2256. bubbleIframeMouseMove(inner);
  2257. }, 2000);
  2258. };
  2259. }
  2260. function bubbleIframeMouseMove(iframe){
  2261. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2262. iframe.contentWindow.onmousemove = function(e){
  2263. if(existingOnMouseMove) existingOnMouseMove(e);
  2264. var evt = document.createEvent("MouseEvents");
  2265. var boundingClientRect = iframe.getBoundingClientRect();
  2266. evt.initMouseEvent(
  2267. "mousemove",
  2268. true, // bubbles
  2269. false, // not cancelable
  2270. window,
  2271. e.detail,
  2272. e.screenX,
  2273. e.screenY,
  2274. e.clientX + boundingClientRect.left,
  2275. e.clientY + boundingClientRect.top,
  2276. e.ctrlKey,
  2277. e.altKey,
  2278. e.shiftKey,
  2279. e.metaKey,
  2280. e.button,
  2281. null // no related element
  2282. );
  2283. iframe.dispatchEvent(evt);
  2284. };
  2285. }
  2286. /**
  2287. * On video selected event.
  2288. */
  2289. $(document).bind('video.selected', function (event, isPresentation) {
  2290. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2291. Etherpad.toggleEtherpad(isPresentation);
  2292. });
  2293. var Etherpad = {
  2294. /**
  2295. * Initializes the etherpad.
  2296. */
  2297. init: function (name) {
  2298. if (config.etherpad_base && !etherpadName) {
  2299. domain = config.etherpad_base;
  2300. if (!name) {
  2301. // In case we're the focus we generate the name.
  2302. etherpadName = Math.random().toString(36).substring(7) +
  2303. '_' + (new Date().getTime()).toString();
  2304. shareEtherpad();
  2305. }
  2306. else
  2307. etherpadName = name;
  2308. enableEtherpadButton();
  2309. /**
  2310. * Resizes the etherpad, when the window is resized.
  2311. */
  2312. $(window).resize(function () {
  2313. resize();
  2314. });
  2315. }
  2316. },
  2317. /**
  2318. * Opens/hides the Etherpad.
  2319. */
  2320. toggleEtherpad: function (isPresentation) {
  2321. if (!etherpadIFrame)
  2322. createIFrame();
  2323. var largeVideo = null;
  2324. if (Prezi.isPresentationVisible())
  2325. largeVideo = $('#presentation>iframe');
  2326. else
  2327. largeVideo = $('#largeVideo');
  2328. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2329. $('#activeSpeaker').css('visibility', 'hidden');
  2330. largeVideo.fadeOut(300, function () {
  2331. if (Prezi.isPresentationVisible()) {
  2332. largeVideo.css({opacity: '0'});
  2333. } else {
  2334. VideoLayout.setLargeVideoVisible(false);
  2335. }
  2336. });
  2337. $('#etherpad>iframe').fadeIn(300, function () {
  2338. document.body.style.background = '#eeeeee';
  2339. $('#etherpad>iframe').css({visibility: 'visible'});
  2340. $('#etherpad').css({zIndex: 2});
  2341. });
  2342. }
  2343. else if ($('#etherpad>iframe')) {
  2344. $('#etherpad>iframe').fadeOut(300, function () {
  2345. $('#etherpad>iframe').css({visibility: 'hidden'});
  2346. $('#etherpad').css({zIndex: 0});
  2347. document.body.style.background = 'black';
  2348. });
  2349. if (!isPresentation) {
  2350. $('#largeVideo').fadeIn(300, function () {
  2351. VideoLayout.setLargeVideoVisible(true);
  2352. });
  2353. }
  2354. }
  2355. resize();
  2356. },
  2357. isVisible: function() {
  2358. var etherpadIframe = $('#etherpad>iframe');
  2359. return etherpadIframe && etherpadIframe.is(':visible');
  2360. }
  2361. };
  2362. module.exports = Etherpad;
  2363. },{"../prezi/Prezi":14,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2364. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2365. var UIUtil = require("../util/UIUtil");
  2366. var VideoLayout = require("../videolayout/VideoLayout");
  2367. var messageHandler = require("../util/MessageHandler");
  2368. var PreziPlayer = require("./PreziPlayer");
  2369. var preziPlayer = null;
  2370. var Prezi = {
  2371. /**
  2372. * Reloads the current presentation.
  2373. */
  2374. reloadPresentation: function() {
  2375. var iframe = document.getElementById(preziPlayer.options.preziId);
  2376. iframe.src = iframe.src;
  2377. },
  2378. /**
  2379. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2380. * otherwise.
  2381. */
  2382. isPresentationVisible: function () {
  2383. return ($('#presentation>iframe') != null
  2384. && $('#presentation>iframe').css('opacity') == 1);
  2385. },
  2386. /**
  2387. * Opens the Prezi dialog, from which the user could choose a presentation
  2388. * to load.
  2389. */
  2390. openPreziDialog: function() {
  2391. var myprezi = APP.xmpp.getPrezi();
  2392. if (myprezi) {
  2393. messageHandler.openTwoButtonDialog("Remove Prezi",
  2394. "Are you sure you would like to remove your Prezi?",
  2395. false,
  2396. "Remove",
  2397. function(e,v,m,f) {
  2398. if(v) {
  2399. xmpp.removePreziFromPresence();
  2400. }
  2401. }
  2402. );
  2403. }
  2404. else if (preziPlayer != null) {
  2405. messageHandler.openTwoButtonDialog("Share a Prezi",
  2406. "Another participant is already sharing a Prezi." +
  2407. "This conference allows only one Prezi at a time.",
  2408. false,
  2409. "Ok",
  2410. function(e,v,m,f) {
  2411. $.prompt.close();
  2412. }
  2413. );
  2414. }
  2415. else {
  2416. var openPreziState = {
  2417. state0: {
  2418. html: '<h2>Share a Prezi</h2>' +
  2419. '<input id="preziUrl" type="text" ' +
  2420. 'placeholder="e.g. ' +
  2421. 'http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  2422. persistent: false,
  2423. buttons: { "Share": true , "Cancel": false},
  2424. defaultButton: 1,
  2425. submit: function(e,v,m,f){
  2426. e.preventDefault();
  2427. if(v)
  2428. {
  2429. var preziUrl = document.getElementById('preziUrl');
  2430. if (preziUrl.value)
  2431. {
  2432. var urlValue
  2433. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2434. if (urlValue.indexOf('http://prezi.com/') != 0
  2435. && urlValue.indexOf('https://prezi.com/') != 0)
  2436. {
  2437. $.prompt.goToState('state1');
  2438. return false;
  2439. }
  2440. else {
  2441. var presIdTmp = urlValue.substring(
  2442. urlValue.indexOf("prezi.com/") + 10);
  2443. if (!isAlphanumeric(presIdTmp)
  2444. || presIdTmp.indexOf('/') < 2) {
  2445. $.prompt.goToState('state1');
  2446. return false;
  2447. }
  2448. else {
  2449. xmpp.addToPresence("prezi", urlValue);
  2450. $.prompt.close();
  2451. }
  2452. }
  2453. }
  2454. }
  2455. else
  2456. $.prompt.close();
  2457. }
  2458. },
  2459. state1: {
  2460. html: '<h2>Share a Prezi</h2>' +
  2461. 'Please provide a correct prezi link.',
  2462. persistent: false,
  2463. buttons: { "Back": true, "Cancel": false },
  2464. defaultButton: 1,
  2465. submit:function(e,v,m,f) {
  2466. e.preventDefault();
  2467. if(v==0)
  2468. $.prompt.close();
  2469. else
  2470. $.prompt.goToState('state0');
  2471. }
  2472. }
  2473. };
  2474. var focusPreziUrl = function(e) {
  2475. document.getElementById('preziUrl').focus();
  2476. };
  2477. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2478. }
  2479. }
  2480. };
  2481. /**
  2482. * A new presentation has been added.
  2483. *
  2484. * @param event the event indicating the add of a presentation
  2485. * @param jid the jid from which the presentation was added
  2486. * @param presUrl url of the presentation
  2487. * @param currentSlide the current slide to which we should move
  2488. */
  2489. function presentationAdded(event, jid, presUrl, currentSlide) {
  2490. console.log("presentation added", presUrl);
  2491. var presId = getPresentationId(presUrl);
  2492. var elementId = 'participant_'
  2493. + Strophe.getResourceFromJid(jid)
  2494. + '_' + presId;
  2495. // We explicitly don't specify the peer jid here, because we don't want
  2496. // this video to be dealt with as a peer related one (for example we
  2497. // don't want to show a mute/kick menu for this one, etc.).
  2498. VideoLayout.addRemoteVideoContainer(null, elementId);
  2499. VideoLayout.resizeThumbnails();
  2500. var controlsEnabled = false;
  2501. if (jid === xmpp.myJid())
  2502. controlsEnabled = true;
  2503. setPresentationVisible(true);
  2504. $('#largeVideoContainer').hover(
  2505. function (event) {
  2506. if (Prezi.isPresentationVisible()) {
  2507. var reloadButtonRight = window.innerWidth
  2508. - $('#presentation>iframe').offset().left
  2509. - $('#presentation>iframe').width();
  2510. $('#reloadPresentation').css({ right: reloadButtonRight,
  2511. display:'inline-block'});
  2512. }
  2513. },
  2514. function (event) {
  2515. if (!Prezi.isPresentationVisible())
  2516. $('#reloadPresentation').css({display:'none'});
  2517. else {
  2518. var e = event.toElement || event.relatedTarget;
  2519. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2520. $('#reloadPresentation').css({display:'none'});
  2521. }
  2522. });
  2523. preziPlayer = new PreziPlayer(
  2524. 'presentation',
  2525. {preziId: presId,
  2526. width: getPresentationWidth(),
  2527. height: getPresentationHeihgt(),
  2528. controls: controlsEnabled,
  2529. debug: true
  2530. });
  2531. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2532. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2533. console.log("prezi status", event.value);
  2534. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2535. if (jid != xmpp.myJid())
  2536. preziPlayer.flyToStep(currentSlide);
  2537. }
  2538. });
  2539. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2540. console.log("event value", event.value);
  2541. APP.xmpp.addToPresence("preziSlide", event.value);
  2542. });
  2543. $("#" + elementId).css( 'background-image',
  2544. 'url(../images/avatarprezi.png)');
  2545. $("#" + elementId).click(
  2546. function () {
  2547. setPresentationVisible(true);
  2548. }
  2549. );
  2550. };
  2551. /**
  2552. * A presentation has been removed.
  2553. *
  2554. * @param event the event indicating the remove of a presentation
  2555. * @param jid the jid for which the presentation was removed
  2556. * @param the url of the presentation
  2557. */
  2558. function presentationRemoved(event, jid, presUrl) {
  2559. console.log('presentation removed', presUrl);
  2560. var presId = getPresentationId(presUrl);
  2561. setPresentationVisible(false);
  2562. $('#participant_'
  2563. + Strophe.getResourceFromJid(jid)
  2564. + '_' + presId).remove();
  2565. $('#presentation>iframe').remove();
  2566. if (preziPlayer != null) {
  2567. preziPlayer.destroy();
  2568. preziPlayer = null;
  2569. }
  2570. };
  2571. /**
  2572. * Indicates if the given string is an alphanumeric string.
  2573. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2574. * purpose of checking URIs.
  2575. */
  2576. function isAlphanumeric(unsafeText) {
  2577. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2578. return regex.test(unsafeText);
  2579. }
  2580. /**
  2581. * Returns the presentation id from the given url.
  2582. */
  2583. function getPresentationId (presUrl) {
  2584. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2585. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2586. }
  2587. /**
  2588. * Returns the presentation width.
  2589. */
  2590. function getPresentationWidth() {
  2591. var availableWidth = UIUtil.getAvailableVideoWidth();
  2592. var availableHeight = getPresentationHeihgt();
  2593. var aspectRatio = 16.0 / 9.0;
  2594. if (availableHeight < availableWidth / aspectRatio) {
  2595. availableWidth = Math.floor(availableHeight * aspectRatio);
  2596. }
  2597. return availableWidth;
  2598. }
  2599. /**
  2600. * Returns the presentation height.
  2601. */
  2602. function getPresentationHeihgt() {
  2603. var remoteVideos = $('#remoteVideos');
  2604. return window.innerHeight - remoteVideos.outerHeight();
  2605. }
  2606. /**
  2607. * Resizes the presentation iframe.
  2608. */
  2609. function resize() {
  2610. if ($('#presentation>iframe')) {
  2611. $('#presentation>iframe').width(getPresentationWidth());
  2612. $('#presentation>iframe').height(getPresentationHeihgt());
  2613. }
  2614. }
  2615. /**
  2616. * Shows/hides a presentation.
  2617. */
  2618. function setPresentationVisible(visible) {
  2619. var prezi = $('#presentation>iframe');
  2620. if (visible) {
  2621. // Trigger the video.selected event to indicate a change in the
  2622. // large video.
  2623. $(document).trigger("video.selected", [true]);
  2624. $('#largeVideo').fadeOut(300);
  2625. prezi.fadeIn(300, function() {
  2626. prezi.css({opacity:'1'});
  2627. ToolbarToggler.dockToolbar(true);
  2628. VideoLayout.setLargeVideoVisible(false);
  2629. });
  2630. $('#activeSpeaker').css('visibility', 'hidden');
  2631. }
  2632. else {
  2633. if (prezi.css('opacity') == '1') {
  2634. prezi.fadeOut(300, function () {
  2635. prezi.css({opacity:'0'});
  2636. $('#reloadPresentation').css({display:'none'});
  2637. $('#largeVideo').fadeIn(300, function() {
  2638. VideoLayout.setLargeVideoVisible(true);
  2639. ToolbarToggler.dockToolbar(false);
  2640. });
  2641. });
  2642. }
  2643. }
  2644. }
  2645. /**
  2646. * Presentation has been removed.
  2647. */
  2648. $(document).bind('presentationremoved.muc', presentationRemoved);
  2649. /**
  2650. * Presentation has been added.
  2651. */
  2652. $(document).bind('presentationadded.muc', presentationAdded);
  2653. /*
  2654. * Indicates presentation slide change.
  2655. */
  2656. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2657. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2658. preziPlayer.flyToStep(current);
  2659. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2660. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2661. preziPlayer.flyToStep(current, i);
  2662. }
  2663. }
  2664. });
  2665. /**
  2666. * On video selected event.
  2667. */
  2668. $(document).bind('video.selected', function (event, isPresentation) {
  2669. if (!isPresentation && $('#presentation>iframe')) {
  2670. setPresentationVisible(false);
  2671. }
  2672. });
  2673. $(window).resize(function () {
  2674. resize();
  2675. });
  2676. module.exports = Prezi;
  2677. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":15}],15:[function(require,module,exports){
  2678. (function() {
  2679. "use strict";
  2680. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2681. window.PreziPlayer = (function() {
  2682. PreziPlayer.API_VERSION = 1;
  2683. PreziPlayer.CURRENT_STEP = 'currentStep';
  2684. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2685. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2686. PreziPlayer.STATUS_LOADING = 'loading';
  2687. PreziPlayer.STATUS_READY = 'ready';
  2688. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2689. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2690. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2691. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2692. PreziPlayer.EVENT_STATUS = "statusChange";
  2693. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2694. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2695. PreziPlayer.domain = "https://prezi.com";
  2696. PreziPlayer.path = "/player/";
  2697. PreziPlayer.players = {};
  2698. PreziPlayer.binded_methods = ['changesHandler'];
  2699. PreziPlayer.createMultiplePlayers = function(optionArray){
  2700. for(var i=0; i<optionArray.length; i++) {
  2701. var optionSet = optionArray[i];
  2702. new PreziPlayer(optionSet.id, optionSet);
  2703. };
  2704. };
  2705. PreziPlayer.messageReceived = function(event){
  2706. var message, item, player;
  2707. try {
  2708. message = JSON.parse(event.data);
  2709. } catch (e) {}
  2710. if (message.id && (player = PreziPlayer.players[message.id])){
  2711. if (player.options.debug === true) {
  2712. if (console && console.log) console.log('received', message);
  2713. }
  2714. if (message.type === "changes"){
  2715. player.changesHandler(message);
  2716. }
  2717. for (var i=0; i<player.callbacks.length; i++) {
  2718. item = player.callbacks[i];
  2719. if (item && message.type === item.event){
  2720. item.callback(message);
  2721. }
  2722. }
  2723. }
  2724. };
  2725. function PreziPlayer(id, options) {
  2726. var params, paramString = "", _this = this;
  2727. if (PreziPlayer.players[id]){
  2728. PreziPlayer.players[id].destroy();
  2729. }
  2730. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  2731. var method_name = PreziPlayer.binded_methods[i];
  2732. _this[method_name] = __bind(_this[method_name], _this);
  2733. };
  2734. options = options || {};
  2735. this.options = options;
  2736. this.values = {'status': PreziPlayer.STATUS_LOADING};
  2737. this.values[PreziPlayer.CURRENT_STEP] = 0;
  2738. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  2739. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  2740. this.callbacks = [];
  2741. this.id = id;
  2742. this.embedTo = document.getElementById(id);
  2743. if (!this.embedTo) {
  2744. throw "The element id is not available.";
  2745. }
  2746. this.iframe = document.createElement('iframe');
  2747. params = [
  2748. { name: 'oid', value: options.preziId },
  2749. { name: 'explorable', value: options.explorable ? 1 : 0 },
  2750. { name: 'controls', value: options.controls ? 1 : 0 }
  2751. ];
  2752. for(var i=0; i<params.length; i++) {
  2753. var param = params[i];
  2754. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  2755. };
  2756. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  2757. this.iframe.frameBorder = 0;
  2758. this.iframe.scrolling = "no";
  2759. this.iframe.width = options.width || 640;
  2760. this.iframe.height = options.height || 480;
  2761. this.embedTo.innerHTML = '';
  2762. // JITSI: IN CASE SOMETHING GOES WRONG.
  2763. try {
  2764. this.embedTo.appendChild(this.iframe);
  2765. }
  2766. catch (err) {
  2767. console.log("CATCH ERROR");
  2768. }
  2769. // JITSI: Increase interval from 200 to 500, which fixes prezi
  2770. // crashes for us.
  2771. this.initPollInterval = setInterval(function(){
  2772. _this.sendMessage({'action': 'init'});
  2773. }, 500);
  2774. PreziPlayer.players[id] = this;
  2775. }
  2776. PreziPlayer.prototype.changesHandler = function(message) {
  2777. var key, value, j, item;
  2778. if (this.initPollInterval) {
  2779. clearInterval(this.initPollInterval);
  2780. this.initPollInterval = false;
  2781. }
  2782. for (key in message.data) {
  2783. if (message.data.hasOwnProperty(key)){
  2784. value = message.data[key];
  2785. this.values[key] = value;
  2786. for (j=0; j<this.callbacks.length; j++) {
  2787. item = this.callbacks[j];
  2788. if (item && item.event === key + "Change"){
  2789. item.callback({type: item.event, value: value});
  2790. }
  2791. }
  2792. }
  2793. }
  2794. };
  2795. PreziPlayer.prototype.destroy = function() {
  2796. if (this.initPollInterval) {
  2797. clearInterval(this.initPollInterval);
  2798. this.initPollInterval = false;
  2799. }
  2800. this.embedTo.innerHTML = '';
  2801. };
  2802. PreziPlayer.prototype.sendMessage = function(message) {
  2803. if (this.options.debug === true) {
  2804. if (console && console.log) console.log('sent', message);
  2805. }
  2806. message.version = PreziPlayer.API_VERSION;
  2807. message.id = this.id;
  2808. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  2809. };
  2810. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  2811. PreziPlayer.prototype.flyToNextStep = function() {
  2812. return this.sendMessage({
  2813. 'action': 'present',
  2814. 'data': ['moveToNextStep']
  2815. });
  2816. };
  2817. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  2818. PreziPlayer.prototype.flyToPreviousStep = function() {
  2819. return this.sendMessage({
  2820. 'action': 'present',
  2821. 'data': ['moveToPrevStep']
  2822. });
  2823. };
  2824. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  2825. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  2826. var obj = this;
  2827. // check animation_step
  2828. if (animation_step > 0 &&
  2829. obj.values.animationCountOnSteps &&
  2830. obj.values.animationCountOnSteps[step] <= animation_step) {
  2831. animation_step = obj.values.animationCountOnSteps[step];
  2832. }
  2833. // jump to animation steps by calling flyToNextStep()
  2834. function doAnimationSteps() {
  2835. if (obj.values.isMoving == true) {
  2836. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  2837. return;
  2838. }
  2839. while (animation_step-- > 0) {
  2840. obj.flyToNextStep(); // do the animation steps
  2841. }
  2842. }
  2843. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  2844. // jump to the step
  2845. return this.sendMessage({
  2846. 'action': 'present',
  2847. 'data': ['moveToStep', step]
  2848. });
  2849. };
  2850. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  2851. PreziPlayer.prototype.flyToObject = function(objectId) {
  2852. return this.sendMessage({
  2853. 'action': 'present',
  2854. 'data': ['moveToObject', objectId]
  2855. });
  2856. };
  2857. PreziPlayer.prototype.play = function(defaultDelay) {
  2858. return this.sendMessage({
  2859. 'action': 'present',
  2860. 'data': ['startAutoPlay', defaultDelay]
  2861. });
  2862. };
  2863. PreziPlayer.prototype.stop = function() {
  2864. return this.sendMessage({
  2865. 'action': 'present',
  2866. 'data': ['stopAutoPlay']
  2867. });
  2868. };
  2869. PreziPlayer.prototype.pause = function(defaultDelay) {
  2870. return this.sendMessage({
  2871. 'action': 'present',
  2872. 'data': ['pauseAutoPlay', defaultDelay]
  2873. });
  2874. };
  2875. PreziPlayer.prototype.getCurrentStep = function() {
  2876. return this.values.currentStep;
  2877. };
  2878. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  2879. return this.values.currentAnimationStep;
  2880. };
  2881. PreziPlayer.prototype.getCurrentObject = function() {
  2882. return this.values.currentObject;
  2883. };
  2884. PreziPlayer.prototype.getStatus = function() {
  2885. return this.values.status;
  2886. };
  2887. PreziPlayer.prototype.isPlaying = function() {
  2888. return this.values.isAutoPlaying;
  2889. };
  2890. PreziPlayer.prototype.getStepCount = function() {
  2891. return this.values.stepCount;
  2892. };
  2893. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  2894. return this.values.animationCountOnSteps;
  2895. };
  2896. PreziPlayer.prototype.getTitle = function() {
  2897. return this.values.title;
  2898. };
  2899. PreziPlayer.prototype.setDimensions = function(dims) {
  2900. for (var parameter in dims) {
  2901. this.iframe[parameter] = dims[parameter];
  2902. }
  2903. }
  2904. PreziPlayer.prototype.getDimensions = function() {
  2905. return {
  2906. width: parseInt(this.iframe.width, 10),
  2907. height: parseInt(this.iframe.height, 10)
  2908. }
  2909. }
  2910. PreziPlayer.prototype.on = function(event, callback) {
  2911. this.callbacks.push({
  2912. event: event,
  2913. callback: callback
  2914. });
  2915. };
  2916. PreziPlayer.prototype.off = function(event, callback) {
  2917. var j, item;
  2918. if (event === undefined) {
  2919. this.callbacks = [];
  2920. }
  2921. j = this.callbacks.length;
  2922. while (j--) {
  2923. item = this.callbacks[j];
  2924. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  2925. this.callbacks.splice(j, 1);
  2926. }
  2927. }
  2928. };
  2929. if (window.addEventListener) {
  2930. window.addEventListener('message', PreziPlayer.messageReceived, false);
  2931. } else {
  2932. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  2933. }
  2934. return PreziPlayer;
  2935. })();
  2936. })();
  2937. module.exports = PreziPlayer;
  2938. },{}],16:[function(require,module,exports){
  2939. var Chat = require("./chat/Chat");
  2940. var ContactList = require("./contactlist/ContactList");
  2941. var Settings = require("./settings/Settings");
  2942. var SettingsMenu = require("./settings/SettingsMenu");
  2943. var VideoLayout = require("../videolayout/VideoLayout");
  2944. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2945. var UIUtil = require("../util/UIUtil");
  2946. /**
  2947. * Toggler for the chat, contact list, settings menu, etc..
  2948. */
  2949. var PanelToggler = (function(my) {
  2950. var currentlyOpen = null;
  2951. var buttons = {
  2952. '#chatspace': '#chatBottomButton',
  2953. '#contactlist': '#contactListButton',
  2954. '#settingsmenu': '#settingsButton'
  2955. };
  2956. /**
  2957. * Resizes the video area
  2958. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  2959. * @param completeFunction a function to be called when the video space is resized
  2960. */
  2961. var resizeVideoArea = function(isClosing, completeFunction) {
  2962. var videospace = $('#videospace');
  2963. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  2964. var videospaceWidth = window.innerWidth - panelSize[0];
  2965. var videospaceHeight = window.innerHeight;
  2966. var videoSize
  2967. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  2968. var videoWidth = videoSize[0];
  2969. var videoHeight = videoSize[1];
  2970. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  2971. videoHeight,
  2972. videospaceWidth,
  2973. videospaceHeight);
  2974. var horizontalIndent = videoPosition[0];
  2975. var verticalIndent = videoPosition[1];
  2976. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  2977. var thumbnailsWidth = thumbnailSize[0];
  2978. var thumbnailsHeight = thumbnailSize[1];
  2979. //for chat
  2980. videospace.animate({
  2981. right: panelSize[0],
  2982. width: videospaceWidth,
  2983. height: videospaceHeight
  2984. },
  2985. {
  2986. queue: false,
  2987. duration: 500,
  2988. complete: completeFunction
  2989. });
  2990. $('#remoteVideos').animate({
  2991. height: thumbnailsHeight
  2992. },
  2993. {
  2994. queue: false,
  2995. duration: 500
  2996. });
  2997. $('#remoteVideos>span').animate({
  2998. height: thumbnailsHeight,
  2999. width: thumbnailsWidth
  3000. },
  3001. {
  3002. queue: false,
  3003. duration: 500,
  3004. complete: function () {
  3005. $(document).trigger(
  3006. "remotevideo.resized",
  3007. [thumbnailsWidth,
  3008. thumbnailsHeight]);
  3009. }
  3010. });
  3011. $('#largeVideoContainer').animate({
  3012. width: videospaceWidth,
  3013. height: videospaceHeight
  3014. },
  3015. {
  3016. queue: false,
  3017. duration: 500
  3018. });
  3019. $('#largeVideo').animate({
  3020. width: videoWidth,
  3021. height: videoHeight,
  3022. top: verticalIndent,
  3023. bottom: verticalIndent,
  3024. left: horizontalIndent,
  3025. right: horizontalIndent
  3026. },
  3027. {
  3028. queue: false,
  3029. duration: 500
  3030. });
  3031. };
  3032. /**
  3033. * Toggles the windows in the side panel
  3034. * @param object the window that should be shown
  3035. * @param selector the selector for the element containing the panel
  3036. * @param onOpenComplete function to be called when the panel is opened
  3037. * @param onOpen function to be called if the window is going to be opened
  3038. * @param onClose function to be called if the window is going to be closed
  3039. */
  3040. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3041. UIUtil.buttonClick(buttons[selector], "active");
  3042. if (object.isVisible()) {
  3043. $("#toast-container").animate({
  3044. right: '5px'
  3045. },
  3046. {
  3047. queue: false,
  3048. duration: 500
  3049. });
  3050. $(selector).hide("slide", {
  3051. direction: "right",
  3052. queue: false,
  3053. duration: 500
  3054. });
  3055. if(typeof onClose === "function") {
  3056. onClose();
  3057. }
  3058. currentlyOpen = null;
  3059. }
  3060. else {
  3061. // Undock the toolbar when the chat is shown and if we're in a
  3062. // video mode.
  3063. if (VideoLayout.isLargeVideoVisible()) {
  3064. ToolbarToggler.dockToolbar(false);
  3065. }
  3066. if(currentlyOpen) {
  3067. var current = $(currentlyOpen);
  3068. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3069. current.css('z-index', 4);
  3070. setTimeout(function () {
  3071. current.css('display', 'none');
  3072. current.css('z-index', 5);
  3073. }, 500);
  3074. }
  3075. $("#toast-container").animate({
  3076. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3077. },
  3078. {
  3079. queue: false,
  3080. duration: 500
  3081. });
  3082. $(selector).show("slide", {
  3083. direction: "right",
  3084. queue: false,
  3085. duration: 500,
  3086. complete: onOpenComplete
  3087. });
  3088. if(typeof onOpen === "function") {
  3089. onOpen();
  3090. }
  3091. currentlyOpen = selector;
  3092. }
  3093. };
  3094. /**
  3095. * Opens / closes the chat area.
  3096. */
  3097. my.toggleChat = function() {
  3098. var chatCompleteFunction = Chat.isVisible() ?
  3099. function() {} : function () {
  3100. Chat.scrollChatToBottom();
  3101. $('#chatspace').trigger('shown');
  3102. };
  3103. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3104. toggle(Chat,
  3105. '#chatspace',
  3106. function () {
  3107. // Request the focus in the nickname field or the chat input field.
  3108. if ($('#nickname').css('visibility') === 'visible') {
  3109. $('#nickinput').focus();
  3110. } else {
  3111. $('#usermsg').focus();
  3112. }
  3113. },
  3114. null,
  3115. Chat.resizeChat,
  3116. null);
  3117. };
  3118. /**
  3119. * Opens / closes the contact list area.
  3120. */
  3121. my.toggleContactList = function () {
  3122. var completeFunction = ContactList.isVisible() ?
  3123. function() {} : function () { $('#contactlist').trigger('shown');};
  3124. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3125. toggle(ContactList,
  3126. '#contactlist',
  3127. null,
  3128. function() {
  3129. ContactList.setVisualNotification(false);
  3130. },
  3131. null);
  3132. };
  3133. /**
  3134. * Opens / closes the settings menu
  3135. */
  3136. my.toggleSettingsMenu = function() {
  3137. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3138. toggle(SettingsMenu,
  3139. '#settingsmenu',
  3140. null,
  3141. function() {
  3142. var settings = Settings.getSettings();
  3143. $('#setDisplayName').get(0).value = settings.displayName;
  3144. $('#setEmail').get(0).value = settings.email;
  3145. },
  3146. null);
  3147. };
  3148. /**
  3149. * Returns the size of the side panel.
  3150. */
  3151. my.getPanelSize = function () {
  3152. var availableHeight = window.innerHeight;
  3153. var availableWidth = window.innerWidth;
  3154. var panelWidth = 200;
  3155. if (availableWidth * 0.2 < 200) {
  3156. panelWidth = availableWidth * 0.2;
  3157. }
  3158. return [panelWidth, availableHeight];
  3159. };
  3160. my.isVisible = function() {
  3161. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3162. };
  3163. return my;
  3164. }(PanelToggler || {}));
  3165. module.exports = PanelToggler;
  3166. },{"../toolbars/ToolbarToggler":26,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./chat/Chat":17,"./contactlist/ContactList":21,"./settings/Settings":22,"./settings/SettingsMenu":23}],17:[function(require,module,exports){
  3167. /* global $, Util, nickname:true */
  3168. var Replacement = require("./Replacement");
  3169. var CommandsProcessor = require("./Commands");
  3170. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3171. var smileys = require("./smileys.json").smileys;
  3172. var NicknameHandler = require("../../util/NicknameHandler");
  3173. var UIUtil = require("../../util/UIUtil");
  3174. var UIEvents = require("../../../../service/UI/UIEvents");
  3175. var notificationInterval = false;
  3176. var unreadMessages = 0;
  3177. /**
  3178. * Shows/hides a visual notification, indicating that a message has arrived.
  3179. */
  3180. function setVisualNotification(show) {
  3181. var unreadMsgElement = document.getElementById('unreadMessages');
  3182. var unreadMsgBottomElement
  3183. = document.getElementById('bottomUnreadMessages');
  3184. var glower = $('#chatButton');
  3185. var bottomGlower = $('#chatBottomButton');
  3186. if (unreadMessages) {
  3187. unreadMsgElement.innerHTML = unreadMessages.toString();
  3188. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3189. ToolbarToggler.dockToolbar(true);
  3190. var chatButtonElement
  3191. = document.getElementById('chatButton').parentNode;
  3192. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3193. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3194. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3195. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3196. unreadMsgElement.setAttribute(
  3197. 'style',
  3198. 'top:' + topIndent +
  3199. '; left:' + leftIndent + ';');
  3200. var chatBottomButtonElement
  3201. = document.getElementById('chatBottomButton').parentNode;
  3202. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3203. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3204. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3205. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3206. unreadMsgBottomElement.setAttribute(
  3207. 'style',
  3208. 'top:' + bottomTopIndent +
  3209. '; left:' + bottomLeftIndent + ';');
  3210. if (!glower.hasClass('icon-chat-simple')) {
  3211. glower.removeClass('icon-chat');
  3212. glower.addClass('icon-chat-simple');
  3213. }
  3214. }
  3215. else {
  3216. unreadMsgElement.innerHTML = '';
  3217. unreadMsgBottomElement.innerHTML = '';
  3218. glower.removeClass('icon-chat-simple');
  3219. glower.addClass('icon-chat');
  3220. }
  3221. if (show && !notificationInterval) {
  3222. notificationInterval = window.setInterval(function () {
  3223. glower.toggleClass('active');
  3224. bottomGlower.toggleClass('active glowing');
  3225. }, 800);
  3226. }
  3227. else if (!show && notificationInterval) {
  3228. window.clearInterval(notificationInterval);
  3229. notificationInterval = false;
  3230. glower.removeClass('active');
  3231. bottomGlower.removeClass('glowing');
  3232. bottomGlower.addClass('active');
  3233. }
  3234. }
  3235. /**
  3236. * Returns the current time in the format it is shown to the user
  3237. * @returns {string}
  3238. */
  3239. function getCurrentTime() {
  3240. var now = new Date();
  3241. var hour = now.getHours();
  3242. var minute = now.getMinutes();
  3243. var second = now.getSeconds();
  3244. if(hour.toString().length === 1) {
  3245. hour = '0'+hour;
  3246. }
  3247. if(minute.toString().length === 1) {
  3248. minute = '0'+minute;
  3249. }
  3250. if(second.toString().length === 1) {
  3251. second = '0'+second;
  3252. }
  3253. return hour+':'+minute+':'+second;
  3254. }
  3255. function toggleSmileys()
  3256. {
  3257. var smileys = $('#smileysContainer');
  3258. if(!smileys.is(':visible')) {
  3259. smileys.show("slide", { direction: "down", duration: 300});
  3260. } else {
  3261. smileys.hide("slide", { direction: "down", duration: 300});
  3262. }
  3263. $('#usermsg').focus();
  3264. }
  3265. function addClickFunction(smiley, number) {
  3266. smiley.onclick = function addSmileyToMessage() {
  3267. var usermsg = $('#usermsg');
  3268. var message = usermsg.val();
  3269. message += smileys['smiley' + number];
  3270. usermsg.val(message);
  3271. usermsg.get(0).setSelectionRange(message.length, message.length);
  3272. toggleSmileys();
  3273. usermsg.focus();
  3274. };
  3275. }
  3276. /**
  3277. * Adds the smileys container to the chat
  3278. */
  3279. function addSmileys() {
  3280. var smileysContainer = document.createElement('div');
  3281. smileysContainer.id = 'smileysContainer';
  3282. for(var i = 1; i <= 21; i++) {
  3283. var smileyContainer = document.createElement('div');
  3284. smileyContainer.id = 'smiley' + i;
  3285. smileyContainer.className = 'smileyContainer';
  3286. var smiley = document.createElement('img');
  3287. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3288. smiley.className = 'smiley';
  3289. addClickFunction(smiley, i);
  3290. smileyContainer.appendChild(smiley);
  3291. smileysContainer.appendChild(smileyContainer);
  3292. }
  3293. $("#chatspace").append(smileysContainer);
  3294. }
  3295. /**
  3296. * Resizes the chat conversation.
  3297. */
  3298. function resizeChatConversation() {
  3299. var msgareaHeight = $('#usermsg').outerHeight();
  3300. var chatspace = $('#chatspace');
  3301. var width = chatspace.width();
  3302. var chat = $('#chatconversation');
  3303. var smileys = $('#smileysarea');
  3304. smileys.height(msgareaHeight);
  3305. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3306. $('#smileysContainer').css('bottom', msgareaHeight);
  3307. chat.width(width - 10);
  3308. chat.height(window.innerHeight - 15 - msgareaHeight);
  3309. }
  3310. /**
  3311. * Chat related user interface.
  3312. */
  3313. var Chat = (function (my) {
  3314. /**
  3315. * Initializes chat related interface.
  3316. */
  3317. my.init = function () {
  3318. if(NicknameHandler.getNickname())
  3319. Chat.setChatConversationMode(true);
  3320. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3321. function (nickname) {
  3322. Chat.setChatConversationMode(true);
  3323. });
  3324. $('#nickinput').keydown(function (event) {
  3325. if (event.keyCode === 13) {
  3326. event.preventDefault();
  3327. var val = UIUtil.escapeHtml(this.value);
  3328. this.value = '';
  3329. if (!NicknameHandler.getNickname()) {
  3330. NicknameHandler.setNickname(val);
  3331. return;
  3332. }
  3333. }
  3334. });
  3335. $('#usermsg').keydown(function (event) {
  3336. if (event.keyCode === 13) {
  3337. event.preventDefault();
  3338. var value = this.value;
  3339. $('#usermsg').val('').trigger('autosize.resize');
  3340. this.focus();
  3341. var command = new CommandsProcessor(value);
  3342. if(command.isCommand())
  3343. {
  3344. command.processCommand();
  3345. }
  3346. else
  3347. {
  3348. var message = UIUtil.escapeHtml(value);
  3349. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3350. }
  3351. }
  3352. });
  3353. var onTextAreaResize = function () {
  3354. resizeChatConversation();
  3355. Chat.scrollChatToBottom();
  3356. };
  3357. $('#usermsg').autosize({callback: onTextAreaResize});
  3358. $("#chatspace").bind("shown",
  3359. function () {
  3360. unreadMessages = 0;
  3361. setVisualNotification(false);
  3362. });
  3363. addSmileys();
  3364. };
  3365. /**
  3366. * Appends the given message to the chat conversation.
  3367. */
  3368. my.updateChatConversation = function (from, displayName, message) {
  3369. var divClassName = '';
  3370. if (APP.xmpp.myJid() === from) {
  3371. divClassName = "localuser";
  3372. }
  3373. else {
  3374. divClassName = "remoteuser";
  3375. if (!Chat.isVisible()) {
  3376. unreadMessages++;
  3377. UIUtil.playSoundNotification('chatNotification');
  3378. setVisualNotification(true);
  3379. }
  3380. }
  3381. // replace links and smileys
  3382. // Strophe already escapes special symbols on sending,
  3383. // so we escape here only tags to avoid double &amp;
  3384. var escMessage = message.replace(/</g, '&lt;').
  3385. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3386. var escDisplayName = UIUtil.escapeHtml(displayName);
  3387. message = Replacement.processReplacements(escMessage);
  3388. var messageContainer =
  3389. '<div class="chatmessage">'+
  3390. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3391. '<div class="username ' + divClassName +'">' + escDisplayName +
  3392. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3393. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3394. '</div>';
  3395. $('#chatconversation').append(messageContainer);
  3396. $('#chatconversation').animate(
  3397. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3398. };
  3399. /**
  3400. * Appends error message to the conversation
  3401. * @param errorMessage the received error message.
  3402. * @param originalText the original message.
  3403. */
  3404. my.chatAddError = function(errorMessage, originalText)
  3405. {
  3406. errorMessage = UIUtil.escapeHtml(errorMessage);
  3407. originalText = UIUtil.escapeHtml(originalText);
  3408. $('#chatconversation').append(
  3409. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3410. (originalText? (' \"'+ originalText + '\"') : "") +
  3411. ' was not sent.' +
  3412. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3413. $('#chatconversation').animate(
  3414. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3415. };
  3416. /**
  3417. * Sets the subject to the UI
  3418. * @param subject the subject
  3419. */
  3420. my.chatSetSubject = function(subject)
  3421. {
  3422. if(subject)
  3423. subject = subject.trim();
  3424. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3425. if(subject === "")
  3426. {
  3427. $("#subject").css({display: "none"});
  3428. }
  3429. else
  3430. {
  3431. $("#subject").css({display: "block"});
  3432. }
  3433. };
  3434. /**
  3435. * Sets the chat conversation mode.
  3436. */
  3437. my.setChatConversationMode = function (isConversationMode) {
  3438. if (isConversationMode) {
  3439. $('#nickname').css({visibility: 'hidden'});
  3440. $('#chatconversation').css({visibility: 'visible'});
  3441. $('#usermsg').css({visibility: 'visible'});
  3442. $('#smileysarea').css({visibility: 'visible'});
  3443. $('#usermsg').focus();
  3444. }
  3445. };
  3446. /**
  3447. * Resizes the chat area.
  3448. */
  3449. my.resizeChat = function () {
  3450. var chatSize = require("../SidePanelToggler").getPanelSize();
  3451. $('#chatspace').width(chatSize[0]);
  3452. $('#chatspace').height(chatSize[1]);
  3453. resizeChatConversation();
  3454. };
  3455. /**
  3456. * Indicates if the chat is currently visible.
  3457. */
  3458. my.isVisible = function () {
  3459. return $('#chatspace').is(":visible");
  3460. };
  3461. /**
  3462. * Shows and hides the window with the smileys
  3463. */
  3464. my.toggleSmileys = toggleSmileys;
  3465. /**
  3466. * Scrolls chat to the bottom.
  3467. */
  3468. my.scrollChatToBottom = function() {
  3469. setTimeout(function () {
  3470. $('#chatconversation').scrollTop(
  3471. $('#chatconversation')[0].scrollHeight);
  3472. }, 5);
  3473. };
  3474. return my;
  3475. }(Chat || {}));
  3476. module.exports = Chat;
  3477. },{"../../../../service/UI/UIEvents":80,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":16,"./Commands":18,"./Replacement":19,"./smileys.json":20}],18:[function(require,module,exports){
  3478. var UIUtil = require("../../util/UIUtil");
  3479. /**
  3480. * List with supported commands. The keys are the names of the commands and
  3481. * the value is the function that processes the message.
  3482. * @type {{String: function}}
  3483. */
  3484. var commands = {
  3485. "topic" : processTopic
  3486. };
  3487. /**
  3488. * Extracts the command from the message.
  3489. * @param message the received message
  3490. * @returns {string} the command
  3491. */
  3492. function getCommand(message)
  3493. {
  3494. if(message)
  3495. {
  3496. for(var command in commands)
  3497. {
  3498. if(message.indexOf("/" + command) == 0)
  3499. return command;
  3500. }
  3501. }
  3502. return "";
  3503. };
  3504. /**
  3505. * Processes the data for topic command.
  3506. * @param commandArguments the arguments of the topic command.
  3507. */
  3508. function processTopic(commandArguments)
  3509. {
  3510. var topic = UIUtil.escapeHtml(commandArguments);
  3511. APP.xmpp.setSubject(topic);
  3512. }
  3513. /**
  3514. * Constructs new CommandProccessor instance from a message that
  3515. * handles commands received via chat messages.
  3516. * @param message the message
  3517. * @constructor
  3518. */
  3519. function CommandsProcessor(message)
  3520. {
  3521. var command = getCommand(message);
  3522. /**
  3523. * Returns the name of the command.
  3524. * @returns {String} the command
  3525. */
  3526. this.getCommand = function()
  3527. {
  3528. return command;
  3529. };
  3530. var messageArgument = message.substr(command.length + 2);
  3531. /**
  3532. * Returns the arguments of the command.
  3533. * @returns {string}
  3534. */
  3535. this.getArgument = function()
  3536. {
  3537. return messageArgument;
  3538. };
  3539. }
  3540. /**
  3541. * Checks whether this instance is valid command or not.
  3542. * @returns {boolean}
  3543. */
  3544. CommandsProcessor.prototype.isCommand = function()
  3545. {
  3546. if(this.getCommand())
  3547. return true;
  3548. return false;
  3549. };
  3550. /**
  3551. * Processes the command.
  3552. */
  3553. CommandsProcessor.prototype.processCommand = function()
  3554. {
  3555. if(!this.isCommand())
  3556. return;
  3557. commands[this.getCommand()](this.getArgument());
  3558. };
  3559. module.exports = CommandsProcessor;
  3560. },{"../../util/UIUtil":30}],19:[function(require,module,exports){
  3561. var Smileys = require("./smileys.json");
  3562. /**
  3563. * Processes links and smileys in "body"
  3564. */
  3565. function processReplacements(body)
  3566. {
  3567. //make links clickable
  3568. body = linkify(body);
  3569. //add smileys
  3570. body = smilify(body);
  3571. return body;
  3572. }
  3573. /**
  3574. * Finds and replaces all links in the links in "body"
  3575. * with their <a href=""></a>
  3576. */
  3577. function linkify(inputText)
  3578. {
  3579. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3580. //URLs starting with http://, https://, or ftp://
  3581. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3582. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3583. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3584. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3585. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3586. //Change email addresses to mailto:: links.
  3587. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3588. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3589. return replacedText;
  3590. }
  3591. /**
  3592. * Replaces common smiley strings with images
  3593. */
  3594. function smilify(body)
  3595. {
  3596. if(!body) {
  3597. return body;
  3598. }
  3599. var regexs = Smileys["regexs"];
  3600. for(var smiley in regexs) {
  3601. if(regexs.hasOwnProperty(smiley)) {
  3602. body = body.replace(regexs[smiley],
  3603. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3604. }
  3605. }
  3606. return body;
  3607. }
  3608. module.exports = {
  3609. processReplacements: processReplacements,
  3610. linkify: linkify
  3611. };
  3612. },{"./smileys.json":20}],20:[function(require,module,exports){
  3613. module.exports={
  3614. "smileys": {
  3615. "smiley1": ":)",
  3616. "smiley2": ":(",
  3617. "smiley3": ":D",
  3618. "smiley4": "(y)",
  3619. "smiley5": " :P",
  3620. "smiley6": "(wave)",
  3621. "smiley7": "(blush)",
  3622. "smiley8": "(chuckle)",
  3623. "smiley9": "(shocked)",
  3624. "smiley10": ":*",
  3625. "smiley11": "(n)",
  3626. "smiley12": "(search)",
  3627. "smiley13": " <3",
  3628. "smiley14": "(oops)",
  3629. "smiley15": "(angry)",
  3630. "smiley16": "(angel)",
  3631. "smiley17": "(sick)",
  3632. "smiley18": ";(",
  3633. "smiley19": "(bomb)",
  3634. "smiley20": "(clap)",
  3635. "smiley21": " ;)"
  3636. },
  3637. "regexs": {
  3638. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3639. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3640. "smiley1": /(:-\)|:\))/gi,
  3641. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3642. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3643. "smiley6": /(\(wave\))/gi,
  3644. "smiley7": /(\(blush\))/gi,
  3645. "smiley8": /(\(chuckle\))/gi,
  3646. "smiley9": /(:-0|\(shocked\))/gi,
  3647. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3648. "smiley11": /(\(n\))/gi,
  3649. "smiley12": /(\(search\))/g,
  3650. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3651. "smiley14": /(\(oops\))/gi,
  3652. "smiley15": /(\(angry\))/gi,
  3653. "smiley16": /(\(angel\))/gi,
  3654. "smiley17": /(\(sick\))/gi,
  3655. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3656. "smiley19": /(\(bomb\))/gi,
  3657. "smiley20": /(\(clap\))/gi,
  3658. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3659. }
  3660. }
  3661. },{}],21:[function(require,module,exports){
  3662. var numberOfContacts = 0;
  3663. var notificationInterval;
  3664. /**
  3665. * Updates the number of participants in the contact list button and sets
  3666. * the glow
  3667. * @param delta indicates whether a new user has joined (1) or someone has
  3668. * left(-1)
  3669. */
  3670. function updateNumberOfParticipants(delta) {
  3671. //when the user is alone we don't show the number of participants
  3672. if(numberOfContacts === 0) {
  3673. $("#numberOfParticipants").text('');
  3674. numberOfContacts += delta;
  3675. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3676. ContactList.setVisualNotification(true);
  3677. numberOfContacts += delta;
  3678. $("#numberOfParticipants").text(numberOfContacts);
  3679. }
  3680. }
  3681. /**
  3682. * Creates the avatar element.
  3683. *
  3684. * @return the newly created avatar element
  3685. */
  3686. function createAvatar(id) {
  3687. var avatar = document.createElement('img');
  3688. avatar.className = "icon-avatar avatar";
  3689. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3690. return avatar;
  3691. }
  3692. /**
  3693. * Creates the display name paragraph.
  3694. *
  3695. * @param displayName the display name to set
  3696. */
  3697. function createDisplayNameParagraph(displayName) {
  3698. var p = document.createElement('p');
  3699. p.innerText = displayName;
  3700. return p;
  3701. }
  3702. function stopGlowing(glower) {
  3703. window.clearInterval(notificationInterval);
  3704. notificationInterval = false;
  3705. glower.removeClass('glowing');
  3706. if (!ContactList.isVisible()) {
  3707. glower.removeClass('active');
  3708. }
  3709. }
  3710. /**
  3711. * Contact list.
  3712. */
  3713. var ContactList = {
  3714. /**
  3715. * Indicates if the chat is currently visible.
  3716. *
  3717. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  3718. * otherwise
  3719. */
  3720. isVisible: function () {
  3721. return $('#contactlist').is(":visible");
  3722. },
  3723. /**
  3724. * Adds a contact for the given peerJid if such doesn't yet exist.
  3725. *
  3726. * @param peerJid the peerJid corresponding to the contact
  3727. * @param id the user's email or userId used to get the user's avatar
  3728. */
  3729. ensureAddContact: function (peerJid, id) {
  3730. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3731. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3732. if (!contact || contact.length <= 0)
  3733. ContactList.addContact(peerJid, id);
  3734. },
  3735. /**
  3736. * Adds a contact for the given peer jid.
  3737. *
  3738. * @param peerJid the jid of the contact to add
  3739. * @param id the email or userId of the user
  3740. */
  3741. addContact: function (peerJid, id) {
  3742. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3743. var contactlist = $('#contactlist>ul');
  3744. var newContact = document.createElement('li');
  3745. newContact.id = resourceJid;
  3746. newContact.className = "clickable";
  3747. newContact.onclick = function (event) {
  3748. if (event.currentTarget.className === "clickable") {
  3749. $(ContactList).trigger('contactclicked', [peerJid]);
  3750. }
  3751. };
  3752. newContact.appendChild(createAvatar(id));
  3753. newContact.appendChild(createDisplayNameParagraph("Participant"));
  3754. var clElement = contactlist.get(0);
  3755. if (resourceJid === APP.xmpp.myResource()
  3756. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  3757. clElement.insertBefore(newContact,
  3758. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  3759. }
  3760. else {
  3761. clElement.appendChild(newContact);
  3762. }
  3763. updateNumberOfParticipants(1);
  3764. },
  3765. /**
  3766. * Removes a contact for the given peer jid.
  3767. *
  3768. * @param peerJid the peerJid corresponding to the contact to remove
  3769. */
  3770. removeContact: function (peerJid) {
  3771. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3772. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3773. if (contact && contact.length > 0) {
  3774. var contactlist = $('#contactlist>ul');
  3775. contactlist.get(0).removeChild(contact.get(0));
  3776. updateNumberOfParticipants(-1);
  3777. }
  3778. },
  3779. setVisualNotification: function (show, stopGlowingIn) {
  3780. var glower = $('#contactListButton');
  3781. if (show && !notificationInterval) {
  3782. notificationInterval = window.setInterval(function () {
  3783. glower.toggleClass('active glowing');
  3784. }, 800);
  3785. }
  3786. else if (!show && notificationInterval) {
  3787. stopGlowing(glower);
  3788. }
  3789. if (stopGlowingIn) {
  3790. setTimeout(function () {
  3791. stopGlowing(glower);
  3792. }, stopGlowingIn);
  3793. }
  3794. },
  3795. setClickable: function (resourceJid, isClickable) {
  3796. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3797. if (isClickable) {
  3798. contact.addClass('clickable');
  3799. } else {
  3800. contact.removeClass('clickable');
  3801. }
  3802. },
  3803. onDisplayNameChange: function (peerJid, displayName) {
  3804. if (peerJid === 'localVideoContainer')
  3805. peerJid = xmpp.myJid();
  3806. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3807. var contactName = $('#contactlist #' + resourceJid + '>p');
  3808. if (contactName && displayName && displayName.length > 0)
  3809. contactName.html(displayName);
  3810. }
  3811. };
  3812. module.exports = ContactList;
  3813. },{}],22:[function(require,module,exports){
  3814. var email = '';
  3815. var displayName = '';
  3816. var userId;
  3817. function supportsLocalStorage() {
  3818. try {
  3819. return 'localStorage' in window && window.localStorage !== null;
  3820. } catch (e) {
  3821. console.log("localstorage is not supported");
  3822. return false;
  3823. }
  3824. }
  3825. function generateUniqueId() {
  3826. function _p8() {
  3827. return (Math.random().toString(16)+"000000000").substr(2,8);
  3828. }
  3829. return _p8() + _p8() + _p8() + _p8();
  3830. }
  3831. if(supportsLocalStorage()) {
  3832. if(!window.localStorage.jitsiMeetId) {
  3833. window.localStorage.jitsiMeetId = generateUniqueId();
  3834. console.log("generated id", window.localStorage.jitsiMeetId);
  3835. }
  3836. userId = window.localStorage.jitsiMeetId || '';
  3837. email = window.localStorage.email || '';
  3838. displayName = window.localStorage.displayname || '';
  3839. } else {
  3840. console.log("local storage is not supported");
  3841. userId = generateUniqueId();
  3842. }
  3843. var Settings =
  3844. {
  3845. setDisplayName: function (newDisplayName) {
  3846. displayName = newDisplayName;
  3847. window.localStorage.displayname = displayName;
  3848. return displayName;
  3849. },
  3850. setEmail: function(newEmail)
  3851. {
  3852. email = newEmail;
  3853. window.localStorage.email = newEmail;
  3854. return email;
  3855. },
  3856. getSettings: function () {
  3857. return {
  3858. email: email,
  3859. displayName: displayName,
  3860. uid: userId
  3861. };
  3862. }
  3863. };
  3864. module.exports = Settings;
  3865. },{}],23:[function(require,module,exports){
  3866. var Avatar = require("../../avatar/Avatar");
  3867. var Settings = require("./Settings");
  3868. var UIUtil = require("../../util/UIUtil");
  3869. var SettingsMenu = {
  3870. update: function() {
  3871. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  3872. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  3873. if(newDisplayName) {
  3874. var displayName = Settings.setDisplayName(newDisplayName);
  3875. APP.xmpp.addToPresence("displayName", displayName, true);
  3876. }
  3877. APP.xmpp.addToPresence("email", newEmail);
  3878. var email = Settings.setEmail(newEmail);
  3879. Avatar.setUserAvatar(xmpp.myJid(), email);
  3880. },
  3881. isVisible: function() {
  3882. return $('#settingsmenu').is(':visible');
  3883. },
  3884. setDisplayName: function(newDisplayName) {
  3885. var displayName = Settings.setDisplayName(newDisplayName);
  3886. $('#setDisplayName').get(0).value = displayName;
  3887. },
  3888. onDisplayNameChange: function(peerJid, newDisplayName) {
  3889. if(peerJid === 'localVideoContainer' ||
  3890. peerJid === xmpp.myJid()) {
  3891. this.setDisplayName(newDisplayName);
  3892. }
  3893. }
  3894. };
  3895. module.exports = SettingsMenu;
  3896. },{"../../avatar/Avatar":12,"../../util/UIUtil":30,"./Settings":22}],24:[function(require,module,exports){
  3897. var PanelToggler = require("../side_pannels/SidePanelToggler");
  3898. var buttonHandlers = {
  3899. "bottom_toolbar_contact_list": function () {
  3900. BottomToolbar.toggleContactList();
  3901. },
  3902. "bottom_toolbar_film_strip": function () {
  3903. BottomToolbar.toggleFilmStrip();
  3904. },
  3905. "bottom_toolbar_chat": function () {
  3906. BottomToolbar.toggleChat();
  3907. }
  3908. };
  3909. var BottomToolbar = (function (my) {
  3910. my.init = function () {
  3911. for(var k in buttonHandlers)
  3912. $("#" + k).click(buttonHandlers[k]);
  3913. };
  3914. my.toggleChat = function() {
  3915. PanelToggler.toggleChat();
  3916. };
  3917. my.toggleContactList = function() {
  3918. PanelToggler.toggleContactList();
  3919. };
  3920. my.toggleFilmStrip = function() {
  3921. var filmstrip = $("#remoteVideos");
  3922. filmstrip.toggleClass("hidden");
  3923. };
  3924. $(document).bind("remotevideo.resized", function (event, width, height) {
  3925. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  3926. $('#bottomToolbar').css({bottom: bottom + 'px'});
  3927. });
  3928. return my;
  3929. }(BottomToolbar || {}));
  3930. module.exports = BottomToolbar;
  3931. },{"../side_pannels/SidePanelToggler":16}],25:[function(require,module,exports){
  3932. /* global $, buttonClick, config, lockRoom,
  3933. setSharedKey, Util */
  3934. var messageHandler = require("../util/MessageHandler");
  3935. var BottomToolbar = require("./BottomToolbar");
  3936. var Prezi = require("../prezi/Prezi");
  3937. var Etherpad = require("../etherpad/Etherpad");
  3938. var PanelToggler = require("../side_pannels/SidePanelToggler");
  3939. var Authentication = require("../authentication/Authentication");
  3940. var UIUtil = require("../util/UIUtil");
  3941. var roomUrl = null;
  3942. var sharedKey = '';
  3943. var UI = null;
  3944. var buttonHandlers =
  3945. {
  3946. "toolbar_button_mute": function () {
  3947. return APP.UI.toggleAudio();
  3948. },
  3949. "toolbar_button_camera": function () {
  3950. return APP.UI.toggleVideo();
  3951. },
  3952. "toolbar_button_authentication": function () {
  3953. return Toolbar.authenticateClicked();
  3954. },
  3955. "toolbar_button_record": function () {
  3956. return toggleRecording();
  3957. },
  3958. "toolbar_button_security": function () {
  3959. return Toolbar.openLockDialog();
  3960. },
  3961. "toolbar_button_link": function () {
  3962. return Toolbar.openLinkDialog();
  3963. },
  3964. "toolbar_button_chat": function () {
  3965. return BottomToolbar.toggleChat();
  3966. },
  3967. "toolbar_button_prezi": function () {
  3968. return Prezi.openPreziDialog();
  3969. },
  3970. "toolbar_button_etherpad": function () {
  3971. return Etherpad.toggleEtherpad(0);
  3972. },
  3973. "toolbar_button_desktopsharing": function () {
  3974. return APP.desktopsharing.toggleScreenSharing();
  3975. },
  3976. "toolbar_button_fullScreen": function()
  3977. {
  3978. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  3979. return Toolbar.toggleFullScreen();
  3980. },
  3981. "toolbar_button_sip": function () {
  3982. return callSipButtonClicked();
  3983. },
  3984. "toolbar_button_settings": function () {
  3985. PanelToggler.toggleSettingsMenu();
  3986. },
  3987. "toolbar_button_hangup": function () {
  3988. return hangup();
  3989. }
  3990. };
  3991. function hangup() {
  3992. APP.xmpp.disposeConference();
  3993. if(config.enableWelcomePage)
  3994. {
  3995. setTimeout(function()
  3996. {
  3997. window.localStorage.welcomePageDisabled = false;
  3998. window.location.pathname = "/";
  3999. }, 10000);
  4000. }
  4001. UI.messageHandler.openDialog(
  4002. "Session Terminated",
  4003. "You hung up the call",
  4004. true,
  4005. { "Join again": true },
  4006. function(event, value, message, formVals)
  4007. {
  4008. window.location.reload();
  4009. return false;
  4010. }
  4011. );
  4012. }
  4013. /**
  4014. * Starts or stops the recording for the conference.
  4015. */
  4016. function toggleRecording() {
  4017. xmpp.toggleRecording(function (callback) {
  4018. APP.UI.messageHandler.openTwoButtonDialog(null,
  4019. '<h2>Enter recording token</h2>' +
  4020. '<input id="recordingToken" type="text" ' +
  4021. 'placeholder="token" autofocus>',
  4022. false,
  4023. "Save",
  4024. function (e, v, m, f) {
  4025. if (v) {
  4026. var token = document.getElementById('recordingToken');
  4027. if (token.value) {
  4028. callback(UIUtil.escapeHtml(token.value));
  4029. }
  4030. }
  4031. },
  4032. function (event) {
  4033. document.getElementById('recordingToken').focus();
  4034. },
  4035. function () {
  4036. }
  4037. );
  4038. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4039. }
  4040. /**
  4041. * Locks / unlocks the room.
  4042. */
  4043. function lockRoom(lock) {
  4044. var currentSharedKey = '';
  4045. if (lock)
  4046. currentSharedKey = sharedKey;
  4047. xmpp.lockRoom(currentSharedKey, function (res) {
  4048. // password is required
  4049. if (sharedKey)
  4050. {
  4051. console.log('set room password');
  4052. Toolbar.lockLockButton();
  4053. }
  4054. else
  4055. {
  4056. console.log('removed room password');
  4057. Toolbar.unlockLockButton();
  4058. }
  4059. }, function (err) {
  4060. console.warn('setting password failed', err);
  4061. messageHandler.showError('Lock failed',
  4062. 'Failed to lock conference.',
  4063. err);
  4064. Toolbar.setSharedKey('');
  4065. }, function () {
  4066. console.warn('room passwords not supported');
  4067. messageHandler.showError('Warning',
  4068. 'Room passwords are currently not supported.');
  4069. Toolbar.setSharedKey('');
  4070. });
  4071. };
  4072. /**
  4073. * Invite participants to conference.
  4074. */
  4075. function inviteParticipants() {
  4076. if (roomUrl === null)
  4077. return;
  4078. var sharedKeyText = "";
  4079. if (sharedKey && sharedKey.length > 0) {
  4080. sharedKeyText =
  4081. "This conference is password protected. Please use the " +
  4082. "following pin when joining:%0D%0A%0D%0A" +
  4083. sharedKey + "%0D%0A%0D%0A";
  4084. }
  4085. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4086. var subject = "Invitation to a " + interfaceConfig.APP_NAME + " (" + conferenceName + ")";
  4087. var body = "Hey there, I%27d like to invite you to a " + interfaceConfig.APP_NAME +
  4088. " conference I%27ve just set up.%0D%0A%0D%0A" +
  4089. "Please click on the following link in order" +
  4090. " to join the conference.%0D%0A%0D%0A" +
  4091. roomUrl +
  4092. "%0D%0A%0D%0A" +
  4093. sharedKeyText +
  4094. "Note that " + interfaceConfig.APP_NAME + " is currently" +
  4095. " only supported by Chromium," +
  4096. " Google Chrome and Opera, so you need" +
  4097. " to be using one of these browsers.%0D%0A%0D%0A" +
  4098. "Talk to you in a sec!";
  4099. if (window.localStorage.displayname) {
  4100. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4101. }
  4102. if (interfaceConfig.INVITATION_POWERED_BY) {
  4103. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4104. }
  4105. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4106. }
  4107. function callSipButtonClicked()
  4108. {
  4109. var defaultNumber
  4110. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4111. messageHandler.openTwoButtonDialog(null,
  4112. '<h2>Enter SIP number</h2>' +
  4113. '<input id="sipNumber" type="text"' +
  4114. ' value="' + defaultNumber + '" autofocus>',
  4115. false,
  4116. "Dial",
  4117. function (e, v, m, f) {
  4118. if (v) {
  4119. var numberInput = document.getElementById('sipNumber');
  4120. if (numberInput.value) {
  4121. xmpp.dial(numberInput.value, 'fromnumber',
  4122. UI.getRoomName(), sharedKey);
  4123. }
  4124. }
  4125. },
  4126. function (event) {
  4127. document.getElementById('sipNumber').focus();
  4128. }
  4129. );
  4130. }
  4131. var Toolbar = (function (my) {
  4132. my.init = function (ui) {
  4133. for(var k in buttonHandlers)
  4134. $("#" + k).click(buttonHandlers[k]);
  4135. UI = ui;
  4136. }
  4137. /**
  4138. * Sets shared key
  4139. * @param sKey the shared key
  4140. */
  4141. my.setSharedKey = function (sKey) {
  4142. sharedKey = sKey;
  4143. };
  4144. my.authenticateClicked = function () {
  4145. Authentication.focusAuthenticationWindow();
  4146. // Get authentication URL
  4147. APP.xmpp.getAuthUrl(APP.UI.getRoomName(), function (url) {
  4148. // Open popup with authentication URL
  4149. var authenticationWindow = Authentication.createAuthenticationWindow(function () {
  4150. // On popup closed - retry room allocation
  4151. APP.xmpp.allocateConferenceFocus(APP.UI.getRoomName(), APP.UI.checkForNicknameAndJoin);
  4152. }, url);
  4153. if (!authenticationWindow) {
  4154. Toolbar.showAuthenticateButton(true);
  4155. messageHandler.openMessageDialog(
  4156. null, "Your browser is blocking popup windows from this site." +
  4157. " Please enable popups in your browser security settings" +
  4158. " and try again.");
  4159. }
  4160. });
  4161. };
  4162. /**
  4163. * Updates the room invite url.
  4164. */
  4165. my.updateRoomUrl = function (newRoomUrl) {
  4166. roomUrl = newRoomUrl;
  4167. // If the invite dialog has been already opened we update the information.
  4168. var inviteLink = document.getElementById('inviteLinkRef');
  4169. if (inviteLink) {
  4170. inviteLink.value = roomUrl;
  4171. inviteLink.select();
  4172. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4173. }
  4174. };
  4175. /**
  4176. * Disables and enables some of the buttons.
  4177. */
  4178. my.setupButtonsFromConfig = function () {
  4179. if (config.disablePrezi)
  4180. {
  4181. $("#prezi_button").css({display: "none"});
  4182. }
  4183. };
  4184. /**
  4185. * Opens the lock room dialog.
  4186. */
  4187. my.openLockDialog = function () {
  4188. // Only the focus is able to set a shared key.
  4189. if (!APP.xmpp.isModerator()) {
  4190. if (sharedKey) {
  4191. messageHandler.openMessageDialog(null,
  4192. "This conversation is currently protected by" +
  4193. " a password. Only the owner of the conference" +
  4194. " could set a password.",
  4195. false,
  4196. "Password");
  4197. } else {
  4198. messageHandler.openMessageDialog(null,
  4199. "This conversation isn't currently protected by" +
  4200. " a password. Only the owner of the conference" +
  4201. " could set a password.",
  4202. false,
  4203. "Password");
  4204. }
  4205. } else {
  4206. if (sharedKey) {
  4207. messageHandler.openTwoButtonDialog(null,
  4208. "Are you sure you would like to remove your password?",
  4209. false,
  4210. "Remove",
  4211. function (e, v) {
  4212. if (v) {
  4213. Toolbar.setSharedKey('');
  4214. lockRoom(false);
  4215. }
  4216. });
  4217. } else {
  4218. messageHandler.openTwoButtonDialog(null,
  4219. '<h2>Set a password to lock your room</h2>' +
  4220. '<input id="lockKey" type="text"' +
  4221. 'placeholder="your password" autofocus>',
  4222. false,
  4223. "Save",
  4224. function (e, v) {
  4225. if (v) {
  4226. var lockKey = document.getElementById('lockKey');
  4227. if (lockKey.value) {
  4228. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4229. lockRoom(true);
  4230. }
  4231. }
  4232. },
  4233. function () {
  4234. document.getElementById('lockKey').focus();
  4235. }
  4236. );
  4237. }
  4238. }
  4239. };
  4240. /**
  4241. * Opens the invite link dialog.
  4242. */
  4243. my.openLinkDialog = function () {
  4244. var inviteLink;
  4245. if (roomUrl === null) {
  4246. inviteLink = "Your conference is currently being created...";
  4247. } else {
  4248. inviteLink = encodeURI(roomUrl);
  4249. }
  4250. messageHandler.openTwoButtonDialog(
  4251. "Share this link with everyone you want to invite",
  4252. '<input id="inviteLinkRef" type="text" value="' +
  4253. inviteLink + '" onclick="this.select();" readonly>',
  4254. false,
  4255. "Invite",
  4256. function (e, v) {
  4257. if (v) {
  4258. if (roomUrl) {
  4259. inviteParticipants();
  4260. }
  4261. }
  4262. },
  4263. function () {
  4264. if (roomUrl) {
  4265. document.getElementById('inviteLinkRef').select();
  4266. } else {
  4267. document.getElementById('jqi_state0_buttonInvite')
  4268. .disabled = true;
  4269. }
  4270. }
  4271. );
  4272. };
  4273. /**
  4274. * Opens the settings dialog.
  4275. */
  4276. my.openSettingsDialog = function () {
  4277. messageHandler.openTwoButtonDialog(
  4278. '<h2>Configure your conference</h2>' +
  4279. '<input type="checkbox" id="initMuted">' +
  4280. 'Participants join muted<br/>' +
  4281. '<input type="checkbox" id="requireNicknames">' +
  4282. 'Require nicknames<br/><br/>' +
  4283. 'Set a password to lock your room:' +
  4284. '<input id="lockKey" type="text" placeholder="your password"' +
  4285. 'autofocus>',
  4286. null,
  4287. false,
  4288. "Save",
  4289. function () {
  4290. document.getElementById('lockKey').focus();
  4291. },
  4292. function (e, v) {
  4293. if (v) {
  4294. if ($('#initMuted').is(":checked")) {
  4295. // it is checked
  4296. }
  4297. if ($('#requireNicknames').is(":checked")) {
  4298. // it is checked
  4299. }
  4300. /*
  4301. var lockKey = document.getElementById('lockKey');
  4302. if (lockKey.value) {
  4303. setSharedKey(lockKey.value);
  4304. lockRoom(true);
  4305. }
  4306. */
  4307. }
  4308. }
  4309. );
  4310. };
  4311. /**
  4312. * Toggles the application in and out of full screen mode
  4313. * (a.k.a. presentation mode in Chrome).
  4314. */
  4315. my.toggleFullScreen = function () {
  4316. var fsElement = document.documentElement;
  4317. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4318. //Enter Full Screen
  4319. if (fsElement.mozRequestFullScreen) {
  4320. fsElement.mozRequestFullScreen();
  4321. }
  4322. else {
  4323. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4324. }
  4325. } else {
  4326. //Exit Full Screen
  4327. if (document.mozCancelFullScreen) {
  4328. document.mozCancelFullScreen();
  4329. } else {
  4330. document.webkitCancelFullScreen();
  4331. }
  4332. }
  4333. };
  4334. /**
  4335. * Unlocks the lock button state.
  4336. */
  4337. my.unlockLockButton = function () {
  4338. if ($("#lockIcon").hasClass("icon-security-locked"))
  4339. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4340. };
  4341. /**
  4342. * Updates the lock button state to locked.
  4343. */
  4344. my.lockLockButton = function () {
  4345. if ($("#lockIcon").hasClass("icon-security"))
  4346. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4347. };
  4348. /**
  4349. * Shows or hides authentication button
  4350. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4351. */
  4352. my.showAuthenticateButton = function (show) {
  4353. if (show) {
  4354. $('#authentication').css({display: "inline"});
  4355. }
  4356. else {
  4357. $('#authentication').css({display: "none"});
  4358. }
  4359. };
  4360. // Shows or hides the 'recording' button.
  4361. my.showRecordingButton = function (show) {
  4362. if (!config.enableRecording) {
  4363. return;
  4364. }
  4365. if (show) {
  4366. $('#recording').css({display: "inline"});
  4367. }
  4368. else {
  4369. $('#recording').css({display: "none"});
  4370. }
  4371. };
  4372. // Sets the state of the recording button
  4373. my.setRecordingButtonState = function (isRecording) {
  4374. if (isRecording) {
  4375. $('#recordButton').removeClass("icon-recEnable");
  4376. $('#recordButton').addClass("icon-recEnable active");
  4377. } else {
  4378. $('#recordButton').removeClass("icon-recEnable active");
  4379. $('#recordButton').addClass("icon-recEnable");
  4380. }
  4381. };
  4382. // Shows or hides SIP calls button
  4383. my.showSipCallButton = function (show) {
  4384. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4385. $('#sipCallButton').css({display: "inline"});
  4386. } else {
  4387. $('#sipCallButton').css({display: "none"});
  4388. }
  4389. };
  4390. /**
  4391. * Sets the state of the button. The button has blue glow if desktop
  4392. * streaming is active.
  4393. * @param active the state of the desktop streaming.
  4394. */
  4395. my.changeDesktopSharingButtonState = function (active) {
  4396. var button = $("#desktopsharing > a");
  4397. if (active)
  4398. {
  4399. button.addClass("glow");
  4400. }
  4401. else
  4402. {
  4403. button.removeClass("glow");
  4404. }
  4405. };
  4406. return my;
  4407. }(Toolbar || {}));
  4408. module.exports = Toolbar;
  4409. },{"../authentication/Authentication":11,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/SidePanelToggler":16,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){
  4410. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4411. var toolbarTimeoutObject,
  4412. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4413. function showDesktopSharingButton() {
  4414. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4415. $('#desktopsharing').css({display: "inline"});
  4416. } else {
  4417. $('#desktopsharing').css({display: "none"});
  4418. }
  4419. }
  4420. /**
  4421. * Hides the toolbar.
  4422. */
  4423. function hideToolbar() {
  4424. var header = $("#header"),
  4425. bottomToolbar = $("#bottomToolbar");
  4426. var isToolbarHover = false;
  4427. header.find('*').each(function () {
  4428. var id = $(this).attr('id');
  4429. if ($("#" + id + ":hover").length > 0) {
  4430. isToolbarHover = true;
  4431. }
  4432. });
  4433. if ($("#bottomToolbar:hover").length > 0) {
  4434. isToolbarHover = true;
  4435. }
  4436. clearTimeout(toolbarTimeoutObject);
  4437. toolbarTimeoutObject = null;
  4438. if (!isToolbarHover) {
  4439. header.hide("slide", { direction: "up", duration: 300});
  4440. $('#subject').animate({top: "-=40"}, 300);
  4441. if ($("#remoteVideos").hasClass("hidden")) {
  4442. bottomToolbar.hide(
  4443. "slide", {direction: "right", duration: 300});
  4444. }
  4445. }
  4446. else {
  4447. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4448. }
  4449. }
  4450. var ToolbarToggler = {
  4451. /**
  4452. * Shows the main toolbar.
  4453. */
  4454. showToolbar: function () {
  4455. var header = $("#header"),
  4456. bottomToolbar = $("#bottomToolbar");
  4457. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4458. header.show("slide", { direction: "up", duration: 300});
  4459. $('#subject').animate({top: "+=40"}, 300);
  4460. if (!bottomToolbar.is(":visible")) {
  4461. bottomToolbar.show(
  4462. "slide", {direction: "right", duration: 300});
  4463. }
  4464. if (toolbarTimeoutObject) {
  4465. clearTimeout(toolbarTimeoutObject);
  4466. toolbarTimeoutObject = null;
  4467. }
  4468. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4469. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4470. }
  4471. if (APP.xmpp.isModerator())
  4472. {
  4473. // TODO: Enable settings functionality.
  4474. // Need to uncomment the settings button in index.html.
  4475. // $('#settingsButton').css({visibility:"visible"});
  4476. }
  4477. // Show/hide desktop sharing button
  4478. showDesktopSharingButton();
  4479. },
  4480. /**
  4481. * Docks/undocks the toolbar.
  4482. *
  4483. * @param isDock indicates what operation to perform
  4484. */
  4485. dockToolbar: function (isDock) {
  4486. if (isDock) {
  4487. // First make sure the toolbar is shown.
  4488. if (!$('#header').is(':visible')) {
  4489. this.showToolbar();
  4490. }
  4491. // Then clear the time out, to dock the toolbar.
  4492. if (toolbarTimeoutObject) {
  4493. clearTimeout(toolbarTimeoutObject);
  4494. toolbarTimeoutObject = null;
  4495. }
  4496. }
  4497. else {
  4498. if (!$('#header').is(':visible')) {
  4499. this.showToolbar();
  4500. }
  4501. else {
  4502. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4503. }
  4504. }
  4505. },
  4506. showDesktopSharingButton: showDesktopSharingButton
  4507. };
  4508. module.exports = ToolbarToggler;
  4509. },{}],27:[function(require,module,exports){
  4510. var JitsiPopover = (function () {
  4511. /**
  4512. * Constructs new JitsiPopover and attaches it to the element
  4513. * @param element jquery selector
  4514. * @param options the options for the popover.
  4515. * @constructor
  4516. */
  4517. function JitsiPopover(element, options)
  4518. {
  4519. this.options = {
  4520. skin: "white",
  4521. content: ""
  4522. };
  4523. if(options)
  4524. {
  4525. if(options.skin)
  4526. this.options.skin = options.skin;
  4527. if(options.content)
  4528. this.options.content = options.content;
  4529. }
  4530. this.elementIsHovered = false;
  4531. this.popoverIsHovered = false;
  4532. this.popoverShown = false;
  4533. element.data("jitsi_popover", this);
  4534. this.element = element;
  4535. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4536. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4537. '<div class="jitsiPopupmenuPadding"></div></div>';
  4538. var self = this;
  4539. this.element.on("mouseenter", function () {
  4540. self.elementIsHovered = true;
  4541. self.show();
  4542. }).on("mouseleave", function () {
  4543. self.elementIsHovered = false;
  4544. setTimeout(function () {
  4545. self.hide();
  4546. }, 10);
  4547. });
  4548. }
  4549. /**
  4550. * Shows the popover
  4551. */
  4552. JitsiPopover.prototype.show = function () {
  4553. this.createPopover();
  4554. this.popoverShown = true;
  4555. };
  4556. /**
  4557. * Hides the popover
  4558. */
  4559. JitsiPopover.prototype.hide = function () {
  4560. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4561. {
  4562. this.forceHide();
  4563. }
  4564. };
  4565. /**
  4566. * Hides the popover
  4567. */
  4568. JitsiPopover.prototype.forceHide = function () {
  4569. $(".jitsipopover").remove();
  4570. this.popoverShown = false;
  4571. };
  4572. /**
  4573. * Creates the popover html
  4574. */
  4575. JitsiPopover.prototype.createPopover = function () {
  4576. $("body").append(this.template);
  4577. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4578. var self = this;
  4579. $(".jitsipopover").on("mouseenter", function () {
  4580. self.popoverIsHovered = true;
  4581. }).on("mouseleave", function () {
  4582. self.popoverIsHovered = false;
  4583. self.hide();
  4584. });
  4585. this.refreshPosition();
  4586. };
  4587. /**
  4588. * Refreshes the position of the popover
  4589. */
  4590. JitsiPopover.prototype.refreshPosition = function () {
  4591. $(".jitsipopover").position({
  4592. my: "bottom",
  4593. at: "top",
  4594. collision: "fit",
  4595. of: this.element,
  4596. using: function (position, elements) {
  4597. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4598. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4599. $(".jitsipopover > .arrow").css({left: calcLeft});
  4600. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4601. }
  4602. });
  4603. };
  4604. /**
  4605. * Updates the content of popover.
  4606. * @param content new content
  4607. */
  4608. JitsiPopover.prototype.updateContent = function (content) {
  4609. this.options.content = content;
  4610. if(!this.popoverShown)
  4611. return;
  4612. $(".jitsipopover").remove();
  4613. this.createPopover();
  4614. };
  4615. return JitsiPopover;
  4616. })();
  4617. module.exports = JitsiPopover;
  4618. },{}],28:[function(require,module,exports){
  4619. /* global $, jQuery */
  4620. var messageHandler = (function(my) {
  4621. /**
  4622. * Shows a message to the user.
  4623. *
  4624. * @param titleString the title of the message
  4625. * @param messageString the text of the message
  4626. */
  4627. my.openMessageDialog = function(titleString, messageString) {
  4628. $.prompt(messageString,
  4629. {
  4630. title: titleString,
  4631. persistent: false
  4632. }
  4633. );
  4634. };
  4635. /**
  4636. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4637. *
  4638. * @param titleString the title of the message
  4639. * @param msgString the text of the message
  4640. * @param persistent boolean value which determines whether the message is persistent or not
  4641. * @param leftButton the fist button's text
  4642. * @param submitFunction function to be called on submit
  4643. * @param loadedFunction function to be called after the prompt is fully loaded
  4644. * @param closeFunction function to be called after the prompt is closed
  4645. */
  4646. my.openTwoButtonDialog = function(titleString, msgString, persistent, leftButton,
  4647. submitFunction, loadedFunction, closeFunction) {
  4648. var buttons = {};
  4649. buttons[leftButton] = true;
  4650. buttons.Cancel = false;
  4651. $.prompt(msgString, {
  4652. title: titleString,
  4653. persistent: false,
  4654. buttons: buttons,
  4655. defaultButton: 1,
  4656. loaded: loadedFunction,
  4657. submit: submitFunction,
  4658. close: closeFunction
  4659. });
  4660. };
  4661. /**
  4662. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4663. *
  4664. * @param titleString the title of the message
  4665. * @param msgString the text of the message
  4666. * @param persistent boolean value which determines whether the message is persistent or not
  4667. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  4668. * that will be passed to submitFunction
  4669. * @param submitFunction function to be called on submit
  4670. * @param loadedFunction function to be called after the prompt is fully loaded
  4671. */
  4672. my.openDialog = function (titleString, msgString, persistent, buttons,
  4673. submitFunction, loadedFunction) {
  4674. var args = {
  4675. title: titleString,
  4676. persistent: persistent,
  4677. buttons: buttons,
  4678. defaultButton: 1,
  4679. loaded: loadedFunction,
  4680. submit: submitFunction
  4681. };
  4682. if (persistent) {
  4683. args.closeText = '';
  4684. }
  4685. return $.prompt(msgString, args);
  4686. };
  4687. /**
  4688. * Closes currently opened dialog.
  4689. */
  4690. my.closeDialog = function () {
  4691. $.prompt.close();
  4692. };
  4693. /**
  4694. * Shows a dialog with different states to the user.
  4695. *
  4696. * @param statesObject object containing all the states of the dialog
  4697. * @param loadedFunction function to be called after the prompt is fully loaded
  4698. * @param stateChangedFunction function to be called when the state of the dialog is changed
  4699. */
  4700. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  4701. var myPrompt = $.prompt(statesObject);
  4702. myPrompt.on('impromptu:loaded', loadedFunction);
  4703. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  4704. };
  4705. /**
  4706. * Opens new popup window for given <tt>url</tt> centered over current
  4707. * window.
  4708. *
  4709. * @param url the URL to be displayed in the popup window
  4710. * @param w the width of the popup window
  4711. * @param h the height of the popup window
  4712. * @param onPopupClosed optional callback function called when popup window
  4713. * has been closed.
  4714. *
  4715. * @returns popup window object if opened successfully or undefined
  4716. * in case we failed to open it(popup blocked)
  4717. */
  4718. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  4719. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  4720. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  4721. var popup = window.open(
  4722. url, '_blank',
  4723. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  4724. if (popup && onPopupClosed) {
  4725. var pollTimer = window.setInterval(function () {
  4726. if (popup.closed !== false) {
  4727. window.clearInterval(pollTimer);
  4728. onPopupClosed();
  4729. }
  4730. }, 200);
  4731. }
  4732. return popup;
  4733. };
  4734. /**
  4735. * Shows a dialog prompting the user to send an error report.
  4736. *
  4737. * @param titleString the title of the message
  4738. * @param msgString the text of the message
  4739. * @param error the error that is being reported
  4740. */
  4741. my.openReportDialog = function(titleString, msgString, error) {
  4742. my.openMessageDialog(titleString, msgString);
  4743. console.log(error);
  4744. //FIXME send the error to the server
  4745. };
  4746. /**
  4747. * Shows an error dialog to the user.
  4748. * @param title the title of the message
  4749. * @param message the text of the messafe
  4750. */
  4751. my.showError = function(title, message) {
  4752. if(!(title || message)) {
  4753. title = title || "Oops!";
  4754. message = message || "There was some kind of error";
  4755. }
  4756. messageHandler.openMessageDialog(title, message);
  4757. };
  4758. my.notify = function(displayName, cls, message) {
  4759. toastr.info(
  4760. '<span class="nickname">' +
  4761. displayName +
  4762. '</span><br>' +
  4763. '<span class=' + cls + '>' +
  4764. message +
  4765. '</span>');
  4766. };
  4767. return my;
  4768. }(messageHandler || {}));
  4769. module.exports = messageHandler;
  4770. },{}],29:[function(require,module,exports){
  4771. var UIEvents = require("../../../service/UI/UIEvents");
  4772. var nickname = null;
  4773. var eventEmitter = null;
  4774. var NickanameHandler = {
  4775. init: function (emitter) {
  4776. eventEmitter = emitter;
  4777. var storedDisplayName = window.localStorage.displayname;
  4778. if (storedDisplayName) {
  4779. nickname = storedDisplayName;
  4780. }
  4781. },
  4782. setNickname: function (newNickname) {
  4783. if (!newNickname || nickname === newNickname)
  4784. return;
  4785. nickname = newNickname;
  4786. window.localStorage.displayname = nickname;
  4787. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  4788. },
  4789. getNickname: function () {
  4790. return nickname;
  4791. },
  4792. addListener: function (type, listener) {
  4793. eventEmitter.on(type, listener);
  4794. }
  4795. };
  4796. module.exports = NickanameHandler;
  4797. },{"../../../service/UI/UIEvents":80}],30:[function(require,module,exports){
  4798. /**
  4799. * Created by hristo on 12/22/14.
  4800. */
  4801. module.exports = {
  4802. /**
  4803. * Returns the available video width.
  4804. */
  4805. getAvailableVideoWidth: function () {
  4806. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4807. var rightPanelWidth
  4808. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  4809. return window.innerWidth - rightPanelWidth;
  4810. },
  4811. /**
  4812. * Changes the style class of the element given by id.
  4813. */
  4814. buttonClick: function(id, classname) {
  4815. $(id).toggleClass(classname); // add the class to the clicked element
  4816. },
  4817. /**
  4818. * Returns the text width for the given element.
  4819. *
  4820. * @param el the element
  4821. */
  4822. getTextWidth: function (el) {
  4823. return (el.clientWidth + 1);
  4824. },
  4825. /**
  4826. * Returns the text height for the given element.
  4827. *
  4828. * @param el the element
  4829. */
  4830. getTextHeight: function (el) {
  4831. return (el.clientHeight + 1);
  4832. },
  4833. /**
  4834. * Plays the sound given by id.
  4835. *
  4836. * @param id the identifier of the audio element.
  4837. */
  4838. playSoundNotification: function (id) {
  4839. document.getElementById(id).play();
  4840. },
  4841. /**
  4842. * Escapes the given text.
  4843. */
  4844. escapeHtml: function (unsafeText) {
  4845. return $('<div/>').text(unsafeText).html();
  4846. },
  4847. imageToGrayScale: function (canvas) {
  4848. var context = canvas.getContext('2d');
  4849. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  4850. var pixels = imgData.data;
  4851. for (var i = 0, n = pixels.length; i < n; i += 4) {
  4852. var grayscale
  4853. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  4854. pixels[i ] = grayscale; // red
  4855. pixels[i+1] = grayscale; // green
  4856. pixels[i+2] = grayscale; // blue
  4857. // pixels[i+3] is alpha
  4858. }
  4859. // redraw the image in black & white
  4860. context.putImageData(imgData, 0, 0);
  4861. },
  4862. setTooltip: function (element, tooltipText, position) {
  4863. element.setAttribute("data-content", tooltipText);
  4864. element.setAttribute("data-toggle", "popover");
  4865. element.setAttribute("data-placement", position);
  4866. element.setAttribute("data-html", true);
  4867. element.setAttribute("data-container", "body");
  4868. }
  4869. };
  4870. },{"../side_pannels/SidePanelToggler":16}],31:[function(require,module,exports){
  4871. var JitsiPopover = require("../util/JitsiPopover");
  4872. /**
  4873. * Constructs new connection indicator.
  4874. * @param videoContainer the video container associated with the indicator.
  4875. * @constructor
  4876. */
  4877. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  4878. {
  4879. this.videoContainer = videoContainer;
  4880. this.bandwidth = null;
  4881. this.packetLoss = null;
  4882. this.bitrate = null;
  4883. this.showMoreValue = false;
  4884. this.resolution = null;
  4885. this.transport = [];
  4886. this.popover = null;
  4887. this.jid = jid;
  4888. this.create();
  4889. this.videoLayout = VideoLayout;
  4890. }
  4891. /**
  4892. * Values for the connection quality
  4893. * @type {{98: string,
  4894. * 81: string,
  4895. * 64: string,
  4896. * 47: string,
  4897. * 30: string,
  4898. * 0: string}}
  4899. */
  4900. ConnectionIndicator.connectionQualityValues = {
  4901. 98: "18px", //full
  4902. 81: "15px",//4 bars
  4903. 64: "11px",//3 bars
  4904. 47: "7px",//2 bars
  4905. 30: "3px",//1 bar
  4906. 0: "0px"//empty
  4907. };
  4908. ConnectionIndicator.getIP = function(value)
  4909. {
  4910. return value.substring(0, value.lastIndexOf(":"));
  4911. };
  4912. ConnectionIndicator.getPort = function(value)
  4913. {
  4914. return value.substring(value.lastIndexOf(":") + 1, value.length);
  4915. };
  4916. ConnectionIndicator.getStringFromArray = function (array) {
  4917. var res = "";
  4918. for(var i = 0; i < array.length; i++)
  4919. {
  4920. res += (i === 0? "" : ", ") + array[i];
  4921. }
  4922. return res;
  4923. };
  4924. /**
  4925. * Generates the html content.
  4926. * @returns {string} the html content.
  4927. */
  4928. ConnectionIndicator.prototype.generateText = function () {
  4929. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  4930. if(this.bitrate === null)
  4931. {
  4932. downloadBitrate = "N/A";
  4933. uploadBitrate = "N/A";
  4934. }
  4935. else
  4936. {
  4937. downloadBitrate =
  4938. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  4939. uploadBitrate =
  4940. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  4941. }
  4942. if(this.packetLoss === null)
  4943. {
  4944. packetLoss = "N/A";
  4945. }
  4946. else
  4947. {
  4948. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  4949. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  4950. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  4951. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  4952. }
  4953. var resolutionValue = null;
  4954. if(this.resolution && this.jid != null)
  4955. {
  4956. var keys = Object.keys(this.resolution);
  4957. if(keys.length == 1)
  4958. {
  4959. for(var ssrc in this.resolution)
  4960. {
  4961. resolutionValue = this.resolution[ssrc];
  4962. }
  4963. }
  4964. else if(keys.length > 1)
  4965. {
  4966. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  4967. resolutionValue = this.resolution[displayedSsrc];
  4968. }
  4969. }
  4970. if(this.jid === null)
  4971. {
  4972. resolution = "";
  4973. if(this.resolution === null || !Object.keys(this.resolution) ||
  4974. Object.keys(this.resolution).length === 0)
  4975. {
  4976. resolution = "N/A";
  4977. }
  4978. else
  4979. for(i in this.resolution)
  4980. {
  4981. resolutionValue = this.resolution[i];
  4982. if(resolutionValue)
  4983. {
  4984. if(resolutionValue.height &&
  4985. resolutionValue.width)
  4986. {
  4987. resolution += (resolution === ""? "" : ", ") +
  4988. resolutionValue.width + "x" +
  4989. resolutionValue.height;
  4990. }
  4991. }
  4992. }
  4993. }
  4994. else if(!resolutionValue ||
  4995. !resolutionValue.height ||
  4996. !resolutionValue.width)
  4997. {
  4998. resolution = "N/A";
  4999. }
  5000. else
  5001. {
  5002. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5003. }
  5004. var result = "<table style='width:100%'>" +
  5005. "<tr>" +
  5006. "<td><span class='jitsipopover_blue'>Bitrate:</span></td>" +
  5007. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5008. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5009. uploadBitrate + "</td>" +
  5010. "</tr><tr>" +
  5011. "<td><span class='jitsipopover_blue'>Packet loss: </span></td>" +
  5012. "<td>" + packetLoss + "</td>" +
  5013. "</tr><tr>" +
  5014. "<td><span class='jitsipopover_blue'>Resolution:</span></td>" +
  5015. "<td>" + resolution + "</td></tr></table>";
  5016. if(this.videoContainer.id == "localVideoContainer")
  5017. result += "<div class=\"jitsipopover_showmore\" " +
  5018. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5019. this.videoContainer.id + "')\">" +
  5020. (this.showMoreValue? "Show less" : "Show More") + "</div><br />";
  5021. if(this.showMoreValue)
  5022. {
  5023. var downloadBandwidth, uploadBandwidth, transport;
  5024. if(this.bandwidth === null)
  5025. {
  5026. downloadBandwidth = "N/A";
  5027. uploadBandwidth = "N/A";
  5028. }
  5029. else
  5030. {
  5031. downloadBandwidth = this.bandwidth.download?
  5032. this.bandwidth.download + " Kbps" :
  5033. "N/A";
  5034. uploadBandwidth = this.bandwidth.upload?
  5035. this.bandwidth.upload + " Kbps" :
  5036. "N/A";
  5037. }
  5038. if(!this.transport || this.transport.length === 0)
  5039. {
  5040. transport = "<tr>" +
  5041. "<td><span class='jitsipopover_blue'>Address:</span></td>" +
  5042. "<td> N/A</td></tr>";
  5043. }
  5044. else
  5045. {
  5046. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5047. for(i = 0; i < this.transport.length; i++)
  5048. {
  5049. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5050. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5051. var localIP =
  5052. ConnectionIndicator.getIP(this.transport[i].localip);
  5053. var localPort =
  5054. ConnectionIndicator.getPort(this.transport[i].localip);
  5055. if(data.remoteIP.indexOf(ip) == -1)
  5056. {
  5057. data.remoteIP.push(ip);
  5058. }
  5059. if(data.remotePort.indexOf(port) == -1)
  5060. {
  5061. data.remotePort.push(port);
  5062. }
  5063. if(data.localIP.indexOf(localIP) == -1)
  5064. {
  5065. data.localIP.push(localIP);
  5066. }
  5067. if(data.localPort.indexOf(localPort) == -1)
  5068. {
  5069. data.localPort.push(localPort);
  5070. }
  5071. }
  5072. var localTransport =
  5073. "<tr><td><span class='jitsipopover_blue'>Local address" +
  5074. (data.localIP.length > 1? "es" : "") + ": </span></td><td> " +
  5075. ConnectionIndicator.getStringFromArray(data.localIP) +
  5076. "</td></tr>";
  5077. transport =
  5078. "<tr><td><span class='jitsipopover_blue'>Remote address"+
  5079. (data.remoteIP.length > 1? "es" : "") + ":</span></td><td> " +
  5080. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5081. "</td></tr>";
  5082. if(this.transport.length > 1)
  5083. {
  5084. transport += "<tr>" +
  5085. "<td>" +
  5086. "<span class='jitsipopover_blue'>Remote ports:</span>" +
  5087. "</td><td>";
  5088. localTransport += "<tr>" +
  5089. "<td>" +
  5090. "<span class='jitsipopover_blue'>Local ports:</span>" +
  5091. "</td><td>";
  5092. }
  5093. else
  5094. {
  5095. transport +=
  5096. "<tr>" +
  5097. "<td>" +
  5098. "<span class='jitsipopover_blue'>Remote port:</span>" +
  5099. "</td><td>";
  5100. localTransport +=
  5101. "<tr>" +
  5102. "<td>" +
  5103. "<span class='jitsipopover_blue'>Local port:</span>" +
  5104. "</td><td>";
  5105. }
  5106. transport +=
  5107. ConnectionIndicator.getStringFromArray(data.remotePort);
  5108. localTransport +=
  5109. ConnectionIndicator.getStringFromArray(data.localPort);
  5110. transport += "</td></tr>";
  5111. transport += localTransport + "</td></tr>";
  5112. transport +="<tr>" +
  5113. "<td><span class='jitsipopover_blue'>Transport:</span></td>" +
  5114. "<td>" + this.transport[0].type + "</td></tr>";
  5115. }
  5116. result += "<table style='width:100%'>" +
  5117. "<tr>" +
  5118. "<td>" +
  5119. "<span class='jitsipopover_blue'>Estimated bandwidth:</span>" +
  5120. "</td><td>" +
  5121. "<span class='jitsipopover_green'>&darr;</span>" +
  5122. downloadBandwidth +
  5123. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5124. uploadBandwidth + "</td></tr>";
  5125. result += transport + "</table>";
  5126. }
  5127. return result;
  5128. };
  5129. /**
  5130. * Shows or hide the additional information.
  5131. */
  5132. ConnectionIndicator.prototype.showMore = function () {
  5133. this.showMoreValue = !this.showMoreValue;
  5134. this.updatePopoverData();
  5135. };
  5136. function createIcon(classes)
  5137. {
  5138. var icon = document.createElement("span");
  5139. for(var i in classes)
  5140. {
  5141. icon.classList.add(classes[i]);
  5142. }
  5143. icon.appendChild(
  5144. document.createElement("i")).classList.add("icon-connection");
  5145. return icon;
  5146. }
  5147. /**
  5148. * Creates the indicator
  5149. */
  5150. ConnectionIndicator.prototype.create = function () {
  5151. this.connectionIndicatorContainer = document.createElement("div");
  5152. this.connectionIndicatorContainer.className = "connectionindicator";
  5153. this.connectionIndicatorContainer.style.display = "none";
  5154. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5155. this.popover = new JitsiPopover(
  5156. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5157. {content: "<div class=\"connection_info\">Come back here for " +
  5158. "connection information once the conference starts</div>",
  5159. skin: "black"});
  5160. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5161. createIcon(["connection", "connection_empty"]));
  5162. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5163. createIcon(["connection", "connection_full"]));
  5164. };
  5165. /**
  5166. * Removes the indicator
  5167. */
  5168. ConnectionIndicator.prototype.remove = function()
  5169. {
  5170. this.connectionIndicatorContainer.remove();
  5171. this.popover.forceHide();
  5172. };
  5173. /**
  5174. * Updates the data of the indicator
  5175. * @param percent the percent of connection quality
  5176. * @param object the statistics data.
  5177. */
  5178. ConnectionIndicator.prototype.updateConnectionQuality =
  5179. function (percent, object) {
  5180. if(percent === null)
  5181. {
  5182. this.connectionIndicatorContainer.style.display = "none";
  5183. this.popover.forceHide();
  5184. return;
  5185. }
  5186. else
  5187. {
  5188. if(this.connectionIndicatorContainer.style.display == "none") {
  5189. this.connectionIndicatorContainer.style.display = "block";
  5190. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5191. }
  5192. }
  5193. this.bandwidth = object.bandwidth;
  5194. this.bitrate = object.bitrate;
  5195. this.packetLoss = object.packetLoss;
  5196. this.transport = object.transport;
  5197. if(object.resolution)
  5198. {
  5199. this.resolution = object.resolution;
  5200. }
  5201. for(var quality in ConnectionIndicator.connectionQualityValues)
  5202. {
  5203. if(percent >= quality)
  5204. {
  5205. this.fullIcon.style.width =
  5206. ConnectionIndicator.connectionQualityValues[quality];
  5207. }
  5208. }
  5209. this.updatePopoverData();
  5210. };
  5211. /**
  5212. * Updates the resolution
  5213. * @param resolution the new resolution
  5214. */
  5215. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5216. this.resolution = resolution;
  5217. this.updatePopoverData();
  5218. };
  5219. /**
  5220. * Updates the content of the popover
  5221. */
  5222. ConnectionIndicator.prototype.updatePopoverData = function () {
  5223. this.popover.updateContent(
  5224. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5225. };
  5226. /**
  5227. * Hides the popover
  5228. */
  5229. ConnectionIndicator.prototype.hide = function () {
  5230. this.popover.forceHide();
  5231. };
  5232. /**
  5233. * Hides the indicator
  5234. */
  5235. ConnectionIndicator.prototype.hideIndicator = function () {
  5236. this.connectionIndicatorContainer.style.display = "none";
  5237. if(this.popover)
  5238. this.popover.forceHide();
  5239. };
  5240. module.exports = ConnectionIndicator;
  5241. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5242. var AudioLevels = require("../audio_levels/AudioLevels");
  5243. var Avatar = require("../avatar/Avatar");
  5244. var Chat = require("../side_pannels/chat/Chat");
  5245. var ContactList = require("../side_pannels/contactlist/ContactList");
  5246. var UIUtil = require("../util/UIUtil");
  5247. var ConnectionIndicator = require("./ConnectionIndicator");
  5248. var NicknameHandler = require("../util/NicknameHandler");
  5249. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5250. var UIEvents = require("../../../service/UI/UIEvents");
  5251. var currentDominantSpeaker = null;
  5252. var lastNCount = config.channelLastN;
  5253. var localLastNCount = config.channelLastN;
  5254. var localLastNSet = [];
  5255. var lastNEndpointsCache = [];
  5256. var lastNPickupJid = null;
  5257. var largeVideoState = {
  5258. updateInProgress: false,
  5259. newSrc: ''
  5260. };
  5261. var eventEmitter = null;
  5262. /**
  5263. * Currently focused video "src"(displayed in large video).
  5264. * @type {String}
  5265. */
  5266. var focusedVideoInfo = null;
  5267. /**
  5268. * Indicates if we have muted our audio before the conference has started.
  5269. * @type {boolean}
  5270. */
  5271. var preMuted = false;
  5272. var mutedAudios = {};
  5273. var flipXLocalVideo = true;
  5274. var currentVideoWidth = null;
  5275. var currentVideoHeight = null;
  5276. var localVideoSrc = null;
  5277. function videoactive( videoelem) {
  5278. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5279. // ignore mixedmslabela0 and v0
  5280. videoelem.show();
  5281. VideoLayout.resizeThumbnails();
  5282. var videoParent = videoelem.parent();
  5283. var parentResourceJid = null;
  5284. if (videoParent)
  5285. parentResourceJid
  5286. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5287. // Update the large video to the last added video only if there's no
  5288. // current dominant, focused speaker or prezi playing or update it to
  5289. // the current dominant speaker.
  5290. if ((!focusedVideoInfo &&
  5291. !VideoLayout.getDominantSpeakerResourceJid() &&
  5292. !require("../prezi/Prezi").isPresentationVisible()) ||
  5293. (parentResourceJid &&
  5294. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5295. VideoLayout.updateLargeVideo(
  5296. APP.RTC.getVideoSrc(videoelem[0]),
  5297. 1,
  5298. parentResourceJid);
  5299. }
  5300. VideoLayout.showModeratorIndicator();
  5301. }
  5302. }
  5303. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5304. // XXX(gp) so, every call to this function is *always* preceded by a call
  5305. // to the RTC.attachMediaStream() function but that call is *not* followed
  5306. // by an update to the videoSrcToSsrc map!
  5307. //
  5308. // The above way of doing things results in video SRCs that don't correspond
  5309. // to any SSRC for a short period of time (to be more precise, for as long
  5310. // the waitForRemoteVideo takes to complete). This causes problems (see
  5311. // bellow).
  5312. //
  5313. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5314. // a second time in here and only then update the videoSrcToSsrc map? Why
  5315. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5316. // is called the first time? I actually do that in the lastN changed event
  5317. // handler because the "orphan" video SRC is causing troubles there. The
  5318. // purpose of this method would then be to fire the "videoactive.jingle".
  5319. //
  5320. // Food for though I guess :-)
  5321. if (selector.removed || !selector.parent().is(":visible")) {
  5322. console.warn("Media removed before had started", selector);
  5323. return;
  5324. }
  5325. if (stream.id === 'mixedmslabel') return;
  5326. if (selector[0].currentTime > 0) {
  5327. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5328. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5329. videoactive(selector);
  5330. } else {
  5331. setTimeout(function () {
  5332. waitForRemoteVideo(selector, ssrc, stream, jid);
  5333. }, 250);
  5334. }
  5335. }
  5336. /**
  5337. * Returns an array of the video horizontal and vertical indents,
  5338. * so that if fits its parent.
  5339. *
  5340. * @return an array with 2 elements, the horizontal indent and the vertical
  5341. * indent
  5342. */
  5343. function getCameraVideoPosition(videoWidth,
  5344. videoHeight,
  5345. videoSpaceWidth,
  5346. videoSpaceHeight) {
  5347. // Parent height isn't completely calculated when we position the video in
  5348. // full screen mode and this is why we use the screen height in this case.
  5349. // Need to think it further at some point and implement it properly.
  5350. var isFullScreen = document.fullScreen ||
  5351. document.mozFullScreen ||
  5352. document.webkitIsFullScreen;
  5353. if (isFullScreen)
  5354. videoSpaceHeight = window.innerHeight;
  5355. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5356. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5357. return [horizontalIndent, verticalIndent];
  5358. }
  5359. /**
  5360. * Returns an array of the video horizontal and vertical indents.
  5361. * Centers horizontally and top aligns vertically.
  5362. *
  5363. * @return an array with 2 elements, the horizontal indent and the vertical
  5364. * indent
  5365. */
  5366. function getDesktopVideoPosition(videoWidth,
  5367. videoHeight,
  5368. videoSpaceWidth,
  5369. videoSpaceHeight) {
  5370. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5371. var verticalIndent = 0;// Top aligned
  5372. return [horizontalIndent, verticalIndent];
  5373. }
  5374. /**
  5375. * Returns an array of the video dimensions, so that it covers the screen.
  5376. * It leaves no empty areas, but some parts of the video might not be visible.
  5377. *
  5378. * @return an array with 2 elements, the video width and the video height
  5379. */
  5380. function getCameraVideoSize(videoWidth,
  5381. videoHeight,
  5382. videoSpaceWidth,
  5383. videoSpaceHeight) {
  5384. if (!videoWidth)
  5385. videoWidth = currentVideoWidth;
  5386. if (!videoHeight)
  5387. videoHeight = currentVideoHeight;
  5388. var aspectRatio = videoWidth / videoHeight;
  5389. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5390. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5391. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5392. availableHeight = videoSpaceHeight;
  5393. availableWidth = availableHeight * aspectRatio;
  5394. }
  5395. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5396. availableWidth = videoSpaceWidth;
  5397. availableHeight = availableWidth / aspectRatio;
  5398. }
  5399. return [availableWidth, availableHeight];
  5400. }
  5401. /**
  5402. * Sets the display name for the given video span id.
  5403. */
  5404. function setDisplayName(videoSpanId, displayName) {
  5405. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5406. var defaultLocalDisplayName = interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME;
  5407. // If we already have a display name for this video.
  5408. if (nameSpan.length > 0) {
  5409. var nameSpanElement = nameSpan.get(0);
  5410. if (nameSpanElement.id === 'localDisplayName' &&
  5411. $('#localDisplayName').text() !== displayName) {
  5412. if (displayName && displayName.length > 0)
  5413. $('#localDisplayName').html(displayName + ' (me)');
  5414. else
  5415. $('#localDisplayName').text(defaultLocalDisplayName);
  5416. } else {
  5417. if (displayName && displayName.length > 0)
  5418. $('#' + videoSpanId + '_name').html(displayName);
  5419. else
  5420. $('#' + videoSpanId + '_name').text(interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5421. }
  5422. } else {
  5423. var editButton = null;
  5424. nameSpan = document.createElement('span');
  5425. nameSpan.className = 'displayname';
  5426. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5427. if (videoSpanId === 'localVideoContainer') {
  5428. editButton = createEditDisplayNameButton();
  5429. nameSpan.innerText = defaultLocalDisplayName;
  5430. }
  5431. else {
  5432. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5433. }
  5434. if (displayName && displayName.length > 0) {
  5435. nameSpan.innerText = displayName;
  5436. }
  5437. if (!editButton) {
  5438. nameSpan.id = videoSpanId + '_name';
  5439. } else {
  5440. nameSpan.id = 'localDisplayName';
  5441. $('#' + videoSpanId)[0].appendChild(editButton);
  5442. var editableText = document.createElement('input');
  5443. editableText.className = 'displayname';
  5444. editableText.type = 'text';
  5445. editableText.id = 'editDisplayName';
  5446. if (displayName && displayName.length) {
  5447. editableText.value
  5448. = displayName.substring(0, displayName.indexOf(' (me)'));
  5449. }
  5450. editableText.setAttribute('style', 'display:none;');
  5451. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  5452. $('#' + videoSpanId)[0].appendChild(editableText);
  5453. $('#localVideoContainer .displayname')
  5454. .bind("click", function (e) {
  5455. e.preventDefault();
  5456. e.stopPropagation();
  5457. $('#localDisplayName').hide();
  5458. $('#editDisplayName').show();
  5459. $('#editDisplayName').focus();
  5460. $('#editDisplayName').select();
  5461. $('#editDisplayName').one("focusout", function (e) {
  5462. VideoLayout.inputDisplayNameHandler(this.value);
  5463. });
  5464. $('#editDisplayName').on('keydown', function (e) {
  5465. if (e.keyCode === 13) {
  5466. e.preventDefault();
  5467. VideoLayout.inputDisplayNameHandler(this.value);
  5468. }
  5469. });
  5470. });
  5471. }
  5472. }
  5473. }
  5474. /**
  5475. * Gets the selector of video thumbnail container for the user identified by
  5476. * given <tt>userJid</tt>
  5477. * @param resourceJid user's Jid for whom we want to get the video container.
  5478. */
  5479. function getParticipantContainer(resourceJid)
  5480. {
  5481. if (!resourceJid)
  5482. return null;
  5483. if (resourceJid === APP.xmpp.myResource())
  5484. return $("#localVideoContainer");
  5485. else
  5486. return $("#participant_" + resourceJid);
  5487. }
  5488. /**
  5489. * Sets the size and position of the given video element.
  5490. *
  5491. * @param video the video element to position
  5492. * @param width the desired video width
  5493. * @param height the desired video height
  5494. * @param horizontalIndent the left and right indent
  5495. * @param verticalIndent the top and bottom indent
  5496. */
  5497. function positionVideo(video,
  5498. width,
  5499. height,
  5500. horizontalIndent,
  5501. verticalIndent) {
  5502. video.width(width);
  5503. video.height(height);
  5504. video.css({ top: verticalIndent + 'px',
  5505. bottom: verticalIndent + 'px',
  5506. left: horizontalIndent + 'px',
  5507. right: horizontalIndent + 'px'});
  5508. }
  5509. /**
  5510. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5511. * given <tt>parentElement</tt>.
  5512. *
  5513. * @param jid the jid indicating the video for which we're adding a menu.
  5514. * @param parentElement the parent element where this menu will be added
  5515. */
  5516. function addRemoteVideoMenu(jid, parentElement) {
  5517. var spanElement = document.createElement('span');
  5518. spanElement.className = 'remotevideomenu';
  5519. parentElement.appendChild(spanElement);
  5520. var menuElement = document.createElement('i');
  5521. menuElement.className = 'fa fa-angle-down';
  5522. menuElement.title = 'Remote user controls';
  5523. spanElement.appendChild(menuElement);
  5524. // <ul class="popupmenu">
  5525. // <li><a href="#">Mute</a></li>
  5526. // <li><a href="#">Eject</a></li>
  5527. // </ul>
  5528. var popupmenuElement = document.createElement('ul');
  5529. popupmenuElement.className = 'popupmenu';
  5530. popupmenuElement.id
  5531. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5532. spanElement.appendChild(popupmenuElement);
  5533. var muteMenuItem = document.createElement('li');
  5534. var muteLinkItem = document.createElement('a');
  5535. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  5536. if (!mutedAudios[jid]) {
  5537. muteLinkItem.innerHTML = mutedIndicator + 'Mute';
  5538. muteLinkItem.className = 'mutelink';
  5539. }
  5540. else {
  5541. muteLinkItem.innerHTML = mutedIndicator + ' Muted';
  5542. muteLinkItem.className = 'mutelink disabled';
  5543. }
  5544. muteLinkItem.onclick = function(){
  5545. if ($(this).attr('disabled') != undefined) {
  5546. event.preventDefault();
  5547. }
  5548. var isMute = mutedAudios[jid] == true;
  5549. APP.xmpp.setMute(jid, !isMute);
  5550. popupmenuElement.setAttribute('style', 'display:none;');
  5551. if (isMute) {
  5552. this.innerHTML = mutedIndicator + ' Muted';
  5553. this.className = 'mutelink disabled';
  5554. }
  5555. else {
  5556. this.innerHTML = mutedIndicator + ' Mute';
  5557. this.className = 'mutelink';
  5558. }
  5559. };
  5560. muteMenuItem.appendChild(muteLinkItem);
  5561. popupmenuElement.appendChild(muteMenuItem);
  5562. var ejectIndicator = "<i class='fa fa-eject'></i>";
  5563. var ejectMenuItem = document.createElement('li');
  5564. var ejectLinkItem = document.createElement('a');
  5565. ejectLinkItem.innerHTML = ejectIndicator + ' Kick out';
  5566. ejectLinkItem.onclick = function(){
  5567. APP.xmpp.eject(jid);
  5568. popupmenuElement.setAttribute('style', 'display:none;');
  5569. };
  5570. ejectMenuItem.appendChild(ejectLinkItem);
  5571. popupmenuElement.appendChild(ejectMenuItem);
  5572. var paddingSpan = document.createElement('span');
  5573. paddingSpan.className = 'popupmenuPadding';
  5574. popupmenuElement.appendChild(paddingSpan);
  5575. }
  5576. /**
  5577. * Removes remote video menu element from video element identified by
  5578. * given <tt>videoElementId</tt>.
  5579. *
  5580. * @param videoElementId the id of local or remote video element.
  5581. */
  5582. function removeRemoteVideoMenu(videoElementId) {
  5583. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  5584. if (menuSpan.length) {
  5585. menuSpan.remove();
  5586. }
  5587. }
  5588. /**
  5589. * Updates the data for the indicator
  5590. * @param id the id of the indicator
  5591. * @param percent the percent for connection quality
  5592. * @param object the data
  5593. */
  5594. function updateStatsIndicator(id, percent, object) {
  5595. if(VideoLayout.connectionIndicators[id])
  5596. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  5597. }
  5598. /**
  5599. * Returns an array of the video dimensions, so that it keeps it's aspect
  5600. * ratio and fits available area with it's larger dimension. This method
  5601. * ensures that whole video will be visible and can leave empty areas.
  5602. *
  5603. * @return an array with 2 elements, the video width and the video height
  5604. */
  5605. function getDesktopVideoSize(videoWidth,
  5606. videoHeight,
  5607. videoSpaceWidth,
  5608. videoSpaceHeight) {
  5609. if (!videoWidth)
  5610. videoWidth = currentVideoWidth;
  5611. if (!videoHeight)
  5612. videoHeight = currentVideoHeight;
  5613. var aspectRatio = videoWidth / videoHeight;
  5614. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5615. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5616. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  5617. if (availableWidth / aspectRatio >= videoSpaceHeight)
  5618. {
  5619. availableHeight = videoSpaceHeight;
  5620. availableWidth = availableHeight * aspectRatio;
  5621. }
  5622. if (availableHeight * aspectRatio >= videoSpaceWidth)
  5623. {
  5624. availableWidth = videoSpaceWidth;
  5625. availableHeight = availableWidth / aspectRatio;
  5626. }
  5627. return [availableWidth, availableHeight];
  5628. }
  5629. /**
  5630. * Creates the edit display name button.
  5631. *
  5632. * @returns the edit button
  5633. */
  5634. function createEditDisplayNameButton() {
  5635. var editButton = document.createElement('a');
  5636. editButton.className = 'displayname';
  5637. UIUtil.setTooltip(editButton,
  5638. 'Click to edit your<br/>display name',
  5639. "top");
  5640. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  5641. return editButton;
  5642. }
  5643. /**
  5644. * Creates the element indicating the moderator(owner) of the conference.
  5645. *
  5646. * @param parentElement the parent element where the owner indicator will
  5647. * be added
  5648. */
  5649. function createModeratorIndicatorElement(parentElement) {
  5650. var moderatorIndicator = document.createElement('i');
  5651. moderatorIndicator.className = 'fa fa-star';
  5652. parentElement.appendChild(moderatorIndicator);
  5653. UIUtil.setTooltip(parentElement,
  5654. "The owner of<br/>this conference",
  5655. "top");
  5656. }
  5657. var VideoLayout = (function (my) {
  5658. my.connectionIndicators = {};
  5659. // By default we use camera
  5660. my.getVideoSize = getCameraVideoSize;
  5661. my.getVideoPosition = getCameraVideoPosition;
  5662. my.init = function (emitter) {
  5663. // Listen for large video size updates
  5664. document.getElementById('largeVideo')
  5665. .addEventListener('loadedmetadata', function (e) {
  5666. currentVideoWidth = this.videoWidth;
  5667. currentVideoHeight = this.videoHeight;
  5668. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  5669. });
  5670. eventEmitter = emitter;
  5671. };
  5672. my.isInLastN = function(resource) {
  5673. return lastNCount < 0 // lastN is disabled, return true
  5674. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  5675. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  5676. };
  5677. my.changeLocalStream = function (stream) {
  5678. VideoLayout.changeLocalVideo(stream);
  5679. };
  5680. my.changeLocalAudio = function(stream) {
  5681. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  5682. document.getElementById('localAudio').autoplay = true;
  5683. document.getElementById('localAudio').volume = 0;
  5684. if (preMuted) {
  5685. if(!APP.UI.setAudioMuted(true))
  5686. {
  5687. preMuted = mute;
  5688. }
  5689. preMuted = false;
  5690. }
  5691. };
  5692. my.changeLocalVideo = function(stream) {
  5693. var flipX = true;
  5694. if(stream.videoType == "screen")
  5695. flipX = false;
  5696. var localVideo = document.createElement('video');
  5697. localVideo.id = 'localVideo_' +
  5698. APP.RTC.getStreamID(stream.getOriginalStream());
  5699. localVideo.autoplay = true;
  5700. localVideo.volume = 0; // is it required if audio is separated ?
  5701. localVideo.oncontextmenu = function () { return false; };
  5702. var localVideoContainer = document.getElementById('localVideoWrapper');
  5703. localVideoContainer.appendChild(localVideo);
  5704. // Set default display name.
  5705. setDisplayName('localVideoContainer');
  5706. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  5707. VideoLayout.connectionIndicators["localVideoContainer"]
  5708. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  5709. }
  5710. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  5711. var localVideoSelector = $('#' + localVideo.id);
  5712. function localVideoClick(event) {
  5713. event.stopPropagation();
  5714. VideoLayout.handleVideoThumbClicked(
  5715. APP.RTC.getVideoSrc(localVideo),
  5716. false,
  5717. APP.xmpp.myResource());
  5718. }
  5719. // Add click handler to both video and video wrapper elements in case
  5720. // there's no video.
  5721. localVideoSelector.click(localVideoClick);
  5722. $('#localVideoContainer').click(localVideoClick);
  5723. // Add hover handler
  5724. $('#localVideoContainer').hover(
  5725. function() {
  5726. VideoLayout.showDisplayName('localVideoContainer', true);
  5727. },
  5728. function() {
  5729. if (!VideoLayout.isLargeVideoVisible()
  5730. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  5731. VideoLayout.showDisplayName('localVideoContainer', false);
  5732. }
  5733. );
  5734. // Add stream ended handler
  5735. stream.getOriginalStream().onended = function () {
  5736. localVideoContainer.removeChild(localVideo);
  5737. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  5738. };
  5739. // Flip video x axis if needed
  5740. flipXLocalVideo = flipX;
  5741. if (flipX) {
  5742. localVideoSelector.addClass("flipVideoX");
  5743. }
  5744. // Attach WebRTC stream
  5745. var videoStream = APP.simulcast.getLocalVideoStream();
  5746. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  5747. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  5748. var myResourceJid = APP.xmpp.myResource();
  5749. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  5750. myResourceJid);
  5751. };
  5752. /**
  5753. * Checks if removed video is currently displayed and tries to display
  5754. * another one instead.
  5755. * @param removedVideoSrc src stream identifier of the video.
  5756. */
  5757. my.updateRemovedVideo = function(removedVideoSrc) {
  5758. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  5759. // this is currently displayed as large
  5760. // pick the last visible video in the row
  5761. // if nobody else is left, this picks the local video
  5762. var pick
  5763. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  5764. .get(0);
  5765. if (!pick) {
  5766. console.info("Last visible video no longer exists");
  5767. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  5768. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  5769. // Try local video
  5770. console.info("Fallback to local video...");
  5771. pick = $('#remoteVideos>span>span>video').get(0);
  5772. }
  5773. }
  5774. // mute if localvideo
  5775. if (pick) {
  5776. var container = pick.parentNode;
  5777. var jid = null;
  5778. if(container)
  5779. {
  5780. if(container.id == "localVideoWrapper")
  5781. {
  5782. jid = APP.xmpp.myResource();
  5783. }
  5784. else
  5785. {
  5786. jid = VideoLayout.getPeerContainerResourceJid(container);
  5787. }
  5788. }
  5789. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  5790. } else {
  5791. console.warn("Failed to elect large video");
  5792. }
  5793. }
  5794. };
  5795. my.onRemoteStreamAdded = function (stream) {
  5796. var container;
  5797. var remotes = document.getElementById('remoteVideos');
  5798. if (stream.peerjid) {
  5799. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  5800. container = document.getElementById(
  5801. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  5802. } else {
  5803. var id = stream.getOriginalStream().id;
  5804. if (id !== 'mixedmslabel'
  5805. // FIXME: default stream is added always with new focus
  5806. // (to be investigated)
  5807. && id !== 'default') {
  5808. console.error('can not associate stream',
  5809. id,
  5810. 'with a participant');
  5811. // We don't want to add it here since it will cause troubles
  5812. return;
  5813. }
  5814. // FIXME: for the mixed ms we dont need a video -- currently
  5815. container = document.createElement('span');
  5816. container.id = 'mixedstream';
  5817. container.className = 'videocontainer';
  5818. remotes.appendChild(container);
  5819. UIUtil.playSoundNotification('userJoined');
  5820. }
  5821. if (container) {
  5822. VideoLayout.addRemoteStreamElement( container,
  5823. stream.sid,
  5824. stream.getOriginalStream(),
  5825. stream.peerjid,
  5826. stream.ssrc);
  5827. }
  5828. }
  5829. my.getLargeVideoState = function () {
  5830. return largeVideoState;
  5831. };
  5832. /**
  5833. * Updates the large video with the given new video source.
  5834. */
  5835. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  5836. console.log('hover in', newSrc);
  5837. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  5838. $('#activeSpeaker').css('visibility', 'hidden');
  5839. // Due to the simulcast the localVideoSrc may have changed when the
  5840. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  5841. // isVideoSrcDesktop methods will not function correctly.
  5842. //
  5843. // Also, again due to the simulcast, the updateLargeVideo method can
  5844. // be called multiple times almost simultaneously. Therefore, we
  5845. // store the state here and update only once.
  5846. largeVideoState.newSrc = newSrc;
  5847. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  5848. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  5849. if(largeVideoState.userResourceJid) {
  5850. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  5851. } else {
  5852. largeVideoState.oldResourceJid = null;
  5853. }
  5854. largeVideoState.userResourceJid = resourceJid;
  5855. // Screen stream is already rotated
  5856. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  5857. var userChanged = false;
  5858. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  5859. userChanged = true;
  5860. // we want the notification to trigger even if userJid is undefined,
  5861. // or null.
  5862. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  5863. largeVideoState.userResourceJid);
  5864. }
  5865. if (!largeVideoState.updateInProgress) {
  5866. largeVideoState.updateInProgress = true;
  5867. var doUpdate = function () {
  5868. Avatar.updateActiveSpeakerAvatarSrc(
  5869. APP.xmpp.findJidFromResource(
  5870. largeVideoState.userResourceJid));
  5871. if (!userChanged && largeVideoState.preload &&
  5872. largeVideoState.preload !== null &&
  5873. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  5874. {
  5875. console.info('Switching to preloaded video');
  5876. var attributes = $('#largeVideo').prop("attributes");
  5877. // loop through largeVideo attributes and apply them on
  5878. // preload.
  5879. $.each(attributes, function () {
  5880. if (this.name !== 'id' && this.name !== 'src') {
  5881. largeVideoState.preload.attr(this.name, this.value);
  5882. }
  5883. });
  5884. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  5885. $('#largeVideo').attr('id', 'previousLargeVideo');
  5886. largeVideoState.preload.attr('id', 'largeVideo');
  5887. $('#previousLargeVideo').remove();
  5888. largeVideoState.preload.on('loadedmetadata', function (e) {
  5889. currentVideoWidth = this.videoWidth;
  5890. currentVideoHeight = this.videoHeight;
  5891. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  5892. });
  5893. largeVideoState.preload = null;
  5894. largeVideoState.preload_ssrc = 0;
  5895. } else {
  5896. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  5897. }
  5898. var videoTransform = document.getElementById('largeVideo')
  5899. .style.webkitTransform;
  5900. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  5901. document.getElementById('largeVideo').style.webkitTransform
  5902. = "scaleX(-1)";
  5903. }
  5904. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  5905. document.getElementById('largeVideo').style.webkitTransform
  5906. = "none";
  5907. }
  5908. // Change the way we'll be measuring and positioning large video
  5909. VideoLayout.getVideoSize = largeVideoState.isDesktop
  5910. ? getDesktopVideoSize
  5911. : getCameraVideoSize;
  5912. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  5913. ? getDesktopVideoPosition
  5914. : getCameraVideoPosition;
  5915. // Only if the large video is currently visible.
  5916. // Disable previous dominant speaker video.
  5917. if (largeVideoState.oldResourceJid) {
  5918. VideoLayout.enableDominantSpeaker(
  5919. largeVideoState.oldResourceJid,
  5920. false);
  5921. }
  5922. // Enable new dominant speaker in the remote videos section.
  5923. if (largeVideoState.userResourceJid) {
  5924. VideoLayout.enableDominantSpeaker(
  5925. largeVideoState.userResourceJid,
  5926. true);
  5927. }
  5928. if (userChanged && largeVideoState.isVisible) {
  5929. // using "this" should be ok because we're called
  5930. // from within the fadeOut event.
  5931. $(this).fadeIn(300);
  5932. }
  5933. if(userChanged) {
  5934. Avatar.showUserAvatar(
  5935. APP.xmpp.findJidFromResource(
  5936. largeVideoState.oldResourceJid));
  5937. }
  5938. largeVideoState.updateInProgress = false;
  5939. };
  5940. if (userChanged) {
  5941. $('#largeVideo').fadeOut(300, doUpdate);
  5942. } else {
  5943. doUpdate();
  5944. }
  5945. }
  5946. } else {
  5947. Avatar.showUserAvatar(
  5948. APP.xmpp.findJidFromResource(
  5949. largeVideoState.userResourceJid));
  5950. }
  5951. };
  5952. my.handleVideoThumbClicked = function(videoSrc,
  5953. noPinnedEndpointChangedEvent,
  5954. resourceJid) {
  5955. // Restore style for previously focused video
  5956. var oldContainer = null;
  5957. if(focusedVideoInfo) {
  5958. var focusResourceJid = focusedVideoInfo.resourceJid;
  5959. oldContainer = getParticipantContainer(focusResourceJid);
  5960. }
  5961. if (oldContainer) {
  5962. oldContainer.removeClass("videoContainerFocused");
  5963. }
  5964. // Unlock current focused.
  5965. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  5966. {
  5967. focusedVideoInfo = null;
  5968. var dominantSpeakerVideo = null;
  5969. // Enable the currently set dominant speaker.
  5970. if (currentDominantSpeaker) {
  5971. dominantSpeakerVideo
  5972. = $('#participant_' + currentDominantSpeaker + '>video')
  5973. .get(0);
  5974. if (dominantSpeakerVideo) {
  5975. VideoLayout.updateLargeVideo(
  5976. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  5977. 1,
  5978. currentDominantSpeaker);
  5979. }
  5980. }
  5981. if (!noPinnedEndpointChangedEvent) {
  5982. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  5983. }
  5984. return;
  5985. }
  5986. // Lock new video
  5987. focusedVideoInfo = {
  5988. src: videoSrc,
  5989. resourceJid: resourceJid
  5990. };
  5991. // Update focused/pinned interface.
  5992. if (resourceJid)
  5993. {
  5994. var container = getParticipantContainer(resourceJid);
  5995. container.addClass("videoContainerFocused");
  5996. if (!noPinnedEndpointChangedEvent) {
  5997. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  5998. }
  5999. }
  6000. if ($('#largeVideo').attr('src') === videoSrc &&
  6001. VideoLayout.isLargeVideoOnTop()) {
  6002. return;
  6003. }
  6004. // Triggers a "video.selected" event. The "false" parameter indicates
  6005. // this isn't a prezi.
  6006. $(document).trigger("video.selected", [false]);
  6007. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6008. $('audio').each(function (idx, el) {
  6009. if (el.id.indexOf('mixedmslabel') !== -1) {
  6010. el.volume = 0;
  6011. el.volume = 1;
  6012. }
  6013. });
  6014. };
  6015. /**
  6016. * Positions the large video.
  6017. *
  6018. * @param videoWidth the stream video width
  6019. * @param videoHeight the stream video height
  6020. */
  6021. my.positionLarge = function (videoWidth, videoHeight) {
  6022. var videoSpaceWidth = $('#videospace').width();
  6023. var videoSpaceHeight = window.innerHeight;
  6024. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6025. videoHeight,
  6026. videoSpaceWidth,
  6027. videoSpaceHeight);
  6028. var largeVideoWidth = videoSize[0];
  6029. var largeVideoHeight = videoSize[1];
  6030. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6031. largeVideoHeight,
  6032. videoSpaceWidth,
  6033. videoSpaceHeight);
  6034. var horizontalIndent = videoPosition[0];
  6035. var verticalIndent = videoPosition[1];
  6036. positionVideo($('#largeVideo'),
  6037. largeVideoWidth,
  6038. largeVideoHeight,
  6039. horizontalIndent, verticalIndent);
  6040. };
  6041. /**
  6042. * Shows/hides the large video.
  6043. */
  6044. my.setLargeVideoVisible = function(isVisible) {
  6045. var resourceJid = largeVideoState.userResourceJid;
  6046. if (isVisible) {
  6047. $('#largeVideo').css({visibility: 'visible'});
  6048. $('.watermark').css({visibility: 'visible'});
  6049. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6050. }
  6051. else {
  6052. $('#largeVideo').css({visibility: 'hidden'});
  6053. $('#activeSpeaker').css('visibility', 'hidden');
  6054. $('.watermark').css({visibility: 'hidden'});
  6055. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6056. if(focusedVideoInfo) {
  6057. var focusResourceJid = focusedVideoInfo.resourceJid;
  6058. var oldContainer = getParticipantContainer(focusResourceJid);
  6059. if (oldContainer && oldContainer.length > 0) {
  6060. oldContainer.removeClass("videoContainerFocused");
  6061. }
  6062. focusedVideoInfo = null;
  6063. if(focusResourceJid) {
  6064. Avatar.showUserAvatar(
  6065. APP.xmpp.findJidFromResource(focusResourceJid));
  6066. }
  6067. }
  6068. }
  6069. };
  6070. /**
  6071. * Indicates if the large video is currently visible.
  6072. *
  6073. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6074. */
  6075. my.isLargeVideoVisible = function() {
  6076. return $('#largeVideo').is(':visible');
  6077. };
  6078. my.isLargeVideoOnTop = function () {
  6079. var Etherpad = require("../etherpad/Etherpad");
  6080. var Prezi = require("../prezi/Prezi");
  6081. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6082. };
  6083. /**
  6084. * Checks if container for participant identified by given peerJid exists
  6085. * in the document and creates it eventually.
  6086. *
  6087. * @param peerJid peer Jid to check.
  6088. * @param userId user email or id for setting the avatar
  6089. *
  6090. * @return Returns <tt>true</tt> if the peer container exists,
  6091. * <tt>false</tt> - otherwise
  6092. */
  6093. my.ensurePeerContainerExists = function(peerJid, userId) {
  6094. ContactList.ensureAddContact(peerJid, userId);
  6095. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6096. var videoSpanId = 'participant_' + resourceJid;
  6097. if (!$('#' + videoSpanId).length) {
  6098. var container =
  6099. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6100. Avatar.setUserAvatar(peerJid, userId);
  6101. // Set default display name.
  6102. setDisplayName(videoSpanId);
  6103. VideoLayout.connectionIndicators[videoSpanId] =
  6104. new ConnectionIndicator(container, peerJid, VideoLayout);
  6105. var nickfield = document.createElement('span');
  6106. nickfield.className = "nick";
  6107. nickfield.appendChild(document.createTextNode(resourceJid));
  6108. container.appendChild(nickfield);
  6109. // In case this is not currently in the last n we don't show it.
  6110. if (localLastNCount
  6111. && localLastNCount > 0
  6112. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6113. showPeerContainer(resourceJid, 'hide');
  6114. }
  6115. else
  6116. VideoLayout.resizeThumbnails();
  6117. }
  6118. };
  6119. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6120. var container = document.createElement('span');
  6121. container.id = spanId;
  6122. container.className = 'videocontainer';
  6123. var remotes = document.getElementById('remoteVideos');
  6124. // If the peerJid is null then this video span couldn't be directly
  6125. // associated with a participant (this could happen in the case of prezi).
  6126. if (APP.xmpp.isModerator() && peerJid !== null)
  6127. addRemoteVideoMenu(peerJid, container);
  6128. remotes.appendChild(container);
  6129. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6130. return container;
  6131. };
  6132. /**
  6133. * Creates an audio or video stream element.
  6134. */
  6135. my.createStreamElement = function (sid, stream) {
  6136. var isVideo = stream.getVideoTracks().length > 0;
  6137. var element = isVideo
  6138. ? document.createElement('video')
  6139. : document.createElement('audio');
  6140. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6141. + sid + '_' + APP.RTC.getStreamID(stream);
  6142. element.id = id;
  6143. element.autoplay = true;
  6144. element.oncontextmenu = function () { return false; };
  6145. return element;
  6146. };
  6147. my.addRemoteStreamElement
  6148. = function (container, sid, stream, peerJid, thessrc) {
  6149. var newElementId = null;
  6150. var isVideo = stream.getVideoTracks().length > 0;
  6151. if (container) {
  6152. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6153. newElementId = streamElement.id;
  6154. container.appendChild(streamElement);
  6155. var sel = $('#' + newElementId);
  6156. sel.hide();
  6157. // If the container is currently visible we attach the stream.
  6158. if (!isVideo
  6159. || (container.offsetParent !== null && isVideo)) {
  6160. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6161. APP.RTC.attachMediaStream(sel, videoStream);
  6162. if (isVideo)
  6163. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6164. }
  6165. stream.onended = function () {
  6166. console.log('stream ended', this);
  6167. VideoLayout.removeRemoteStreamElement(
  6168. stream, isVideo, container);
  6169. // NOTE(gp) it seems that under certain circumstances, the
  6170. // onended event is not fired and thus the contact list is not
  6171. // updated.
  6172. //
  6173. // The onended event of a stream should be fired when the SSRCs
  6174. // corresponding to that stream are removed from the SDP; but
  6175. // this doesn't seem to always be the case, resulting in ghost
  6176. // contacts.
  6177. //
  6178. // In an attempt to fix the ghost contacts problem, I'm moving
  6179. // the removeContact() method call in app.js, inside the
  6180. // 'muc.left' event handler.
  6181. //if (peerJid)
  6182. // ContactList.removeContact(peerJid);
  6183. };
  6184. // Add click handler.
  6185. container.onclick = function (event) {
  6186. /*
  6187. * FIXME It turns out that videoThumb may not exist (if there is
  6188. * no actual video).
  6189. */
  6190. var videoThumb = $('#' + container.id + '>video').get(0);
  6191. if (videoThumb) {
  6192. VideoLayout.handleVideoThumbClicked(
  6193. APP.RTC.getVideoSrc(videoThumb),
  6194. false,
  6195. Strophe.getResourceFromJid(peerJid));
  6196. }
  6197. event.stopPropagation();
  6198. event.preventDefault();
  6199. return false;
  6200. };
  6201. // Add hover handler
  6202. $(container).hover(
  6203. function() {
  6204. VideoLayout.showDisplayName(container.id, true);
  6205. },
  6206. function() {
  6207. var videoSrc = null;
  6208. if ($('#' + container.id + '>video')
  6209. && $('#' + container.id + '>video').length > 0) {
  6210. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6211. }
  6212. // If the video has been "pinned" by the user we want to
  6213. // keep the display name on place.
  6214. if (!VideoLayout.isLargeVideoVisible()
  6215. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6216. VideoLayout.showDisplayName(container.id, false);
  6217. }
  6218. );
  6219. }
  6220. return newElementId;
  6221. };
  6222. /**
  6223. * Removes the remote stream element corresponding to the given stream and
  6224. * parent container.
  6225. *
  6226. * @param stream the stream
  6227. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6228. * @param container
  6229. */
  6230. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6231. if (!container)
  6232. return;
  6233. var select = null;
  6234. var removedVideoSrc = null;
  6235. if (isVideo) {
  6236. select = $('#' + container.id + '>video');
  6237. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6238. }
  6239. else
  6240. select = $('#' + container.id + '>audio');
  6241. // Mark video as removed to cancel waiting loop(if video is removed
  6242. // before has started)
  6243. select.removed = true;
  6244. select.remove();
  6245. var audioCount = $('#' + container.id + '>audio').length;
  6246. var videoCount = $('#' + container.id + '>video').length;
  6247. if (!audioCount && !videoCount) {
  6248. console.log("Remove whole user", container.id);
  6249. if(VideoLayout.connectionIndicators[container.id])
  6250. VideoLayout.connectionIndicators[container.id].remove();
  6251. // Remove whole container
  6252. container.remove();
  6253. UIUtil.playSoundNotification('userLeft');
  6254. VideoLayout.resizeThumbnails();
  6255. }
  6256. if (removedVideoSrc)
  6257. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6258. };
  6259. /**
  6260. * Show/hide peer container for the given resourceJid.
  6261. */
  6262. function showPeerContainer(resourceJid, state) {
  6263. var peerContainer = $('#participant_' + resourceJid);
  6264. if (!peerContainer)
  6265. return;
  6266. var isHide = state === 'hide';
  6267. var resizeThumbnails = false;
  6268. if (!isHide) {
  6269. if (!peerContainer.is(':visible')) {
  6270. resizeThumbnails = true;
  6271. peerContainer.show();
  6272. }
  6273. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6274. if (state == 'show')
  6275. {
  6276. // peerContainer.css('-webkit-filter', '');
  6277. Avatar.showUserAvatar(jid, false);
  6278. }
  6279. else // if (state == 'avatar')
  6280. {
  6281. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6282. Avatar.showUserAvatar(jid, true);
  6283. }
  6284. }
  6285. else if (peerContainer.is(':visible') && isHide)
  6286. {
  6287. resizeThumbnails = true;
  6288. peerContainer.hide();
  6289. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6290. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6291. }
  6292. if (resizeThumbnails) {
  6293. VideoLayout.resizeThumbnails();
  6294. }
  6295. // We want to be able to pin a participant from the contact list, even
  6296. // if he's not in the lastN set!
  6297. // ContactList.setClickable(resourceJid, !isHide);
  6298. };
  6299. my.inputDisplayNameHandler = function (name) {
  6300. NicknameHandler.setNickname(name);
  6301. if (!$('#localDisplayName').is(":visible")) {
  6302. if (NicknameHandler.getNickname())
  6303. $('#localDisplayName').text(NicknameHandler.getNickname() + " (me)");
  6304. else
  6305. $('#localDisplayName')
  6306. .text(interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6307. $('#localDisplayName').show();
  6308. }
  6309. $('#editDisplayName').hide();
  6310. };
  6311. /**
  6312. * Shows/hides the display name on the remote video.
  6313. * @param videoSpanId the identifier of the video span element
  6314. * @param isShow indicates if the display name should be shown or hidden
  6315. */
  6316. my.showDisplayName = function(videoSpanId, isShow) {
  6317. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6318. if (isShow) {
  6319. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6320. nameSpan.setAttribute("style", "display:inline-block;");
  6321. }
  6322. else {
  6323. if (nameSpan)
  6324. nameSpan.setAttribute("style", "display:none;");
  6325. }
  6326. };
  6327. /**
  6328. * Shows the presence status message for the given video.
  6329. */
  6330. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6331. if (!$('#' + videoSpanId).length) {
  6332. // No container
  6333. return;
  6334. }
  6335. var statusSpan = $('#' + videoSpanId + '>span.status');
  6336. if (!statusSpan.length) {
  6337. //Add status span
  6338. statusSpan = document.createElement('span');
  6339. statusSpan.className = 'status';
  6340. statusSpan.id = videoSpanId + '_status';
  6341. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6342. statusSpan = $('#' + videoSpanId + '>span.status');
  6343. }
  6344. // Display status
  6345. if (statusMsg && statusMsg.length) {
  6346. $('#' + videoSpanId + '_status').text(statusMsg);
  6347. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6348. }
  6349. else {
  6350. // Hide
  6351. statusSpan.get(0).setAttribute("style", "display:none;");
  6352. }
  6353. };
  6354. /**
  6355. * Shows a visual indicator for the moderator of the conference.
  6356. */
  6357. my.showModeratorIndicator = function () {
  6358. var isModerator = APP.xmpp.isModerator();
  6359. if (isModerator) {
  6360. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6361. if (indicatorSpan.children().length === 0)
  6362. {
  6363. createModeratorIndicatorElement(indicatorSpan[0]);
  6364. }
  6365. }
  6366. var members = APP.xmpp.getMembers();
  6367. Object.keys(members).forEach(function (jid) {
  6368. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6369. // Skip server side focus
  6370. return;
  6371. }
  6372. var resourceJid = Strophe.getResourceFromJid(jid);
  6373. var videoSpanId = 'participant_' + resourceJid;
  6374. var videoContainer = document.getElementById(videoSpanId);
  6375. if (!videoContainer) {
  6376. console.error("No video container for " + jid);
  6377. return;
  6378. }
  6379. var member = members[jid];
  6380. if (member.role === 'moderator') {
  6381. // Remove menu if peer is moderator
  6382. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6383. if (menuSpan.length) {
  6384. removeRemoteVideoMenu(videoSpanId);
  6385. }
  6386. // Show moderator indicator
  6387. var indicatorSpan
  6388. = $('#' + videoSpanId + ' .focusindicator');
  6389. if (!indicatorSpan || indicatorSpan.length === 0) {
  6390. indicatorSpan = document.createElement('span');
  6391. indicatorSpan.className = 'focusindicator';
  6392. videoContainer.appendChild(indicatorSpan);
  6393. createModeratorIndicatorElement(indicatorSpan);
  6394. }
  6395. } else if (isModerator) {
  6396. // We are moderator, but user is not - add menu
  6397. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6398. addRemoteVideoMenu(
  6399. jid,
  6400. document.getElementById('participant_' + resourceJid));
  6401. }
  6402. }
  6403. });
  6404. };
  6405. /**
  6406. * Shows video muted indicator over small videos.
  6407. */
  6408. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6409. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6410. if (isMuted === 'false') {
  6411. if (videoMutedSpan.length > 0) {
  6412. videoMutedSpan.remove();
  6413. }
  6414. }
  6415. else {
  6416. if(videoMutedSpan.length == 0) {
  6417. videoMutedSpan = document.createElement('span');
  6418. videoMutedSpan.className = 'videoMuted';
  6419. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6420. var mutedIndicator = document.createElement('i');
  6421. mutedIndicator.className = 'icon-camera-disabled';
  6422. UIUtil.setTooltip(mutedIndicator,
  6423. "Participant has<br/>stopped the camera.",
  6424. "top");
  6425. videoMutedSpan.appendChild(mutedIndicator);
  6426. }
  6427. VideoLayout.updateMutePosition(videoSpanId);
  6428. }
  6429. };
  6430. my.updateMutePosition = function (videoSpanId) {
  6431. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6432. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6433. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6434. if(connectionIndicator.length > 0
  6435. && connectionIndicator[0].style.display != "none") {
  6436. audioMutedSpan.css({right: "23px"});
  6437. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6438. }
  6439. else
  6440. {
  6441. audioMutedSpan.css({right: "0px"});
  6442. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6443. }
  6444. }
  6445. /**
  6446. * Shows audio muted indicator over small videos.
  6447. * @param {string} isMuted
  6448. */
  6449. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6450. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6451. if (isMuted === 'false') {
  6452. if (audioMutedSpan.length > 0) {
  6453. audioMutedSpan.popover('hide');
  6454. audioMutedSpan.remove();
  6455. }
  6456. }
  6457. else {
  6458. if(audioMutedSpan.length == 0 ) {
  6459. audioMutedSpan = document.createElement('span');
  6460. audioMutedSpan.className = 'audioMuted';
  6461. UIUtil.setTooltip(audioMutedSpan,
  6462. "Participant is muted",
  6463. "top");
  6464. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6465. var mutedIndicator = document.createElement('i');
  6466. mutedIndicator.className = 'icon-mic-disabled';
  6467. audioMutedSpan.appendChild(mutedIndicator);
  6468. }
  6469. VideoLayout.updateMutePosition(videoSpanId);
  6470. }
  6471. };
  6472. /*
  6473. * Shows or hides the audio muted indicator over the local thumbnail video.
  6474. * @param {boolean} isMuted
  6475. */
  6476. my.showLocalAudioIndicator = function(isMuted) {
  6477. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6478. };
  6479. /**
  6480. * Resizes the large video container.
  6481. */
  6482. my.resizeLargeVideoContainer = function () {
  6483. Chat.resizeChat();
  6484. var availableHeight = window.innerHeight;
  6485. var availableWidth = UIUtil.getAvailableVideoWidth();
  6486. if (availableWidth < 0 || availableHeight < 0) return;
  6487. $('#videospace').width(availableWidth);
  6488. $('#videospace').height(availableHeight);
  6489. $('#largeVideoContainer').width(availableWidth);
  6490. $('#largeVideoContainer').height(availableHeight);
  6491. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6492. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6493. $('#activeSpeaker').css('top', top);
  6494. VideoLayout.resizeThumbnails();
  6495. };
  6496. /**
  6497. * Resizes thumbnails.
  6498. */
  6499. my.resizeThumbnails = function() {
  6500. var videoSpaceWidth = $('#remoteVideos').width();
  6501. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6502. var width = thumbnailSize[0];
  6503. var height = thumbnailSize[1];
  6504. // size videos so that while keeping AR and max height, we have a
  6505. // nice fit
  6506. $('#remoteVideos').height(height);
  6507. $('#remoteVideos>span').width(width);
  6508. $('#remoteVideos>span').height(height);
  6509. $('.userAvatar').css('left', (width - height) / 2);
  6510. $(document).trigger("remotevideo.resized", [width, height]);
  6511. };
  6512. /**
  6513. * Enables the dominant speaker UI.
  6514. *
  6515. * @param resourceJid the jid indicating the video element to
  6516. * activate/deactivate
  6517. * @param isEnable indicates if the dominant speaker should be enabled or
  6518. * disabled
  6519. */
  6520. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  6521. var videoSpanId = null;
  6522. var videoContainerId = null;
  6523. if (resourceJid
  6524. === APP.xmpp.myResource()) {
  6525. videoSpanId = 'localVideoWrapper';
  6526. videoContainerId = 'localVideoContainer';
  6527. }
  6528. else {
  6529. videoSpanId = 'participant_' + resourceJid;
  6530. videoContainerId = videoSpanId;
  6531. }
  6532. var displayName = resourceJid;
  6533. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  6534. if (nameSpan.length > 0)
  6535. displayName = nameSpan.html();
  6536. console.log("UI enable dominant speaker",
  6537. displayName,
  6538. resourceJid,
  6539. isEnable);
  6540. videoSpan = document.getElementById(videoContainerId);
  6541. if (!videoSpan) {
  6542. return;
  6543. }
  6544. var video = $('#' + videoSpanId + '>video');
  6545. if (video && video.length > 0) {
  6546. if (isEnable) {
  6547. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  6548. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  6549. if (!videoSpan.classList.contains("dominantspeaker"))
  6550. videoSpan.classList.add("dominantspeaker");
  6551. }
  6552. else {
  6553. VideoLayout.showDisplayName(videoContainerId, false);
  6554. if (videoSpan.classList.contains("dominantspeaker"))
  6555. videoSpan.classList.remove("dominantspeaker");
  6556. }
  6557. Avatar.showUserAvatar(
  6558. APP.xmpp.findJidFromResource(resourceJid));
  6559. }
  6560. };
  6561. /**
  6562. * Calculates the thumbnail size.
  6563. *
  6564. * @param videoSpaceWidth the width of the video space
  6565. */
  6566. my.calculateThumbnailSize = function (videoSpaceWidth) {
  6567. // Calculate the available height, which is the inner window height minus
  6568. // 39px for the header minus 2px for the delimiter lines on the top and
  6569. // bottom of the large video, minus the 36px space inside the remoteVideos
  6570. // container used for highlighting shadow.
  6571. var availableHeight = 100;
  6572. var numvids = $('#remoteVideos>span:visible').length;
  6573. if (localLastNCount && localLastNCount > 0) {
  6574. numvids = Math.min(localLastNCount + 1, numvids);
  6575. }
  6576. // Remove the 3px borders arround videos and border around the remote
  6577. // videos area and the 4 pixels between the local video and the others
  6578. //TODO: Find out where the 4 pixels come from and remove them
  6579. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  6580. var availableWidth = availableWinWidth / numvids;
  6581. var aspectRatio = 16.0 / 9.0;
  6582. var maxHeight = Math.min(160, availableHeight);
  6583. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  6584. if (availableHeight < availableWidth / aspectRatio) {
  6585. availableWidth = Math.floor(availableHeight * aspectRatio);
  6586. }
  6587. return [availableWidth, availableHeight];
  6588. };
  6589. /**
  6590. * Updates the remote video menu.
  6591. *
  6592. * @param jid the jid indicating the video for which we're adding a menu.
  6593. * @param isMuted indicates the current mute state
  6594. */
  6595. my.updateRemoteVideoMenu = function(jid, isMuted) {
  6596. var muteMenuItem
  6597. = $('#remote_popupmenu_'
  6598. + Strophe.getResourceFromJid(jid)
  6599. + '>li>a.mutelink');
  6600. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  6601. if (muteMenuItem.length) {
  6602. var muteLink = muteMenuItem.get(0);
  6603. if (isMuted === 'true') {
  6604. muteLink.innerHTML = mutedIndicator + ' Muted';
  6605. muteLink.className = 'mutelink disabled';
  6606. }
  6607. else {
  6608. muteLink.innerHTML = mutedIndicator + ' Mute';
  6609. muteLink.className = 'mutelink';
  6610. }
  6611. }
  6612. };
  6613. /**
  6614. * Returns the current dominant speaker resource jid.
  6615. */
  6616. my.getDominantSpeakerResourceJid = function () {
  6617. return currentDominantSpeaker;
  6618. };
  6619. /**
  6620. * Returns the corresponding resource jid to the given peer container
  6621. * DOM element.
  6622. *
  6623. * @return the corresponding resource jid to the given peer container
  6624. * DOM element
  6625. */
  6626. my.getPeerContainerResourceJid = function (containerElement) {
  6627. var i = containerElement.id.indexOf('participant_');
  6628. if (i >= 0)
  6629. return containerElement.id.substring(i + 12);
  6630. };
  6631. /**
  6632. * On contact list item clicked.
  6633. */
  6634. $(ContactList).bind('contactclicked', function(event, jid) {
  6635. if (!jid) {
  6636. return;
  6637. }
  6638. var resource = Strophe.getResourceFromJid(jid);
  6639. var videoContainer = $("#participant_" + resource);
  6640. if (videoContainer.length > 0) {
  6641. var videoThumb = $('video', videoContainer).get(0);
  6642. // It is not always the case that a videoThumb exists (if there is
  6643. // no actual video).
  6644. if (videoThumb) {
  6645. if (videoThumb.src && videoThumb.src != '') {
  6646. // We have a video src, great! Let's update the large video
  6647. // now.
  6648. VideoLayout.handleVideoThumbClicked(
  6649. videoThumb.src,
  6650. false,
  6651. Strophe.getResourceFromJid(jid));
  6652. } else {
  6653. // If we don't have a video src for jid, there's absolutely
  6654. // no point in calling handleVideoThumbClicked; Quite
  6655. // simply, it won't work because it needs an src to attach
  6656. // to the large video.
  6657. //
  6658. // Instead, we trigger the pinned endpoint changed event to
  6659. // let the bridge adjust its lastN set for myjid and store
  6660. // the pinned user in the lastNPickupJid variable to be
  6661. // picked up later by the lastN changed event handler.
  6662. lastNPickupJid = jid;
  6663. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  6664. Strophe.getResourceFromJid(jid));
  6665. }
  6666. } else if (jid == APP.xmpp.myJid()) {
  6667. $("#localVideoContainer").click();
  6668. }
  6669. }
  6670. });
  6671. /**
  6672. * On audio muted event.
  6673. */
  6674. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  6675. /*
  6676. // FIXME: but focus can not mute in this case ? - check
  6677. if (jid === xmpp.myJid()) {
  6678. // The local mute indicator is controlled locally
  6679. return;
  6680. }*/
  6681. var videoSpanId = null;
  6682. if (jid === APP.xmpp.myJid()) {
  6683. videoSpanId = 'localVideoContainer';
  6684. } else {
  6685. VideoLayout.ensurePeerContainerExists(jid);
  6686. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6687. }
  6688. mutedAudios[jid] = isMuted;
  6689. if (APP.xmpp.isModerator()) {
  6690. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  6691. }
  6692. if (videoSpanId)
  6693. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  6694. });
  6695. /**
  6696. * On video muted event.
  6697. */
  6698. $(document).bind('videomuted.muc', function (event, jid, value) {
  6699. var isMuted = (value === "true");
  6700. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  6701. return;
  6702. Avatar.showUserAvatar(jid, isMuted);
  6703. var videoSpanId = null;
  6704. if (jid === APP.xmpp.myJid()) {
  6705. videoSpanId = 'localVideoContainer';
  6706. } else {
  6707. VideoLayout.ensurePeerContainerExists(jid);
  6708. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6709. }
  6710. if (videoSpanId)
  6711. VideoLayout.showVideoIndicator(videoSpanId, value);
  6712. });
  6713. /**
  6714. * Display name changed.
  6715. */
  6716. my.onDisplayNameChanged =
  6717. function (jid, displayName, status) {
  6718. if (jid === 'localVideoContainer'
  6719. || jid === APP.xmpp.myJid()) {
  6720. setDisplayName('localVideoContainer',
  6721. displayName);
  6722. } else {
  6723. VideoLayout.ensurePeerContainerExists(jid);
  6724. setDisplayName(
  6725. 'participant_' + Strophe.getResourceFromJid(jid),
  6726. displayName,
  6727. status);
  6728. }
  6729. };
  6730. /**
  6731. * On dominant speaker changed event.
  6732. */
  6733. my.onDominantSpeakerChanged = function (resourceJid) {
  6734. // We ignore local user events.
  6735. if (resourceJid
  6736. === APP.xmpp.myResource())
  6737. return;
  6738. // Update the current dominant speaker.
  6739. if (resourceJid !== currentDominantSpeaker) {
  6740. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  6741. newSpeakerVideoSpanId = "participant_" + resourceJid;
  6742. if($("#" + oldSpeakerVideoSpanId + ">span.displayname").text() ===
  6743. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME) {
  6744. setDisplayName(oldSpeakerVideoSpanId, null);
  6745. }
  6746. if($("#" + newSpeakerVideoSpanId + ">span.displayname").text() ===
  6747. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME) {
  6748. setDisplayName(newSpeakerVideoSpanId,
  6749. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  6750. }
  6751. currentDominantSpeaker = resourceJid;
  6752. } else {
  6753. return;
  6754. }
  6755. // Obtain container for new dominant speaker.
  6756. var container = document.getElementById(
  6757. 'participant_' + resourceJid);
  6758. // Local video will not have container found, but that's ok
  6759. // since we don't want to switch to local video.
  6760. if (container && !focusedVideoInfo)
  6761. {
  6762. var video = container.getElementsByTagName("video");
  6763. // Update the large video if the video source is already available,
  6764. // otherwise wait for the "videoactive.jingle" event.
  6765. if (video.length && video[0].currentTime > 0)
  6766. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  6767. }
  6768. };
  6769. /**
  6770. * On last N change event.
  6771. *
  6772. * @param lastNEndpoints the list of last N endpoints
  6773. * @param endpointsEnteringLastN the list currently entering last N
  6774. * endpoints
  6775. */
  6776. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  6777. endpointsEnteringLastN,
  6778. stream) {
  6779. if (lastNCount !== lastNEndpoints.length)
  6780. lastNCount = lastNEndpoints.length;
  6781. lastNEndpointsCache = lastNEndpoints;
  6782. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  6783. //
  6784. // If LastN drops to, say, 2, because of adaptivity, then E should see
  6785. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  6786. // so E sees them. C is only in E's local LastN set.
  6787. //
  6788. // If F starts talking and LastN = 3, then E should see thumbnails for
  6789. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  6790. // enters E's local LastN ejecting C.
  6791. // Increase the local LastN set size, if necessary.
  6792. if (lastNCount > localLastNCount) {
  6793. localLastNCount = lastNCount;
  6794. }
  6795. // Update the local LastN set preserving the order in which the
  6796. // endpoints appeared in the LastN/local LastN set.
  6797. var nextLocalLastNSet = lastNEndpoints.slice(0);
  6798. for (var i = 0; i < localLastNSet.length; i++) {
  6799. if (nextLocalLastNSet.length >= localLastNCount) {
  6800. break;
  6801. }
  6802. var resourceJid = localLastNSet[i];
  6803. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  6804. nextLocalLastNSet.push(resourceJid);
  6805. }
  6806. }
  6807. localLastNSet = nextLocalLastNSet;
  6808. var updateLargeVideo = false;
  6809. // Handle LastN/local LastN changes.
  6810. $('#remoteVideos>span').each(function( index, element ) {
  6811. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  6812. var isReceived = true;
  6813. if (resourceJid
  6814. && lastNEndpoints.indexOf(resourceJid) < 0
  6815. && localLastNSet.indexOf(resourceJid) < 0) {
  6816. console.log("Remove from last N", resourceJid);
  6817. showPeerContainer(resourceJid, 'hide');
  6818. isReceived = false;
  6819. } else if (resourceJid
  6820. && $('#participant_' + resourceJid).is(':visible')
  6821. && lastNEndpoints.indexOf(resourceJid) < 0
  6822. && localLastNSet.indexOf(resourceJid) >= 0) {
  6823. showPeerContainer(resourceJid, 'avatar');
  6824. isReceived = false;
  6825. }
  6826. if (!isReceived) {
  6827. // resourceJid has dropped out of the server side lastN set, so
  6828. // it is no longer being received. If resourceJid was being
  6829. // displayed in the large video we have to switch to another
  6830. // user.
  6831. var largeVideoResource = largeVideoState.userResourceJid;
  6832. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  6833. updateLargeVideo = true;
  6834. }
  6835. }
  6836. });
  6837. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  6838. endpointsEnteringLastN = lastNEndpoints;
  6839. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  6840. endpointsEnteringLastN.forEach(function (resourceJid) {
  6841. var isVisible = $('#participant_' + resourceJid).is(':visible');
  6842. showPeerContainer(resourceJid, 'show');
  6843. if (!isVisible) {
  6844. console.log("Add to last N", resourceJid);
  6845. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6846. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  6847. var sel = $('#participant_' + resourceJid + '>video');
  6848. var videoStream = APP.simulcast.getReceivingVideoStream(
  6849. mediaStream.stream);
  6850. APP.RTC.attachMediaStream(sel, videoStream);
  6851. if (lastNPickupJid == mediaStream.peerjid) {
  6852. // Clean up the lastN pickup jid.
  6853. lastNPickupJid = null;
  6854. // Don't fire the events again, they've already
  6855. // been fired in the contact list click handler.
  6856. VideoLayout.handleVideoThumbClicked(
  6857. $(sel).attr('src'),
  6858. false,
  6859. Strophe.getResourceFromJid(mediaStream.peerjid));
  6860. updateLargeVideo = false;
  6861. }
  6862. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  6863. }
  6864. })
  6865. }
  6866. // The endpoint that was being shown in the large video has dropped out
  6867. // of the lastN set and there was no lastN pickup jid. We need to update
  6868. // the large video now.
  6869. if (updateLargeVideo) {
  6870. var resource, container, src;
  6871. var myResource
  6872. = APP.xmpp.myResource();
  6873. // Find out which endpoint to show in the large video.
  6874. for (var i = 0; i < lastNEndpoints.length; i++) {
  6875. resource = lastNEndpoints[i];
  6876. if (!resource || resource === myResource)
  6877. continue;
  6878. container = $("#participant_" + resource);
  6879. if (container.length == 0)
  6880. continue;
  6881. src = $('video', container).attr('src');
  6882. if (!src)
  6883. continue;
  6884. // videoSrcToSsrc needs to be update for this call to succeed.
  6885. VideoLayout.updateLargeVideo(src);
  6886. break;
  6887. }
  6888. }
  6889. };
  6890. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  6891. endpointSimulcastLayers.forEach(function (esl) {
  6892. var resource = esl.endpoint;
  6893. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  6894. // then ignore the event (= do not preload anything).
  6895. //
  6896. // The bridge could probably stop sending this message if it's for
  6897. // an endpoint that's not in lastN.
  6898. if (lastNCount != -1
  6899. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  6900. return;
  6901. }
  6902. var primarySSRC = esl.simulcastLayer.primarySSRC;
  6903. // Get session and stream from primary ssrc.
  6904. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  6905. var sid = res.sid;
  6906. var electedStream = res.stream;
  6907. if (sid && electedStream) {
  6908. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  6909. console.info([esl, primarySSRC, msid, sid, electedStream]);
  6910. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  6911. if (preload) {
  6912. if (largeVideoState.preload)
  6913. {
  6914. $(largeVideoState.preload).remove();
  6915. }
  6916. console.info('Preloading remote video');
  6917. largeVideoState.preload = $('<video autoplay></video>');
  6918. // ssrcs are unique in an rtp session
  6919. largeVideoState.preload_ssrc = primarySSRC;
  6920. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  6921. }
  6922. } else {
  6923. console.error('Could not find a stream or a session.', sid, electedStream);
  6924. }
  6925. });
  6926. };
  6927. /**
  6928. * On simulcast layers changed event.
  6929. */
  6930. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  6931. endpointSimulcastLayers.forEach(function (esl) {
  6932. var resource = esl.endpoint;
  6933. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  6934. // then ignore the event (= do not change large video/thumbnail
  6935. // SRCs).
  6936. //
  6937. // Note that even if we ignore the "changed" event in this event
  6938. // handler, the bridge must continue sending these events because
  6939. // the simulcast code in simulcast.js uses it to know what's going
  6940. // to be streamed by the bridge when/if the endpoint gets back into
  6941. // the lastN set.
  6942. if (lastNCount != -1
  6943. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  6944. return;
  6945. }
  6946. var primarySSRC = esl.simulcastLayer.primarySSRC;
  6947. // Get session and stream from primary ssrc.
  6948. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  6949. var sid = res.sid;
  6950. var electedStream = res.stream;
  6951. if (sid && electedStream) {
  6952. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  6953. console.info('Switching simulcast substream.');
  6954. console.info([esl, primarySSRC, msid, sid, electedStream]);
  6955. var msidParts = msid.split(' ');
  6956. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  6957. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  6958. == largeVideoState.userResourceJid);
  6959. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  6960. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  6961. var electedStreamUrl;
  6962. if (largeVideoState.preload_ssrc == primarySSRC)
  6963. {
  6964. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  6965. }
  6966. else
  6967. {
  6968. if (largeVideoState.preload
  6969. && largeVideoState.preload != null) {
  6970. $(largeVideoState.preload).remove();
  6971. }
  6972. largeVideoState.preload_ssrc = 0;
  6973. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  6974. }
  6975. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  6976. if (updateLargeVideo) {
  6977. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  6978. Strophe.getResourceFromJid(jid));
  6979. }
  6980. if (updateFocusedVideoSrc) {
  6981. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  6982. }
  6983. var videoId;
  6984. if(resource == APP.xmpp.myResource())
  6985. {
  6986. videoId = "localVideoContainer";
  6987. }
  6988. else
  6989. {
  6990. videoId = "participant_" + resource;
  6991. }
  6992. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  6993. if(connectionIndicator)
  6994. connectionIndicator.updatePopoverData();
  6995. } else {
  6996. console.error('Could not find a stream or a sid.', sid, electedStream);
  6997. }
  6998. });
  6999. };
  7000. /**
  7001. * Updates local stats
  7002. * @param percent
  7003. * @param object
  7004. */
  7005. my.updateLocalConnectionStats = function (percent, object) {
  7006. var resolution = null;
  7007. if(object.resolution !== null)
  7008. {
  7009. resolution = object.resolution;
  7010. object.resolution = resolution[APP.xmpp.myJid()];
  7011. delete resolution[APP.xmpp.myJid()];
  7012. }
  7013. updateStatsIndicator("localVideoContainer", percent, object);
  7014. for(var jid in resolution)
  7015. {
  7016. if(resolution[jid] === null)
  7017. continue;
  7018. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7019. if(VideoLayout.connectionIndicators[id])
  7020. {
  7021. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7022. }
  7023. }
  7024. };
  7025. /**
  7026. * Updates remote stats.
  7027. * @param jid the jid associated with the stats
  7028. * @param percent the connection quality percent
  7029. * @param object the stats data
  7030. */
  7031. my.updateConnectionStats = function (jid, percent, object) {
  7032. var resourceJid = Strophe.getResourceFromJid(jid);
  7033. var videoSpanId = 'participant_' + resourceJid;
  7034. updateStatsIndicator(videoSpanId, percent, object);
  7035. };
  7036. /**
  7037. * Removes the connection
  7038. * @param jid
  7039. */
  7040. my.removeConnectionIndicator = function (jid) {
  7041. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7042. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7043. };
  7044. /**
  7045. * Hides the connection indicator
  7046. * @param jid
  7047. */
  7048. my.hideConnectionIndicator = function (jid) {
  7049. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7050. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7051. };
  7052. /**
  7053. * Hides all the indicators
  7054. */
  7055. my.onStatsStop = function () {
  7056. for(var indicator in VideoLayout.connectionIndicators)
  7057. {
  7058. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7059. }
  7060. };
  7061. my.participantLeft = function (jid) {
  7062. // Unlock large video
  7063. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7064. {
  7065. console.info("Focused video owner has left the conference");
  7066. focusedVideoInfo = null;
  7067. }
  7068. }
  7069. return my;
  7070. }(VideoLayout || {}));
  7071. module.exports = VideoLayout;
  7072. },{"../../../service/RTC/MediaStreamTypes":76,"../../../service/UI/UIEvents":80,"../audio_levels/AudioLevels":9,"../avatar/Avatar":12,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/chat/Chat":17,"../side_pannels/contactlist/ContactList":21,"../util/NicknameHandler":29,"../util/UIUtil":30,"./ConnectionIndicator":31}],33:[function(require,module,exports){
  7073. //var nouns = [
  7074. //];
  7075. var pluralNouns = [
  7076. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7077. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7078. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7079. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7080. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7081. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7082. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7083. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7084. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7085. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7086. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7087. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7088. ];
  7089. //var places = [
  7090. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7091. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7092. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7093. // "Bridge"
  7094. //];
  7095. var verbs = [
  7096. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7097. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7098. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7099. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7100. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7101. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7102. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7103. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7104. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7105. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7106. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7107. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7108. ];
  7109. var adverbs = [
  7110. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7111. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7112. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7113. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7114. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7115. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7116. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7117. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7118. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7119. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7120. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7121. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7122. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7123. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7124. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7125. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7126. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7127. ];
  7128. var adjectives = [
  7129. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7130. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7131. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7132. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7133. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7134. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7135. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7136. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7137. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7138. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7139. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7140. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7141. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7142. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7143. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7144. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7145. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7146. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7147. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7148. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7149. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7150. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7151. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7152. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7153. "Zealous"
  7154. ];
  7155. //var pronouns = [
  7156. //];
  7157. //var conjunctions = [
  7158. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7159. //];
  7160. /*
  7161. * Maps a string (category name) to the array of words from that category.
  7162. */
  7163. var CATEGORIES =
  7164. {
  7165. //"_NOUN_": nouns,
  7166. "_PLURALNOUN_": pluralNouns,
  7167. //"_PLACE_": places,
  7168. "_VERB_": verbs,
  7169. "_ADVERB_": adverbs,
  7170. "_ADJECTIVE_": adjectives
  7171. //"_PRONOUN_": pronouns,
  7172. //"_CONJUNCTION_": conjunctions,
  7173. };
  7174. var PATTERNS = [
  7175. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7176. // BeautifulFungiOrSpaghetti
  7177. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7178. // AmazinglyScaryToy
  7179. //"_ADVERB__ADJECTIVE__NOUN_",
  7180. // NeitherTrashNorRifle
  7181. //"Neither_NOUN_Nor_NOUN_",
  7182. //"Either_NOUN_Or_NOUN_",
  7183. // EitherCopulateOrInvestigate
  7184. //"Either_VERB_Or_VERB_",
  7185. //"Neither_VERB_Nor_VERB_",
  7186. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7187. //"The_ADVERB__ADJECTIVE__NOUN_",
  7188. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7189. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7190. // WolvesComputeBadly
  7191. //"_PLURALNOUN__VERB__ADVERB_",
  7192. // UniteFacilitateAndMerge
  7193. //"_VERB__VERB_And_VERB_",
  7194. //NastyWitchesAtThePub
  7195. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7196. ];
  7197. /*
  7198. * Returns a random element from the array 'arr'
  7199. */
  7200. function randomElement(arr)
  7201. {
  7202. return arr[Math.floor(Math.random() * arr.length)];
  7203. }
  7204. /*
  7205. * Returns true if the string 's' contains one of the
  7206. * template strings.
  7207. */
  7208. function hasTemplate(s)
  7209. {
  7210. for (var template in CATEGORIES){
  7211. if (s.indexOf(template) >= 0){
  7212. return true;
  7213. }
  7214. }
  7215. }
  7216. /**
  7217. * Generates new room name.
  7218. */
  7219. var RoomNameGenerator = {
  7220. generateRoomWithoutSeparator: function()
  7221. {
  7222. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7223. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7224. var name = randomElement(PATTERNS);
  7225. var word;
  7226. while (hasTemplate(name)){
  7227. for (var template in CATEGORIES){
  7228. word = randomElement(CATEGORIES[template]);
  7229. name = name.replace(template, word);
  7230. }
  7231. }
  7232. return name;
  7233. }
  7234. }
  7235. module.exports = RoomNameGenerator;
  7236. },{}],34:[function(require,module,exports){
  7237. var animateTimeout, updateTimeout;
  7238. var RoomNameGenerator = require("./RoomnameGenerator");
  7239. function enter_room()
  7240. {
  7241. var val = $("#enter_room_field").val();
  7242. if(!val) {
  7243. val = $("#enter_room_field").attr("room_name");
  7244. }
  7245. if (val) {
  7246. window.location.pathname = "/" + val;
  7247. }
  7248. }
  7249. function animate(word) {
  7250. var currentVal = $("#enter_room_field").attr("placeholder");
  7251. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7252. animateTimeout = setTimeout(function() {
  7253. animate(word.substring(1, word.length))
  7254. }, 70);
  7255. }
  7256. function update_roomname()
  7257. {
  7258. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7259. $("#enter_room_field").attr("room_name", word);
  7260. $("#enter_room_field").attr("placeholder", "");
  7261. clearTimeout(animateTimeout);
  7262. animate(word);
  7263. updateTimeout = setTimeout(update_roomname, 10000);
  7264. }
  7265. function setupWelcomePage()
  7266. {
  7267. $("#videoconference_page").hide();
  7268. $("#domain_name").text(
  7269. window.location.protocol + "//" + window.location.host + "/");
  7270. $("span[name='appName']").text(interfaceConfig.APP_NAME);
  7271. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7272. var leftWatermarkDiv
  7273. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7274. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7275. {
  7276. leftWatermarkDiv.css({display: 'block'});
  7277. leftWatermarkDiv.parent().get(0).href
  7278. = interfaceConfig.JITSI_WATERMARK_LINK;
  7279. }
  7280. }
  7281. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7282. var rightWatermarkDiv
  7283. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7284. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7285. rightWatermarkDiv.css({display: 'block'});
  7286. rightWatermarkDiv.parent().get(0).href
  7287. = interfaceConfig.BRAND_WATERMARK_LINK;
  7288. rightWatermarkDiv.get(0).style.backgroundImage
  7289. = "url(images/rightwatermark.png)";
  7290. }
  7291. }
  7292. if (interfaceConfig.SHOW_POWERED_BY) {
  7293. $("#welcome_page_header>a[class='poweredby']")
  7294. .css({display: 'block'});
  7295. }
  7296. $("#enter_room_button").click(function()
  7297. {
  7298. enter_room();
  7299. });
  7300. $("#enter_room_field").keydown(function (event) {
  7301. if (event.keyCode === 13 /* enter */) {
  7302. enter_room();
  7303. }
  7304. });
  7305. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7306. var updateTimeout;
  7307. var animateTimeout;
  7308. $("#reload_roomname").click(function () {
  7309. clearTimeout(updateTimeout);
  7310. clearTimeout(animateTimeout);
  7311. update_roomname();
  7312. });
  7313. $("#reload_roomname").show();
  7314. update_roomname();
  7315. }
  7316. $("#disable_welcome").click(function () {
  7317. window.localStorage.welcomePageDisabled
  7318. = $("#disable_welcome").is(":checked");
  7319. });
  7320. }
  7321. module.exports = setupWelcomePage;
  7322. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7323. var EventEmitter = require("events");
  7324. var eventEmitter = new EventEmitter();
  7325. var CQEvents = require("../../service/connectionquality/CQEvents");
  7326. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7327. /**
  7328. * local stats
  7329. * @type {{}}
  7330. */
  7331. var stats = {};
  7332. /**
  7333. * remote stats
  7334. * @type {{}}
  7335. */
  7336. var remoteStats = {};
  7337. /**
  7338. * Interval for sending statistics to other participants
  7339. * @type {null}
  7340. */
  7341. var sendIntervalId = null;
  7342. /**
  7343. * Start statistics sending.
  7344. */
  7345. function startSendingStats() {
  7346. sendStats();
  7347. sendIntervalId = setInterval(sendStats, 10000);
  7348. }
  7349. /**
  7350. * Sends statistics to other participants
  7351. */
  7352. function sendStats() {
  7353. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7354. }
  7355. /**
  7356. * Converts statistics to format for sending through XMPP
  7357. * @param stats the statistics
  7358. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7359. */
  7360. function convertToMUCStats(stats) {
  7361. return {
  7362. "bitrate_download": stats.bitrate.download,
  7363. "bitrate_upload": stats.bitrate.upload,
  7364. "packetLoss_total": stats.packetLoss.total,
  7365. "packetLoss_download": stats.packetLoss.download,
  7366. "packetLoss_upload": stats.packetLoss.upload
  7367. };
  7368. }
  7369. /**
  7370. * Converts statitistics to format used by VideoLayout
  7371. * @param stats
  7372. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7373. */
  7374. function parseMUCStats(stats) {
  7375. return {
  7376. bitrate: {
  7377. download: stats.bitrate_download,
  7378. upload: stats.bitrate_upload
  7379. },
  7380. packetLoss: {
  7381. total: stats.packetLoss_total,
  7382. download: stats.packetLoss_download,
  7383. upload: stats.packetLoss_upload
  7384. }
  7385. };
  7386. }
  7387. var ConnectionQuality = {
  7388. init: function () {
  7389. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7390. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7391. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7392. },
  7393. /**
  7394. * Updates the local statistics
  7395. * @param data new statistics
  7396. */
  7397. updateLocalStats: function (data) {
  7398. stats = data;
  7399. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7400. if (sendIntervalId == null) {
  7401. startSendingStats();
  7402. }
  7403. },
  7404. /**
  7405. * Updates remote statistics
  7406. * @param jid the jid associated with the statistics
  7407. * @param data the statistics
  7408. */
  7409. updateRemoteStats: function (jid, data) {
  7410. if (data == null || data.packetLoss_total == null) {
  7411. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7412. return;
  7413. }
  7414. remoteStats[jid] = parseMUCStats(data);
  7415. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7416. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7417. },
  7418. /**
  7419. * Stops statistics sending.
  7420. */
  7421. stopSendingStats: function () {
  7422. clearInterval(sendIntervalId);
  7423. sendIntervalId = null;
  7424. //notify UI about stopping statistics gathering
  7425. eventEmitter.emit(CQEvents.STOP);
  7426. },
  7427. /**
  7428. * Returns the local statistics.
  7429. */
  7430. getStats: function () {
  7431. return stats;
  7432. },
  7433. addListener: function (type, listener) {
  7434. eventEmitter.on(type, listener);
  7435. }
  7436. };
  7437. module.exports = ConnectionQuality;
  7438. },{"../../service/connectionquality/CQEvents":81,"../../service/xmpp/XMPPEvents":83,"events":84}],36:[function(require,module,exports){
  7439. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7440. /**
  7441. * Indicates that desktop stream is currently in use(for toggle purpose).
  7442. * @type {boolean}
  7443. */
  7444. var isUsingScreenStream = false;
  7445. /**
  7446. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7447. * @type {boolean}
  7448. */
  7449. var switchInProgress = false;
  7450. /**
  7451. * Method used to get screen sharing stream.
  7452. *
  7453. * @type {function (stream_callback, failure_callback}
  7454. */
  7455. var obtainDesktopStream = null;
  7456. /**
  7457. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7458. * @type {null|boolean}
  7459. */
  7460. var _desktopSharingEnabled = null;
  7461. var EventEmitter = require("events");
  7462. var eventEmitter = new EventEmitter();
  7463. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7464. /**
  7465. * Method obtains desktop stream from WebRTC 'screen' source.
  7466. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7467. */
  7468. function obtainWebRTCScreen(streamCallback, failCallback) {
  7469. APP.RTC.getUserMediaWithConstraints(
  7470. ['screen'],
  7471. streamCallback,
  7472. failCallback
  7473. );
  7474. }
  7475. /**
  7476. * Constructs inline install URL for Chrome desktop streaming extension.
  7477. * The 'chromeExtensionId' must be defined in config.js.
  7478. * @returns {string}
  7479. */
  7480. function getWebStoreInstallUrl()
  7481. {
  7482. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7483. }
  7484. /**
  7485. * Checks whether extension update is required.
  7486. * @param minVersion minimal required version
  7487. * @param extVersion current extension version
  7488. * @returns {boolean}
  7489. */
  7490. function isUpdateRequired(minVersion, extVersion)
  7491. {
  7492. try
  7493. {
  7494. var s1 = minVersion.split('.');
  7495. var s2 = extVersion.split('.');
  7496. var len = Math.max(s1.length, s2.length);
  7497. for (var i = 0; i < len; i++)
  7498. {
  7499. var n1 = 0,
  7500. n2 = 0;
  7501. if (i < s1.length)
  7502. n1 = parseInt(s1[i]);
  7503. if (i < s2.length)
  7504. n2 = parseInt(s2[i]);
  7505. if (isNaN(n1) || isNaN(n2))
  7506. {
  7507. return true;
  7508. }
  7509. else if (n1 !== n2)
  7510. {
  7511. return n1 > n2;
  7512. }
  7513. }
  7514. // will happen if boths version has identical numbers in
  7515. // their components (even if one of them is longer, has more components)
  7516. return false;
  7517. }
  7518. catch (e)
  7519. {
  7520. console.error("Failed to parse extension version", e);
  7521. APP.UI.messageHandler.showError('Error',
  7522. 'Error when trying to detect desktopsharing extension.');
  7523. return true;
  7524. }
  7525. }
  7526. function checkExtInstalled(isInstalledCallback) {
  7527. if (!chrome.runtime) {
  7528. // No API, so no extension for sure
  7529. isInstalledCallback(false);
  7530. return;
  7531. }
  7532. chrome.runtime.sendMessage(
  7533. config.chromeExtensionId,
  7534. { getVersion: true },
  7535. function (response) {
  7536. if (!response || !response.version) {
  7537. // Communication failure - assume that no endpoint exists
  7538. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  7539. isInstalledCallback(false);
  7540. } else {
  7541. // Check installed extension version
  7542. var extVersion = response.version;
  7543. console.log('Extension version is: ' + extVersion);
  7544. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  7545. if (updateRequired) {
  7546. alert(
  7547. 'Jitsi Desktop Streamer requires update. ' +
  7548. 'Changes will take effect after next Chrome restart.');
  7549. }
  7550. isInstalledCallback(!updateRequired);
  7551. }
  7552. }
  7553. );
  7554. }
  7555. function doGetStreamFromExtension(streamCallback, failCallback) {
  7556. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  7557. chrome.runtime.sendMessage(
  7558. config.chromeExtensionId,
  7559. { getStream: true, sources: config.desktopSharingSources },
  7560. function (response) {
  7561. if (!response) {
  7562. failCallback(chrome.runtime.lastError);
  7563. return;
  7564. }
  7565. console.log("Response from extension: " + response);
  7566. if (response.streamId) {
  7567. APP.RTC.getUserMediaWithConstraints(
  7568. ['desktop'],
  7569. function (stream) {
  7570. streamCallback(stream);
  7571. },
  7572. failCallback,
  7573. null, null, null,
  7574. response.streamId);
  7575. } else {
  7576. failCallback("Extension failed to get the stream");
  7577. }
  7578. }
  7579. );
  7580. }
  7581. /**
  7582. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  7583. */
  7584. function obtainScreenFromExtension(streamCallback, failCallback) {
  7585. checkExtInstalled(
  7586. function (isInstalled) {
  7587. if (isInstalled) {
  7588. doGetStreamFromExtension(streamCallback, failCallback);
  7589. } else {
  7590. chrome.webstore.install(
  7591. getWebStoreInstallUrl(),
  7592. function (arg) {
  7593. console.log("Extension installed successfully", arg);
  7594. // We need to reload the page in order to get the access to chrome.runtime
  7595. window.location.reload(false);
  7596. },
  7597. function (arg) {
  7598. console.log("Failed to install the extension", arg);
  7599. failCallback(arg);
  7600. APP.UI.messageHandler.showError('Error',
  7601. 'Failed to install desktop sharing extension');
  7602. }
  7603. );
  7604. }
  7605. }
  7606. );
  7607. }
  7608. /**
  7609. * Call this method to toggle desktop sharing feature.
  7610. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  7611. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  7612. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  7613. */
  7614. function setDesktopSharing(method) {
  7615. // Check if we are running chrome
  7616. if (!navigator.webkitGetUserMedia) {
  7617. obtainDesktopStream = null;
  7618. console.info("Desktop sharing disabled");
  7619. } else if (method == "ext") {
  7620. obtainDesktopStream = obtainScreenFromExtension;
  7621. console.info("Using Chrome extension for desktop sharing");
  7622. } else if (method == "webrtc") {
  7623. obtainDesktopStream = obtainWebRTCScreen;
  7624. console.info("Using Chrome WebRTC for desktop sharing");
  7625. }
  7626. // Reset enabled cache
  7627. _desktopSharingEnabled = null;
  7628. }
  7629. /**
  7630. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  7631. * Host site must be selected as main website of published extension.
  7632. */
  7633. function initInlineInstalls()
  7634. {
  7635. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  7636. }
  7637. function getSwitchStreamFailed(error) {
  7638. console.error("Failed to obtain the stream to switch to", error);
  7639. switchInProgress = false;
  7640. }
  7641. function streamSwitchDone() {
  7642. switchInProgress = false;
  7643. eventEmitter.emit(
  7644. DesktopSharingEventTypes.SWITCHING_DONE,
  7645. isUsingScreenStream);
  7646. }
  7647. function newStreamCreated(stream)
  7648. {
  7649. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  7650. stream, isUsingScreenStream, streamSwitchDone);
  7651. }
  7652. module.exports = {
  7653. isUsingScreenStream: function () {
  7654. return isUsingScreenStream;
  7655. },
  7656. /**
  7657. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  7658. */
  7659. isDesktopSharingEnabled: function () {
  7660. if (_desktopSharingEnabled === null) {
  7661. if (obtainDesktopStream === obtainScreenFromExtension) {
  7662. // Parse chrome version
  7663. var userAgent = navigator.userAgent.toLowerCase();
  7664. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  7665. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  7666. console.log("Chrome version" + userAgent, ver);
  7667. _desktopSharingEnabled = ver >= 34;
  7668. } else {
  7669. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  7670. }
  7671. }
  7672. return _desktopSharingEnabled;
  7673. },
  7674. init: function () {
  7675. setDesktopSharing(config.desktopSharing);
  7676. // Initialize Chrome extension inline installs
  7677. if (config.chromeExtensionId) {
  7678. initInlineInstalls();
  7679. }
  7680. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  7681. },
  7682. addListener: function(listener, type)
  7683. {
  7684. eventEmitter.on(type, listener);
  7685. },
  7686. removeListener: function (listener,type) {
  7687. eventEmitter.removeListener(type, listener);
  7688. },
  7689. /*
  7690. * Toggles screen sharing.
  7691. */
  7692. toggleScreenSharing: function () {
  7693. if (switchInProgress || !obtainDesktopStream) {
  7694. console.warn("Switch in progress or no method defined");
  7695. return;
  7696. }
  7697. switchInProgress = true;
  7698. if (!isUsingScreenStream)
  7699. {
  7700. // Switch to desktop stream
  7701. obtainDesktopStream(
  7702. function (stream) {
  7703. // We now use screen stream
  7704. isUsingScreenStream = true;
  7705. // Hook 'ended' event to restore camera when screen stream stops
  7706. stream.addEventListener('ended',
  7707. function (e) {
  7708. if (!switchInProgress && isUsingScreenStream) {
  7709. toggleScreenSharing();
  7710. }
  7711. }
  7712. );
  7713. newStreamCreated(stream);
  7714. },
  7715. getSwitchStreamFailed);
  7716. } else {
  7717. // Disable screen stream
  7718. APP.RTC.getUserMediaWithConstraints(
  7719. ['video'],
  7720. function (stream) {
  7721. // We are now using camera stream
  7722. isUsingScreenStream = false;
  7723. newStreamCreated(stream);
  7724. },
  7725. getSwitchStreamFailed, config.resolution || '360'
  7726. );
  7727. }
  7728. }
  7729. };
  7730. },{"../../service/desktopsharing/DesktopSharingEventTypes":82,"events":84}],37:[function(require,module,exports){
  7731. //maps keycode to character, id of popover for given function and function
  7732. var shortcuts = {
  7733. 67: {
  7734. character: "C",
  7735. id: "toggleChatPopover",
  7736. function: APP.UI.toggleChat
  7737. },
  7738. 70: {
  7739. character: "F",
  7740. id: "filmstripPopover",
  7741. function: APP.UI.toggleFilmStrip
  7742. },
  7743. 77: {
  7744. character: "M",
  7745. id: "mutePopover",
  7746. function: APP.UI.toggleAudio
  7747. },
  7748. 84: {
  7749. character: "T",
  7750. function: function() {
  7751. if(!APP.RTC.localAudio.isMuted()) {
  7752. APP.UI.toggleAudio();
  7753. }
  7754. }
  7755. },
  7756. 86: {
  7757. character: "V",
  7758. id: "toggleVideoPopover",
  7759. function: APP.UI.toggleVideo
  7760. }
  7761. };
  7762. var KeyboardShortcut = {
  7763. init: function () {
  7764. window.onkeyup = function(e) {
  7765. var keycode = e.which;
  7766. if(!($(":focus").is("input[type=text]") ||
  7767. $(":focus").is("input[type=password]") ||
  7768. $(":focus").is("textarea"))) {
  7769. if (typeof shortcuts[keycode] === "object") {
  7770. shortcuts[keycode].function();
  7771. }
  7772. else if (keycode >= "0".charCodeAt(0) &&
  7773. keycode <= "9".charCodeAt(0)) {
  7774. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  7775. }
  7776. //esc while the smileys are visible hides them
  7777. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  7778. APP.UI.toggleSmileys();
  7779. }
  7780. };
  7781. window.onkeydown = function(e) {
  7782. if(!($(":focus").is("input[type=text]") ||
  7783. $(":focus").is("input[type=password]") ||
  7784. $(":focus").is("textarea"))) {
  7785. if(e.which === "T".charCodeAt(0)) {
  7786. if(APP.RTC.localAudio.isMuted()) {
  7787. APP.UI.toggleAudio();
  7788. }
  7789. }
  7790. }
  7791. };
  7792. var self = this;
  7793. $('body').popover({ selector: '[data-toggle=popover]',
  7794. trigger: 'click hover',
  7795. content: function() {
  7796. return this.getAttribute("content") +
  7797. self.getShortcut(this.getAttribute("shortcut"));
  7798. }
  7799. });
  7800. },
  7801. /**
  7802. *
  7803. * @param id indicates the popover associated with the shortcut
  7804. * @returns {string} the keyboard shortcut used for the id given
  7805. */
  7806. getShortcut: function (id) {
  7807. for (var keycode in shortcuts) {
  7808. if (shortcuts.hasOwnProperty(keycode)) {
  7809. if (shortcuts[keycode].id === id) {
  7810. return " (" + shortcuts[keycode].character + ")";
  7811. }
  7812. }
  7813. }
  7814. return "";
  7815. }
  7816. };
  7817. module.exports = KeyboardShortcut;
  7818. },{}],38:[function(require,module,exports){
  7819. /**
  7820. *
  7821. * @constructor
  7822. */
  7823. function SimulcastLogger(name, lvl) {
  7824. this.name = name;
  7825. this.lvl = lvl;
  7826. }
  7827. SimulcastLogger.prototype.log = function (text) {
  7828. if (this.lvl) {
  7829. console.log(text);
  7830. }
  7831. };
  7832. SimulcastLogger.prototype.info = function (text) {
  7833. if (this.lvl > 1) {
  7834. console.info(text);
  7835. }
  7836. };
  7837. SimulcastLogger.prototype.fine = function (text) {
  7838. if (this.lvl > 2) {
  7839. console.log(text);
  7840. }
  7841. };
  7842. SimulcastLogger.prototype.error = function (text) {
  7843. console.error(text);
  7844. };
  7845. module.exports = SimulcastLogger;
  7846. },{}],39:[function(require,module,exports){
  7847. var SimulcastLogger = require("./SimulcastLogger");
  7848. var SimulcastUtils = require("./SimulcastUtils");
  7849. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  7850. function SimulcastReceiver() {
  7851. this.simulcastUtils = new SimulcastUtils();
  7852. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  7853. }
  7854. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  7855. SimulcastReceiver.prototype._remoteMaps = {
  7856. msid2Quality: {},
  7857. ssrc2Msid: {},
  7858. msid2ssrc: {},
  7859. receivingVideoStreams: {}
  7860. };
  7861. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  7862. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  7863. };
  7864. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  7865. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  7866. };
  7867. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  7868. var sb;
  7869. this.logger.info('Ensuring x-google-conference flag...')
  7870. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  7871. // TODO(gp) do that for the audio as well as suggested by fippo.
  7872. // Add the google conference flag
  7873. sb = this.simulcastUtils._getVideoSources(lines);
  7874. sb = ['a=x-google-flag:conference'].concat(sb);
  7875. this.simulcastUtils._replaceVideoSources(lines, sb);
  7876. }
  7877. };
  7878. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  7879. this._restoreRemoteVideoSources(sb);
  7880. };
  7881. /**
  7882. * Restores the simulcast groups of the remote description. In
  7883. * transformRemoteDescription we remove those in order for the set remote
  7884. * description to succeed. The focus needs the signal the groups to new
  7885. * participants.
  7886. *
  7887. * @param desc
  7888. * @returns {*}
  7889. */
  7890. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  7891. var sb;
  7892. if (!this.simulcastUtils.isValidDescription(desc)) {
  7893. return desc;
  7894. }
  7895. if (config.enableSimulcast) {
  7896. sb = desc.sdp.split('\r\n');
  7897. this._restoreSimulcastGroups(sb);
  7898. desc = new RTCSessionDescription({
  7899. type: desc.type,
  7900. sdp: sb.join('\r\n')
  7901. });
  7902. }
  7903. return desc;
  7904. };
  7905. SimulcastUtils.prototype._ensureOrder = function (lines) {
  7906. var videoSources, sb;
  7907. videoSources = this.parseMedia(lines, ['video'])[0];
  7908. sb = this._compileVideoSources(videoSources);
  7909. this._replaceVideoSources(lines, sb);
  7910. };
  7911. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  7912. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  7913. videoSource, quality;
  7914. // (re) initialize the remote maps.
  7915. this._remoteMaps.msid2Quality = {};
  7916. this._remoteMaps.ssrc2Msid = {};
  7917. this._remoteMaps.msid2ssrc = {};
  7918. var self = this;
  7919. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  7920. remoteVideoSources.groups.forEach(function (group) {
  7921. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  7922. quality = 0;
  7923. group.ssrcs.forEach(function (ssrc) {
  7924. videoSource = remoteVideoSources.sources[ssrc];
  7925. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  7926. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  7927. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  7928. });
  7929. }
  7930. });
  7931. }
  7932. };
  7933. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  7934. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  7935. };
  7936. /**
  7937. * Returns a stream with single video track, the one currently being
  7938. * received by this endpoint.
  7939. *
  7940. * @param stream the remote simulcast stream.
  7941. * @returns {webkitMediaStream}
  7942. */
  7943. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  7944. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  7945. var self = this;
  7946. if (config.enableSimulcast) {
  7947. stream.getVideoTracks().some(function (track) {
  7948. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  7949. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  7950. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  7951. if (msid == [stream.id, track.id].join(' ')) {
  7952. electedTrack = track;
  7953. return true;
  7954. }
  7955. });
  7956. });
  7957. if (!electedTrack) {
  7958. // we don't have an elected track, choose by initial quality.
  7959. tracks = stream.getVideoTracks();
  7960. for (i = 0; i < tracks.length; i++) {
  7961. msid = [stream.id, tracks[i].id].join(' ');
  7962. if (this._remoteMaps.msid2Quality[msid] === quality) {
  7963. electedTrack = tracks[i];
  7964. break;
  7965. }
  7966. }
  7967. // TODO(gp) if the initialQuality could not be satisfied, lower
  7968. // the requirement and try again.
  7969. }
  7970. }
  7971. return (electedTrack)
  7972. ? new webkitMediaStream([electedTrack])
  7973. : stream;
  7974. };
  7975. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  7976. var resource = Strophe.getResourceFromJid(jid);
  7977. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  7978. // If we haven't receiving a "changed" event yet, then we must be receiving
  7979. // low quality (that the sender always streams).
  7980. if(!ssrc)
  7981. {
  7982. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7983. var remoteStream = remoteStreamObject.getOriginalStream();
  7984. var tracks = remoteStream.getVideoTracks();
  7985. if (tracks) {
  7986. for (var k = 0; k < tracks.length; k++) {
  7987. var track = tracks[k];
  7988. var msid = [remoteStream.id, track.id].join(' ');
  7989. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  7990. var quality = this._remoteMaps.msid2Quality[msid];
  7991. if (quality == 0) {
  7992. ssrc = _ssrc;
  7993. }
  7994. }
  7995. }
  7996. }
  7997. return ssrc;
  7998. };
  7999. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8000. {
  8001. var sid, electedStream;
  8002. var i, j, k;
  8003. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8004. if(jid && APP.RTC.remoteStreams[jid])
  8005. {
  8006. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8007. var remoteStream = remoteStreamObject.getOriginalStream();
  8008. var tracks = remoteStream.getVideoTracks();
  8009. if (tracks) {
  8010. for (k = 0; k < tracks.length; k++) {
  8011. var track = tracks[k];
  8012. var msid = [remoteStream.id, track.id].join(' ');
  8013. var tmp = this._remoteMaps.msid2ssrc[msid];
  8014. if (tmp == ssrc) {
  8015. electedStream = new webkitMediaStream([track]);
  8016. sid = remoteStreamObject.sid;
  8017. // stream found, stop.
  8018. break;
  8019. }
  8020. }
  8021. }
  8022. }
  8023. else
  8024. {
  8025. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8026. }
  8027. return {
  8028. sid: sid,
  8029. stream: electedStream
  8030. };
  8031. };
  8032. /**
  8033. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8034. * SSRC.
  8035. *
  8036. * @param ssrc
  8037. * @returns {*}
  8038. */
  8039. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8040. return this._remoteMaps.ssrc2Msid[ssrc];
  8041. };
  8042. /**
  8043. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8044. * either gets confused and thinks this is an FID group or, if an FID group
  8045. * is already present, it fails to set the remote description.
  8046. *
  8047. * @param desc
  8048. * @returns {*}
  8049. */
  8050. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8051. if (desc && desc.sdp) {
  8052. var sb = desc.sdp.split('\r\n');
  8053. this._updateRemoteMaps(sb);
  8054. this._cacheRemoteVideoSources(sb);
  8055. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8056. // need the simulcast group in the _updateRemoteMaps() method.
  8057. this.simulcastUtils._removeSimulcastGroup(sb);
  8058. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8059. // We don't need the goog conference flag if we're not doing
  8060. // simulcast.
  8061. this._ensureGoogConference(sb);
  8062. }
  8063. desc = new RTCSessionDescription({
  8064. type: desc.type,
  8065. sdp: sb.join('\r\n')
  8066. });
  8067. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8068. }
  8069. return desc;
  8070. };
  8071. module.exports = SimulcastReceiver;
  8072. },{"../../service/RTC/MediaStreamTypes":76,"./SimulcastLogger":38,"./SimulcastUtils":41}],40:[function(require,module,exports){
  8073. var SimulcastLogger = require("./SimulcastLogger");
  8074. var SimulcastUtils = require("./SimulcastUtils");
  8075. function SimulcastSender() {
  8076. this.simulcastUtils = new SimulcastUtils();
  8077. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8078. }
  8079. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8080. SimulcastSender.prototype._generateGuid = (function () {
  8081. function s4() {
  8082. return Math.floor((1 + Math.random()) * 0x10000)
  8083. .toString(16)
  8084. .substring(1);
  8085. }
  8086. return function () {
  8087. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8088. s4() + '-' + s4() + s4() + s4();
  8089. };
  8090. }());
  8091. // Returns a random integer between min (included) and max (excluded)
  8092. // Using Math.round() gives a non-uniform distribution!
  8093. SimulcastSender.prototype._generateRandomSSRC = function () {
  8094. var min = 0, max = 0xffffffff;
  8095. return Math.floor(Math.random() * (max - min)) + min;
  8096. };
  8097. SimulcastSender.prototype.getLocalVideoStream = function () {
  8098. return (this.displayedLocalVideoStream != null)
  8099. ? this.displayedLocalVideoStream
  8100. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8101. : APP.RTC.localVideo.getOriginalStream();
  8102. };
  8103. function NativeSimulcastSender() {
  8104. SimulcastSender.call(this); // call the super constructor.
  8105. }
  8106. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8107. NativeSimulcastSender.prototype._localExplosionMap = {};
  8108. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8109. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8110. NativeSimulcastSender.prototype.reset = function () {
  8111. this._localExplosionMap = {};
  8112. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8113. };
  8114. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8115. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8116. };
  8117. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8118. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8119. };
  8120. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8121. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8122. this.logger.info('Appending simulcast group...');
  8123. // Get the primary SSRC information.
  8124. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8125. // Start building the SIM SSRC group.
  8126. ssrcGroup = ['a=ssrc-group:SIM'];
  8127. // The video source buffer.
  8128. sb = [];
  8129. // Create the simulcast sub-streams.
  8130. for (i = 0; i < numOfSubs; i++) {
  8131. // TODO(gp) prevent SSRC collision.
  8132. simSSRC = this._generateRandomSSRC();
  8133. ssrcGroup.push(simSSRC);
  8134. if (videoSources.base) {
  8135. sb.splice.apply(sb, [sb.length, 0].concat(
  8136. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8137. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8138. ));
  8139. }
  8140. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8141. }
  8142. // Add the group sim layers.
  8143. sb.splice(0, 0, ssrcGroup.join(' '))
  8144. this.simulcastUtils._replaceVideoSources(lines, sb);
  8145. };
  8146. // Does the actual patching.
  8147. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8148. this.logger.info('Ensuring simulcast group...');
  8149. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8150. this._appendSimulcastGroup(lines);
  8151. this._cacheLocalVideoSources(lines);
  8152. } else {
  8153. // verify that the ssrcs participating in the SIM group are present
  8154. // in the SDP (needed for presence).
  8155. this._restoreLocalVideoSources(lines);
  8156. }
  8157. };
  8158. /**
  8159. * Produces a single stream with multiple tracks for local video sources.
  8160. *
  8161. * @param lines
  8162. * @private
  8163. */
  8164. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8165. var sb, msid, sid, tid, videoSources, self;
  8166. this.logger.info('Exploding local video sources...');
  8167. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8168. self = this;
  8169. if (videoSources.groups && videoSources.groups.length !== 0) {
  8170. videoSources.groups.forEach(function (group) {
  8171. if (group.semantics === 'SIM') {
  8172. group.ssrcs.forEach(function (ssrc) {
  8173. // Get the msid for this ssrc..
  8174. if (self._localExplosionMap[ssrc]) {
  8175. // .. either from the explosion map..
  8176. msid = self._localExplosionMap[ssrc];
  8177. } else {
  8178. // .. or generate a new one (msid).
  8179. sid = videoSources.sources[ssrc].msid
  8180. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8181. tid = self._generateGuid();
  8182. msid = [sid, tid].join(' ');
  8183. self._localExplosionMap[ssrc] = msid;
  8184. }
  8185. // Assign it to the source object.
  8186. videoSources.sources[ssrc].msid = msid;
  8187. // TODO(gp) Change the msid of associated sources.
  8188. });
  8189. }
  8190. });
  8191. }
  8192. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8193. this.simulcastUtils._replaceVideoSources(lines, sb);
  8194. };
  8195. /**
  8196. * GUM for simulcast.
  8197. *
  8198. * @param constraints
  8199. * @param success
  8200. * @param err
  8201. */
  8202. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8203. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8204. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8205. success(hqStream);
  8206. }, err);
  8207. };
  8208. /**
  8209. * Prepares the local description for public usage (i.e. to be signaled
  8210. * through Jingle to the focus).
  8211. *
  8212. * @param desc
  8213. * @returns {RTCSessionDescription}
  8214. */
  8215. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8216. var sb;
  8217. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8218. return desc;
  8219. }
  8220. sb = desc.sdp.split('\r\n');
  8221. this._explodeSimulcastSenderSources(sb);
  8222. desc = new RTCSessionDescription({
  8223. type: desc.type,
  8224. sdp: sb.join('\r\n')
  8225. });
  8226. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8227. return desc;
  8228. };
  8229. /**
  8230. * Ensures that the simulcast group is present in the answer, _if_ native
  8231. * simulcast is enabled,
  8232. *
  8233. * @param desc
  8234. * @returns {*}
  8235. */
  8236. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8237. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8238. return desc;
  8239. }
  8240. var sb = desc.sdp.split('\r\n');
  8241. // Even if we have enabled native simulcasting previously
  8242. // (with a call to SLD with an appropriate SDP, for example),
  8243. // createAnswer seems to consistently generate incomplete SDP
  8244. // with missing SSRCS.
  8245. //
  8246. // So, subsequent calls to SLD will have missing SSRCS and presence
  8247. // won't have the complete list of SRCs.
  8248. this._ensureSimulcastGroup(sb);
  8249. desc = new RTCSessionDescription({
  8250. type: desc.type,
  8251. sdp: sb.join('\r\n')
  8252. });
  8253. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8254. return desc;
  8255. };
  8256. /**
  8257. *
  8258. *
  8259. * @param desc
  8260. * @returns {*}
  8261. */
  8262. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8263. return desc;
  8264. };
  8265. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8266. // Nothing to do here, native simulcast does that auto-magically.
  8267. };
  8268. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8269. function SimpleSimulcastSender() {
  8270. SimulcastSender.call(this);
  8271. }
  8272. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8273. SimpleSimulcastSender.prototype.localStream = null;
  8274. SimpleSimulcastSender.prototype._localMaps = {
  8275. msids: [],
  8276. msid2ssrc: {}
  8277. };
  8278. /**
  8279. * Groups local video sources together in the ssrc-group:SIM group.
  8280. *
  8281. * @param lines
  8282. * @private
  8283. */
  8284. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8285. var sb, videoSources, ssrcs = [], ssrc;
  8286. this.logger.info('Grouping local video sources...');
  8287. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8288. for (ssrc in videoSources.sources) {
  8289. // jitsi-meet destroys/creates streams at various places causing
  8290. // the original local stream ids to change. The only thing that
  8291. // remains unchanged is the trackid.
  8292. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8293. }
  8294. var self = this;
  8295. // TODO(gp) add only "free" sources.
  8296. this._localMaps.msids.forEach(function (msid) {
  8297. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8298. });
  8299. if (!videoSources.groups) {
  8300. videoSources.groups = [];
  8301. }
  8302. videoSources.groups.push({
  8303. 'semantics': 'SIM',
  8304. 'ssrcs': ssrcs
  8305. });
  8306. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8307. this.simulcastUtils._replaceVideoSources(lines, sb);
  8308. };
  8309. /**
  8310. * GUM for simulcast.
  8311. *
  8312. * @param constraints
  8313. * @param success
  8314. * @param err
  8315. */
  8316. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8317. // TODO(gp) what if we request a resolution not supported by the hardware?
  8318. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8319. var lqConstraints = {
  8320. audio: false,
  8321. video: {
  8322. mandatory: {
  8323. maxWidth: 320,
  8324. maxHeight: 180,
  8325. maxFrameRate: 15
  8326. }
  8327. }
  8328. };
  8329. this.logger.info('HQ constraints: ', constraints);
  8330. this.logger.info('LQ constraints: ', lqConstraints);
  8331. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8332. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8333. // reason appears to be that Chrome only acquires the cam once and
  8334. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8335. var self = this;
  8336. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8337. self.localStream = hqStream;
  8338. // reset local maps.
  8339. self._localMaps.msids = [];
  8340. self._localMaps.msid2ssrc = {};
  8341. // add hq trackid to local map
  8342. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8343. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8344. self.displayedLocalVideoStream = lqStream;
  8345. // NOTE(gp) The specification says Array.forEach() will visit
  8346. // the array elements in numeric order, and that it doesn't
  8347. // visit elements that don't exist.
  8348. // add lq trackid to local map
  8349. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8350. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8351. success(self.localStream);
  8352. }, err);
  8353. }, err);
  8354. };
  8355. /**
  8356. * Prepares the local description for public usage (i.e. to be signaled
  8357. * through Jingle to the focus).
  8358. *
  8359. * @param desc
  8360. * @returns {RTCSessionDescription}
  8361. */
  8362. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8363. var sb;
  8364. if (!this.simulcastUtils.isValidDescription(desc)) {
  8365. return desc;
  8366. }
  8367. sb = desc.sdp.split('\r\n');
  8368. this._groupLocalVideoSources(sb);
  8369. desc = new RTCSessionDescription({
  8370. type: desc.type,
  8371. sdp: sb.join('\r\n')
  8372. });
  8373. this.logger.fine('Grouped local video sources');
  8374. this.logger.fine(desc.sdp);
  8375. return desc;
  8376. };
  8377. /**
  8378. * Ensures that the simulcast group is present in the answer, _if_ native
  8379. * simulcast is enabled,
  8380. *
  8381. * @param desc
  8382. * @returns {*}
  8383. */
  8384. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8385. return desc;
  8386. };
  8387. /**
  8388. *
  8389. *
  8390. * @param desc
  8391. * @returns {*}
  8392. */
  8393. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8394. var sb = desc.sdp.split('\r\n');
  8395. this.simulcastUtils._removeSimulcastGroup(sb);
  8396. desc = new RTCSessionDescription({
  8397. type: desc.type,
  8398. sdp: sb.join('\r\n')
  8399. });
  8400. this.logger.fine('Transformed local description');
  8401. this.logger.fine(desc.sdp);
  8402. return desc;
  8403. };
  8404. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8405. var trackid;
  8406. var self = this;
  8407. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8408. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8409. // Search for the track id that corresponds to the ssrc
  8410. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8411. trackid = tid;
  8412. return true;
  8413. }
  8414. }) && self.localStream.getVideoTracks().some(function (track) {
  8415. // Start/stop the track that corresponds to the track id
  8416. if (track.id === trackid) {
  8417. track.enabled = enabled;
  8418. return true;
  8419. }
  8420. })) {
  8421. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8422. $(document).trigger(enabled
  8423. ? 'simulcastlayerstarted'
  8424. : 'simulcastlayerstopped');
  8425. } else {
  8426. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8427. }
  8428. };
  8429. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8430. function NoSimulcastSender() {
  8431. SimulcastSender.call(this);
  8432. }
  8433. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8434. /**
  8435. * GUM for simulcast.
  8436. *
  8437. * @param constraints
  8438. * @param success
  8439. * @param err
  8440. */
  8441. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8442. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8443. success(hqStream);
  8444. }, err);
  8445. };
  8446. /**
  8447. * Prepares the local description for public usage (i.e. to be signaled
  8448. * through Jingle to the focus).
  8449. *
  8450. * @param desc
  8451. * @returns {RTCSessionDescription}
  8452. */
  8453. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8454. return desc;
  8455. };
  8456. /**
  8457. * Ensures that the simulcast group is present in the answer, _if_ native
  8458. * simulcast is enabled,
  8459. *
  8460. * @param desc
  8461. * @returns {*}
  8462. */
  8463. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  8464. return desc;
  8465. };
  8466. /**
  8467. *
  8468. *
  8469. * @param desc
  8470. * @returns {*}
  8471. */
  8472. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8473. return desc;
  8474. };
  8475. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8476. };
  8477. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  8478. module.exports = {
  8479. "native": NativeSimulcastSender,
  8480. "no": NoSimulcastSender
  8481. }
  8482. },{"./SimulcastLogger":38,"./SimulcastUtils":41}],41:[function(require,module,exports){
  8483. var SimulcastLogger = require("./SimulcastLogger");
  8484. /**
  8485. *
  8486. * @constructor
  8487. */
  8488. function SimulcastUtils() {
  8489. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  8490. }
  8491. /**
  8492. *
  8493. * @type {{}}
  8494. * @private
  8495. */
  8496. SimulcastUtils.prototype._emptyCompoundIndex = {};
  8497. /**
  8498. *
  8499. * @param lines
  8500. * @param videoSources
  8501. * @private
  8502. */
  8503. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  8504. var i, inVideo = false, index = -1, howMany = 0;
  8505. this.logger.info('Replacing video sources...');
  8506. for (i = 0; i < lines.length; i++) {
  8507. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8508. // Out of video.
  8509. break;
  8510. }
  8511. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8512. // In video.
  8513. inVideo = true;
  8514. }
  8515. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  8516. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  8517. if (index === -1) {
  8518. index = i;
  8519. }
  8520. howMany++;
  8521. }
  8522. }
  8523. // efficiency baby ;)
  8524. lines.splice.apply(lines,
  8525. [index, howMany].concat(videoSources));
  8526. };
  8527. SimulcastUtils.prototype.isValidDescription = function (desc)
  8528. {
  8529. return desc && desc != null
  8530. && desc.type && desc.type != ''
  8531. && desc.sdp && desc.sdp != '';
  8532. };
  8533. SimulcastUtils.prototype._getVideoSources = function (lines) {
  8534. var i, inVideo = false, sb = [];
  8535. this.logger.info('Getting video sources...');
  8536. for (i = 0; i < lines.length; i++) {
  8537. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8538. // Out of video.
  8539. break;
  8540. }
  8541. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8542. // In video.
  8543. inVideo = true;
  8544. }
  8545. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8546. // In SSRC.
  8547. sb.push(lines[i]);
  8548. }
  8549. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8550. sb.push(lines[i]);
  8551. }
  8552. }
  8553. return sb;
  8554. };
  8555. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  8556. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  8557. ssrc_attribute, group, semantics, skip = true;
  8558. this.logger.info('Parsing media sources...');
  8559. for (i = 0; i < lines.length; i++) {
  8560. if (lines[i].substring(0, 'm='.length) === 'm=') {
  8561. type = lines[i]
  8562. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  8563. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  8564. if (!skip) {
  8565. cur_media = {
  8566. 'type': type,
  8567. 'sources': {},
  8568. 'groups': []
  8569. };
  8570. res.push(cur_media);
  8571. }
  8572. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8573. idx = lines[i].indexOf(' ');
  8574. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  8575. if (cur_media.sources[ssrc] === undefined) {
  8576. cur_ssrc = {'ssrc': ssrc};
  8577. cur_media.sources[ssrc] = cur_ssrc;
  8578. }
  8579. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  8580. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  8581. if (cur_media.base === undefined) {
  8582. cur_media.base = cur_ssrc;
  8583. }
  8584. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8585. idx = lines[i].indexOf(' ');
  8586. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  8587. ssrcs = lines[i].substr(idx).trim().split(' ');
  8588. group = {
  8589. 'semantics': semantics,
  8590. 'ssrcs': ssrcs
  8591. };
  8592. cur_media.groups.push(group);
  8593. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  8594. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  8595. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  8596. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  8597. cur_media.direction = lines[i].substring('a='.length);
  8598. }
  8599. }
  8600. return res;
  8601. };
  8602. /**
  8603. * The _indexOfArray() method returns the first a CompoundIndex at which a
  8604. * given element can be found in the array, or _emptyCompoundIndex if it is
  8605. * not present.
  8606. *
  8607. * Example:
  8608. *
  8609. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  8610. *
  8611. * returns {row: 2, column: 14}
  8612. *
  8613. * @param needle
  8614. * @param haystack
  8615. * @param start
  8616. * @returns {}
  8617. * @private
  8618. */
  8619. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  8620. var length = haystack.length, idx, i;
  8621. if (!start) {
  8622. start = 0;
  8623. }
  8624. for (i = start; i < length; i++) {
  8625. idx = haystack[i].indexOf(needle);
  8626. if (idx !== -1) {
  8627. return {row: i, column: idx};
  8628. }
  8629. }
  8630. return this._emptyCompoundIndex;
  8631. };
  8632. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  8633. var i;
  8634. for (i = lines.length - 1; i >= 0; i--) {
  8635. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  8636. lines.splice(i, 1);
  8637. }
  8638. }
  8639. };
  8640. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  8641. var sb = [], ssrc, addedSSRCs = [];
  8642. this.logger.info('Compiling video sources...');
  8643. // Add the groups
  8644. if (videoSources.groups && videoSources.groups.length !== 0) {
  8645. videoSources.groups.forEach(function (group) {
  8646. if (group.ssrcs && group.ssrcs.length !== 0) {
  8647. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  8648. // if (group.semantics !== 'SIM') {
  8649. group.ssrcs.forEach(function (ssrc) {
  8650. addedSSRCs.push(ssrc);
  8651. sb.splice.apply(sb, [sb.length, 0].concat([
  8652. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8653. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8654. });
  8655. //}
  8656. }
  8657. });
  8658. }
  8659. // Then add any free sources.
  8660. if (videoSources.sources) {
  8661. for (ssrc in videoSources.sources) {
  8662. if (addedSSRCs.indexOf(ssrc) === -1) {
  8663. sb.splice.apply(sb, [sb.length, 0].concat([
  8664. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8665. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8666. }
  8667. }
  8668. }
  8669. return sb;
  8670. };
  8671. module.exports = SimulcastUtils;
  8672. },{"./SimulcastLogger":38}],42:[function(require,module,exports){
  8673. /*jslint plusplus: true */
  8674. /*jslint nomen: true*/
  8675. var SimulcastSender = require("./SimulcastSender");
  8676. var NoSimulcastSender = SimulcastSender["no"];
  8677. var NativeSimulcastSender = SimulcastSender["native"];
  8678. var SimulcastReceiver = require("./SimulcastReceiver");
  8679. var SimulcastUtils = require("./SimulcastUtils");
  8680. var RTCEvents = require("../../service/RTC/RTCEvents");
  8681. /**
  8682. *
  8683. * @constructor
  8684. */
  8685. function SimulcastManager() {
  8686. // Create the simulcast utilities.
  8687. this.simulcastUtils = new SimulcastUtils();
  8688. // Create remote simulcast.
  8689. this.simulcastReceiver = new SimulcastReceiver();
  8690. // Initialize local simulcast.
  8691. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  8692. // account constraints.
  8693. if (!config.enableSimulcast) {
  8694. this.simulcastSender = new NoSimulcastSender();
  8695. } else {
  8696. var isChromium = window.chrome,
  8697. vendorName = window.navigator.vendor;
  8698. if(isChromium !== null && isChromium !== undefined
  8699. /* skip opera */
  8700. && vendorName === "Google Inc."
  8701. /* skip Chromium as suggested by fippo */
  8702. && !window.navigator.appVersion.match(/Chromium\//) ) {
  8703. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  8704. if (ver > 37) {
  8705. this.simulcastSender = new NativeSimulcastSender();
  8706. } else {
  8707. this.simulcastSender = new NoSimulcastSender();
  8708. }
  8709. } else {
  8710. this.simulcastSender = new NoSimulcastSender();
  8711. }
  8712. }
  8713. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  8714. function (endpointSimulcastLayers) {
  8715. endpointSimulcastLayers.forEach(function (esl) {
  8716. var ssrc = esl.simulcastLayer.primarySSRC;
  8717. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  8718. });
  8719. });
  8720. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  8721. var ssrc = simulcastLayer.primarySSRC;
  8722. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  8723. });
  8724. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  8725. var ssrc = simulcastLayer.primarySSRC;
  8726. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  8727. });
  8728. }
  8729. /**
  8730. * Restores the simulcast groups of the remote description. In
  8731. * transformRemoteDescription we remove those in order for the set remote
  8732. * description to succeed. The focus needs the signal the groups to new
  8733. * participants.
  8734. *
  8735. * @param desc
  8736. * @returns {*}
  8737. */
  8738. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  8739. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  8740. };
  8741. /**
  8742. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8743. * either gets confused and thinks this is an FID group or, if an FID group
  8744. * is already present, it fails to set the remote description.
  8745. *
  8746. * @param desc
  8747. * @returns {*}
  8748. */
  8749. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  8750. return this.simulcastReceiver.transformRemoteDescription(desc);
  8751. };
  8752. /**
  8753. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8754. * SSRC.
  8755. *
  8756. * @param ssrc
  8757. * @returns {*}
  8758. */
  8759. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8760. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  8761. };
  8762. /**
  8763. * Returns a stream with single video track, the one currently being
  8764. * received by this endpoint.
  8765. *
  8766. * @param stream the remote simulcast stream.
  8767. * @returns {webkitMediaStream}
  8768. */
  8769. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  8770. return this.simulcastReceiver.getReceivingVideoStream(stream);
  8771. };
  8772. /**
  8773. *
  8774. *
  8775. * @param desc
  8776. * @returns {*}
  8777. */
  8778. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  8779. return this.simulcastSender.transformLocalDescription(desc);
  8780. };
  8781. /**
  8782. *
  8783. * @returns {*}
  8784. */
  8785. SimulcastManager.prototype.getLocalVideoStream = function() {
  8786. return this.simulcastSender.getLocalVideoStream();
  8787. };
  8788. /**
  8789. * GUM for simulcast.
  8790. *
  8791. * @param constraints
  8792. * @param success
  8793. * @param err
  8794. */
  8795. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  8796. this.simulcastSender.getUserMedia(constraints, success, err);
  8797. };
  8798. /**
  8799. * Prepares the local description for public usage (i.e. to be signaled
  8800. * through Jingle to the focus).
  8801. *
  8802. * @param desc
  8803. * @returns {RTCSessionDescription}
  8804. */
  8805. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  8806. return this.simulcastSender.reverseTransformLocalDescription(desc);
  8807. };
  8808. /**
  8809. * Ensures that the simulcast group is present in the answer, _if_ native
  8810. * simulcast is enabled,
  8811. *
  8812. * @param desc
  8813. * @returns {*}
  8814. */
  8815. SimulcastManager.prototype.transformAnswer = function (desc) {
  8816. return this.simulcastSender.transformAnswer(desc);
  8817. };
  8818. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  8819. return this.simulcastReceiver.getReceivingSSRC(jid);
  8820. };
  8821. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  8822. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  8823. };
  8824. /**
  8825. *
  8826. * @param lines
  8827. * @param mediatypes
  8828. * @returns {*}
  8829. */
  8830. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  8831. var sb = lines.sdp.split('\r\n');
  8832. return this.simulcastUtils.parseMedia(sb, mediatypes);
  8833. };
  8834. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  8835. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  8836. };
  8837. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  8838. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  8839. };
  8840. SimulcastManager.prototype.resetSender = function() {
  8841. if (typeof this.simulcastSender.reset === 'function'){
  8842. this.simulcastSender.reset();
  8843. }
  8844. };
  8845. var simulcast = new SimulcastManager();
  8846. module.exports = simulcast;
  8847. },{"../../service/RTC/RTCEvents":78,"./SimulcastReceiver":39,"./SimulcastSender":40,"./SimulcastUtils":41}],43:[function(require,module,exports){
  8848. /**
  8849. * Provides statistics for the local stream.
  8850. */
  8851. /**
  8852. * Size of the webaudio analizer buffer.
  8853. * @type {number}
  8854. */
  8855. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  8856. /**
  8857. * Value of the webaudio analizer smoothing time parameter.
  8858. * @type {number}
  8859. */
  8860. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  8861. /**
  8862. * Converts time domain data array to audio level.
  8863. * @param array the time domain data array.
  8864. * @returns {number} the audio level
  8865. */
  8866. function timeDomainDataToAudioLevel(samples) {
  8867. var maxVolume = 0;
  8868. var length = samples.length;
  8869. for (var i = 0; i < length; i++) {
  8870. if (maxVolume < samples[i])
  8871. maxVolume = samples[i];
  8872. }
  8873. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  8874. };
  8875. /**
  8876. * Animates audio level change
  8877. * @param newLevel the new audio level
  8878. * @param lastLevel the last audio level
  8879. * @returns {Number} the audio level to be set
  8880. */
  8881. function animateLevel(newLevel, lastLevel)
  8882. {
  8883. var value = 0;
  8884. var diff = lastLevel - newLevel;
  8885. if(diff > 0.2)
  8886. {
  8887. value = lastLevel - 0.2;
  8888. }
  8889. else if(diff < -0.4)
  8890. {
  8891. value = lastLevel + 0.4;
  8892. }
  8893. else
  8894. {
  8895. value = newLevel;
  8896. }
  8897. return parseFloat(value.toFixed(3));
  8898. }
  8899. /**
  8900. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  8901. *
  8902. * @param stream the local stream
  8903. * @param interval stats refresh interval given in ms.
  8904. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  8905. * update.
  8906. * @constructor
  8907. */
  8908. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  8909. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  8910. this.stream = stream;
  8911. this.intervalId = null;
  8912. this.intervalMilis = interval;
  8913. this.eventEmitter = eventEmitter;
  8914. this.audioLevel = 0;
  8915. this.statisticsService = statisticsService;
  8916. }
  8917. /**
  8918. * Starts the collecting the statistics.
  8919. */
  8920. LocalStatsCollector.prototype.start = function () {
  8921. if (!window.AudioContext)
  8922. return;
  8923. var context = new AudioContext();
  8924. var analyser = context.createAnalyser();
  8925. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  8926. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  8927. var source = context.createMediaStreamSource(this.stream);
  8928. source.connect(analyser);
  8929. var self = this;
  8930. this.intervalId = setInterval(
  8931. function () {
  8932. var array = new Uint8Array(analyser.frequencyBinCount);
  8933. analyser.getByteTimeDomainData(array);
  8934. var audioLevel = timeDomainDataToAudioLevel(array);
  8935. if(audioLevel != self.audioLevel) {
  8936. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  8937. self.eventEmitter.emit(
  8938. "statistics.audioLevel",
  8939. self.statisticsService.LOCAL_JID,
  8940. self.audioLevel);
  8941. }
  8942. },
  8943. this.intervalMilis
  8944. );
  8945. };
  8946. /**
  8947. * Stops collecting the statistics.
  8948. */
  8949. LocalStatsCollector.prototype.stop = function () {
  8950. if (this.intervalId) {
  8951. clearInterval(this.intervalId);
  8952. this.intervalId = null;
  8953. }
  8954. };
  8955. module.exports = LocalStatsCollector;
  8956. },{}],44:[function(require,module,exports){
  8957. /* global ssrc2jid */
  8958. /* jshint -W117 */
  8959. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  8960. /**
  8961. * Calculates packet lost percent using the number of lost packets and the
  8962. * number of all packet.
  8963. * @param lostPackets the number of lost packets
  8964. * @param totalPackets the number of all packets.
  8965. * @returns {number} packet loss percent
  8966. */
  8967. function calculatePacketLoss(lostPackets, totalPackets) {
  8968. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  8969. return 0;
  8970. return Math.round((lostPackets/totalPackets)*100);
  8971. }
  8972. function getStatValue(item, name) {
  8973. if(!keyMap[APP.RTC.getBrowserType()][name])
  8974. throw "The property isn't supported!";
  8975. var key = keyMap[APP.RTC.getBrowserType()][name];
  8976. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  8977. }
  8978. /**
  8979. * Peer statistics data holder.
  8980. * @constructor
  8981. */
  8982. function PeerStats()
  8983. {
  8984. this.ssrc2Loss = {};
  8985. this.ssrc2AudioLevel = {};
  8986. this.ssrc2bitrate = {};
  8987. this.ssrc2resolution = {};
  8988. }
  8989. /**
  8990. * The bandwidth
  8991. * @type {{}}
  8992. */
  8993. PeerStats.bandwidth = {};
  8994. /**
  8995. * The bit rate
  8996. * @type {{}}
  8997. */
  8998. PeerStats.bitrate = {};
  8999. /**
  9000. * The packet loss rate
  9001. * @type {{}}
  9002. */
  9003. PeerStats.packetLoss = null;
  9004. /**
  9005. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9006. * represented by this instance.
  9007. * @param ssrc audio or video RTP stream SSRC.
  9008. * @param lossRate new packet loss rate value to be set.
  9009. */
  9010. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9011. {
  9012. this.ssrc2Loss[ssrc] = lossRate;
  9013. };
  9014. /**
  9015. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9016. * represented by this instance.
  9017. * @param ssrc audio or video RTP stream SSRC.
  9018. * @param resolution new resolution value to be set.
  9019. */
  9020. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9021. {
  9022. if(resolution === null && this.ssrc2resolution[ssrc])
  9023. {
  9024. delete this.ssrc2resolution[ssrc];
  9025. }
  9026. else if(resolution !== null)
  9027. this.ssrc2resolution[ssrc] = resolution;
  9028. };
  9029. /**
  9030. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9031. * represented by this instance.
  9032. * @param ssrc audio or video RTP stream SSRC.
  9033. * @param bitrate new bitrate value to be set.
  9034. */
  9035. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9036. {
  9037. if(this.ssrc2bitrate[ssrc])
  9038. {
  9039. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9040. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9041. }
  9042. else {
  9043. this.ssrc2bitrate[ssrc] = bitrate;
  9044. }
  9045. };
  9046. /**
  9047. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9048. * the stream which belongs to the peer represented by this instance.
  9049. * @param ssrc RTP stream SSRC for which current audio level value will be
  9050. * updated.
  9051. * @param audioLevel the new audio level value to be set. Value is truncated to
  9052. * fit the range from 0 to 1.
  9053. */
  9054. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9055. {
  9056. // Range limit 0 - 1
  9057. this.ssrc2AudioLevel[ssrc] = Math.min(Math.max(audioLevel, 0), 1);
  9058. };
  9059. /**
  9060. * Array with the transport information.
  9061. * @type {Array}
  9062. */
  9063. PeerStats.transport = [];
  9064. /**
  9065. * <tt>StatsCollector</tt> registers for stats updates of given
  9066. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9067. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9068. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9069. * instance as an event source.
  9070. *
  9071. * @param peerconnection webRTC peer connection object.
  9072. * @param interval stats refresh interval given in ms.
  9073. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9074. * called on stats update.
  9075. * @constructor
  9076. */
  9077. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9078. {
  9079. this.peerconnection = peerconnection;
  9080. this.baselineAudioLevelsReport = null;
  9081. this.currentAudioLevelsReport = null;
  9082. this.currentStatsReport = null;
  9083. this.baselineStatsReport = null;
  9084. this.audioLevelsIntervalId = null;
  9085. this.eventEmitter = eventEmitter;
  9086. /**
  9087. * Gather PeerConnection stats once every this many milliseconds.
  9088. */
  9089. this.GATHER_INTERVAL = 10000;
  9090. /**
  9091. * Log stats via the focus once every this many milliseconds.
  9092. */
  9093. this.LOG_INTERVAL = 60000;
  9094. /**
  9095. * Gather stats and store them in this.statsToBeLogged.
  9096. */
  9097. this.gatherStatsIntervalId = null;
  9098. /**
  9099. * Send the stats already saved in this.statsToBeLogged to be logged via
  9100. * the focus.
  9101. */
  9102. this.logStatsIntervalId = null;
  9103. /**
  9104. * Stores the statistics which will be send to the focus to be logged.
  9105. */
  9106. this.statsToBeLogged =
  9107. {
  9108. timestamps: [],
  9109. stats: {}
  9110. };
  9111. // Updates stats interval
  9112. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9113. this.statsIntervalId = null;
  9114. this.statsIntervalMilis = statsInterval;
  9115. // Map of jids to PeerStats
  9116. this.jid2stats = {};
  9117. }
  9118. module.exports = StatsCollector;
  9119. /**
  9120. * Stops stats updates.
  9121. */
  9122. StatsCollector.prototype.stop = function ()
  9123. {
  9124. if (this.audioLevelsIntervalId)
  9125. {
  9126. clearInterval(this.audioLevelsIntervalId);
  9127. this.audioLevelsIntervalId = null;
  9128. clearInterval(this.statsIntervalId);
  9129. this.statsIntervalId = null;
  9130. clearInterval(this.logStatsIntervalId);
  9131. this.logStatsIntervalId = null;
  9132. clearInterval(this.gatherStatsIntervalId);
  9133. this.gatherStatsIntervalId = null;
  9134. }
  9135. };
  9136. /**
  9137. * Callback passed to <tt>getStats</tt> method.
  9138. * @param error an error that occurred on <tt>getStats</tt> call.
  9139. */
  9140. StatsCollector.prototype.errorCallback = function (error)
  9141. {
  9142. console.error("Get stats error", error);
  9143. this.stop();
  9144. };
  9145. /**
  9146. * Starts stats updates.
  9147. */
  9148. StatsCollector.prototype.start = function ()
  9149. {
  9150. var self = this;
  9151. this.audioLevelsIntervalId = setInterval(
  9152. function ()
  9153. {
  9154. // Interval updates
  9155. self.peerconnection.getStats(
  9156. function (report)
  9157. {
  9158. var results = null;
  9159. if(!report || !report.result || typeof report.result != 'function')
  9160. {
  9161. results = report;
  9162. }
  9163. else
  9164. {
  9165. results = report.result();
  9166. }
  9167. //console.error("Got interval report", results);
  9168. self.currentAudioLevelsReport = results;
  9169. self.processAudioLevelReport();
  9170. self.baselineAudioLevelsReport =
  9171. self.currentAudioLevelsReport;
  9172. },
  9173. self.errorCallback
  9174. );
  9175. },
  9176. self.audioLevelsIntervalMilis
  9177. );
  9178. this.statsIntervalId = setInterval(
  9179. function () {
  9180. // Interval updates
  9181. self.peerconnection.getStats(
  9182. function (report)
  9183. {
  9184. var results = null;
  9185. if(!report || !report.result || typeof report.result != 'function')
  9186. {
  9187. //firefox
  9188. results = report;
  9189. }
  9190. else
  9191. {
  9192. //chrome
  9193. results = report.result();
  9194. }
  9195. //console.error("Got interval report", results);
  9196. self.currentStatsReport = results;
  9197. try
  9198. {
  9199. self.processStatsReport();
  9200. }
  9201. catch (e)
  9202. {
  9203. console.error("Unsupported key:" + e, e);
  9204. }
  9205. self.baselineStatsReport = self.currentStatsReport;
  9206. },
  9207. self.errorCallback
  9208. );
  9209. },
  9210. self.statsIntervalMilis
  9211. );
  9212. if (config.logStats) {
  9213. this.gatherStatsIntervalId = setInterval(
  9214. function () {
  9215. self.peerconnection.getStats(
  9216. function (report) {
  9217. self.addStatsToBeLogged(report.result());
  9218. },
  9219. function () {
  9220. }
  9221. );
  9222. },
  9223. this.GATHER_INTERVAL
  9224. );
  9225. this.logStatsIntervalId = setInterval(
  9226. function() { self.logStats(); },
  9227. this.LOG_INTERVAL);
  9228. }
  9229. };
  9230. /**
  9231. * Converts the stats to the format used for logging, and saves the data in
  9232. * this.statsToBeLogged.
  9233. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9234. */
  9235. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9236. var self = this;
  9237. var num_records = this.statsToBeLogged.timestamps.length;
  9238. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9239. reports.map(function (report) {
  9240. var stat = self.statsToBeLogged.stats[report.id];
  9241. if (!stat) {
  9242. stat = self.statsToBeLogged.stats[report.id] = {};
  9243. }
  9244. stat.type = report.type;
  9245. report.names().map(function (name) {
  9246. var values = stat[name];
  9247. if (!values) {
  9248. values = stat[name] = [];
  9249. }
  9250. while (values.length < num_records) {
  9251. values.push(null);
  9252. }
  9253. values.push(report.stat(name));
  9254. });
  9255. });
  9256. };
  9257. StatsCollector.prototype.logStats = function () {
  9258. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9259. return;
  9260. // Reset the stats
  9261. this.statsToBeLogged.stats = {};
  9262. this.statsToBeLogged.timestamps = [];
  9263. };
  9264. var keyMap = {};
  9265. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9266. "ssrc": "ssrc",
  9267. "packetsReceived": "packetsReceived",
  9268. "packetsLost": "packetsLost",
  9269. "packetsSent": "packetsSent",
  9270. "bytesReceived": "bytesReceived",
  9271. "bytesSent": "bytesSent"
  9272. };
  9273. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9274. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9275. "sendBandwidth": "googAvailableSendBandwidth",
  9276. "remoteAddress": "googRemoteAddress",
  9277. "transportType": "googTransportType",
  9278. "localAddress": "googLocalAddress",
  9279. "activeConnection": "googActiveConnection",
  9280. "ssrc": "ssrc",
  9281. "packetsReceived": "packetsReceived",
  9282. "packetsSent": "packetsSent",
  9283. "packetsLost": "packetsLost",
  9284. "bytesReceived": "bytesReceived",
  9285. "bytesSent": "bytesSent",
  9286. "googFrameHeightReceived": "googFrameHeightReceived",
  9287. "googFrameWidthReceived": "googFrameWidthReceived",
  9288. "googFrameHeightSent": "googFrameHeightSent",
  9289. "googFrameWidthSent": "googFrameWidthSent",
  9290. "audioInputLevel": "audioInputLevel",
  9291. "audioOutputLevel": "audioOutputLevel"
  9292. };
  9293. /**
  9294. * Stats processing logic.
  9295. */
  9296. StatsCollector.prototype.processStatsReport = function () {
  9297. if (!this.baselineStatsReport) {
  9298. return;
  9299. }
  9300. for (var idx in this.currentStatsReport) {
  9301. var now = this.currentStatsReport[idx];
  9302. try {
  9303. if (getStatValue(now, 'receiveBandwidth') ||
  9304. getStatValue(now, 'sendBandwidth')) {
  9305. PeerStats.bandwidth = {
  9306. "download": Math.round(
  9307. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9308. "upload": Math.round(
  9309. (getStatValue(now, 'sendBandwidth')) / 1000)
  9310. };
  9311. }
  9312. }
  9313. catch(e){/*not supported*/}
  9314. if(now.type == 'googCandidatePair')
  9315. {
  9316. var ip, type, localIP, active;
  9317. try {
  9318. ip = getStatValue(now, 'remoteAddress');
  9319. type = getStatValue(now, "transportType");
  9320. localIP = getStatValue(now, "localAddress");
  9321. active = getStatValue(now, "activeConnection");
  9322. }
  9323. catch(e){/*not supported*/}
  9324. if(!ip || !type || !localIP || active != "true")
  9325. continue;
  9326. var addressSaved = false;
  9327. for(var i = 0; i < PeerStats.transport.length; i++)
  9328. {
  9329. if(PeerStats.transport[i].ip == ip &&
  9330. PeerStats.transport[i].type == type &&
  9331. PeerStats.transport[i].localip == localIP)
  9332. {
  9333. addressSaved = true;
  9334. }
  9335. }
  9336. if(addressSaved)
  9337. continue;
  9338. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9339. continue;
  9340. }
  9341. if(now.type == "candidatepair")
  9342. {
  9343. if(now.state == "succeeded")
  9344. continue;
  9345. var local = this.currentStatsReport[now.localCandidateId];
  9346. var remote = this.currentStatsReport[now.remoteCandidateId];
  9347. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9348. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9349. }
  9350. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9351. now.type != "inboundrtp") {
  9352. continue;
  9353. }
  9354. var before = this.baselineStatsReport[idx];
  9355. if (!before) {
  9356. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9357. continue;
  9358. }
  9359. var ssrc = getStatValue(now, 'ssrc');
  9360. if(!ssrc)
  9361. continue;
  9362. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9363. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9364. console.warn("No jid for ssrc: " + ssrc);
  9365. continue;
  9366. }
  9367. var jidStats = this.jid2stats[jid];
  9368. if (!jidStats) {
  9369. jidStats = new PeerStats();
  9370. this.jid2stats[jid] = jidStats;
  9371. }
  9372. var isDownloadStream = true;
  9373. var key = 'packetsReceived';
  9374. if (!getStatValue(now, key))
  9375. {
  9376. isDownloadStream = false;
  9377. key = 'packetsSent';
  9378. if (!getStatValue(now, key))
  9379. {
  9380. console.warn("No packetsReceived nor packetSent stat found");
  9381. continue;
  9382. }
  9383. }
  9384. var packetsNow = getStatValue(now, key);
  9385. if(!packetsNow || packetsNow < 0)
  9386. packetsNow = 0;
  9387. var packetsBefore = getStatValue(before, key);
  9388. if(!packetsBefore || packetsBefore < 0)
  9389. packetsBefore = 0;
  9390. var packetRate = packetsNow - packetsBefore;
  9391. if(!packetRate || packetRate < 0)
  9392. packetRate = 0;
  9393. var currentLoss = getStatValue(now, 'packetsLost');
  9394. if(!currentLoss || currentLoss < 0)
  9395. currentLoss = 0;
  9396. var previousLoss = getStatValue(before, 'packetsLost');
  9397. if(!previousLoss || previousLoss < 0)
  9398. previousLoss = 0;
  9399. var lossRate = currentLoss - previousLoss;
  9400. if(!lossRate || lossRate < 0)
  9401. lossRate = 0;
  9402. var packetsTotal = (packetRate + lossRate);
  9403. jidStats.setSsrcLoss(ssrc,
  9404. {"packetsTotal": packetsTotal,
  9405. "packetsLost": lossRate,
  9406. "isDownloadStream": isDownloadStream});
  9407. var bytesReceived = 0, bytesSent = 0;
  9408. if(getStatValue(now, "bytesReceived"))
  9409. {
  9410. bytesReceived = getStatValue(now, "bytesReceived") -
  9411. getStatValue(before, "bytesReceived");
  9412. }
  9413. if(getStatValue(now, "bytesSent"))
  9414. {
  9415. bytesSent = getStatValue(now, "bytesSent") -
  9416. getStatValue(before, "bytesSent");
  9417. }
  9418. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9419. if(bytesReceived <= 0 || time <= 0)
  9420. {
  9421. bytesReceived = 0;
  9422. }
  9423. else
  9424. {
  9425. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9426. }
  9427. if(bytesSent <= 0 || time <= 0)
  9428. {
  9429. bytesSent = 0;
  9430. }
  9431. else
  9432. {
  9433. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9434. }
  9435. jidStats.setSsrcBitrate(ssrc, {
  9436. "download": bytesReceived,
  9437. "upload": bytesSent});
  9438. var resolution = {height: null, width: null};
  9439. try {
  9440. if (getStatValue(now, "googFrameHeightReceived") &&
  9441. getStatValue(now, "googFrameWidthReceived")) {
  9442. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9443. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9444. }
  9445. else if (getStatValue(now, "googFrameHeightSent") &&
  9446. getStatValue(now, "googFrameWidthSent")) {
  9447. resolution.height = getStatValue(now, "googFrameHeightSent");
  9448. resolution.width = getStatValue(now, "googFrameWidthSent");
  9449. }
  9450. }
  9451. catch(e){/*not supported*/}
  9452. if(resolution.height && resolution.width)
  9453. {
  9454. jidStats.setSsrcResolution(ssrc, resolution);
  9455. }
  9456. else
  9457. {
  9458. jidStats.setSsrcResolution(ssrc, null);
  9459. }
  9460. }
  9461. var self = this;
  9462. // Jid stats
  9463. var totalPackets = {download: 0, upload: 0};
  9464. var lostPackets = {download: 0, upload: 0};
  9465. var bitrateDownload = 0;
  9466. var bitrateUpload = 0;
  9467. var resolutions = {};
  9468. Object.keys(this.jid2stats).forEach(
  9469. function (jid)
  9470. {
  9471. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9472. function (ssrc)
  9473. {
  9474. var type = "upload";
  9475. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9476. type = "download";
  9477. totalPackets[type] +=
  9478. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9479. lostPackets[type] +=
  9480. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9481. }
  9482. );
  9483. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9484. function (ssrc) {
  9485. bitrateDownload +=
  9486. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9487. bitrateUpload +=
  9488. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9489. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9490. }
  9491. );
  9492. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9493. }
  9494. );
  9495. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9496. PeerStats.packetLoss = {
  9497. total:
  9498. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9499. totalPackets.download + totalPackets.upload),
  9500. download:
  9501. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9502. upload:
  9503. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9504. };
  9505. this.eventEmitter.emit("statistics.connectionstats",
  9506. {
  9507. "bitrate": PeerStats.bitrate,
  9508. "packetLoss": PeerStats.packetLoss,
  9509. "bandwidth": PeerStats.bandwidth,
  9510. "resolution": resolutions,
  9511. "transport": PeerStats.transport
  9512. });
  9513. PeerStats.transport = [];
  9514. };
  9515. /**
  9516. * Stats processing logic.
  9517. */
  9518. StatsCollector.prototype.processAudioLevelReport = function ()
  9519. {
  9520. if (!this.baselineAudioLevelsReport)
  9521. {
  9522. return;
  9523. }
  9524. for (var idx in this.currentAudioLevelsReport)
  9525. {
  9526. var now = this.currentAudioLevelsReport[idx];
  9527. if (now.type != 'ssrc')
  9528. {
  9529. continue;
  9530. }
  9531. var before = this.baselineAudioLevelsReport[idx];
  9532. if (!before)
  9533. {
  9534. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9535. continue;
  9536. }
  9537. var ssrc = getStatValue(now, 'ssrc');
  9538. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9539. if (!jid && (Date.now() - now.timestamp) < 3000)
  9540. {
  9541. console.warn("No jid for ssrc: " + ssrc);
  9542. continue;
  9543. }
  9544. var jidStats = this.jid2stats[jid];
  9545. if (!jidStats)
  9546. {
  9547. jidStats = new PeerStats();
  9548. this.jid2stats[jid] = jidStats;
  9549. }
  9550. // Audio level
  9551. var audioLevel = null;
  9552. try {
  9553. audioLevel = getStatValue(now, 'audioInputLevel');
  9554. if (!audioLevel)
  9555. audioLevel = getStatValue(now, 'audioOutputLevel');
  9556. }
  9557. catch(e) {/*not supported*/
  9558. console.warn("Audio Levels are not available in the statistics.");
  9559. clearInterval(this.audioLevelsIntervalId);
  9560. return;
  9561. }
  9562. if (audioLevel)
  9563. {
  9564. // TODO: can't find specs about what this value really is,
  9565. // but it seems to vary between 0 and around 32k.
  9566. audioLevel = audioLevel / 32767;
  9567. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  9568. if(jid != APP.xmpp.myJid())
  9569. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9570. }
  9571. }
  9572. };
  9573. },{"../../service/RTC/RTCBrowserType":77}],45:[function(require,module,exports){
  9574. /**
  9575. * Created by hristo on 8/4/14.
  9576. */
  9577. var LocalStats = require("./LocalStatsCollector.js");
  9578. var RTPStats = require("./RTPStatsCollector.js");
  9579. var EventEmitter = require("events");
  9580. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9581. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9582. var eventEmitter = new EventEmitter();
  9583. var localStats = null;
  9584. var rtpStats = null;
  9585. function stopLocal()
  9586. {
  9587. if(localStats)
  9588. {
  9589. localStats.stop();
  9590. localStats = null;
  9591. }
  9592. }
  9593. function stopRemote()
  9594. {
  9595. if(rtpStats)
  9596. {
  9597. rtpStats.stop();
  9598. eventEmitter.emit("statistics.stop");
  9599. rtpStats = null;
  9600. }
  9601. }
  9602. function startRemoteStats (peerconnection) {
  9603. if (config.enableRtpStats)
  9604. {
  9605. if(rtpStats)
  9606. {
  9607. rtpStats.stop();
  9608. rtpStats = null;
  9609. }
  9610. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9611. rtpStats.start();
  9612. }
  9613. }
  9614. function onStreamCreated(stream)
  9615. {
  9616. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9617. return;
  9618. localStats = new LocalStats(stream.getOriginalStream(), 100, statistics,
  9619. eventEmitter);
  9620. localStats.start();
  9621. }
  9622. function onDisposeConference(onUnload) {
  9623. stopRemote();
  9624. if(onUnload) {
  9625. stopLocal();
  9626. eventEmitter.removeAllListeners();
  9627. }
  9628. }
  9629. var statistics =
  9630. {
  9631. /**
  9632. * Indicates that this audio level is for local jid.
  9633. * @type {string}
  9634. */
  9635. LOCAL_JID: 'local',
  9636. addAudioLevelListener: function(listener)
  9637. {
  9638. eventEmitter.on("statistics.audioLevel", listener);
  9639. },
  9640. removeAudioLevelListener: function(listener)
  9641. {
  9642. eventEmitter.removeListener("statistics.audioLevel", listener);
  9643. },
  9644. addConnectionStatsListener: function(listener)
  9645. {
  9646. eventEmitter.on("statistics.connectionstats", listener);
  9647. },
  9648. removeConnectionStatsListener: function(listener)
  9649. {
  9650. eventEmitter.removeListener("statistics.connectionstats", listener);
  9651. },
  9652. addRemoteStatsStopListener: function(listener)
  9653. {
  9654. eventEmitter.on("statistics.stop", listener);
  9655. },
  9656. removeRemoteStatsStopListener: function(listener)
  9657. {
  9658. eventEmitter.removeListener("statistics.stop", listener);
  9659. },
  9660. stop: function () {
  9661. stopLocal();
  9662. stopRemote();
  9663. if(eventEmitter)
  9664. {
  9665. eventEmitter.removeAllListeners();
  9666. }
  9667. },
  9668. stopRemoteStatistics: function()
  9669. {
  9670. stopRemote();
  9671. },
  9672. start: function () {
  9673. APP.RTC.addStreamListener(onStreamCreated,
  9674. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  9675. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  9676. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  9677. startRemoteStats(event.peerconnection);
  9678. });
  9679. }
  9680. };
  9681. module.exports = statistics;
  9682. },{"../../service/RTC/StreamEventTypes.js":79,"../../service/xmpp/XMPPEvents":83,"./LocalStatsCollector.js":43,"./RTPStatsCollector.js":44,"events":84}],46:[function(require,module,exports){
  9683. /* jshint -W117 */
  9684. var TraceablePeerConnection = require("./TraceablePeerConnection");
  9685. var SDPDiffer = require("./SDPDiffer");
  9686. var SDPUtil = require("./SDPUtil");
  9687. var SDP = require("./SDP");
  9688. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9689. // Jingle stuff
  9690. function JingleSession(me, sid, connection, service) {
  9691. this.me = me;
  9692. this.sid = sid;
  9693. this.connection = connection;
  9694. this.initiator = null;
  9695. this.responder = null;
  9696. this.isInitiator = null;
  9697. this.peerjid = null;
  9698. this.state = null;
  9699. this.localSDP = null;
  9700. this.remoteSDP = null;
  9701. this.relayedStreams = [];
  9702. this.startTime = null;
  9703. this.stopTime = null;
  9704. this.media_constraints = null;
  9705. this.pc_constraints = null;
  9706. this.ice_config = {};
  9707. this.drip_container = [];
  9708. this.service = service;
  9709. this.usetrickle = true;
  9710. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  9711. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  9712. this.hadstuncandidate = false;
  9713. this.hadturncandidate = false;
  9714. this.lasticecandidate = false;
  9715. this.statsinterval = null;
  9716. this.reason = null;
  9717. this.addssrc = [];
  9718. this.removessrc = [];
  9719. this.pendingop = null;
  9720. this.switchstreams = false;
  9721. this.wait = true;
  9722. this.localStreamsSSRC = null;
  9723. /**
  9724. * The indicator which determines whether the (local) video has been muted
  9725. * in response to a user command in contrast to an automatic decision made
  9726. * by the application logic.
  9727. */
  9728. this.videoMuteByUser = false;
  9729. }
  9730. //TODO: this array must be removed when firefox implement multistream support
  9731. JingleSession.notReceivedSSRCs = [];
  9732. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  9733. var self = this;
  9734. if (this.state !== null) {
  9735. console.error('attempt to initiate on session ' + this.sid +
  9736. 'in state ' + this.state);
  9737. return;
  9738. }
  9739. this.isInitiator = isInitiator;
  9740. this.state = 'pending';
  9741. this.initiator = isInitiator ? this.me : peerjid;
  9742. this.responder = !isInitiator ? this.me : peerjid;
  9743. this.peerjid = peerjid;
  9744. this.hadstuncandidate = false;
  9745. this.hadturncandidate = false;
  9746. this.lasticecandidate = false;
  9747. this.peerconnection
  9748. = new TraceablePeerConnection(
  9749. this.connection.jingle.ice_config,
  9750. this.connection.jingle.pc_constraints );
  9751. this.peerconnection.onicecandidate = function (event) {
  9752. self.sendIceCandidate(event.candidate);
  9753. };
  9754. this.peerconnection.onaddstream = function (event) {
  9755. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  9756. self.remoteStreamAdded(event);
  9757. };
  9758. this.peerconnection.onremovestream = function (event) {
  9759. // Remove the stream from remoteStreams
  9760. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  9761. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  9762. };
  9763. this.peerconnection.onsignalingstatechange = function (event) {
  9764. if (!(self && self.peerconnection)) return;
  9765. };
  9766. this.peerconnection.oniceconnectionstatechange = function (event) {
  9767. if (!(self && self.peerconnection)) return;
  9768. switch (self.peerconnection.iceConnectionState) {
  9769. case 'connected':
  9770. this.startTime = new Date();
  9771. break;
  9772. case 'disconnected':
  9773. this.stopTime = new Date();
  9774. break;
  9775. }
  9776. onIceConnectionStateChange(self.sid, self);
  9777. };
  9778. // add any local and relayed stream
  9779. APP.RTC.localStreams.forEach(function(stream) {
  9780. self.peerconnection.addStream(stream.getOriginalStream());
  9781. });
  9782. this.relayedStreams.forEach(function(stream) {
  9783. self.peerconnection.addStream(stream);
  9784. });
  9785. };
  9786. function onIceConnectionStateChange(sid, session) {
  9787. switch (session.peerconnection.iceConnectionState) {
  9788. case 'checking':
  9789. session.timeChecking = (new Date()).getTime();
  9790. session.firstconnect = true;
  9791. break;
  9792. case 'completed': // on caller side
  9793. case 'connected':
  9794. if (session.firstconnect) {
  9795. session.firstconnect = false;
  9796. var metadata = {};
  9797. metadata.setupTime
  9798. = (new Date()).getTime() - session.timeChecking;
  9799. session.peerconnection.getStats(function (res) {
  9800. if(res && res.result) {
  9801. res.result().forEach(function (report) {
  9802. if (report.type == 'googCandidatePair' &&
  9803. report.stat('googActiveConnection') == 'true') {
  9804. metadata.localCandidateType
  9805. = report.stat('googLocalCandidateType');
  9806. metadata.remoteCandidateType
  9807. = report.stat('googRemoteCandidateType');
  9808. // log pair as well so we can get nice pie
  9809. // charts
  9810. metadata.candidatePair
  9811. = report.stat('googLocalCandidateType') +
  9812. ';' +
  9813. report.stat('googRemoteCandidateType');
  9814. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  9815. {
  9816. metadata.ipv6 = true;
  9817. }
  9818. }
  9819. });
  9820. }
  9821. });
  9822. }
  9823. break;
  9824. }
  9825. }
  9826. JingleSession.prototype.accept = function () {
  9827. var self = this;
  9828. this.state = 'active';
  9829. var pranswer = this.peerconnection.localDescription;
  9830. if (!pranswer || pranswer.type != 'pranswer') {
  9831. return;
  9832. }
  9833. console.log('going from pranswer to answer');
  9834. if (this.usetrickle) {
  9835. // remove candidates already sent from session-accept
  9836. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  9837. for (var i = 0; i < lines.length; i++) {
  9838. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  9839. }
  9840. }
  9841. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  9842. // FIXME: change any inactive to sendrecv or whatever they were originally
  9843. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  9844. }
  9845. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  9846. var prsdp = new SDP(pranswer.sdp);
  9847. var accept = $iq({to: this.peerjid,
  9848. type: 'set'})
  9849. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  9850. action: 'session-accept',
  9851. initiator: this.initiator,
  9852. responder: this.responder,
  9853. sid: this.sid });
  9854. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  9855. var sdp = this.peerconnection.localDescription.sdp;
  9856. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  9857. // FIXME: change any inactive to sendrecv or whatever they were originally
  9858. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  9859. }
  9860. var self = this;
  9861. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  9862. function () {
  9863. //console.log('setLocalDescription success');
  9864. self.setLocalDescription();
  9865. self.connection.sendIQ(accept,
  9866. function () {
  9867. var ack = {};
  9868. ack.source = 'answer';
  9869. $(document).trigger('ack.jingle', [self.sid, ack]);
  9870. },
  9871. function (stanza) {
  9872. var error = ($(stanza).find('error').length) ? {
  9873. code: $(stanza).find('error').attr('code'),
  9874. reason: $(stanza).find('error :first')[0].tagName
  9875. }:{};
  9876. error.source = 'answer';
  9877. JingleSession.onJingleError(self.sid, error);
  9878. },
  9879. 10000);
  9880. },
  9881. function (e) {
  9882. console.error('setLocalDescription failed', e);
  9883. }
  9884. );
  9885. };
  9886. JingleSession.prototype.terminate = function (reason) {
  9887. this.state = 'ended';
  9888. this.reason = reason;
  9889. this.peerconnection.close();
  9890. if (this.statsinterval !== null) {
  9891. window.clearInterval(this.statsinterval);
  9892. this.statsinterval = null;
  9893. }
  9894. };
  9895. JingleSession.prototype.active = function () {
  9896. return this.state == 'active';
  9897. };
  9898. JingleSession.prototype.sendIceCandidate = function (candidate) {
  9899. var self = this;
  9900. if (candidate && !this.lasticecandidate) {
  9901. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  9902. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  9903. if (!(ice && jcand)) {
  9904. console.error('failed to get ice && jcand');
  9905. return;
  9906. }
  9907. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9908. if (jcand.type === 'srflx') {
  9909. this.hadstuncandidate = true;
  9910. } else if (jcand.type === 'relay') {
  9911. this.hadturncandidate = true;
  9912. }
  9913. if (this.usetrickle) {
  9914. if (this.usedrip) {
  9915. if (this.drip_container.length === 0) {
  9916. // start 20ms callout
  9917. window.setTimeout(function () {
  9918. if (self.drip_container.length === 0) return;
  9919. self.sendIceCandidates(self.drip_container);
  9920. self.drip_container = [];
  9921. }, 20);
  9922. }
  9923. this.drip_container.push(candidate);
  9924. return;
  9925. } else {
  9926. self.sendIceCandidate([candidate]);
  9927. }
  9928. }
  9929. } else {
  9930. //console.log('sendIceCandidate: last candidate.');
  9931. if (!this.usetrickle) {
  9932. //console.log('should send full offer now...');
  9933. var init = $iq({to: this.peerjid,
  9934. type: 'set'})
  9935. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  9936. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  9937. initiator: this.initiator,
  9938. sid: this.sid});
  9939. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  9940. var self = this;
  9941. var sendJingle = function (ssrc) {
  9942. if(!ssrc)
  9943. ssrc = {};
  9944. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  9945. self.connection.sendIQ(init,
  9946. function () {
  9947. //console.log('session initiate ack');
  9948. var ack = {};
  9949. ack.source = 'offer';
  9950. $(document).trigger('ack.jingle', [self.sid, ack]);
  9951. },
  9952. function (stanza) {
  9953. self.state = 'error';
  9954. self.peerconnection.close();
  9955. var error = ($(stanza).find('error').length) ? {
  9956. code: $(stanza).find('error').attr('code'),
  9957. reason: $(stanza).find('error :first')[0].tagName,
  9958. }:{};
  9959. error.source = 'offer';
  9960. JingleSession.onJingleError(self.sid, error);
  9961. },
  9962. 10000);
  9963. }
  9964. sendJingle();
  9965. }
  9966. this.lasticecandidate = true;
  9967. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  9968. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  9969. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  9970. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  9971. }
  9972. }
  9973. };
  9974. JingleSession.prototype.sendIceCandidates = function (candidates) {
  9975. console.log('sendIceCandidates', candidates);
  9976. var cand = $iq({to: this.peerjid, type: 'set'})
  9977. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  9978. action: 'transport-info',
  9979. initiator: this.initiator,
  9980. sid: this.sid});
  9981. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  9982. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  9983. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  9984. if (cands.length > 0) {
  9985. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  9986. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9987. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  9988. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  9989. }).c('transport', ice);
  9990. for (var i = 0; i < cands.length; i++) {
  9991. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  9992. }
  9993. // add fingerprint
  9994. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  9995. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  9996. tmp.required = true;
  9997. cand.c(
  9998. 'fingerprint',
  9999. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10000. .t(tmp.fingerprint);
  10001. delete tmp.fingerprint;
  10002. cand.attrs(tmp);
  10003. cand.up();
  10004. }
  10005. cand.up(); // transport
  10006. cand.up(); // content
  10007. }
  10008. }
  10009. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10010. //console.log('was this the last candidate', this.lasticecandidate);
  10011. this.connection.sendIQ(cand,
  10012. function () {
  10013. var ack = {};
  10014. ack.source = 'transportinfo';
  10015. $(document).trigger('ack.jingle', [this.sid, ack]);
  10016. },
  10017. function (stanza) {
  10018. var error = ($(stanza).find('error').length) ? {
  10019. code: $(stanza).find('error').attr('code'),
  10020. reason: $(stanza).find('error :first')[0].tagName,
  10021. }:{};
  10022. error.source = 'transportinfo';
  10023. JingleSession.onJingleError(this.sid, error);
  10024. },
  10025. 10000);
  10026. };
  10027. JingleSession.prototype.sendOffer = function () {
  10028. //console.log('sendOffer...');
  10029. var self = this;
  10030. this.peerconnection.createOffer(function (sdp) {
  10031. self.createdOffer(sdp);
  10032. },
  10033. function (e) {
  10034. console.error('createOffer failed', e);
  10035. },
  10036. this.media_constraints
  10037. );
  10038. };
  10039. JingleSession.prototype.createdOffer = function (sdp) {
  10040. //console.log('createdOffer', sdp);
  10041. var self = this;
  10042. this.localSDP = new SDP(sdp.sdp);
  10043. //this.localSDP.mangle();
  10044. var sendJingle = function () {
  10045. var init = $iq({to: this.peerjid,
  10046. type: 'set'})
  10047. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10048. action: 'session-initiate',
  10049. initiator: this.initiator,
  10050. sid: this.sid});
  10051. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10052. self.connection.sendIQ(init,
  10053. function () {
  10054. var ack = {};
  10055. ack.source = 'offer';
  10056. $(document).trigger('ack.jingle', [self.sid, ack]);
  10057. },
  10058. function (stanza) {
  10059. self.state = 'error';
  10060. self.peerconnection.close();
  10061. var error = ($(stanza).find('error').length) ? {
  10062. code: $(stanza).find('error').attr('code'),
  10063. reason: $(stanza).find('error :first')[0].tagName,
  10064. }:{};
  10065. error.source = 'offer';
  10066. JingleSession.onJingleError(self.sid, error);
  10067. },
  10068. 10000);
  10069. }
  10070. sdp.sdp = this.localSDP.raw;
  10071. this.peerconnection.setLocalDescription(sdp,
  10072. function () {
  10073. if(self.usetrickle)
  10074. {
  10075. sendJingle();
  10076. }
  10077. self.setLocalDescription();
  10078. //console.log('setLocalDescription success');
  10079. },
  10080. function (e) {
  10081. console.error('setLocalDescription failed', e);
  10082. }
  10083. );
  10084. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10085. for (var i = 0; i < cands.length; i++) {
  10086. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10087. if (cand.type == 'srflx') {
  10088. this.hadstuncandidate = true;
  10089. } else if (cand.type == 'relay') {
  10090. this.hadturncandidate = true;
  10091. }
  10092. }
  10093. };
  10094. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10095. //console.log('setting remote description... ', desctype);
  10096. this.remoteSDP = new SDP('');
  10097. this.remoteSDP.fromJingle(elem);
  10098. if (this.peerconnection.remoteDescription !== null) {
  10099. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10100. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10101. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10102. for (var i = 0; i < pranswer.media.length; i++) {
  10103. // make sure we have ice ufrag and pwd
  10104. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10105. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10106. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10107. } else {
  10108. console.warn('no ice ufrag?');
  10109. }
  10110. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10111. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10112. } else {
  10113. console.warn('no ice pwd?');
  10114. }
  10115. }
  10116. // copy over candidates
  10117. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10118. for (var j = 0; j < lines.length; j++) {
  10119. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10120. }
  10121. }
  10122. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10123. }
  10124. }
  10125. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10126. this.peerconnection.setRemoteDescription(remotedesc,
  10127. function () {
  10128. //console.log('setRemoteDescription success');
  10129. },
  10130. function (e) {
  10131. console.error('setRemoteDescription error', e);
  10132. JingleSession.onJingleFatalError(self, e);
  10133. }
  10134. );
  10135. };
  10136. JingleSession.prototype.addIceCandidate = function (elem) {
  10137. var self = this;
  10138. if (this.peerconnection.signalingState == 'closed') {
  10139. return;
  10140. }
  10141. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10142. console.log('trickle ice candidate arriving before session accept...');
  10143. // create a PRANSWER for setRemoteDescription
  10144. if (!this.remoteSDP) {
  10145. var cobbled = 'v=0\r\n' +
  10146. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10147. 's=-\r\n' +
  10148. 't=0 0\r\n';
  10149. // first, take some things from the local description
  10150. for (var i = 0; i < this.localSDP.media.length; i++) {
  10151. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10152. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10153. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10154. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10155. }
  10156. cobbled += 'a=inactive\r\n';
  10157. }
  10158. this.remoteSDP = new SDP(cobbled);
  10159. }
  10160. // then add things like ice and dtls from remote candidate
  10161. elem.each(function () {
  10162. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10163. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10164. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10165. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10166. var tmp = $(this).find('transport');
  10167. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10168. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10169. tmp = $(this).find('transport>fingerprint');
  10170. if (tmp.length) {
  10171. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10172. } else {
  10173. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10174. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10175. }
  10176. break;
  10177. }
  10178. }
  10179. }
  10180. });
  10181. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10182. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10183. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10184. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10185. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10186. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10187. }).length == this.remoteSDP.media.length;
  10188. if (iscomplete) {
  10189. console.log('setting pranswer');
  10190. try {
  10191. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10192. function() {
  10193. },
  10194. function(e) {
  10195. console.log('setRemoteDescription pranswer failed', e.toString());
  10196. });
  10197. } catch (e) {
  10198. console.error('setting pranswer failed', e);
  10199. }
  10200. } else {
  10201. //console.log('not yet setting pranswer');
  10202. }
  10203. }
  10204. // operate on each content element
  10205. elem.each(function () {
  10206. // would love to deactivate this, but firefox still requires it
  10207. var idx = -1;
  10208. var i;
  10209. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10210. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10211. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10212. idx = i;
  10213. break;
  10214. }
  10215. }
  10216. if (idx == -1) { // fall back to localdescription
  10217. for (i = 0; i < self.localSDP.media.length; i++) {
  10218. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10219. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10220. idx = i;
  10221. break;
  10222. }
  10223. }
  10224. }
  10225. var name = $(this).attr('name');
  10226. // TODO: check ice-pwd and ice-ufrag?
  10227. $(this).find('transport>candidate').each(function () {
  10228. var line, candidate;
  10229. line = SDPUtil.candidateFromJingle(this);
  10230. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10231. sdpMid: name,
  10232. candidate: line});
  10233. try {
  10234. self.peerconnection.addIceCandidate(candidate);
  10235. } catch (e) {
  10236. console.error('addIceCandidate failed', e.toString(), line);
  10237. }
  10238. });
  10239. });
  10240. };
  10241. JingleSession.prototype.sendAnswer = function (provisional) {
  10242. //console.log('createAnswer', provisional);
  10243. var self = this;
  10244. this.peerconnection.createAnswer(
  10245. function (sdp) {
  10246. self.createdAnswer(sdp, provisional);
  10247. },
  10248. function (e) {
  10249. console.error('createAnswer failed', e);
  10250. },
  10251. this.media_constraints
  10252. );
  10253. };
  10254. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10255. //console.log('createAnswer callback');
  10256. var self = this;
  10257. this.localSDP = new SDP(sdp.sdp);
  10258. //this.localSDP.mangle();
  10259. this.usepranswer = provisional === true;
  10260. if (this.usetrickle) {
  10261. if (this.usepranswer) {
  10262. sdp.type = 'pranswer';
  10263. for (var i = 0; i < this.localSDP.media.length; i++) {
  10264. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10265. }
  10266. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10267. }
  10268. }
  10269. var self = this;
  10270. var sendJingle = function (ssrcs) {
  10271. var accept = $iq({to: self.peerjid,
  10272. type: 'set'})
  10273. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10274. action: 'session-accept',
  10275. initiator: self.initiator,
  10276. responder: self.responder,
  10277. sid: self.sid });
  10278. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10279. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10280. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10281. self.connection.sendIQ(accept,
  10282. function () {
  10283. var ack = {};
  10284. ack.source = 'answer';
  10285. $(document).trigger('ack.jingle', [self.sid, ack]);
  10286. },
  10287. function (stanza) {
  10288. var error = ($(stanza).find('error').length) ? {
  10289. code: $(stanza).find('error').attr('code'),
  10290. reason: $(stanza).find('error :first')[0].tagName,
  10291. }:{};
  10292. error.source = 'answer';
  10293. JingleSession.onJingleError(self.sid, error);
  10294. },
  10295. 10000);
  10296. }
  10297. sdp.sdp = this.localSDP.raw;
  10298. this.peerconnection.setLocalDescription(sdp,
  10299. function () {
  10300. //console.log('setLocalDescription success');
  10301. if (self.usetrickle && !self.usepranswer) {
  10302. sendJingle();
  10303. }
  10304. self.setLocalDescription();
  10305. },
  10306. function (e) {
  10307. console.error('setLocalDescription failed', e);
  10308. }
  10309. );
  10310. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10311. for (var j = 0; j < cands.length; j++) {
  10312. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10313. if (cand.type == 'srflx') {
  10314. this.hadstuncandidate = true;
  10315. } else if (cand.type == 'relay') {
  10316. this.hadturncandidate = true;
  10317. }
  10318. }
  10319. };
  10320. JingleSession.prototype.sendTerminate = function (reason, text) {
  10321. var self = this,
  10322. term = $iq({to: this.peerjid,
  10323. type: 'set'})
  10324. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10325. action: 'session-terminate',
  10326. initiator: this.initiator,
  10327. sid: this.sid})
  10328. .c('reason')
  10329. .c(reason || 'success');
  10330. if (text) {
  10331. term.up().c('text').t(text);
  10332. }
  10333. this.connection.sendIQ(term,
  10334. function () {
  10335. self.peerconnection.close();
  10336. self.peerconnection = null;
  10337. self.terminate();
  10338. var ack = {};
  10339. ack.source = 'terminate';
  10340. $(document).trigger('ack.jingle', [self.sid, ack]);
  10341. },
  10342. function (stanza) {
  10343. var error = ($(stanza).find('error').length) ? {
  10344. code: $(stanza).find('error').attr('code'),
  10345. reason: $(stanza).find('error :first')[0].tagName,
  10346. }:{};
  10347. $(document).trigger('ack.jingle', [self.sid, error]);
  10348. },
  10349. 10000);
  10350. if (this.statsinterval !== null) {
  10351. window.clearInterval(this.statsinterval);
  10352. this.statsinterval = null;
  10353. }
  10354. };
  10355. JingleSession.prototype.addSource = function (elem, fromJid) {
  10356. var self = this;
  10357. // FIXME: dirty waiting
  10358. if (!this.peerconnection.localDescription)
  10359. {
  10360. console.warn("addSource - localDescription not ready yet")
  10361. setTimeout(function()
  10362. {
  10363. self.addSource(elem, fromJid);
  10364. },
  10365. 200
  10366. );
  10367. return;
  10368. }
  10369. console.log('addssrc', new Date().getTime());
  10370. console.log('ice', this.peerconnection.iceConnectionState);
  10371. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10372. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10373. $(elem).each(function (idx, content) {
  10374. var name = $(content).attr('name');
  10375. var lines = '';
  10376. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10377. var semantics = this.getAttribute('semantics');
  10378. var ssrcs = $(this).find('>source').map(function () {
  10379. return this.getAttribute('ssrc');
  10380. }).get();
  10381. if (ssrcs.length != 0) {
  10382. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10383. }
  10384. });
  10385. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10386. tmp.each(function () {
  10387. var ssrc = $(this).attr('ssrc');
  10388. if(mySdp.containsSSRC(ssrc)){
  10389. /**
  10390. * This happens when multiple participants change their streams at the same time and
  10391. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10392. * addssrc are scheduled for update IQ. See
  10393. */
  10394. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10395. return;
  10396. }
  10397. $(this).find('>parameter').each(function () {
  10398. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10399. if ($(this).attr('value') && $(this).attr('value').length)
  10400. lines += ':' + $(this).attr('value');
  10401. lines += '\r\n';
  10402. });
  10403. });
  10404. sdp.media.forEach(function(media, idx) {
  10405. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10406. return;
  10407. sdp.media[idx] += lines;
  10408. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10409. self.addssrc[idx] += lines;
  10410. });
  10411. sdp.raw = sdp.session + sdp.media.join('');
  10412. });
  10413. this.modifySources();
  10414. };
  10415. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10416. var self = this;
  10417. // FIXME: dirty waiting
  10418. if (!this.peerconnection.localDescription)
  10419. {
  10420. console.warn("removeSource - localDescription not ready yet")
  10421. setTimeout(function()
  10422. {
  10423. self.removeSource(elem, fromJid);
  10424. },
  10425. 200
  10426. );
  10427. return;
  10428. }
  10429. console.log('removessrc', new Date().getTime());
  10430. console.log('ice', this.peerconnection.iceConnectionState);
  10431. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10432. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10433. $(elem).each(function (idx, content) {
  10434. var name = $(content).attr('name');
  10435. var lines = '';
  10436. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10437. var semantics = this.getAttribute('semantics');
  10438. var ssrcs = $(this).find('>source').map(function () {
  10439. return this.getAttribute('ssrc');
  10440. }).get();
  10441. if (ssrcs.length != 0) {
  10442. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10443. }
  10444. });
  10445. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10446. tmp.each(function () {
  10447. var ssrc = $(this).attr('ssrc');
  10448. // This should never happen, but can be useful for bug detection
  10449. if(mySdp.containsSSRC(ssrc)){
  10450. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10451. return;
  10452. }
  10453. $(this).find('>parameter').each(function () {
  10454. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10455. if ($(this).attr('value') && $(this).attr('value').length)
  10456. lines += ':' + $(this).attr('value');
  10457. lines += '\r\n';
  10458. });
  10459. });
  10460. sdp.media.forEach(function(media, idx) {
  10461. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10462. return;
  10463. sdp.media[idx] += lines;
  10464. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10465. self.removessrc[idx] += lines;
  10466. });
  10467. sdp.raw = sdp.session + sdp.media.join('');
  10468. });
  10469. this.modifySources();
  10470. };
  10471. JingleSession.prototype.modifySources = function (successCallback) {
  10472. var self = this;
  10473. if (this.peerconnection.signalingState == 'closed') return;
  10474. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10475. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10476. this.setLocalDescription();
  10477. if(successCallback){
  10478. successCallback();
  10479. }
  10480. return;
  10481. }
  10482. // FIXME: this is a big hack
  10483. // https://code.google.com/p/webrtc/issues/detail?id=2688
  10484. // ^ has been fixed.
  10485. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  10486. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  10487. this.wait = true;
  10488. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  10489. return;
  10490. }
  10491. if (this.wait) {
  10492. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  10493. this.wait = false;
  10494. return;
  10495. }
  10496. // Reset switch streams flag
  10497. this.switchstreams = false;
  10498. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10499. // add sources
  10500. this.addssrc.forEach(function(lines, idx) {
  10501. sdp.media[idx] += lines;
  10502. });
  10503. this.addssrc = [];
  10504. // remove sources
  10505. this.removessrc.forEach(function(lines, idx) {
  10506. lines = lines.split('\r\n');
  10507. lines.pop(); // remove empty last element;
  10508. lines.forEach(function(line) {
  10509. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  10510. });
  10511. });
  10512. this.removessrc = [];
  10513. // FIXME:
  10514. // this was a hack for the situation when only one peer exists
  10515. // in the conference.
  10516. // check if still required and remove
  10517. if (sdp.media[0])
  10518. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  10519. if (sdp.media[1])
  10520. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10521. sdp.raw = sdp.session + sdp.media.join('');
  10522. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  10523. function() {
  10524. if(self.signalingState == 'closed') {
  10525. console.error("createAnswer attempt on closed state");
  10526. return;
  10527. }
  10528. self.peerconnection.createAnswer(
  10529. function(modifiedAnswer) {
  10530. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  10531. if (self.pendingop !== null) {
  10532. var sdp = new SDP(modifiedAnswer.sdp);
  10533. if (sdp.media.length > 1) {
  10534. switch(self.pendingop) {
  10535. case 'mute':
  10536. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  10537. break;
  10538. case 'unmute':
  10539. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10540. break;
  10541. }
  10542. sdp.raw = sdp.session + sdp.media.join('');
  10543. modifiedAnswer.sdp = sdp.raw;
  10544. }
  10545. self.pendingop = null;
  10546. }
  10547. // FIXME: pushing down an answer while ice connection state
  10548. // is still checking is bad...
  10549. //console.log(self.peerconnection.iceConnectionState);
  10550. // trying to work around another chrome bug
  10551. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  10552. self.peerconnection.setLocalDescription(modifiedAnswer,
  10553. function() {
  10554. //console.log('modified setLocalDescription ok');
  10555. self.setLocalDescription();
  10556. if(successCallback){
  10557. successCallback();
  10558. }
  10559. },
  10560. function(error) {
  10561. console.error('modified setLocalDescription failed', error);
  10562. }
  10563. );
  10564. },
  10565. function(error) {
  10566. console.error('modified answer failed', error);
  10567. }
  10568. );
  10569. },
  10570. function(error) {
  10571. console.error('modify failed', error);
  10572. }
  10573. );
  10574. };
  10575. /**
  10576. * Switches video streams.
  10577. * @param new_stream new stream that will be used as video of this session.
  10578. * @param oldStream old video stream of this session.
  10579. * @param success_callback callback executed after successful stream switch.
  10580. */
  10581. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  10582. var self = this;
  10583. // Remember SDP to figure out added/removed SSRCs
  10584. var oldSdp = null;
  10585. if(self.peerconnection) {
  10586. if(self.peerconnection.localDescription) {
  10587. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  10588. }
  10589. self.peerconnection.removeStream(oldStream, true);
  10590. self.peerconnection.addStream(new_stream);
  10591. }
  10592. APP.RTC.switchVideoStreams(new_stream, oldStream);
  10593. // Conference is not active
  10594. if(!oldSdp || !self.peerconnection) {
  10595. success_callback();
  10596. return;
  10597. }
  10598. self.switchstreams = true;
  10599. self.modifySources(function() {
  10600. console.log('modify sources done');
  10601. success_callback();
  10602. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  10603. console.log("SDPs", oldSdp, newSdp);
  10604. self.notifyMySSRCUpdate(oldSdp, newSdp);
  10605. });
  10606. };
  10607. /**
  10608. * Figures out added/removed ssrcs and send update IQs.
  10609. * @param old_sdp SDP object for old description.
  10610. * @param new_sdp SDP object for new description.
  10611. */
  10612. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  10613. if (!(this.peerconnection.signalingState == 'stable' &&
  10614. this.peerconnection.iceConnectionState == 'connected')){
  10615. console.log("Too early to send updates");
  10616. return;
  10617. }
  10618. // send source-remove IQ.
  10619. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  10620. var remove = $iq({to: this.peerjid, type: 'set'})
  10621. .c('jingle', {
  10622. xmlns: 'urn:xmpp:jingle:1',
  10623. action: 'source-remove',
  10624. initiator: this.initiator,
  10625. sid: this.sid
  10626. }
  10627. );
  10628. var removed = sdpDiffer.toJingle(remove);
  10629. if (removed) {
  10630. this.connection.sendIQ(remove,
  10631. function (res) {
  10632. console.info('got remove result', res);
  10633. },
  10634. function (err) {
  10635. console.error('got remove error', err);
  10636. }
  10637. );
  10638. } else {
  10639. console.log('removal not necessary');
  10640. }
  10641. // send source-add IQ.
  10642. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  10643. var add = $iq({to: this.peerjid, type: 'set'})
  10644. .c('jingle', {
  10645. xmlns: 'urn:xmpp:jingle:1',
  10646. action: 'source-add',
  10647. initiator: this.initiator,
  10648. sid: this.sid
  10649. }
  10650. );
  10651. var added = sdpDiffer.toJingle(add);
  10652. if (added) {
  10653. this.connection.sendIQ(add,
  10654. function (res) {
  10655. console.info('got add result', res);
  10656. },
  10657. function (err) {
  10658. console.error('got add error', err);
  10659. }
  10660. );
  10661. } else {
  10662. console.log('addition not necessary');
  10663. }
  10664. };
  10665. /**
  10666. * Determines whether the (local) video is mute i.e. all video tracks are
  10667. * disabled.
  10668. *
  10669. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  10670. * disabled; otherwise, <tt>false</tt>
  10671. */
  10672. JingleSession.prototype.isVideoMute = function () {
  10673. var tracks = RTC.localVideo.getVideoTracks();
  10674. var mute = true;
  10675. for (var i = 0; i < tracks.length; ++i) {
  10676. if (tracks[i].enabled) {
  10677. mute = false;
  10678. break;
  10679. }
  10680. }
  10681. return mute;
  10682. };
  10683. /**
  10684. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  10685. *
  10686. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  10687. * tracks; otherwise, <tt>false</tt>
  10688. * @param callback a function to be invoked with <tt>mute</tt> after all video
  10689. * tracks have been enabled/disabled. The function may, optionally, return
  10690. * another function which is to be invoked after the whole mute/unmute operation
  10691. * has completed successfully.
  10692. * @param options an object which specifies optional arguments such as the
  10693. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  10694. * specifies whether the method was initiated in response to a user command (in
  10695. * contrast to an automatic decision made by the application logic)
  10696. */
  10697. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  10698. var byUser;
  10699. if (options) {
  10700. byUser = options.byUser;
  10701. if (typeof byUser === 'undefined') {
  10702. byUser = true;
  10703. }
  10704. } else {
  10705. byUser = true;
  10706. }
  10707. // The user's command to mute the (local) video takes precedence over any
  10708. // automatic decision made by the application logic.
  10709. if (byUser) {
  10710. this.videoMuteByUser = mute;
  10711. } else if (this.videoMuteByUser) {
  10712. return;
  10713. }
  10714. var self = this;
  10715. var localCallback = function (mute) {
  10716. self.connection.emuc.addVideoInfoToPresence(mute);
  10717. self.connection.emuc.sendPresence();
  10718. return callback(mute)
  10719. };
  10720. if (mute == RTC.localVideo.isMuted())
  10721. {
  10722. // Even if no change occurs, the specified callback is to be executed.
  10723. // The specified callback may, optionally, return a successCallback
  10724. // which is to be executed as well.
  10725. var successCallback = localCallback(mute);
  10726. if (successCallback) {
  10727. successCallback();
  10728. }
  10729. } else {
  10730. APP.RTC.localVideo.setMute(!mute);
  10731. this.hardMuteVideo(mute);
  10732. this.modifySources(localCallback(mute));
  10733. }
  10734. };
  10735. // SDP-based mute by going recvonly/sendrecv
  10736. // FIXME: should probably black out the screen as well
  10737. JingleSession.prototype.toggleVideoMute = function (callback) {
  10738. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  10739. };
  10740. JingleSession.prototype.hardMuteVideo = function (muted) {
  10741. this.pendingop = muted ? 'mute' : 'unmute';
  10742. };
  10743. JingleSession.prototype.sendMute = function (muted, content) {
  10744. var info = $iq({to: this.peerjid,
  10745. type: 'set'})
  10746. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10747. action: 'session-info',
  10748. initiator: this.initiator,
  10749. sid: this.sid });
  10750. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  10751. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  10752. if (content) {
  10753. info.attrs({'name': content});
  10754. }
  10755. this.connection.send(info);
  10756. };
  10757. JingleSession.prototype.sendRinging = function () {
  10758. var info = $iq({to: this.peerjid,
  10759. type: 'set'})
  10760. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10761. action: 'session-info',
  10762. initiator: this.initiator,
  10763. sid: this.sid });
  10764. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  10765. this.connection.send(info);
  10766. };
  10767. JingleSession.prototype.getStats = function (interval) {
  10768. var self = this;
  10769. var recv = {audio: 0, video: 0};
  10770. var lost = {audio: 0, video: 0};
  10771. var lastrecv = {audio: 0, video: 0};
  10772. var lastlost = {audio: 0, video: 0};
  10773. var loss = {audio: 0, video: 0};
  10774. var delta = {audio: 0, video: 0};
  10775. this.statsinterval = window.setInterval(function () {
  10776. if (self && self.peerconnection && self.peerconnection.getStats) {
  10777. self.peerconnection.getStats(function (stats) {
  10778. var results = stats.result();
  10779. // TODO: there are so much statistics you can get from this..
  10780. for (var i = 0; i < results.length; ++i) {
  10781. if (results[i].type == 'ssrc') {
  10782. var packetsrecv = results[i].stat('packetsReceived');
  10783. var packetslost = results[i].stat('packetsLost');
  10784. if (packetsrecv && packetslost) {
  10785. packetsrecv = parseInt(packetsrecv, 10);
  10786. packetslost = parseInt(packetslost, 10);
  10787. if (results[i].stat('googFrameRateReceived')) {
  10788. lastlost.video = lost.video;
  10789. lastrecv.video = recv.video;
  10790. recv.video = packetsrecv;
  10791. lost.video = packetslost;
  10792. } else {
  10793. lastlost.audio = lost.audio;
  10794. lastrecv.audio = recv.audio;
  10795. recv.audio = packetsrecv;
  10796. lost.audio = packetslost;
  10797. }
  10798. }
  10799. }
  10800. }
  10801. delta.audio = recv.audio - lastrecv.audio;
  10802. delta.video = recv.video - lastrecv.video;
  10803. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  10804. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  10805. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  10806. });
  10807. }
  10808. }, interval || 3000);
  10809. return this.statsinterval;
  10810. };
  10811. JingleSession.onJingleError = function (session, error)
  10812. {
  10813. console.error("Jingle error", error);
  10814. }
  10815. JingleSession.onJingleFatalError = function (session, error)
  10816. {
  10817. this.service.sessionTerminated = true;
  10818. this.connection.emuc.doLeave();
  10819. APP.UI.messageHandler.showError( "Sorry",
  10820. "Internal application error[setRemoteDescription]");
  10821. }
  10822. JingleSession.prototype.setLocalDescription = function () {
  10823. // put our ssrcs into presence so other clients can identify our stream
  10824. var newssrcs = [];
  10825. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  10826. media.forEach(function (media) {
  10827. if(Object.keys(media.sources).length > 0) {
  10828. // TODO(gp) maybe exclude FID streams?
  10829. Object.keys(media.sources).forEach(function (ssrc) {
  10830. newssrcs.push({
  10831. 'ssrc': ssrc,
  10832. 'type': media.type,
  10833. 'direction': media.direction
  10834. });
  10835. });
  10836. }
  10837. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  10838. {
  10839. newssrcs.push({
  10840. 'ssrc': this.localStreamsSSRC[media.type],
  10841. 'type': media.type,
  10842. 'direction': media.direction
  10843. });
  10844. }
  10845. });
  10846. console.log('new ssrcs', newssrcs);
  10847. // Have to clear presence map to get rid of removed streams
  10848. this.connection.emuc.clearPresenceMedia();
  10849. if (newssrcs.length > 0) {
  10850. for (var i = 1; i <= newssrcs.length; i ++) {
  10851. // Change video type to screen
  10852. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  10853. newssrcs[i-1].type = 'screen';
  10854. }
  10855. this.connection.emuc.addMediaToPresence(i,
  10856. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  10857. }
  10858. this.connection.emuc.sendPresence();
  10859. }
  10860. }
  10861. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  10862. function sendKeyframe(pc) {
  10863. console.log('sendkeyframe', pc.iceConnectionState);
  10864. if (pc.iceConnectionState !== 'connected') return; // safe...
  10865. pc.setRemoteDescription(
  10866. pc.remoteDescription,
  10867. function () {
  10868. pc.createAnswer(
  10869. function (modifiedAnswer) {
  10870. pc.setLocalDescription(
  10871. modifiedAnswer,
  10872. function () {
  10873. // noop
  10874. },
  10875. function (error) {
  10876. console.log('triggerKeyframe setLocalDescription failed', error);
  10877. UI.messageHandler.showError();
  10878. }
  10879. );
  10880. },
  10881. function (error) {
  10882. console.log('triggerKeyframe createAnswer failed', error);
  10883. UI.messageHandler.showError();
  10884. }
  10885. );
  10886. },
  10887. function (error) {
  10888. console.log('triggerKeyframe setRemoteDescription failed', error);
  10889. UI.messageHandler.showError();
  10890. }
  10891. );
  10892. }
  10893. JingleSession.prototype.remoteStreamAdded = function (data) {
  10894. var self = this;
  10895. var thessrc;
  10896. var ssrc2jid = this.connection.emuc.ssrc2jid;
  10897. // look up an associated JID for a stream id
  10898. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  10899. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  10900. var ssrclines
  10901. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  10902. ssrclines = ssrclines.filter(function (line) {
  10903. // NOTE(gp) previously we filtered on the mslabel, but that property
  10904. // is not always present.
  10905. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  10906. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  10907. });
  10908. if (ssrclines.length) {
  10909. thessrc = ssrclines[0].substring(7).split(' ')[0];
  10910. // We signal our streams (through Jingle to the focus) before we set
  10911. // our presence (through which peers associate remote streams to
  10912. // jids). So, it might arrive that a remote stream is added but
  10913. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  10914. // successfully set. Here we wait for up to a second for the
  10915. // presence to arrive.
  10916. if (!ssrc2jid[thessrc]) {
  10917. // TODO(gp) limit wait duration to 1 sec.
  10918. setTimeout(function(d) {
  10919. return function() {
  10920. self.remoteStreamAdded(d);
  10921. }
  10922. }(data), 250);
  10923. return;
  10924. }
  10925. // ok to overwrite the one from focus? might save work in colibri.js
  10926. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  10927. if (ssrc2jid[thessrc]) {
  10928. data.peerjid = ssrc2jid[thessrc];
  10929. }
  10930. }
  10931. }
  10932. //TODO: this code should be removed when firefox implement multistream support
  10933. if(APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  10934. {
  10935. if((JingleSession.notReceivedSSRCs.length == 0) ||
  10936. !ssrc2jid[JingleSession.notReceivedSSRCs[JingleSession.notReceivedSSRCs.length - 1]])
  10937. {
  10938. // TODO(gp) limit wait duration to 1 sec.
  10939. setTimeout(function(d) {
  10940. return function() {
  10941. self.remoteStreamAdded(d);
  10942. }
  10943. }(data), 250);
  10944. return;
  10945. }
  10946. thessrc = JingleSession.notReceivedSSRCs.pop();
  10947. if (ssrc2jid[thessrc]) {
  10948. data.peerjid = ssrc2jid[thessrc];
  10949. }
  10950. }
  10951. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  10952. var isVideo = data.stream.getVideoTracks().length > 0;
  10953. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  10954. if (isVideo &&
  10955. data.peerjid && this.peerjid === data.peerjid &&
  10956. data.stream.getVideoTracks().length === 0 &&
  10957. APP.RTC.localVideo.getTracks().length > 0) {
  10958. window.setTimeout(function () {
  10959. sendKeyframe(self.peerconnection);
  10960. }, 3000);
  10961. }
  10962. }
  10963. module.exports = JingleSession;
  10964. },{"../../service/RTC/RTCBrowserType":77,"./SDP":47,"./SDPDiffer":48,"./SDPUtil":49,"./TraceablePeerConnection":50}],47:[function(require,module,exports){
  10965. /* jshint -W117 */
  10966. var SDPUtil = require("./SDPUtil");
  10967. // SDP STUFF
  10968. function SDP(sdp) {
  10969. this.media = sdp.split('\r\nm=');
  10970. for (var i = 1; i < this.media.length; i++) {
  10971. this.media[i] = 'm=' + this.media[i];
  10972. if (i != this.media.length - 1) {
  10973. this.media[i] += '\r\n';
  10974. }
  10975. }
  10976. this.session = this.media.shift() + '\r\n';
  10977. this.raw = this.session + this.media.join('');
  10978. }
  10979. /**
  10980. * Returns map of MediaChannel mapped per channel idx.
  10981. */
  10982. SDP.prototype.getMediaSsrcMap = function() {
  10983. var self = this;
  10984. var media_ssrcs = {};
  10985. var tmp;
  10986. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  10987. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  10988. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  10989. var media = {
  10990. mediaindex: mediaindex,
  10991. mid: mid,
  10992. ssrcs: {},
  10993. ssrcGroups: []
  10994. };
  10995. media_ssrcs[mediaindex] = media;
  10996. tmp.forEach(function (line) {
  10997. var linessrc = line.substring(7).split(' ')[0];
  10998. // allocate new ChannelSsrc
  10999. if(!media.ssrcs[linessrc]) {
  11000. media.ssrcs[linessrc] = {
  11001. ssrc: linessrc,
  11002. lines: []
  11003. };
  11004. }
  11005. media.ssrcs[linessrc].lines.push(line);
  11006. });
  11007. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11008. tmp.forEach(function(line){
  11009. var semantics = line.substr(0, idx).substr(13);
  11010. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11011. if (ssrcs.length != 0) {
  11012. media.ssrcGroups.push({
  11013. semantics: semantics,
  11014. ssrcs: ssrcs
  11015. });
  11016. }
  11017. });
  11018. }
  11019. return media_ssrcs;
  11020. };
  11021. /**
  11022. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11023. * @param ssrc the ssrc to check.
  11024. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11025. */
  11026. SDP.prototype.containsSSRC = function(ssrc) {
  11027. var medias = this.getMediaSsrcMap();
  11028. var contains = false;
  11029. Object.keys(medias).forEach(function(mediaindex){
  11030. var media = medias[mediaindex];
  11031. //console.log("Check", channel, ssrc);
  11032. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11033. contains = true;
  11034. }
  11035. });
  11036. return contains;
  11037. };
  11038. // remove iSAC and CN from SDP
  11039. SDP.prototype.mangle = function () {
  11040. var i, j, mline, lines, rtpmap, newdesc;
  11041. for (i = 0; i < this.media.length; i++) {
  11042. lines = this.media[i].split('\r\n');
  11043. lines.pop(); // remove empty last element
  11044. mline = SDPUtil.parse_mline(lines.shift());
  11045. if (mline.media != 'audio')
  11046. continue;
  11047. newdesc = '';
  11048. mline.fmt.length = 0;
  11049. for (j = 0; j < lines.length; j++) {
  11050. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11051. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11052. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11053. continue;
  11054. mline.fmt.push(rtpmap.id);
  11055. newdesc += lines[j] + '\r\n';
  11056. } else {
  11057. newdesc += lines[j] + '\r\n';
  11058. }
  11059. }
  11060. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11061. this.media[i] += newdesc;
  11062. }
  11063. this.raw = this.session + this.media.join('');
  11064. };
  11065. // remove lines matching prefix from session section
  11066. SDP.prototype.removeSessionLines = function(prefix) {
  11067. var self = this;
  11068. var lines = SDPUtil.find_lines(this.session, prefix);
  11069. lines.forEach(function(line) {
  11070. self.session = self.session.replace(line + '\r\n', '');
  11071. });
  11072. this.raw = this.session + this.media.join('');
  11073. return lines;
  11074. }
  11075. // remove lines matching prefix from a media section specified by mediaindex
  11076. // TODO: non-numeric mediaindex could match mid
  11077. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11078. var self = this;
  11079. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11080. lines.forEach(function(line) {
  11081. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11082. });
  11083. this.raw = this.session + this.media.join('');
  11084. return lines;
  11085. }
  11086. // add content's to a jingle element
  11087. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11088. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11089. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11090. var self = this;
  11091. // new bundle plan
  11092. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11093. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11094. for (i = 0; i < lines.length; i++) {
  11095. tmp = lines[i].split(' ');
  11096. var semantics = tmp.shift().substr(8);
  11097. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11098. for (j = 0; j < tmp.length; j++) {
  11099. elem.c('content', {name: tmp[j]}).up();
  11100. }
  11101. elem.up();
  11102. }
  11103. }
  11104. for (i = 0; i < this.media.length; i++) {
  11105. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11106. if (!(mline.media === 'audio' ||
  11107. mline.media === 'video' ||
  11108. mline.media === 'application'))
  11109. {
  11110. continue;
  11111. }
  11112. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11113. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11114. } else {
  11115. if(ssrcs && ssrcs[mline.media])
  11116. {
  11117. ssrc = ssrcs[mline.media];
  11118. }
  11119. else
  11120. ssrc = false;
  11121. }
  11122. elem.c('content', {creator: thecreator, name: mline.media});
  11123. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11124. // prefer identifier from a=mid if present
  11125. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11126. elem.attrs({ name: mid });
  11127. }
  11128. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11129. {
  11130. elem.c('description',
  11131. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11132. media: mline.media });
  11133. if (ssrc) {
  11134. elem.attrs({ssrc: ssrc});
  11135. }
  11136. for (j = 0; j < mline.fmt.length; j++) {
  11137. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11138. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11139. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11140. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11141. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11142. for (k = 0; k < tmp.length; k++) {
  11143. elem.c('parameter', tmp[k]).up();
  11144. }
  11145. }
  11146. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11147. elem.up();
  11148. }
  11149. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11150. elem.c('encryption', {required: 1});
  11151. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11152. crypto.forEach(function(line) {
  11153. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11154. });
  11155. elem.up(); // end of encryption
  11156. }
  11157. if (ssrc) {
  11158. // new style mapping
  11159. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11160. // FIXME: group by ssrc and support multiple different ssrcs
  11161. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11162. if(ssrclines.length > 0) {
  11163. ssrclines.forEach(function (line) {
  11164. idx = line.indexOf(' ');
  11165. var linessrc = line.substr(0, idx).substr(7);
  11166. if (linessrc != ssrc) {
  11167. elem.up();
  11168. ssrc = linessrc;
  11169. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11170. }
  11171. var kv = line.substr(idx + 1);
  11172. elem.c('parameter');
  11173. if (kv.indexOf(':') == -1) {
  11174. elem.attrs({ name: kv });
  11175. } else {
  11176. elem.attrs({ name: kv.split(':', 2)[0] });
  11177. elem.attrs({ value: kv.split(':', 2)[1] });
  11178. }
  11179. elem.up();
  11180. });
  11181. elem.up();
  11182. }
  11183. else
  11184. {
  11185. elem.up();
  11186. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11187. elem.c('parameter');
  11188. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11189. elem.up();
  11190. var msid = null;
  11191. if(mline.media == "audio")
  11192. {
  11193. msid = APP.RTC.localAudio.getId();
  11194. }
  11195. else
  11196. {
  11197. msid = APP.RTC.localVideo.getId();
  11198. }
  11199. if(msid != null)
  11200. {
  11201. msid = msid.replace(/[\{,\}]/g,"");
  11202. elem.c('parameter');
  11203. elem.attrs({name: "msid", value:msid});
  11204. elem.up();
  11205. elem.c('parameter');
  11206. elem.attrs({name: "mslabel", value:msid});
  11207. elem.up();
  11208. elem.c('parameter');
  11209. elem.attrs({name: "label", value:msid});
  11210. elem.up();
  11211. elem.up();
  11212. }
  11213. }
  11214. // XEP-0339 handle ssrc-group attributes
  11215. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11216. ssrc_group_lines.forEach(function(line) {
  11217. idx = line.indexOf(' ');
  11218. var semantics = line.substr(0, idx).substr(13);
  11219. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11220. if (ssrcs.length != 0) {
  11221. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11222. ssrcs.forEach(function(ssrc) {
  11223. elem.c('source', { ssrc: ssrc })
  11224. .up();
  11225. });
  11226. elem.up();
  11227. }
  11228. });
  11229. }
  11230. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11231. elem.c('rtcp-mux').up();
  11232. }
  11233. // XEP-0293 -- map a=rtcp-fb:*
  11234. this.RtcpFbToJingle(i, elem, '*');
  11235. // XEP-0294
  11236. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11237. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11238. for (j = 0; j < lines.length; j++) {
  11239. tmp = SDPUtil.parse_extmap(lines[j]);
  11240. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11241. uri: tmp.uri,
  11242. id: tmp.value });
  11243. if (tmp.hasOwnProperty('direction')) {
  11244. switch (tmp.direction) {
  11245. case 'sendonly':
  11246. elem.attrs({senders: 'responder'});
  11247. break;
  11248. case 'recvonly':
  11249. elem.attrs({senders: 'initiator'});
  11250. break;
  11251. case 'sendrecv':
  11252. elem.attrs({senders: 'both'});
  11253. break;
  11254. case 'inactive':
  11255. elem.attrs({senders: 'none'});
  11256. break;
  11257. }
  11258. }
  11259. // TODO: handle params
  11260. elem.up();
  11261. }
  11262. }
  11263. elem.up(); // end of description
  11264. }
  11265. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11266. this.TransportToJingle(i, elem);
  11267. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11268. elem.attrs({senders: 'both'});
  11269. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11270. elem.attrs({senders: 'initiator'});
  11271. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11272. elem.attrs({senders: 'responder'});
  11273. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11274. elem.attrs({senders: 'none'});
  11275. }
  11276. if (mline.port == '0') {
  11277. // estos hack to reject an m-line
  11278. elem.attrs({senders: 'rejected'});
  11279. }
  11280. elem.up(); // end of content
  11281. }
  11282. elem.up();
  11283. return elem;
  11284. };
  11285. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11286. var i = mediaindex;
  11287. var tmp;
  11288. var self = this;
  11289. elem.c('transport');
  11290. // XEP-0343 DTLS/SCTP
  11291. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11292. {
  11293. var sctpmap = SDPUtil.find_line(
  11294. this.media[i], 'a=sctpmap:', self.session);
  11295. if (sctpmap)
  11296. {
  11297. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11298. elem.c('sctpmap',
  11299. {
  11300. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11301. number: sctpAttrs[0], /* SCTP port */
  11302. protocol: sctpAttrs[1], /* protocol */
  11303. });
  11304. // Optional stream count attribute
  11305. if (sctpAttrs.length > 2)
  11306. elem.attrs({ streams: sctpAttrs[2]});
  11307. elem.up();
  11308. }
  11309. }
  11310. // XEP-0320
  11311. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11312. fingerprints.forEach(function(line) {
  11313. tmp = SDPUtil.parse_fingerprint(line);
  11314. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11315. elem.c('fingerprint').t(tmp.fingerprint);
  11316. delete tmp.fingerprint;
  11317. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11318. if (line) {
  11319. tmp.setup = line.substr(8);
  11320. }
  11321. elem.attrs(tmp);
  11322. elem.up(); // end of fingerprint
  11323. });
  11324. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11325. if (tmp) {
  11326. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11327. elem.attrs(tmp);
  11328. // XEP-0176
  11329. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11330. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11331. lines.forEach(function (line) {
  11332. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11333. });
  11334. }
  11335. }
  11336. elem.up(); // end of transport
  11337. }
  11338. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11339. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11340. lines.forEach(function (line) {
  11341. var tmp = SDPUtil.parse_rtcpfb(line);
  11342. if (tmp.type == 'trr-int') {
  11343. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11344. elem.up();
  11345. } else {
  11346. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11347. if (tmp.params.length > 0) {
  11348. elem.attrs({'subtype': tmp.params[0]});
  11349. }
  11350. elem.up();
  11351. }
  11352. });
  11353. };
  11354. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11355. var media = '';
  11356. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11357. if (tmp.length) {
  11358. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11359. if (tmp.attr('value')) {
  11360. media += tmp.attr('value');
  11361. } else {
  11362. media += '0';
  11363. }
  11364. media += '\r\n';
  11365. }
  11366. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11367. tmp.each(function () {
  11368. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11369. if ($(this).attr('subtype')) {
  11370. media += ' ' + $(this).attr('subtype');
  11371. }
  11372. media += '\r\n';
  11373. });
  11374. return media;
  11375. };
  11376. // construct an SDP from a jingle stanza
  11377. SDP.prototype.fromJingle = function (jingle) {
  11378. var self = this;
  11379. this.raw = 'v=0\r\n' +
  11380. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11381. 's=-\r\n' +
  11382. 't=0 0\r\n';
  11383. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11384. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11385. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11386. var contents = $(group).find('>content').map(function (idx, content) {
  11387. return content.getAttribute('name');
  11388. }).get();
  11389. if (contents.length > 0) {
  11390. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11391. }
  11392. });
  11393. }
  11394. this.session = this.raw;
  11395. jingle.find('>content').each(function () {
  11396. var m = self.jingle2media($(this));
  11397. self.media.push(m);
  11398. });
  11399. // reconstruct msid-semantic -- apparently not necessary
  11400. /*
  11401. var msid = SDPUtil.parse_ssrc(this.raw);
  11402. if (msid.hasOwnProperty('mslabel')) {
  11403. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11404. }
  11405. */
  11406. this.raw = this.session + this.media.join('');
  11407. };
  11408. // translate a jingle content element into an an SDP media part
  11409. SDP.prototype.jingle2media = function (content) {
  11410. var media = '',
  11411. desc = content.find('description'),
  11412. ssrc = desc.attr('ssrc'),
  11413. self = this,
  11414. tmp;
  11415. var sctp = content.find(
  11416. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11417. tmp = { media: desc.attr('media') };
  11418. tmp.port = '1';
  11419. if (content.attr('senders') == 'rejected') {
  11420. // estos hack to reject an m-line.
  11421. tmp.port = '0';
  11422. }
  11423. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11424. if (sctp.length)
  11425. tmp.proto = 'DTLS/SCTP';
  11426. else
  11427. tmp.proto = 'RTP/SAVPF';
  11428. } else {
  11429. tmp.proto = 'RTP/AVPF';
  11430. }
  11431. if (!sctp.length)
  11432. {
  11433. tmp.fmt = desc.find('payload-type').map(
  11434. function () { return this.getAttribute('id'); }).get();
  11435. media += SDPUtil.build_mline(tmp) + '\r\n';
  11436. }
  11437. else
  11438. {
  11439. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11440. media += 'a=sctpmap:' + sctp.attr('number') +
  11441. ' ' + sctp.attr('protocol');
  11442. var streamCount = sctp.attr('streams');
  11443. if (streamCount)
  11444. media += ' ' + streamCount + '\r\n';
  11445. else
  11446. media += '\r\n';
  11447. }
  11448. media += 'c=IN IP4 0.0.0.0\r\n';
  11449. if (!sctp.length)
  11450. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11451. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11452. if (tmp.length) {
  11453. if (tmp.attr('ufrag')) {
  11454. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11455. }
  11456. if (tmp.attr('pwd')) {
  11457. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11458. }
  11459. tmp.find('>fingerprint').each(function () {
  11460. // FIXME: check namespace at some point
  11461. media += 'a=fingerprint:' + this.getAttribute('hash');
  11462. media += ' ' + $(this).text();
  11463. media += '\r\n';
  11464. if (this.getAttribute('setup')) {
  11465. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11466. }
  11467. });
  11468. }
  11469. switch (content.attr('senders')) {
  11470. case 'initiator':
  11471. media += 'a=sendonly\r\n';
  11472. break;
  11473. case 'responder':
  11474. media += 'a=recvonly\r\n';
  11475. break;
  11476. case 'none':
  11477. media += 'a=inactive\r\n';
  11478. break;
  11479. case 'both':
  11480. media += 'a=sendrecv\r\n';
  11481. break;
  11482. }
  11483. media += 'a=mid:' + content.attr('name') + '\r\n';
  11484. // <description><rtcp-mux/></description>
  11485. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11486. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11487. if (desc.find('rtcp-mux').length) {
  11488. media += 'a=rtcp-mux\r\n';
  11489. }
  11490. if (desc.find('encryption').length) {
  11491. desc.find('encryption>crypto').each(function () {
  11492. media += 'a=crypto:' + this.getAttribute('tag');
  11493. media += ' ' + this.getAttribute('crypto-suite');
  11494. media += ' ' + this.getAttribute('key-params');
  11495. if (this.getAttribute('session-params')) {
  11496. media += ' ' + this.getAttribute('session-params');
  11497. }
  11498. media += '\r\n';
  11499. });
  11500. }
  11501. desc.find('payload-type').each(function () {
  11502. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11503. if ($(this).find('>parameter').length) {
  11504. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11505. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11506. media += '\r\n';
  11507. }
  11508. // xep-0293
  11509. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11510. });
  11511. // xep-0293
  11512. media += self.RtcpFbFromJingle(desc, '*');
  11513. // xep-0294
  11514. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11515. tmp.each(function () {
  11516. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11517. });
  11518. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  11519. media += SDPUtil.candidateFromJingle(this);
  11520. });
  11521. // XEP-0339 handle ssrc-group attributes
  11522. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11523. var semantics = this.getAttribute('semantics');
  11524. var ssrcs = $(this).find('>source').map(function() {
  11525. return this.getAttribute('ssrc');
  11526. }).get();
  11527. if (ssrcs.length != 0) {
  11528. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11529. }
  11530. });
  11531. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11532. tmp.each(function () {
  11533. var ssrc = this.getAttribute('ssrc');
  11534. $(this).find('>parameter').each(function () {
  11535. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  11536. if (this.getAttribute('value') && this.getAttribute('value').length)
  11537. media += ':' + this.getAttribute('value');
  11538. media += '\r\n';
  11539. });
  11540. });
  11541. return media;
  11542. };
  11543. module.exports = SDP;
  11544. },{"./SDPUtil":49}],48:[function(require,module,exports){
  11545. function SDPDiffer(mySDP, otherSDP) {
  11546. this.mySDP = mySDP;
  11547. this.otherSDP = otherSDP;
  11548. }
  11549. /**
  11550. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  11551. * @param otherSdp the other SDP to check ssrc with.
  11552. */
  11553. SDPDiffer.prototype.getNewMedia = function() {
  11554. // this could be useful in Array.prototype.
  11555. function arrayEquals(array) {
  11556. // if the other array is a falsy value, return
  11557. if (!array)
  11558. return false;
  11559. // compare lengths - can save a lot of time
  11560. if (this.length != array.length)
  11561. return false;
  11562. for (var i = 0, l=this.length; i < l; i++) {
  11563. // Check if we have nested arrays
  11564. if (this[i] instanceof Array && array[i] instanceof Array) {
  11565. // recurse into the nested arrays
  11566. if (!this[i].equals(array[i]))
  11567. return false;
  11568. }
  11569. else if (this[i] != array[i]) {
  11570. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  11571. return false;
  11572. }
  11573. }
  11574. return true;
  11575. }
  11576. var myMedias = this.mySDP.getMediaSsrcMap();
  11577. var othersMedias = this.otherSDP.getMediaSsrcMap();
  11578. var newMedia = {};
  11579. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  11580. var myMedia = myMedias[othersMediaIdx];
  11581. var othersMedia = othersMedias[othersMediaIdx];
  11582. if(!myMedia && othersMedia) {
  11583. // Add whole channel
  11584. newMedia[othersMediaIdx] = othersMedia;
  11585. return;
  11586. }
  11587. // Look for new ssrcs accross the channel
  11588. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  11589. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  11590. // Allocate channel if we've found ssrc that doesn't exist in our channel
  11591. if(!newMedia[othersMediaIdx]){
  11592. newMedia[othersMediaIdx] = {
  11593. mediaindex: othersMedia.mediaindex,
  11594. mid: othersMedia.mid,
  11595. ssrcs: {},
  11596. ssrcGroups: []
  11597. };
  11598. }
  11599. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  11600. }
  11601. });
  11602. // Look for new ssrc groups across the channels
  11603. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  11604. // try to match the other ssrc-group with an ssrc-group of ours
  11605. var matched = false;
  11606. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  11607. var mySsrcGroup = myMedia.ssrcGroups[i];
  11608. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  11609. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  11610. matched = true;
  11611. break;
  11612. }
  11613. }
  11614. if (!matched) {
  11615. // Allocate channel if we've found an ssrc-group that doesn't
  11616. // exist in our channel
  11617. if(!newMedia[othersMediaIdx]){
  11618. newMedia[othersMediaIdx] = {
  11619. mediaindex: othersMedia.mediaindex,
  11620. mid: othersMedia.mid,
  11621. ssrcs: {},
  11622. ssrcGroups: []
  11623. };
  11624. }
  11625. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  11626. }
  11627. });
  11628. });
  11629. return newMedia;
  11630. };
  11631. /**
  11632. * Sends SSRC update IQ.
  11633. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  11634. * @param sid session identifier that will be put into the IQ.
  11635. * @param initiator initiator identifier.
  11636. * @param toJid destination Jid
  11637. * @param isAdd indicates if this is remove or add operation.
  11638. */
  11639. SDPDiffer.prototype.toJingle = function(modify) {
  11640. var sdpMediaSsrcs = this.getNewMedia();
  11641. var self = this;
  11642. // FIXME: only announce video ssrcs since we mix audio and dont need
  11643. // the audio ssrcs therefore
  11644. var modified = false;
  11645. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  11646. modified = true;
  11647. var media = sdpMediaSsrcs[mediaindex];
  11648. modify.c('content', {name: media.mid});
  11649. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  11650. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  11651. // generate sources from lines
  11652. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  11653. var mediaSsrc = media.ssrcs[ssrcNum];
  11654. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11655. modify.attrs({ssrc: mediaSsrc.ssrc});
  11656. // iterate over ssrc lines
  11657. mediaSsrc.lines.forEach(function (line) {
  11658. var idx = line.indexOf(' ');
  11659. var kv = line.substr(idx + 1);
  11660. modify.c('parameter');
  11661. if (kv.indexOf(':') == -1) {
  11662. modify.attrs({ name: kv });
  11663. } else {
  11664. modify.attrs({ name: kv.split(':', 2)[0] });
  11665. modify.attrs({ value: kv.split(':', 2)[1] });
  11666. }
  11667. modify.up(); // end of parameter
  11668. });
  11669. modify.up(); // end of source
  11670. });
  11671. // generate source groups from lines
  11672. media.ssrcGroups.forEach(function(ssrcGroup) {
  11673. if (ssrcGroup.ssrcs.length != 0) {
  11674. modify.c('ssrc-group', {
  11675. semantics: ssrcGroup.semantics,
  11676. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  11677. });
  11678. ssrcGroup.ssrcs.forEach(function (ssrc) {
  11679. modify.c('source', { ssrc: ssrc })
  11680. .up(); // end of source
  11681. });
  11682. modify.up(); // end of ssrc-group
  11683. }
  11684. });
  11685. modify.up(); // end of description
  11686. modify.up(); // end of content
  11687. });
  11688. return modified;
  11689. };
  11690. module.exports = SDPDiffer;
  11691. },{}],49:[function(require,module,exports){
  11692. SDPUtil = {
  11693. iceparams: function (mediadesc, sessiondesc) {
  11694. var data = null;
  11695. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  11696. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  11697. data = {
  11698. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  11699. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  11700. };
  11701. }
  11702. return data;
  11703. },
  11704. parse_iceufrag: function (line) {
  11705. return line.substring(12);
  11706. },
  11707. build_iceufrag: function (frag) {
  11708. return 'a=ice-ufrag:' + frag;
  11709. },
  11710. parse_icepwd: function (line) {
  11711. return line.substring(10);
  11712. },
  11713. build_icepwd: function (pwd) {
  11714. return 'a=ice-pwd:' + pwd;
  11715. },
  11716. parse_mid: function (line) {
  11717. return line.substring(6);
  11718. },
  11719. parse_mline: function (line) {
  11720. var parts = line.substring(2).split(' '),
  11721. data = {};
  11722. data.media = parts.shift();
  11723. data.port = parts.shift();
  11724. data.proto = parts.shift();
  11725. if (parts[parts.length - 1] === '') { // trailing whitespace
  11726. parts.pop();
  11727. }
  11728. data.fmt = parts;
  11729. return data;
  11730. },
  11731. build_mline: function (mline) {
  11732. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  11733. },
  11734. parse_rtpmap: function (line) {
  11735. var parts = line.substring(9).split(' '),
  11736. data = {};
  11737. data.id = parts.shift();
  11738. parts = parts[0].split('/');
  11739. data.name = parts.shift();
  11740. data.clockrate = parts.shift();
  11741. data.channels = parts.length ? parts.shift() : '1';
  11742. return data;
  11743. },
  11744. /**
  11745. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  11746. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  11747. * @returns [SCTP port number, protocol, streams]
  11748. */
  11749. parse_sctpmap: function (line)
  11750. {
  11751. var parts = line.substring(10).split(' ');
  11752. var sctpPort = parts[0];
  11753. var protocol = parts[1];
  11754. // Stream count is optional
  11755. var streamCount = parts.length > 2 ? parts[2] : null;
  11756. return [sctpPort, protocol, streamCount];// SCTP port
  11757. },
  11758. build_rtpmap: function (el) {
  11759. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  11760. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  11761. line += '/' + el.getAttribute('channels');
  11762. }
  11763. return line;
  11764. },
  11765. parse_crypto: function (line) {
  11766. var parts = line.substring(9).split(' '),
  11767. data = {};
  11768. data.tag = parts.shift();
  11769. data['crypto-suite'] = parts.shift();
  11770. data['key-params'] = parts.shift();
  11771. if (parts.length) {
  11772. data['session-params'] = parts.join(' ');
  11773. }
  11774. return data;
  11775. },
  11776. parse_fingerprint: function (line) { // RFC 4572
  11777. var parts = line.substring(14).split(' '),
  11778. data = {};
  11779. data.hash = parts.shift();
  11780. data.fingerprint = parts.shift();
  11781. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  11782. return data;
  11783. },
  11784. parse_fmtp: function (line) {
  11785. var parts = line.split(' '),
  11786. i, key, value,
  11787. data = [];
  11788. parts.shift();
  11789. parts = parts.join(' ').split(';');
  11790. for (i = 0; i < parts.length; i++) {
  11791. key = parts[i].split('=')[0];
  11792. while (key.length && key[0] == ' ') {
  11793. key = key.substring(1);
  11794. }
  11795. value = parts[i].split('=')[1];
  11796. if (key && value) {
  11797. data.push({name: key, value: value});
  11798. } else if (key) {
  11799. // rfc 4733 (DTMF) style stuff
  11800. data.push({name: '', value: key});
  11801. }
  11802. }
  11803. return data;
  11804. },
  11805. parse_icecandidate: function (line) {
  11806. var candidate = {},
  11807. elems = line.split(' ');
  11808. candidate.foundation = elems[0].substring(12);
  11809. candidate.component = elems[1];
  11810. candidate.protocol = elems[2].toLowerCase();
  11811. candidate.priority = elems[3];
  11812. candidate.ip = elems[4];
  11813. candidate.port = elems[5];
  11814. // elems[6] => "typ"
  11815. candidate.type = elems[7];
  11816. candidate.generation = 0; // default value, may be overwritten below
  11817. for (var i = 8; i < elems.length; i += 2) {
  11818. switch (elems[i]) {
  11819. case 'raddr':
  11820. candidate['rel-addr'] = elems[i + 1];
  11821. break;
  11822. case 'rport':
  11823. candidate['rel-port'] = elems[i + 1];
  11824. break;
  11825. case 'generation':
  11826. candidate.generation = elems[i + 1];
  11827. break;
  11828. case 'tcptype':
  11829. candidate.tcptype = elems[i + 1];
  11830. break;
  11831. default: // TODO
  11832. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  11833. }
  11834. }
  11835. candidate.network = '1';
  11836. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  11837. return candidate;
  11838. },
  11839. build_icecandidate: function (cand) {
  11840. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  11841. line += ' ';
  11842. switch (cand.type) {
  11843. case 'srflx':
  11844. case 'prflx':
  11845. case 'relay':
  11846. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  11847. line += 'raddr';
  11848. line += ' ';
  11849. line += cand['rel-addr'];
  11850. line += ' ';
  11851. line += 'rport';
  11852. line += ' ';
  11853. line += cand['rel-port'];
  11854. line += ' ';
  11855. }
  11856. break;
  11857. }
  11858. if (cand.hasOwnAttribute('tcptype')) {
  11859. line += 'tcptype';
  11860. line += ' ';
  11861. line += cand.tcptype;
  11862. line += ' ';
  11863. }
  11864. line += 'generation';
  11865. line += ' ';
  11866. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  11867. return line;
  11868. },
  11869. parse_ssrc: function (desc) {
  11870. // proprietary mapping of a=ssrc lines
  11871. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  11872. // and parse according to that
  11873. var lines = desc.split('\r\n'),
  11874. data = {};
  11875. for (var i = 0; i < lines.length; i++) {
  11876. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  11877. var idx = lines[i].indexOf(' ');
  11878. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  11879. }
  11880. }
  11881. return data;
  11882. },
  11883. parse_rtcpfb: function (line) {
  11884. var parts = line.substr(10).split(' ');
  11885. var data = {};
  11886. data.pt = parts.shift();
  11887. data.type = parts.shift();
  11888. data.params = parts;
  11889. return data;
  11890. },
  11891. parse_extmap: function (line) {
  11892. var parts = line.substr(9).split(' ');
  11893. var data = {};
  11894. data.value = parts.shift();
  11895. if (data.value.indexOf('/') != -1) {
  11896. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  11897. data.value = data.value.substr(0, data.value.indexOf('/'));
  11898. } else {
  11899. data.direction = 'both';
  11900. }
  11901. data.uri = parts.shift();
  11902. data.params = parts;
  11903. return data;
  11904. },
  11905. find_line: function (haystack, needle, sessionpart) {
  11906. var lines = haystack.split('\r\n');
  11907. for (var i = 0; i < lines.length; i++) {
  11908. if (lines[i].substring(0, needle.length) == needle) {
  11909. return lines[i];
  11910. }
  11911. }
  11912. if (!sessionpart) {
  11913. return false;
  11914. }
  11915. // search session part
  11916. lines = sessionpart.split('\r\n');
  11917. for (var j = 0; j < lines.length; j++) {
  11918. if (lines[j].substring(0, needle.length) == needle) {
  11919. return lines[j];
  11920. }
  11921. }
  11922. return false;
  11923. },
  11924. find_lines: function (haystack, needle, sessionpart) {
  11925. var lines = haystack.split('\r\n'),
  11926. needles = [];
  11927. for (var i = 0; i < lines.length; i++) {
  11928. if (lines[i].substring(0, needle.length) == needle)
  11929. needles.push(lines[i]);
  11930. }
  11931. if (needles.length || !sessionpart) {
  11932. return needles;
  11933. }
  11934. // search session part
  11935. lines = sessionpart.split('\r\n');
  11936. for (var j = 0; j < lines.length; j++) {
  11937. if (lines[j].substring(0, needle.length) == needle) {
  11938. needles.push(lines[j]);
  11939. }
  11940. }
  11941. return needles;
  11942. },
  11943. candidateToJingle: function (line) {
  11944. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  11945. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  11946. if (line.indexOf('candidate:') === 0) {
  11947. line = 'a=' + line;
  11948. } else if (line.substring(0, 12) != 'a=candidate:') {
  11949. console.log('parseCandidate called with a line that is not a candidate line');
  11950. console.log(line);
  11951. return null;
  11952. }
  11953. if (line.substring(line.length - 2) == '\r\n') // chomp it
  11954. line = line.substring(0, line.length - 2);
  11955. var candidate = {},
  11956. elems = line.split(' '),
  11957. i;
  11958. if (elems[6] != 'typ') {
  11959. console.log('did not find typ in the right place');
  11960. console.log(line);
  11961. return null;
  11962. }
  11963. candidate.foundation = elems[0].substring(12);
  11964. candidate.component = elems[1];
  11965. candidate.protocol = elems[2].toLowerCase();
  11966. candidate.priority = elems[3];
  11967. candidate.ip = elems[4];
  11968. candidate.port = elems[5];
  11969. // elems[6] => "typ"
  11970. candidate.type = elems[7];
  11971. candidate.generation = '0'; // default, may be overwritten below
  11972. for (i = 8; i < elems.length; i += 2) {
  11973. switch (elems[i]) {
  11974. case 'raddr':
  11975. candidate['rel-addr'] = elems[i + 1];
  11976. break;
  11977. case 'rport':
  11978. candidate['rel-port'] = elems[i + 1];
  11979. break;
  11980. case 'generation':
  11981. candidate.generation = elems[i + 1];
  11982. break;
  11983. case 'tcptype':
  11984. candidate.tcptype = elems[i + 1];
  11985. break;
  11986. default: // TODO
  11987. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  11988. }
  11989. }
  11990. candidate.network = '1';
  11991. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  11992. return candidate;
  11993. },
  11994. candidateFromJingle: function (cand) {
  11995. var line = 'a=candidate:';
  11996. line += cand.getAttribute('foundation');
  11997. line += ' ';
  11998. line += cand.getAttribute('component');
  11999. line += ' ';
  12000. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12001. line += ' ';
  12002. line += cand.getAttribute('priority');
  12003. line += ' ';
  12004. line += cand.getAttribute('ip');
  12005. line += ' ';
  12006. line += cand.getAttribute('port');
  12007. line += ' ';
  12008. line += 'typ';
  12009. line += ' ' + cand.getAttribute('type');
  12010. line += ' ';
  12011. switch (cand.getAttribute('type')) {
  12012. case 'srflx':
  12013. case 'prflx':
  12014. case 'relay':
  12015. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12016. line += 'raddr';
  12017. line += ' ';
  12018. line += cand.getAttribute('rel-addr');
  12019. line += ' ';
  12020. line += 'rport';
  12021. line += ' ';
  12022. line += cand.getAttribute('rel-port');
  12023. line += ' ';
  12024. }
  12025. break;
  12026. }
  12027. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12028. line += 'tcptype';
  12029. line += ' ';
  12030. line += cand.getAttribute('tcptype');
  12031. line += ' ';
  12032. }
  12033. line += 'generation';
  12034. line += ' ';
  12035. line += cand.getAttribute('generation') || '0';
  12036. return line + '\r\n';
  12037. }
  12038. };
  12039. module.exports = SDPUtil;
  12040. },{}],50:[function(require,module,exports){
  12041. function TraceablePeerConnection(ice_config, constraints) {
  12042. var self = this;
  12043. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12044. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12045. this.updateLog = [];
  12046. this.stats = {};
  12047. this.statsinterval = null;
  12048. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12049. // override as desired
  12050. this.trace = function (what, info) {
  12051. //console.warn('WTRACE', what, info);
  12052. self.updateLog.push({
  12053. time: new Date(),
  12054. type: what,
  12055. value: info || ""
  12056. });
  12057. };
  12058. this.onicecandidate = null;
  12059. this.peerconnection.onicecandidate = function (event) {
  12060. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12061. if (self.onicecandidate !== null) {
  12062. self.onicecandidate(event);
  12063. }
  12064. };
  12065. this.onaddstream = null;
  12066. this.peerconnection.onaddstream = function (event) {
  12067. self.trace('onaddstream', event.stream.id);
  12068. if (self.onaddstream !== null) {
  12069. self.onaddstream(event);
  12070. }
  12071. };
  12072. this.onremovestream = null;
  12073. this.peerconnection.onremovestream = function (event) {
  12074. self.trace('onremovestream', event.stream.id);
  12075. if (self.onremovestream !== null) {
  12076. self.onremovestream(event);
  12077. }
  12078. };
  12079. this.onsignalingstatechange = null;
  12080. this.peerconnection.onsignalingstatechange = function (event) {
  12081. self.trace('onsignalingstatechange', self.signalingState);
  12082. if (self.onsignalingstatechange !== null) {
  12083. self.onsignalingstatechange(event);
  12084. }
  12085. };
  12086. this.oniceconnectionstatechange = null;
  12087. this.peerconnection.oniceconnectionstatechange = function (event) {
  12088. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12089. if (self.oniceconnectionstatechange !== null) {
  12090. self.oniceconnectionstatechange(event);
  12091. }
  12092. };
  12093. this.onnegotiationneeded = null;
  12094. this.peerconnection.onnegotiationneeded = function (event) {
  12095. self.trace('onnegotiationneeded');
  12096. if (self.onnegotiationneeded !== null) {
  12097. self.onnegotiationneeded(event);
  12098. }
  12099. };
  12100. self.ondatachannel = null;
  12101. this.peerconnection.ondatachannel = function (event) {
  12102. self.trace('ondatachannel', event);
  12103. if (self.ondatachannel !== null) {
  12104. self.ondatachannel(event);
  12105. }
  12106. };
  12107. if (!navigator.mozGetUserMedia && this.maxstats) {
  12108. this.statsinterval = window.setInterval(function() {
  12109. self.peerconnection.getStats(function(stats) {
  12110. var results = stats.result();
  12111. for (var i = 0; i < results.length; ++i) {
  12112. //console.log(results[i].type, results[i].id, results[i].names())
  12113. var now = new Date();
  12114. results[i].names().forEach(function (name) {
  12115. var id = results[i].id + '-' + name;
  12116. if (!self.stats[id]) {
  12117. self.stats[id] = {
  12118. startTime: now,
  12119. endTime: now,
  12120. values: [],
  12121. times: []
  12122. };
  12123. }
  12124. self.stats[id].values.push(results[i].stat(name));
  12125. self.stats[id].times.push(now.getTime());
  12126. if (self.stats[id].values.length > self.maxstats) {
  12127. self.stats[id].values.shift();
  12128. self.stats[id].times.shift();
  12129. }
  12130. self.stats[id].endTime = now;
  12131. });
  12132. }
  12133. });
  12134. }, 1000);
  12135. }
  12136. };
  12137. dumpSDP = function(description) {
  12138. return 'type: ' + description.type + '\r\n' + description.sdp;
  12139. }
  12140. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12141. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12142. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12143. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12144. var publicLocalDescription = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12145. return publicLocalDescription;
  12146. });
  12147. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12148. var publicRemoteDescription = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12149. return publicRemoteDescription;
  12150. });
  12151. }
  12152. TraceablePeerConnection.prototype.addStream = function (stream) {
  12153. this.trace('addStream', stream.id);
  12154. APP.simulcast.resetSender();
  12155. try
  12156. {
  12157. this.peerconnection.addStream(stream);
  12158. }
  12159. catch (e)
  12160. {
  12161. console.error(e);
  12162. return;
  12163. }
  12164. };
  12165. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12166. this.trace('removeStream', stream.id);
  12167. APP.simulcast.resetSender();
  12168. if(stopStreams) {
  12169. stream.getAudioTracks().forEach(function (track) {
  12170. track.stop();
  12171. });
  12172. stream.getVideoTracks().forEach(function (track) {
  12173. track.stop();
  12174. });
  12175. }
  12176. this.peerconnection.removeStream(stream);
  12177. };
  12178. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12179. this.trace('createDataChannel', label, opts);
  12180. return this.peerconnection.createDataChannel(label, opts);
  12181. };
  12182. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12183. var self = this;
  12184. description = APP.simulcast.transformLocalDescription(description);
  12185. this.trace('setLocalDescription', dumpSDP(description));
  12186. this.peerconnection.setLocalDescription(description,
  12187. function () {
  12188. self.trace('setLocalDescriptionOnSuccess');
  12189. successCallback();
  12190. },
  12191. function (err) {
  12192. self.trace('setLocalDescriptionOnFailure', err);
  12193. failureCallback(err);
  12194. }
  12195. );
  12196. /*
  12197. if (this.statsinterval === null && this.maxstats > 0) {
  12198. // start gathering stats
  12199. }
  12200. */
  12201. };
  12202. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12203. var self = this;
  12204. description = APP.simulcast.transformRemoteDescription(description);
  12205. this.trace('setRemoteDescription', dumpSDP(description));
  12206. this.peerconnection.setRemoteDescription(description,
  12207. function () {
  12208. self.trace('setRemoteDescriptionOnSuccess');
  12209. successCallback();
  12210. },
  12211. function (err) {
  12212. self.trace('setRemoteDescriptionOnFailure', err);
  12213. failureCallback(err);
  12214. }
  12215. );
  12216. /*
  12217. if (this.statsinterval === null && this.maxstats > 0) {
  12218. // start gathering stats
  12219. }
  12220. */
  12221. };
  12222. TraceablePeerConnection.prototype.close = function () {
  12223. this.trace('stop');
  12224. if (this.statsinterval !== null) {
  12225. window.clearInterval(this.statsinterval);
  12226. this.statsinterval = null;
  12227. }
  12228. this.peerconnection.close();
  12229. };
  12230. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12231. var self = this;
  12232. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12233. this.peerconnection.createOffer(
  12234. function (offer) {
  12235. self.trace('createOfferOnSuccess', dumpSDP(offer));
  12236. successCallback(offer);
  12237. },
  12238. function(err) {
  12239. self.trace('createOfferOnFailure', err);
  12240. failureCallback(err);
  12241. },
  12242. constraints
  12243. );
  12244. };
  12245. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12246. var self = this;
  12247. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12248. this.peerconnection.createAnswer(
  12249. function (answer) {
  12250. answer = APP.simulcast.transformAnswer(answer);
  12251. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  12252. successCallback(answer);
  12253. },
  12254. function(err) {
  12255. self.trace('createAnswerOnFailure', err);
  12256. failureCallback(err);
  12257. },
  12258. constraints
  12259. );
  12260. };
  12261. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12262. var self = this;
  12263. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12264. this.peerconnection.addIceCandidate(candidate);
  12265. /* maybe later
  12266. this.peerconnection.addIceCandidate(candidate,
  12267. function () {
  12268. self.trace('addIceCandidateOnSuccess');
  12269. successCallback();
  12270. },
  12271. function (err) {
  12272. self.trace('addIceCandidateOnFailure', err);
  12273. failureCallback(err);
  12274. }
  12275. );
  12276. */
  12277. };
  12278. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12279. if (navigator.mozGetUserMedia) {
  12280. // ignore for now...
  12281. if(!errback)
  12282. errback = function () {
  12283. }
  12284. this.peerconnection.getStats(null,callback,errback);
  12285. } else {
  12286. this.peerconnection.getStats(callback);
  12287. }
  12288. };
  12289. module.exports = TraceablePeerConnection;
  12290. },{}],51:[function(require,module,exports){
  12291. /* global $, $iq, config, connection, UI, messageHandler,
  12292. roomName, sessionTerminated, Strophe, Util */
  12293. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12294. /**
  12295. * Contains logic responsible for enabling/disabling functionality available
  12296. * only to moderator users.
  12297. */
  12298. var connection = null;
  12299. var focusUserJid;
  12300. function createExpBackoffTimer(step) {
  12301. var count = 1;
  12302. return function (reset) {
  12303. // Reset call
  12304. if (reset) {
  12305. count = 1;
  12306. return;
  12307. }
  12308. // Calculate next timeout
  12309. var timeout = Math.pow(2, count - 1);
  12310. count += 1;
  12311. return timeout * step;
  12312. };
  12313. }
  12314. var getNextTimeout = createExpBackoffTimer(1000);
  12315. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12316. // External authentication stuff
  12317. var externalAuthEnabled = false;
  12318. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12319. // it will be enabled automatically if focus detects the component through
  12320. // service discovery.
  12321. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12322. var eventEmitter = null;
  12323. var Moderator = {
  12324. isModerator: function () {
  12325. return connection && connection.emuc.isModerator();
  12326. },
  12327. isPeerModerator: function (peerJid) {
  12328. return connection &&
  12329. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12330. },
  12331. isExternalAuthEnabled: function () {
  12332. return externalAuthEnabled;
  12333. },
  12334. isSipGatewayEnabled: function () {
  12335. return sipGatewayEnabled;
  12336. },
  12337. setConnection: function (con) {
  12338. connection = con;
  12339. },
  12340. init: function (xmpp, emitter) {
  12341. this.xmppService = xmpp;
  12342. eventEmitter = emitter;
  12343. },
  12344. onMucLeft: function (jid) {
  12345. console.info("Someone left is it focus ? " + jid);
  12346. var resource = Strophe.getResourceFromJid(jid);
  12347. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12348. console.info(
  12349. "Focus has left the room - leaving conference");
  12350. //hangUp();
  12351. // We'd rather reload to have everything re-initialized
  12352. // FIXME: show some message before reload
  12353. location.reload();
  12354. }
  12355. },
  12356. setFocusUserJid: function (focusJid) {
  12357. if (!focusUserJid) {
  12358. focusUserJid = focusJid;
  12359. console.info("Focus jid set to: " + focusUserJid);
  12360. }
  12361. },
  12362. getFocusUserJid: function () {
  12363. return focusUserJid;
  12364. },
  12365. getFocusComponent: function () {
  12366. // Get focus component address
  12367. var focusComponent = config.hosts.focus;
  12368. // If not specified use default: 'focus.domain'
  12369. if (!focusComponent) {
  12370. focusComponent = 'focus.' + config.hosts.domain;
  12371. }
  12372. return focusComponent;
  12373. },
  12374. createConferenceIq: function (roomName) {
  12375. // Generate create conference IQ
  12376. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12377. elem.c('conference', {
  12378. xmlns: 'http://jitsi.org/protocol/focus',
  12379. room: roomName
  12380. });
  12381. if (config.hosts.bridge !== undefined) {
  12382. elem.c(
  12383. 'property',
  12384. { name: 'bridge', value: config.hosts.bridge})
  12385. .up();
  12386. }
  12387. // Tell the focus we have Jigasi configured
  12388. if (config.hosts.call_control !== undefined) {
  12389. elem.c(
  12390. 'property',
  12391. { name: 'call_control', value: config.hosts.call_control})
  12392. .up();
  12393. }
  12394. if (config.channelLastN !== undefined) {
  12395. elem.c(
  12396. 'property',
  12397. { name: 'channelLastN', value: config.channelLastN})
  12398. .up();
  12399. }
  12400. if (config.adaptiveLastN !== undefined) {
  12401. elem.c(
  12402. 'property',
  12403. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12404. .up();
  12405. }
  12406. if (config.adaptiveSimulcast !== undefined) {
  12407. elem.c(
  12408. 'property',
  12409. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12410. .up();
  12411. }
  12412. if (config.openSctp !== undefined) {
  12413. elem.c(
  12414. 'property',
  12415. { name: 'openSctp', value: config.openSctp})
  12416. .up();
  12417. }
  12418. if (config.enableFirefoxSupport !== undefined) {
  12419. elem.c(
  12420. 'property',
  12421. { name: 'enableFirefoxHacks',
  12422. value: config.enableFirefoxSupport})
  12423. .up();
  12424. }
  12425. elem.up();
  12426. return elem;
  12427. },
  12428. parseConfigOptions: function (resultIq) {
  12429. Moderator.setFocusUserJid(
  12430. $(resultIq).find('conference').attr('focusjid'));
  12431. var extAuthParam
  12432. = $(resultIq).find('>conference>property[name=\'externalAuth\']');
  12433. if (extAuthParam.length) {
  12434. externalAuthEnabled = extAuthParam.attr('value') === 'true';
  12435. }
  12436. console.info("External authentication enabled: " + externalAuthEnabled);
  12437. // Check if focus has auto-detected Jigasi component(this will be also
  12438. // included if we have passed our host from the config)
  12439. if ($(resultIq).find(
  12440. '>conference>property[name=\'sipGatewayEnabled\']').length) {
  12441. sipGatewayEnabled = true;
  12442. }
  12443. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  12444. },
  12445. // FIXME: we need to show the fact that we're waiting for the focus
  12446. // to the user(or that focus is not available)
  12447. allocateConferenceFocus: function (roomName, callback) {
  12448. // Try to use focus user JID from the config
  12449. Moderator.setFocusUserJid(config.focusUserJid);
  12450. // Send create conference IQ
  12451. var iq = Moderator.createConferenceIq(roomName);
  12452. var self = this;
  12453. connection.sendIQ(
  12454. iq,
  12455. function (result) {
  12456. if ('true' === $(result).find('conference').attr('ready')) {
  12457. // Reset both timers
  12458. getNextTimeout(true);
  12459. getNextErrorTimeout(true);
  12460. // Setup config options
  12461. Moderator.parseConfigOptions(result);
  12462. // Exec callback
  12463. callback();
  12464. } else {
  12465. var waitMs = getNextTimeout();
  12466. console.info("Waiting for the focus... " + waitMs);
  12467. // Reset error timeout
  12468. getNextErrorTimeout(true);
  12469. window.setTimeout(
  12470. function () {
  12471. Moderator.allocateConferenceFocus(
  12472. roomName, callback);
  12473. }, waitMs);
  12474. }
  12475. },
  12476. function (error) {
  12477. // Not authorized to create new room
  12478. if ($(error).find('>error>not-authorized').length) {
  12479. console.warn("Unauthorized to start the conference");
  12480. var toDomain
  12481. = Strophe.getDomainFromJid(error.getAttribute('to'));
  12482. if (toDomain === config.hosts.anonymousdomain) {
  12483. // we are connected with anonymous domain and
  12484. // only non anonymous users can create rooms
  12485. // we must authorize the user
  12486. self.xmppService.promptLogin();
  12487. } else {
  12488. eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED, // External authentication mode
  12489. function () {
  12490. Moderator.allocateConferenceFocus(
  12491. roomName, callback);
  12492. });
  12493. }
  12494. return;
  12495. }
  12496. var waitMs = getNextErrorTimeout();
  12497. console.error("Focus error, retry after " + waitMs, error);
  12498. // Show message
  12499. APP.UI.messageHandler.notify(
  12500. 'Conference focus', 'disconnected',
  12501. Moderator.getFocusComponent() +
  12502. ' not available - retry in ' +
  12503. (waitMs / 1000) + ' sec');
  12504. // Reset response timeout
  12505. getNextTimeout(true);
  12506. window.setTimeout(
  12507. function () {
  12508. Moderator.allocateConferenceFocus(roomName, callback);
  12509. }, waitMs);
  12510. }
  12511. );
  12512. },
  12513. getAuthUrl: function (roomName, urlCallback) {
  12514. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  12515. iq.c('auth-url', {
  12516. xmlns: 'http://jitsi.org/protocol/focus',
  12517. room: roomName
  12518. });
  12519. connection.sendIQ(
  12520. iq,
  12521. function (result) {
  12522. var url = $(result).find('auth-url').attr('url');
  12523. if (url) {
  12524. console.info("Got auth url: " + url);
  12525. urlCallback(url);
  12526. } else {
  12527. console.error(
  12528. "Failed to get auth url fro mthe focus", result);
  12529. }
  12530. },
  12531. function (error) {
  12532. console.error("Get auth url error", error);
  12533. }
  12534. );
  12535. }
  12536. };
  12537. module.exports = Moderator;
  12538. },{"../../service/xmpp/XMPPEvents":83}],52:[function(require,module,exports){
  12539. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  12540. Toolbar, Util */
  12541. var Moderator = require("./moderator");
  12542. var recordingToken = null;
  12543. var recordingEnabled;
  12544. /**
  12545. * Whether to use a jirecon component for recording, or use the videobridge
  12546. * through COLIBRI.
  12547. */
  12548. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  12549. /**
  12550. * The ID of the jirecon recording session. Jirecon generates it when we
  12551. * initially start recording, and it needs to be used in subsequent requests
  12552. * to jirecon.
  12553. */
  12554. var jireconRid = null;
  12555. function setRecordingToken(token) {
  12556. recordingToken = token;
  12557. }
  12558. function setRecording(state, token, callback, connection) {
  12559. if (useJirecon){
  12560. setRecordingJirecon(state, token, callback, connection);
  12561. } else {
  12562. setRecordingColibri(state, token, callback, connection);
  12563. }
  12564. }
  12565. function setRecordingJirecon(state, token, callback, connection) {
  12566. if (state == recordingEnabled){
  12567. return;
  12568. }
  12569. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  12570. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  12571. action: state ? 'start' : 'stop',
  12572. mucjid: connection.emuc.roomjid});
  12573. if (!state){
  12574. iq.attrs({rid: jireconRid});
  12575. }
  12576. console.log('Start recording');
  12577. connection.sendIQ(
  12578. iq,
  12579. function (result) {
  12580. // TODO wait for an IQ with the real status, since this is
  12581. // provisional?
  12582. jireconRid = $(result).find('recording').attr('rid');
  12583. console.log('Recording ' + (state ? 'started' : 'stopped') +
  12584. '(jirecon)' + result);
  12585. recordingEnabled = state;
  12586. if (!state){
  12587. jireconRid = null;
  12588. }
  12589. callback(state);
  12590. },
  12591. function (error) {
  12592. console.log('Failed to start recording, error: ', error);
  12593. callback(recordingEnabled);
  12594. });
  12595. }
  12596. // Sends a COLIBRI message which enables or disables (according to 'state')
  12597. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  12598. // with the new recording state, according to the IQ.
  12599. function setRecordingColibri(state, token, callback, connection) {
  12600. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  12601. elem.c('conference', {
  12602. xmlns: 'http://jitsi.org/protocol/colibri'
  12603. });
  12604. elem.c('recording', {state: state, token: token});
  12605. connection.sendIQ(elem,
  12606. function (result) {
  12607. console.log('Set recording "', state, '". Result:', result);
  12608. var recordingElem = $(result).find('>conference>recording');
  12609. var newState = ('true' === recordingElem.attr('state'));
  12610. recordingEnabled = newState;
  12611. callback(newState);
  12612. },
  12613. function (error) {
  12614. console.warn(error);
  12615. callback(recordingEnabled);
  12616. }
  12617. );
  12618. }
  12619. var Recording = {
  12620. toggleRecording: function (tokenEmptyCallback,
  12621. startingCallback, startedCallback, connection) {
  12622. if (!Moderator.isModerator()) {
  12623. console.log(
  12624. 'non-focus, or conference not yet organized:' +
  12625. ' not enabling recording');
  12626. return;
  12627. }
  12628. // Jirecon does not (currently) support a token.
  12629. if (!recordingToken && !useJirecon) {
  12630. tokenEmptyCallback(function (value) {
  12631. setRecordingToken(value);
  12632. this.toggleRecording();
  12633. });
  12634. return;
  12635. }
  12636. var oldState = recordingEnabled;
  12637. startingCallback(!oldState);
  12638. setRecording(!oldState,
  12639. recordingToken,
  12640. function (state) {
  12641. console.log("New recording state: ", state);
  12642. if (state === oldState) {
  12643. // FIXME: new focus:
  12644. // this will not work when moderator changes
  12645. // during active session. Then it will assume that
  12646. // recording status has changed to true, but it might have
  12647. // been already true(and we only received actual status from
  12648. // the focus).
  12649. //
  12650. // SO we start with status null, so that it is initialized
  12651. // here and will fail only after second click, so if invalid
  12652. // token was used we have to press the button twice before
  12653. // current status will be fetched and token will be reset.
  12654. //
  12655. // Reliable way would be to return authentication error.
  12656. // Or status update when moderator connects.
  12657. // Or we have to stop recording session when current
  12658. // moderator leaves the room.
  12659. // Failed to change, reset the token because it might
  12660. // have been wrong
  12661. setRecordingToken(null);
  12662. }
  12663. startedCallback(state);
  12664. },
  12665. connection
  12666. );
  12667. }
  12668. }
  12669. module.exports = Recording;
  12670. },{"./moderator":51}],53:[function(require,module,exports){
  12671. /* jshint -W117 */
  12672. /* a simple MUC connection plugin
  12673. * can only handle a single MUC room
  12674. */
  12675. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12676. var Moderator = require("./moderator");
  12677. var JingleSession = require("./JingleSession");
  12678. var bridgeIsDown = false;
  12679. module.exports = function(XMPP, eventEmitter) {
  12680. Strophe.addConnectionPlugin('emuc', {
  12681. connection: null,
  12682. roomjid: null,
  12683. myroomjid: null,
  12684. members: {},
  12685. list_members: [], // so we can elect a new focus
  12686. presMap: {},
  12687. preziMap: {},
  12688. joined: false,
  12689. isOwner: false,
  12690. role: null,
  12691. focusMucJid: null,
  12692. ssrc2jid: {},
  12693. init: function (conn) {
  12694. this.connection = conn;
  12695. },
  12696. initPresenceMap: function (myroomjid) {
  12697. this.presMap['to'] = myroomjid;
  12698. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  12699. },
  12700. doJoin: function (jid, password) {
  12701. this.myroomjid = jid;
  12702. console.info("Joined MUC as " + this.myroomjid);
  12703. this.initPresenceMap(this.myroomjid);
  12704. if (!this.roomjid) {
  12705. this.roomjid = Strophe.getBareJidFromJid(jid);
  12706. // add handlers (just once)
  12707. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  12708. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  12709. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  12710. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  12711. }
  12712. if (password !== undefined) {
  12713. this.presMap['password'] = password;
  12714. }
  12715. this.sendPresence();
  12716. },
  12717. doLeave: function () {
  12718. console.log("do leave", this.myroomjid);
  12719. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  12720. this.presMap.length = 0;
  12721. this.connection.send(pres);
  12722. },
  12723. createNonAnonymousRoom: function () {
  12724. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  12725. var getForm = $iq({type: 'get', to: this.roomjid})
  12726. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  12727. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  12728. var self = this;
  12729. this.connection.sendIQ(getForm, function (form) {
  12730. if (!$(form).find(
  12731. '>query>x[xmlns="jabber:x:data"]' +
  12732. '>field[var="muc#roomconfig_whois"]').length) {
  12733. console.error('non-anonymous rooms not supported');
  12734. return;
  12735. }
  12736. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  12737. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  12738. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  12739. formSubmit.c('field', {'var': 'FORM_TYPE'})
  12740. .c('value')
  12741. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  12742. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  12743. .c('value').t('anyone').up().up();
  12744. self.connection.sendIQ(formSubmit);
  12745. }, function (error) {
  12746. console.error("Error getting room configuration form");
  12747. });
  12748. },
  12749. onPresence: function (pres) {
  12750. var from = pres.getAttribute('from');
  12751. // What is this for? A workaround for something?
  12752. if (pres.getAttribute('type')) {
  12753. return true;
  12754. }
  12755. // Parse etherpad tag.
  12756. var etherpad = $(pres).find('>etherpad');
  12757. if (etherpad.length) {
  12758. if (config.etherpad_base && !Moderator.isModerator()) {
  12759. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  12760. }
  12761. }
  12762. // Parse prezi tag.
  12763. var presentation = $(pres).find('>prezi');
  12764. if (presentation.length) {
  12765. var url = presentation.attr('url');
  12766. var current = presentation.find('>current').text();
  12767. console.log('presentation info received from', from, url);
  12768. if (this.preziMap[from] == null) {
  12769. this.preziMap[from] = url;
  12770. $(document).trigger('presentationadded.muc', [from, url, current]);
  12771. }
  12772. else {
  12773. $(document).trigger('gotoslide.muc', [from, url, current]);
  12774. }
  12775. }
  12776. else if (this.preziMap[from] != null) {
  12777. var url = this.preziMap[from];
  12778. delete this.preziMap[from];
  12779. $(document).trigger('presentationremoved.muc', [from, url]);
  12780. }
  12781. // Parse audio info tag.
  12782. var audioMuted = $(pres).find('>audiomuted');
  12783. if (audioMuted.length) {
  12784. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  12785. }
  12786. // Parse video info tag.
  12787. var videoMuted = $(pres).find('>videomuted');
  12788. if (videoMuted.length) {
  12789. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  12790. }
  12791. var stats = $(pres).find('>stats');
  12792. if (stats.length) {
  12793. var statsObj = {};
  12794. Strophe.forEachChild(stats[0], "stat", function (el) {
  12795. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  12796. });
  12797. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  12798. }
  12799. // Parse status.
  12800. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  12801. this.isOwner = true;
  12802. this.createNonAnonymousRoom();
  12803. }
  12804. // Parse roles.
  12805. var member = {};
  12806. member.show = $(pres).find('>show').text();
  12807. member.status = $(pres).find('>status').text();
  12808. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  12809. member.affiliation = tmp.attr('affiliation');
  12810. member.role = tmp.attr('role');
  12811. // Focus recognition
  12812. member.jid = tmp.attr('jid');
  12813. member.isFocus = false;
  12814. if (member.jid
  12815. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  12816. member.isFocus = true;
  12817. }
  12818. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  12819. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  12820. if (from == this.myroomjid) {
  12821. if (member.affiliation == 'owner') this.isOwner = true;
  12822. if (this.role !== member.role) {
  12823. this.role = member.role;
  12824. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  12825. from, member, pres, Moderator.isModerator(),
  12826. Moderator.isExternalAuthEnabled());
  12827. }
  12828. if (!this.joined) {
  12829. this.joined = true;
  12830. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  12831. this.list_members.push(from);
  12832. }
  12833. } else if (this.members[from] === undefined) {
  12834. // new participant
  12835. this.members[from] = member;
  12836. this.list_members.push(from);
  12837. console.log('entered', from, member);
  12838. if (member.isFocus) {
  12839. this.focusMucJid = from;
  12840. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  12841. }
  12842. else {
  12843. var id = $(pres).find('>userID').text();
  12844. var email = $(pres).find('>email');
  12845. if (email.length > 0) {
  12846. id = email.text();
  12847. }
  12848. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  12849. }
  12850. } else {
  12851. // Presence update for existing participant
  12852. // Watch role change:
  12853. if (this.members[from].role != member.role) {
  12854. this.members[from].role = member.role;
  12855. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  12856. member.role, member.displayName);
  12857. }
  12858. }
  12859. // Always trigger presence to update bindings
  12860. this.parsePresence(from, member, pres);
  12861. // Trigger status message update
  12862. if (member.status) {
  12863. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  12864. }
  12865. return true;
  12866. },
  12867. onPresenceUnavailable: function (pres) {
  12868. var from = pres.getAttribute('from');
  12869. // Status code 110 indicates that this notification is "self-presence".
  12870. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  12871. delete this.members[from];
  12872. this.list_members.splice(this.list_members.indexOf(from), 1);
  12873. this.onParticipantLeft(from);
  12874. }
  12875. // If the status code is 110 this means we're leaving and we would like
  12876. // to remove everyone else from our view, so we trigger the event.
  12877. else if (this.list_members.length > 1) {
  12878. for (var i = 0; i < this.list_members.length; i++) {
  12879. var member = this.list_members[i];
  12880. delete this.members[i];
  12881. this.list_members.splice(i, 1);
  12882. this.onParticipantLeft(member);
  12883. }
  12884. }
  12885. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  12886. $(document).trigger('kicked.muc', [from]);
  12887. if (this.myroomjid === from) {
  12888. XMPP.disposeConference(false);
  12889. eventEmitter.emit(XMPPEvents.KICKED);
  12890. }
  12891. }
  12892. return true;
  12893. },
  12894. onPresenceError: function (pres) {
  12895. var from = pres.getAttribute('from');
  12896. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  12897. console.log('on password required', from);
  12898. var self = this;
  12899. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  12900. self.doJoin(from, value);
  12901. });
  12902. } else if ($(pres).find(
  12903. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  12904. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  12905. if (toDomain === config.hosts.anonymousdomain) {
  12906. // enter the room by replying with 'not-authorized'. This would
  12907. // result in reconnection from authorized domain.
  12908. // We're either missing Jicofo/Prosody config for anonymous
  12909. // domains or something is wrong.
  12910. // XMPP.promptLogin();
  12911. APP.UI.messageHandler.openReportDialog(null,
  12912. 'Oops ! We couldn`t join the conference.' +
  12913. ' There might be some problem with security' +
  12914. ' configuration. Please contact service' +
  12915. ' administrator.', pres);
  12916. } else {
  12917. console.warn('onPresError ', pres);
  12918. APP.UI.messageHandler.openReportDialog(null,
  12919. 'Oops! Something went wrong and we couldn`t connect to the conference.',
  12920. pres);
  12921. }
  12922. } else {
  12923. console.warn('onPresError ', pres);
  12924. APP.UI.messageHandler.openReportDialog(null,
  12925. 'Oops! Something went wrong and we couldn`t connect to the conference.',
  12926. pres);
  12927. }
  12928. return true;
  12929. },
  12930. sendMessage: function (body, nickname) {
  12931. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  12932. msg.c('body', body).up();
  12933. if (nickname) {
  12934. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  12935. }
  12936. this.connection.send(msg);
  12937. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  12938. },
  12939. setSubject: function (subject) {
  12940. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  12941. msg.c('subject', subject);
  12942. this.connection.send(msg);
  12943. console.log("topic changed to " + subject);
  12944. },
  12945. onMessage: function (msg) {
  12946. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  12947. var from = msg.getAttribute('from');
  12948. var nick =
  12949. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  12950. .text() ||
  12951. Strophe.getResourceFromJid(from);
  12952. var txt = $(msg).find('>body').text();
  12953. var type = msg.getAttribute("type");
  12954. if (type == "error") {
  12955. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  12956. $(msg).find('>text').text(), txt);
  12957. return true;
  12958. }
  12959. var subject = $(msg).find('>subject');
  12960. if (subject.length) {
  12961. var subjectText = subject.text();
  12962. if (subjectText || subjectText == "") {
  12963. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  12964. console.log("Subject is changed to " + subjectText);
  12965. }
  12966. }
  12967. if (txt) {
  12968. console.log('chat', nick, txt);
  12969. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  12970. from, nick, txt, this.myroomjid);
  12971. }
  12972. return true;
  12973. },
  12974. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  12975. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  12976. var ob = this;
  12977. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  12978. function (res) {
  12979. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  12980. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  12981. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  12982. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  12983. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  12984. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  12985. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  12986. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  12987. ob.connection.sendIQ(formsubmit,
  12988. onSuccess,
  12989. onError);
  12990. } else {
  12991. onNotSupported();
  12992. }
  12993. }, onError);
  12994. },
  12995. kick: function (jid) {
  12996. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  12997. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  12998. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  12999. .c('reason').t('You have been kicked.').up().up().up();
  13000. this.connection.sendIQ(
  13001. kickIQ,
  13002. function (result) {
  13003. console.log('Kick participant with jid: ', jid, result);
  13004. },
  13005. function (error) {
  13006. console.log('Kick participant error: ', error);
  13007. });
  13008. },
  13009. sendPresence: function () {
  13010. var pres = $pres({to: this.presMap['to'] });
  13011. pres.c('x', {xmlns: this.presMap['xns']});
  13012. if (this.presMap['password']) {
  13013. pres.c('password').t(this.presMap['password']).up();
  13014. }
  13015. pres.up();
  13016. // Send XEP-0115 'c' stanza that contains our capabilities info
  13017. if (this.connection.caps) {
  13018. this.connection.caps.node = config.clientNode;
  13019. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13020. }
  13021. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13022. .t(navigator.userAgent).up();
  13023. if (this.presMap['bridgeIsDown']) {
  13024. pres.c('bridgeIsDown').up();
  13025. }
  13026. if (this.presMap['email']) {
  13027. pres.c('email').t(this.presMap['email']).up();
  13028. }
  13029. if (this.presMap['userId']) {
  13030. pres.c('userId').t(this.presMap['userId']).up();
  13031. }
  13032. if (this.presMap['displayName']) {
  13033. // XEP-0172
  13034. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13035. .t(this.presMap['displayName']).up();
  13036. }
  13037. if (this.presMap['audions']) {
  13038. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13039. .t(this.presMap['audiomuted']).up();
  13040. }
  13041. if (this.presMap['videons']) {
  13042. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13043. .t(this.presMap['videomuted']).up();
  13044. }
  13045. if (this.presMap['statsns']) {
  13046. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13047. for (var stat in this.presMap["stats"])
  13048. if (this.presMap["stats"][stat] != null)
  13049. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13050. pres.up();
  13051. }
  13052. if (this.presMap['prezins']) {
  13053. pres.c('prezi',
  13054. {xmlns: this.presMap['prezins'],
  13055. 'url': this.presMap['preziurl']})
  13056. .c('current').t(this.presMap['prezicurrent']).up().up();
  13057. }
  13058. if (this.presMap['etherpadns']) {
  13059. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13060. .t(this.presMap['etherpadname']).up();
  13061. }
  13062. if (this.presMap['medians']) {
  13063. pres.c('media', {xmlns: this.presMap['medians']});
  13064. var sourceNumber = 0;
  13065. Object.keys(this.presMap).forEach(function (key) {
  13066. if (key.indexOf('source') >= 0) {
  13067. sourceNumber++;
  13068. }
  13069. });
  13070. if (sourceNumber > 0)
  13071. for (var i = 1; i <= sourceNumber / 3; i++) {
  13072. pres.c('source',
  13073. {type: this.presMap['source' + i + '_type'],
  13074. ssrc: this.presMap['source' + i + '_ssrc'],
  13075. direction: this.presMap['source' + i + '_direction']
  13076. || 'sendrecv' }
  13077. ).up();
  13078. }
  13079. }
  13080. pres.up();
  13081. this.connection.send(pres);
  13082. },
  13083. addDisplayNameToPresence: function (displayName) {
  13084. this.presMap['displayName'] = displayName;
  13085. },
  13086. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13087. if (!this.presMap['medians'])
  13088. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13089. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13090. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13091. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13092. },
  13093. clearPresenceMedia: function () {
  13094. var self = this;
  13095. Object.keys(this.presMap).forEach(function (key) {
  13096. if (key.indexOf('source') != -1) {
  13097. delete self.presMap[key];
  13098. }
  13099. });
  13100. },
  13101. addPreziToPresence: function (url, currentSlide) {
  13102. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13103. this.presMap['preziurl'] = url;
  13104. this.presMap['prezicurrent'] = currentSlide;
  13105. },
  13106. removePreziFromPresence: function () {
  13107. delete this.presMap['prezins'];
  13108. delete this.presMap['preziurl'];
  13109. delete this.presMap['prezicurrent'];
  13110. },
  13111. addCurrentSlideToPresence: function (currentSlide) {
  13112. this.presMap['prezicurrent'] = currentSlide;
  13113. },
  13114. getPrezi: function (roomjid) {
  13115. return this.preziMap[roomjid];
  13116. },
  13117. addEtherpadToPresence: function (etherpadName) {
  13118. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13119. this.presMap['etherpadname'] = etherpadName;
  13120. },
  13121. addAudioInfoToPresence: function (isMuted) {
  13122. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13123. this.presMap['audiomuted'] = isMuted.toString();
  13124. },
  13125. addVideoInfoToPresence: function (isMuted) {
  13126. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13127. this.presMap['videomuted'] = isMuted.toString();
  13128. },
  13129. addConnectionInfoToPresence: function (stats) {
  13130. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13131. this.presMap['stats'] = stats;
  13132. },
  13133. findJidFromResource: function (resourceJid) {
  13134. if (resourceJid &&
  13135. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13136. return this.myroomjid;
  13137. }
  13138. var peerJid = null;
  13139. Object.keys(this.members).some(function (jid) {
  13140. peerJid = jid;
  13141. return Strophe.getResourceFromJid(jid) === resourceJid;
  13142. });
  13143. return peerJid;
  13144. },
  13145. addBridgeIsDownToPresence: function () {
  13146. this.presMap['bridgeIsDown'] = true;
  13147. },
  13148. addEmailToPresence: function (email) {
  13149. this.presMap['email'] = email;
  13150. },
  13151. addUserIdToPresence: function (userId) {
  13152. this.presMap['userId'] = userId;
  13153. },
  13154. isModerator: function () {
  13155. return this.role === 'moderator';
  13156. },
  13157. getMemberRole: function (peerJid) {
  13158. if (this.members[peerJid]) {
  13159. return this.members[peerJid].role;
  13160. }
  13161. return null;
  13162. },
  13163. onParticipantLeft: function (jid) {
  13164. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13165. this.connection.jingle.terminateByJid(jid);
  13166. if (this.getPrezi(jid)) {
  13167. $(document).trigger('presentationremoved.muc',
  13168. [jid, this.getPrezi(jid)]);
  13169. }
  13170. Moderator.onMucLeft(jid);
  13171. },
  13172. parsePresence: function (from, memeber, pres) {
  13173. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13174. bridgeIsDown = true;
  13175. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13176. }
  13177. if(memeber.isFocus)
  13178. return;
  13179. var self = this;
  13180. // Remove old ssrcs coming from the jid
  13181. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13182. if (self.ssrc2jid[ssrc] == from) {
  13183. delete self.ssrc2jid[ssrc];
  13184. }
  13185. });
  13186. var changedStreams = [];
  13187. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13188. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13189. var ssrcV = ssrc.getAttribute('ssrc');
  13190. self.ssrc2jid[ssrcV] = from;
  13191. JingleSession.notReceivedSSRCs.push(ssrcV);
  13192. var type = ssrc.getAttribute('type');
  13193. var direction = ssrc.getAttribute('direction');
  13194. changedStreams.push({type: type, direction: direction});
  13195. });
  13196. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  13197. var displayName = !config.displayJids
  13198. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13199. if (displayName && displayName.length > 0)
  13200. {
  13201. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13202. }
  13203. var id = $(pres).find('>userID').text();
  13204. var email = $(pres).find('>email');
  13205. if(email.length > 0) {
  13206. id = email.text();
  13207. }
  13208. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13209. }
  13210. });
  13211. };
  13212. },{"../../service/xmpp/XMPPEvents":83,"./JingleSession":46,"./moderator":51}],54:[function(require,module,exports){
  13213. /* jshint -W117 */
  13214. var JingleSession = require("./JingleSession");
  13215. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13216. module.exports = function(XMPP, eventEmitter)
  13217. {
  13218. function CallIncomingJingle(sid, connection) {
  13219. var sess = connection.jingle.sessions[sid];
  13220. // TODO: do we check activecall == null?
  13221. connection.jingle.activecall = sess;
  13222. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13223. // TODO: check affiliation and/or role
  13224. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13225. sess.usedrip = true; // not-so-naive trickle ice
  13226. sess.sendAnswer();
  13227. sess.accept();
  13228. };
  13229. Strophe.addConnectionPlugin('jingle', {
  13230. connection: null,
  13231. sessions: {},
  13232. jid2session: {},
  13233. ice_config: {iceServers: []},
  13234. pc_constraints: {},
  13235. activecall: null,
  13236. media_constraints: {
  13237. mandatory: {
  13238. 'OfferToReceiveAudio': true,
  13239. 'OfferToReceiveVideo': true
  13240. }
  13241. // MozDontOfferDataChannel: true when this is firefox
  13242. },
  13243. init: function (conn) {
  13244. this.connection = conn;
  13245. if (this.connection.disco) {
  13246. // http://xmpp.org/extensions/xep-0167.html#support
  13247. // http://xmpp.org/extensions/xep-0176.html#support
  13248. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13249. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13250. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13251. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13252. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13253. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13254. // this is dealt with by SDP O/A so we don't need to annouce this
  13255. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13256. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13257. if (config.useRtcpMux) {
  13258. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13259. }
  13260. if (config.useBundle) {
  13261. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13262. }
  13263. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13264. }
  13265. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13266. },
  13267. onJingle: function (iq) {
  13268. var sid = $(iq).find('jingle').attr('sid');
  13269. var action = $(iq).find('jingle').attr('action');
  13270. var fromJid = iq.getAttribute('from');
  13271. // send ack first
  13272. var ack = $iq({type: 'result',
  13273. to: fromJid,
  13274. id: iq.getAttribute('id')
  13275. });
  13276. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13277. var sess = this.sessions[sid];
  13278. if ('session-initiate' != action) {
  13279. if (sess === null) {
  13280. ack.type = 'error';
  13281. ack.c('error', {type: 'cancel'})
  13282. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13283. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13284. this.connection.send(ack);
  13285. return true;
  13286. }
  13287. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13288. // local jid is not checked
  13289. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13290. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13291. ack.type = 'error';
  13292. ack.c('error', {type: 'cancel'})
  13293. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13294. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13295. this.connection.send(ack);
  13296. return true;
  13297. }
  13298. } else if (sess !== undefined) {
  13299. // existing session with same session id
  13300. // this might be out-of-order if the sess.peerjid is the same as from
  13301. ack.type = 'error';
  13302. ack.c('error', {type: 'cancel'})
  13303. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13304. console.warn('duplicate session id', sid);
  13305. this.connection.send(ack);
  13306. return true;
  13307. }
  13308. // FIXME: check for a defined action
  13309. this.connection.send(ack);
  13310. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13311. switch (action) {
  13312. case 'session-initiate':
  13313. sess = new JingleSession(
  13314. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13315. this.connection, XMPP);
  13316. // configure session
  13317. sess.media_constraints = this.media_constraints;
  13318. sess.pc_constraints = this.pc_constraints;
  13319. sess.ice_config = this.ice_config;
  13320. sess.initiate(fromJid, false);
  13321. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13322. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13323. this.sessions[sess.sid] = sess;
  13324. this.jid2session[sess.peerjid] = sess;
  13325. // the callback should either
  13326. // .sendAnswer and .accept
  13327. // or .sendTerminate -- not necessarily synchronus
  13328. CallIncomingJingle(sess.sid, this.connection);
  13329. break;
  13330. case 'session-accept':
  13331. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  13332. sess.accept();
  13333. $(document).trigger('callaccepted.jingle', [sess.sid]);
  13334. break;
  13335. case 'session-terminate':
  13336. // If this is not the focus sending the terminate, we have
  13337. // nothing more to do here.
  13338. if (Object.keys(this.sessions).length < 1
  13339. || !(this.sessions[Object.keys(this.sessions)[0]]
  13340. instanceof JingleSession))
  13341. {
  13342. break;
  13343. }
  13344. console.log('terminating...', sess.sid);
  13345. sess.terminate();
  13346. this.terminate(sess.sid);
  13347. if ($(iq).find('>jingle>reason').length) {
  13348. $(document).trigger('callterminated.jingle', [
  13349. sess.sid,
  13350. sess.peerjid,
  13351. $(iq).find('>jingle>reason>:first')[0].tagName,
  13352. $(iq).find('>jingle>reason>text').text()
  13353. ]);
  13354. } else {
  13355. $(document).trigger('callterminated.jingle',
  13356. [sess.sid, sess.peerjid]);
  13357. }
  13358. break;
  13359. case 'transport-info':
  13360. sess.addIceCandidate($(iq).find('>jingle>content'));
  13361. break;
  13362. case 'session-info':
  13363. var affected;
  13364. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13365. $(document).trigger('ringing.jingle', [sess.sid]);
  13366. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13367. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13368. $(document).trigger('mute.jingle', [sess.sid, affected]);
  13369. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13370. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13371. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  13372. }
  13373. break;
  13374. case 'addsource': // FIXME: proprietary, un-jingleish
  13375. case 'source-add': // FIXME: proprietary
  13376. sess.addSource($(iq).find('>jingle>content'), fromJid);
  13377. break;
  13378. case 'removesource': // FIXME: proprietary, un-jingleish
  13379. case 'source-remove': // FIXME: proprietary
  13380. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  13381. break;
  13382. default:
  13383. console.warn('jingle action not implemented', action);
  13384. break;
  13385. }
  13386. return true;
  13387. },
  13388. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  13389. var sess = new JingleSession(myjid || this.connection.jid,
  13390. Math.random().toString(36).substr(2, 12), // random string
  13391. this.connection, XMPP);
  13392. // configure session
  13393. sess.media_constraints = this.media_constraints;
  13394. sess.pc_constraints = this.pc_constraints;
  13395. sess.ice_config = this.ice_config;
  13396. sess.initiate(peerjid, true);
  13397. this.sessions[sess.sid] = sess;
  13398. this.jid2session[sess.peerjid] = sess;
  13399. sess.sendOffer();
  13400. return sess;
  13401. },
  13402. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  13403. if (sid === null || sid === undefined) {
  13404. for (sid in this.sessions) {
  13405. if (this.sessions[sid].state != 'ended') {
  13406. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  13407. this.sessions[sid].terminate();
  13408. }
  13409. delete this.jid2session[this.sessions[sid].peerjid];
  13410. delete this.sessions[sid];
  13411. }
  13412. } else if (this.sessions.hasOwnProperty(sid)) {
  13413. if (this.sessions[sid].state != 'ended') {
  13414. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  13415. this.sessions[sid].terminate();
  13416. }
  13417. delete this.jid2session[this.sessions[sid].peerjid];
  13418. delete this.sessions[sid];
  13419. }
  13420. },
  13421. // Used to terminate a session when an unavailable presence is received.
  13422. terminateByJid: function (jid) {
  13423. if (this.jid2session.hasOwnProperty(jid)) {
  13424. var sess = this.jid2session[jid];
  13425. if (sess) {
  13426. sess.terminate();
  13427. console.log('peer went away silently', jid);
  13428. delete this.sessions[sess.sid];
  13429. delete this.jid2session[jid];
  13430. $(document).trigger('callterminated.jingle',
  13431. [sess.sid, jid], 'gone');
  13432. }
  13433. }
  13434. },
  13435. terminateRemoteByJid: function (jid, reason) {
  13436. if (this.jid2session.hasOwnProperty(jid)) {
  13437. var sess = this.jid2session[jid];
  13438. if (sess) {
  13439. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  13440. sess.terminate();
  13441. console.log('terminate peer with jid', sess.sid, jid);
  13442. delete this.sessions[sess.sid];
  13443. delete this.jid2session[jid];
  13444. $(document).trigger('callterminated.jingle',
  13445. [sess.sid, jid, 'kicked']);
  13446. }
  13447. }
  13448. },
  13449. getStunAndTurnCredentials: function () {
  13450. // get stun and turn configuration from server via xep-0215
  13451. // uses time-limited credentials as described in
  13452. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  13453. //
  13454. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  13455. // for a prosody module which implements this
  13456. //
  13457. // currently, this doesn't work with updateIce and therefore credentials with a long
  13458. // validity have to be fetched before creating the peerconnection
  13459. // TODO: implement refresh via updateIce as described in
  13460. // https://code.google.com/p/webrtc/issues/detail?id=1650
  13461. var self = this;
  13462. this.connection.sendIQ(
  13463. $iq({type: 'get', to: this.connection.domain})
  13464. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  13465. function (res) {
  13466. var iceservers = [];
  13467. $(res).find('>services>service').each(function (idx, el) {
  13468. el = $(el);
  13469. var dict = {};
  13470. var type = el.attr('type');
  13471. switch (type) {
  13472. case 'stun':
  13473. dict.url = 'stun:' + el.attr('host');
  13474. if (el.attr('port')) {
  13475. dict.url += ':' + el.attr('port');
  13476. }
  13477. iceservers.push(dict);
  13478. break;
  13479. case 'turn':
  13480. case 'turns':
  13481. dict.url = type + ':';
  13482. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  13483. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  13484. dict.url += el.attr('username') + '@';
  13485. } else {
  13486. dict.username = el.attr('username'); // only works in M28
  13487. }
  13488. }
  13489. dict.url += el.attr('host');
  13490. if (el.attr('port') && el.attr('port') != '3478') {
  13491. dict.url += ':' + el.attr('port');
  13492. }
  13493. if (el.attr('transport') && el.attr('transport') != 'udp') {
  13494. dict.url += '?transport=' + el.attr('transport');
  13495. }
  13496. if (el.attr('password')) {
  13497. dict.credential = el.attr('password');
  13498. }
  13499. iceservers.push(dict);
  13500. break;
  13501. }
  13502. });
  13503. self.ice_config.iceServers = iceservers;
  13504. },
  13505. function (err) {
  13506. console.warn('getting turn credentials failed', err);
  13507. console.warn('is mod_turncredentials or similar installed?');
  13508. }
  13509. );
  13510. // implement push?
  13511. },
  13512. /**
  13513. * Populates the log data
  13514. */
  13515. populateData: function () {
  13516. var data = {};
  13517. Object.keys(this.sessions).forEach(function (sid) {
  13518. var session = this.sessions[sid];
  13519. if (session.peerconnection && session.peerconnection.updateLog) {
  13520. // FIXME: should probably be a .dump call
  13521. data["jingle_" + session.sid] = {
  13522. updateLog: session.peerconnection.updateLog,
  13523. stats: session.peerconnection.stats,
  13524. url: window.location.href
  13525. };
  13526. }
  13527. });
  13528. return data;
  13529. }
  13530. });
  13531. };
  13532. },{"../../service/xmpp/XMPPEvents":83,"./JingleSession":46}],55:[function(require,module,exports){
  13533. /* global Strophe */
  13534. module.exports = function () {
  13535. Strophe.addConnectionPlugin('logger', {
  13536. // logs raw stanzas and makes them available for download as JSON
  13537. connection: null,
  13538. log: [],
  13539. init: function (conn) {
  13540. this.connection = conn;
  13541. this.connection.rawInput = this.log_incoming.bind(this);
  13542. this.connection.rawOutput = this.log_outgoing.bind(this);
  13543. },
  13544. log_incoming: function (stanza) {
  13545. this.log.push([new Date().getTime(), 'incoming', stanza]);
  13546. },
  13547. log_outgoing: function (stanza) {
  13548. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  13549. }
  13550. });
  13551. };
  13552. },{}],56:[function(require,module,exports){
  13553. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  13554. setAudioMuted, Strophe */
  13555. /**
  13556. * Moderate connection plugin.
  13557. */
  13558. module.exports = function (XMPP) {
  13559. Strophe.addConnectionPlugin('moderate', {
  13560. connection: null,
  13561. init: function (conn) {
  13562. this.connection = conn;
  13563. this.connection.addHandler(this.onMute.bind(this),
  13564. 'http://jitsi.org/jitmeet/audio',
  13565. 'iq',
  13566. 'set',
  13567. null,
  13568. null);
  13569. },
  13570. setMute: function (jid, mute) {
  13571. console.info("set mute", mute);
  13572. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  13573. .c('mute', {
  13574. xmlns: 'http://jitsi.org/jitmeet/audio',
  13575. jid: jid
  13576. })
  13577. .t(mute.toString())
  13578. .up();
  13579. this.connection.sendIQ(
  13580. iqToFocus,
  13581. function (result) {
  13582. console.log('set mute', result);
  13583. },
  13584. function (error) {
  13585. console.log('set mute error', error);
  13586. });
  13587. },
  13588. onMute: function (iq) {
  13589. var from = iq.getAttribute('from');
  13590. if (from !== this.connection.emuc.focusMucJid) {
  13591. console.warn("Ignored mute from non focus peer");
  13592. return false;
  13593. }
  13594. var mute = $(iq).find('mute');
  13595. if (mute.length) {
  13596. var doMuteAudio = mute.text() === "true";
  13597. APP.UI.setAudioMuted(doMuteAudio);
  13598. XMPP.forceMuted = doMuteAudio;
  13599. }
  13600. return true;
  13601. },
  13602. eject: function (jid) {
  13603. // We're not the focus, so can't terminate
  13604. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  13605. this.connection.emuc.kick(jid);
  13606. }
  13607. });
  13608. }
  13609. },{}],57:[function(require,module,exports){
  13610. /* jshint -W117 */
  13611. module.exports = function() {
  13612. Strophe.addConnectionPlugin('rayo',
  13613. {
  13614. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  13615. connection: null,
  13616. init: function (conn) {
  13617. this.connection = conn;
  13618. if (this.connection.disco) {
  13619. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  13620. }
  13621. this.connection.addHandler(
  13622. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  13623. },
  13624. onRayo: function (iq) {
  13625. console.info("Rayo IQ", iq);
  13626. },
  13627. dial: function (to, from, roomName, roomPass) {
  13628. var self = this;
  13629. var req = $iq(
  13630. {
  13631. type: 'set',
  13632. to: this.connection.emuc.focusMucJid
  13633. }
  13634. );
  13635. req.c('dial',
  13636. {
  13637. xmlns: this.RAYO_XMLNS,
  13638. to: to,
  13639. from: from
  13640. });
  13641. req.c('header',
  13642. {
  13643. name: 'JvbRoomName',
  13644. value: roomName
  13645. }).up();
  13646. if (roomPass !== null && roomPass.length) {
  13647. req.c('header',
  13648. {
  13649. name: 'JvbRoomPassword',
  13650. value: roomPass
  13651. }).up();
  13652. }
  13653. this.connection.sendIQ(
  13654. req,
  13655. function (result) {
  13656. console.info('Dial result ', result);
  13657. var resource = $(result).find('ref').attr('uri');
  13658. this.call_resource = resource.substr('xmpp:'.length);
  13659. console.info(
  13660. "Received call resource: " + this.call_resource);
  13661. },
  13662. function (error) {
  13663. console.info('Dial error ', error);
  13664. }
  13665. );
  13666. },
  13667. hang_up: function () {
  13668. if (!this.call_resource) {
  13669. console.warn("No call in progress");
  13670. return;
  13671. }
  13672. var self = this;
  13673. var req = $iq(
  13674. {
  13675. type: 'set',
  13676. to: this.call_resource
  13677. }
  13678. );
  13679. req.c('hangup',
  13680. {
  13681. xmlns: this.RAYO_XMLNS
  13682. });
  13683. this.connection.sendIQ(
  13684. req,
  13685. function (result) {
  13686. console.info('Hangup result ', result);
  13687. self.call_resource = null;
  13688. },
  13689. function (error) {
  13690. console.info('Hangup error ', error);
  13691. self.call_resource = null;
  13692. }
  13693. );
  13694. }
  13695. }
  13696. );
  13697. };
  13698. },{}],58:[function(require,module,exports){
  13699. /**
  13700. * Strophe logger implementation. Logs from level WARN and above.
  13701. */
  13702. module.exports = function () {
  13703. Strophe.log = function (level, msg) {
  13704. switch (level) {
  13705. case Strophe.LogLevel.WARN:
  13706. console.warn("Strophe: " + msg);
  13707. break;
  13708. case Strophe.LogLevel.ERROR:
  13709. case Strophe.LogLevel.FATAL:
  13710. console.error("Strophe: " + msg);
  13711. break;
  13712. }
  13713. };
  13714. Strophe.getStatusString = function (status) {
  13715. switch (status) {
  13716. case Strophe.Status.ERROR:
  13717. return "ERROR";
  13718. case Strophe.Status.CONNECTING:
  13719. return "CONNECTING";
  13720. case Strophe.Status.CONNFAIL:
  13721. return "CONNFAIL";
  13722. case Strophe.Status.AUTHENTICATING:
  13723. return "AUTHENTICATING";
  13724. case Strophe.Status.AUTHFAIL:
  13725. return "AUTHFAIL";
  13726. case Strophe.Status.CONNECTED:
  13727. return "CONNECTED";
  13728. case Strophe.Status.DISCONNECTED:
  13729. return "DISCONNECTED";
  13730. case Strophe.Status.DISCONNECTING:
  13731. return "DISCONNECTING";
  13732. case Strophe.Status.ATTACHED:
  13733. return "ATTACHED";
  13734. default:
  13735. return "unknown";
  13736. }
  13737. };
  13738. };
  13739. },{}],59:[function(require,module,exports){
  13740. var Moderator = require("./moderator");
  13741. var EventEmitter = require("events");
  13742. var Recording = require("./recording");
  13743. var SDP = require("./SDP");
  13744. var Pako = require("pako");
  13745. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  13746. var UIEvents = require("../../service/UI/UIEvents");
  13747. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13748. var eventEmitter = new EventEmitter();
  13749. var connection = null;
  13750. var authenticatedUser = false;
  13751. function connect(jid, password, uiCredentials) {
  13752. var bosh
  13753. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  13754. || config.bosh || '/http-bind';
  13755. connection = new Strophe.Connection(bosh);
  13756. Moderator.setConnection(connection);
  13757. if(uiCredentials) {
  13758. var email = uiCredentials.email;
  13759. var displayName = uiCredentials.displayName;
  13760. if (email) {
  13761. connection.emuc.addEmailToPresence(email);
  13762. } else {
  13763. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  13764. }
  13765. if (displayName) {
  13766. connection.emuc.addDisplayNameToPresence(displayName);
  13767. }
  13768. }
  13769. if (connection.disco) {
  13770. // for chrome, add multistream cap
  13771. }
  13772. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  13773. if (config.useIPv6) {
  13774. // https://code.google.com/p/webrtc/issues/detail?id=2828
  13775. if (!connection.jingle.pc_constraints.optional)
  13776. connection.jingle.pc_constraints.optional = [];
  13777. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  13778. }
  13779. if(!password)
  13780. password = uiCredentials.password;
  13781. var anonymousConnectionFailed = false;
  13782. connection.connect(jid, password, function (status, msg) {
  13783. console.log('Strophe status changed to',
  13784. Strophe.getStatusString(status));
  13785. if (status === Strophe.Status.CONNECTED) {
  13786. if (config.useStunTurn) {
  13787. connection.jingle.getStunAndTurnCredentials();
  13788. }
  13789. APP.UI.disableConnect();
  13790. console.info("My Jabber ID: " + connection.jid);
  13791. if(password)
  13792. authenticatedUser = true;
  13793. maybeDoJoin();
  13794. } else if (status === Strophe.Status.CONNFAIL) {
  13795. if(msg === 'x-strophe-bad-non-anon-jid') {
  13796. anonymousConnectionFailed = true;
  13797. }
  13798. } else if (status === Strophe.Status.DISCONNECTED) {
  13799. if(anonymousConnectionFailed) {
  13800. // prompt user for username and password
  13801. XMPP.promptLogin();
  13802. }
  13803. } else if (status === Strophe.Status.AUTHFAIL) {
  13804. // wrong password or username, prompt user
  13805. XMPP.promptLogin();
  13806. }
  13807. });
  13808. }
  13809. function maybeDoJoin() {
  13810. if (connection && connection.connected &&
  13811. Strophe.getResourceFromJid(connection.jid)
  13812. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  13813. // .connected is true while connecting?
  13814. doJoin();
  13815. }
  13816. }
  13817. function doJoin() {
  13818. var roomName = APP.UI.generateRoomName();
  13819. Moderator.allocateConferenceFocus(
  13820. roomName, APP.UI.checkForNicknameAndJoin);
  13821. }
  13822. function initStrophePlugins()
  13823. {
  13824. require("./strophe.emuc")(XMPP, eventEmitter);
  13825. require("./strophe.jingle")(XMPP, eventEmitter);
  13826. require("./strophe.moderate")(XMPP);
  13827. require("./strophe.util")();
  13828. require("./strophe.rayo")();
  13829. require("./strophe.logger")();
  13830. }
  13831. function registerListeners() {
  13832. APP.RTC.addStreamListener(maybeDoJoin,
  13833. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  13834. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  13835. XMPP.addToPresence("displayName", nickname);
  13836. });
  13837. }
  13838. function setupEvents() {
  13839. $(window).bind('beforeunload', function () {
  13840. if (connection && connection.connected) {
  13841. // ensure signout
  13842. $.ajax({
  13843. type: 'POST',
  13844. url: config.bosh,
  13845. async: false,
  13846. cache: false,
  13847. contentType: 'application/xml',
  13848. data: "<body rid='" + (connection.rid || connection._proto.rid)
  13849. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  13850. + (connection.sid || connection._proto.sid)
  13851. + "' type='terminate'>" +
  13852. "<presence xmlns='jabber:client' type='unavailable'/>" +
  13853. "</body>",
  13854. success: function (data) {
  13855. console.log('signed out');
  13856. console.log(data);
  13857. },
  13858. error: function (XMLHttpRequest, textStatus, errorThrown) {
  13859. console.log('signout error',
  13860. textStatus + ' (' + errorThrown + ')');
  13861. }
  13862. });
  13863. }
  13864. XMPP.disposeConference(true);
  13865. });
  13866. }
  13867. var XMPP = {
  13868. sessionTerminated: false,
  13869. /**
  13870. * Remembers if we were muted by the focus.
  13871. * @type {boolean}
  13872. */
  13873. forceMuted: false,
  13874. start: function (uiCredentials) {
  13875. setupEvents();
  13876. initStrophePlugins();
  13877. registerListeners();
  13878. Moderator.init(this, eventEmitter);
  13879. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  13880. // Force authenticated domain if room is appended with '?login=true'
  13881. if (config.hosts.anonymousdomain &&
  13882. window.location.search.indexOf("login=true") !== -1) {
  13883. configDomain = config.hosts.domain;
  13884. }
  13885. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  13886. connect(jid, null, uiCredentials);
  13887. },
  13888. promptLogin: function () {
  13889. APP.UI.showLoginPopup(connect);
  13890. },
  13891. joinRoom: function(roomName, useNicks, nick)
  13892. {
  13893. var roomjid;
  13894. roomjid = roomName;
  13895. if (useNicks) {
  13896. if (nick) {
  13897. roomjid += '/' + nick;
  13898. } else {
  13899. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  13900. }
  13901. } else {
  13902. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  13903. if(!authenticatedUser)
  13904. tmpJid = tmpJid.substr(0, 8);
  13905. roomjid += '/' + tmpJid;
  13906. }
  13907. connection.emuc.doJoin(roomjid);
  13908. },
  13909. myJid: function () {
  13910. if(!connection)
  13911. return null;
  13912. return connection.emuc.myroomjid;
  13913. },
  13914. myResource: function () {
  13915. if(!connection || ! connection.emuc.myroomjid)
  13916. return null;
  13917. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  13918. },
  13919. disposeConference: function (onUnload) {
  13920. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  13921. var handler = connection.jingle.activecall;
  13922. if (handler && handler.peerconnection) {
  13923. // FIXME: probably removing streams is not required and close() should
  13924. // be enough
  13925. if (APP.RTC.localAudio) {
  13926. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  13927. }
  13928. if (APP.RTC.localVideo) {
  13929. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  13930. }
  13931. handler.peerconnection.close();
  13932. }
  13933. connection.jingle.activecall = null;
  13934. if(!onUnload)
  13935. {
  13936. this.sessionTerminated = true;
  13937. connection.emuc.doLeave();
  13938. }
  13939. },
  13940. addListener: function(type, listener)
  13941. {
  13942. eventEmitter.on(type, listener);
  13943. },
  13944. removeListener: function (type, listener) {
  13945. eventEmitter.removeListener(type, listener);
  13946. },
  13947. allocateConferenceFocus: function(roomName, callback) {
  13948. Moderator.allocateConferenceFocus(roomName, callback);
  13949. },
  13950. isModerator: function () {
  13951. return Moderator.isModerator();
  13952. },
  13953. isSipGatewayEnabled: function () {
  13954. return Moderator.isSipGatewayEnabled();
  13955. },
  13956. isExternalAuthEnabled: function () {
  13957. return Moderator.isExternalAuthEnabled();
  13958. },
  13959. switchStreams: function (stream, oldStream, callback) {
  13960. if (connection && connection.jingle.activecall) {
  13961. // FIXME: will block switchInProgress on true value in case of exception
  13962. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  13963. } else {
  13964. // We are done immediately
  13965. console.error("No conference handler");
  13966. UI.messageHandler.showError('Error',
  13967. 'Unable to switch video stream.');
  13968. callback();
  13969. }
  13970. },
  13971. setVideoMute: function (mute, callback, options) {
  13972. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  13973. {
  13974. connection.jingle.activecall.setVideoMute(mute, callback, options);
  13975. }
  13976. },
  13977. setAudioMute: function (mute, callback) {
  13978. if (!(connection && APP.RTC.localAudio)) {
  13979. return false;
  13980. }
  13981. if (this.forceMuted && !mute) {
  13982. console.info("Asking focus for unmute");
  13983. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  13984. // FIXME: wait for result before resetting muted status
  13985. this.forceMuted = false;
  13986. }
  13987. if (mute == APP.RTC.localAudio.isMuted()) {
  13988. // Nothing to do
  13989. return true;
  13990. }
  13991. // It is not clear what is the right way to handle multiple tracks.
  13992. // So at least make sure that they are all muted or all unmuted and
  13993. // that we send presence just once.
  13994. APP.RTC.localAudio.mute();
  13995. // isMuted is the opposite of audioEnabled
  13996. connection.emuc.addAudioInfoToPresence(mute);
  13997. connection.emuc.sendPresence();
  13998. callback();
  13999. return true;
  14000. },
  14001. // Really mute video, i.e. dont even send black frames
  14002. muteVideo: function (pc, unmute) {
  14003. // FIXME: this probably needs another of those lovely state safeguards...
  14004. // which checks for iceconn == connected and sigstate == stable
  14005. pc.setRemoteDescription(pc.remoteDescription,
  14006. function () {
  14007. pc.createAnswer(
  14008. function (answer) {
  14009. var sdp = new SDP(answer.sdp);
  14010. if (sdp.media.length > 1) {
  14011. if (unmute)
  14012. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14013. else
  14014. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14015. sdp.raw = sdp.session + sdp.media.join('');
  14016. answer.sdp = sdp.raw;
  14017. }
  14018. pc.setLocalDescription(answer,
  14019. function () {
  14020. console.log('mute SLD ok');
  14021. },
  14022. function (error) {
  14023. console.log('mute SLD error');
  14024. APP.UI.messageHandler.showError('Error',
  14025. 'Oops! Something went wrong and we failed to ' +
  14026. 'mute! (SLD Failure)');
  14027. }
  14028. );
  14029. },
  14030. function (error) {
  14031. console.log(error);
  14032. APP.UI.messageHandler.showError();
  14033. }
  14034. );
  14035. },
  14036. function (error) {
  14037. console.log('muteVideo SRD error');
  14038. APP.UI.messageHandler.showError('Error',
  14039. 'Oops! Something went wrong and we failed to stop video!' +
  14040. '(SRD Failure)');
  14041. }
  14042. );
  14043. },
  14044. toggleRecording: function (tokenEmptyCallback,
  14045. startingCallback, startedCallback) {
  14046. Recording.toggleRecording(tokenEmptyCallback,
  14047. startingCallback, startedCallback, connection);
  14048. },
  14049. addToPresence: function (name, value, dontSend) {
  14050. switch (name)
  14051. {
  14052. case "displayName":
  14053. connection.emuc.addDisplayNameToPresence(value);
  14054. break;
  14055. case "etherpad":
  14056. connection.emuc.addEtherpadToPresence(value);
  14057. break;
  14058. case "prezi":
  14059. connection.emuc.addPreziToPresence(value, 0);
  14060. break;
  14061. case "preziSlide":
  14062. connection.emuc.addCurrentSlideToPresence(value);
  14063. break;
  14064. case "connectionQuality":
  14065. connection.emuc.addConnectionInfoToPresence(value);
  14066. break;
  14067. case "email":
  14068. connection.emuc.addEmailToPresence(value);
  14069. default :
  14070. console.log("Unknown tag for presence.");
  14071. return;
  14072. }
  14073. if(!dontSend)
  14074. connection.emuc.sendPresence();
  14075. },
  14076. sendLogs: function (data) {
  14077. if(!connection.emuc.focusMucJid)
  14078. return;
  14079. var deflate = true;
  14080. var content = JSON.stringify(data);
  14081. if (deflate) {
  14082. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14083. }
  14084. content = Base64.encode(content);
  14085. // XEP-0337-ish
  14086. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14087. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14088. id: 'PeerConnectionStats'});
  14089. message.c('message').t(content).up();
  14090. if (deflate) {
  14091. message.c('tag', {name: "deflated", value: "true"}).up();
  14092. }
  14093. message.up();
  14094. connection.send(message);
  14095. },
  14096. populateData: function () {
  14097. var data = {};
  14098. if (connection.jingle) {
  14099. data = connection.jingle.populateData();
  14100. }
  14101. return data;
  14102. },
  14103. getLogger: function () {
  14104. if(connection.logger)
  14105. return connection.logger.log;
  14106. return null;
  14107. },
  14108. getPrezi: function () {
  14109. return connection.emuc.getPrezi(this.myJid());
  14110. },
  14111. removePreziFromPresence: function () {
  14112. connection.emuc.removePreziFromPresence();
  14113. connection.emuc.sendPresence();
  14114. },
  14115. sendChatMessage: function (message, nickname) {
  14116. connection.emuc.sendMessage(message, nickname);
  14117. },
  14118. setSubject: function (topic) {
  14119. connection.emuc.setSubject(topic);
  14120. },
  14121. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14122. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14123. },
  14124. dial: function (to, from, roomName,roomPass) {
  14125. connection.rayo.dial(to, from, roomName,roomPass);
  14126. },
  14127. setMute: function (jid, mute) {
  14128. connection.moderate.setMute(jid, mute);
  14129. },
  14130. eject: function (jid) {
  14131. connection.moderate.eject(jid);
  14132. },
  14133. findJidFromResource: function (resource) {
  14134. return connection.emuc.findJidFromResource(resource);
  14135. },
  14136. getMembers: function () {
  14137. return connection.emuc.members;
  14138. },
  14139. getJidFromSSRC: function (ssrc) {
  14140. if(!connection)
  14141. return null;
  14142. return connection.emuc.ssrc2jid[ssrc];
  14143. }
  14144. };
  14145. module.exports = XMPP;
  14146. },{"../../service/RTC/StreamEventTypes":79,"../../service/UI/UIEvents":80,"../../service/xmpp/XMPPEvents":83,"./SDP":47,"./moderator":51,"./recording":52,"./strophe.emuc":53,"./strophe.jingle":54,"./strophe.logger":55,"./strophe.moderate":56,"./strophe.rayo":57,"./strophe.util":58,"events":84,"pako":60}],60:[function(require,module,exports){
  14147. // Top level file is just a mixin of submodules & constants
  14148. 'use strict';
  14149. var assign = require('./lib/utils/common').assign;
  14150. var deflate = require('./lib/deflate');
  14151. var inflate = require('./lib/inflate');
  14152. var constants = require('./lib/zlib/constants');
  14153. var pako = {};
  14154. assign(pako, deflate, inflate, constants);
  14155. module.exports = pako;
  14156. },{"./lib/deflate":61,"./lib/inflate":62,"./lib/utils/common":63,"./lib/zlib/constants":66}],61:[function(require,module,exports){
  14157. 'use strict';
  14158. var zlib_deflate = require('./zlib/deflate.js');
  14159. var utils = require('./utils/common');
  14160. var strings = require('./utils/strings');
  14161. var msg = require('./zlib/messages');
  14162. var zstream = require('./zlib/zstream');
  14163. /* Public constants ==========================================================*/
  14164. /* ===========================================================================*/
  14165. var Z_NO_FLUSH = 0;
  14166. var Z_FINISH = 4;
  14167. var Z_OK = 0;
  14168. var Z_STREAM_END = 1;
  14169. var Z_DEFAULT_COMPRESSION = -1;
  14170. var Z_DEFAULT_STRATEGY = 0;
  14171. var Z_DEFLATED = 8;
  14172. /* ===========================================================================*/
  14173. /**
  14174. * class Deflate
  14175. *
  14176. * Generic JS-style wrapper for zlib calls. If you don't need
  14177. * streaming behaviour - use more simple functions: [[deflate]],
  14178. * [[deflateRaw]] and [[gzip]].
  14179. **/
  14180. /* internal
  14181. * Deflate.chunks -> Array
  14182. *
  14183. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14184. **/
  14185. /**
  14186. * Deflate.result -> Uint8Array|Array
  14187. *
  14188. * Compressed result, generated by default [[Deflate#onData]]
  14189. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14190. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  14191. **/
  14192. /**
  14193. * Deflate.err -> Number
  14194. *
  14195. * Error code after deflate finished. 0 (Z_OK) on success.
  14196. * You will not need it in real life, because deflate errors
  14197. * are possible only on wrong options or bad `onData` / `onEnd`
  14198. * custom handlers.
  14199. **/
  14200. /**
  14201. * Deflate.msg -> String
  14202. *
  14203. * Error message, if [[Deflate.err]] != 0
  14204. **/
  14205. /**
  14206. * new Deflate(options)
  14207. * - options (Object): zlib deflate options.
  14208. *
  14209. * Creates new deflator instance with specified params. Throws exception
  14210. * on bad params. Supported options:
  14211. *
  14212. * - `level`
  14213. * - `windowBits`
  14214. * - `memLevel`
  14215. * - `strategy`
  14216. *
  14217. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14218. * for more information on these.
  14219. *
  14220. * Additional options, for internal needs:
  14221. *
  14222. * - `chunkSize` - size of generated data chunks (16K by default)
  14223. * - `raw` (Boolean) - do raw deflate
  14224. * - `gzip` (Boolean) - create gzip wrapper
  14225. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14226. * (each char code [0..255])
  14227. * - `header` (Object) - custom header for gzip
  14228. * - `text` (Boolean) - true if compressed data believed to be text
  14229. * - `time` (Number) - modification time, unix timestamp
  14230. * - `os` (Number) - operation system code
  14231. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14232. * - `name` (String) - file name (binary string)
  14233. * - `comment` (String) - comment (binary string)
  14234. * - `hcrc` (Boolean) - true if header crc should be added
  14235. *
  14236. * ##### Example:
  14237. *
  14238. * ```javascript
  14239. * var pako = require('pako')
  14240. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14241. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14242. *
  14243. * var deflate = new pako.Deflate({ level: 3});
  14244. *
  14245. * deflate.push(chunk1, false);
  14246. * deflate.push(chunk2, true); // true -> last chunk
  14247. *
  14248. * if (deflate.err) { throw new Error(deflate.err); }
  14249. *
  14250. * console.log(deflate.result);
  14251. * ```
  14252. **/
  14253. var Deflate = function(options) {
  14254. this.options = utils.assign({
  14255. level: Z_DEFAULT_COMPRESSION,
  14256. method: Z_DEFLATED,
  14257. chunkSize: 16384,
  14258. windowBits: 15,
  14259. memLevel: 8,
  14260. strategy: Z_DEFAULT_STRATEGY,
  14261. to: ''
  14262. }, options || {});
  14263. var opt = this.options;
  14264. if (opt.raw && (opt.windowBits > 0)) {
  14265. opt.windowBits = -opt.windowBits;
  14266. }
  14267. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  14268. opt.windowBits += 16;
  14269. }
  14270. this.err = 0; // error code, if happens (0 = Z_OK)
  14271. this.msg = ''; // error message
  14272. this.ended = false; // used to avoid multiple onEnd() calls
  14273. this.chunks = []; // chunks of compressed data
  14274. this.strm = new zstream();
  14275. this.strm.avail_out = 0;
  14276. var status = zlib_deflate.deflateInit2(
  14277. this.strm,
  14278. opt.level,
  14279. opt.method,
  14280. opt.windowBits,
  14281. opt.memLevel,
  14282. opt.strategy
  14283. );
  14284. if (status !== Z_OK) {
  14285. throw new Error(msg[status]);
  14286. }
  14287. if (opt.header) {
  14288. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  14289. }
  14290. };
  14291. /**
  14292. * Deflate#push(data[, mode]) -> Boolean
  14293. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  14294. * utf8 byte sequence.
  14295. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14296. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14297. *
  14298. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  14299. * new compressed chunks. Returns `true` on success. The last data block must have
  14300. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  14301. * [[Deflate#onEnd]].
  14302. *
  14303. * On fail call [[Deflate#onEnd]] with error code and return false.
  14304. *
  14305. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14306. * array format is detected automatically). Also, don't skip last param and always
  14307. * use the same type in your code (boolean or number). That will improve JS speed.
  14308. *
  14309. * For regular `Array`-s make sure all elements are [0..255].
  14310. *
  14311. * ##### Example
  14312. *
  14313. * ```javascript
  14314. * push(chunk, false); // push one of data chunks
  14315. * ...
  14316. * push(chunk, true); // push last chunk
  14317. * ```
  14318. **/
  14319. Deflate.prototype.push = function(data, mode) {
  14320. var strm = this.strm;
  14321. var chunkSize = this.options.chunkSize;
  14322. var status, _mode;
  14323. if (this.ended) { return false; }
  14324. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  14325. // Convert data if needed
  14326. if (typeof data === 'string') {
  14327. // If we need to compress text, change encoding to utf8.
  14328. strm.input = strings.string2buf(data);
  14329. } else {
  14330. strm.input = data;
  14331. }
  14332. strm.next_in = 0;
  14333. strm.avail_in = strm.input.length;
  14334. do {
  14335. if (strm.avail_out === 0) {
  14336. strm.output = new utils.Buf8(chunkSize);
  14337. strm.next_out = 0;
  14338. strm.avail_out = chunkSize;
  14339. }
  14340. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  14341. if (status !== Z_STREAM_END && status !== Z_OK) {
  14342. this.onEnd(status);
  14343. this.ended = true;
  14344. return false;
  14345. }
  14346. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  14347. if (this.options.to === 'string') {
  14348. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  14349. } else {
  14350. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14351. }
  14352. }
  14353. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  14354. // Finalize on the last chunk.
  14355. if (_mode === Z_FINISH) {
  14356. status = zlib_deflate.deflateEnd(this.strm);
  14357. this.onEnd(status);
  14358. this.ended = true;
  14359. return status === Z_OK;
  14360. }
  14361. return true;
  14362. };
  14363. /**
  14364. * Deflate#onData(chunk) -> Void
  14365. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14366. * on js engine support. When string output requested, each chunk
  14367. * will be string.
  14368. *
  14369. * By default, stores data blocks in `chunks[]` property and glue
  14370. * those in `onEnd`. Override this handler, if you need another behaviour.
  14371. **/
  14372. Deflate.prototype.onData = function(chunk) {
  14373. this.chunks.push(chunk);
  14374. };
  14375. /**
  14376. * Deflate#onEnd(status) -> Void
  14377. * - status (Number): deflate status. 0 (Z_OK) on success,
  14378. * other if not.
  14379. *
  14380. * Called once after you tell deflate that input stream complete
  14381. * or error happenned. By default - join collected chunks,
  14382. * free memory and fill `results` / `err` properties.
  14383. **/
  14384. Deflate.prototype.onEnd = function(status) {
  14385. // On success - join
  14386. if (status === Z_OK) {
  14387. if (this.options.to === 'string') {
  14388. this.result = this.chunks.join('');
  14389. } else {
  14390. this.result = utils.flattenChunks(this.chunks);
  14391. }
  14392. }
  14393. this.chunks = [];
  14394. this.err = status;
  14395. this.msg = this.strm.msg;
  14396. };
  14397. /**
  14398. * deflate(data[, options]) -> Uint8Array|Array|String
  14399. * - data (Uint8Array|Array|String): input data to compress.
  14400. * - options (Object): zlib deflate options.
  14401. *
  14402. * Compress `data` with deflate alrorythm and `options`.
  14403. *
  14404. * Supported options are:
  14405. *
  14406. * - level
  14407. * - windowBits
  14408. * - memLevel
  14409. * - strategy
  14410. *
  14411. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14412. * for more information on these.
  14413. *
  14414. * Sugar (options):
  14415. *
  14416. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14417. * negative windowBits implicitly.
  14418. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14419. * (each char code [0..255])
  14420. *
  14421. * ##### Example:
  14422. *
  14423. * ```javascript
  14424. * var pako = require('pako')
  14425. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  14426. *
  14427. * console.log(pako.deflate(data));
  14428. * ```
  14429. **/
  14430. function deflate(input, options) {
  14431. var deflator = new Deflate(options);
  14432. deflator.push(input, true);
  14433. // That will never happens, if you don't cheat with options :)
  14434. if (deflator.err) { throw deflator.msg; }
  14435. return deflator.result;
  14436. }
  14437. /**
  14438. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  14439. * - data (Uint8Array|Array|String): input data to compress.
  14440. * - options (Object): zlib deflate options.
  14441. *
  14442. * The same as [[deflate]], but creates raw data, without wrapper
  14443. * (header and adler32 crc).
  14444. **/
  14445. function deflateRaw(input, options) {
  14446. options = options || {};
  14447. options.raw = true;
  14448. return deflate(input, options);
  14449. }
  14450. /**
  14451. * gzip(data[, options]) -> Uint8Array|Array|String
  14452. * - data (Uint8Array|Array|String): input data to compress.
  14453. * - options (Object): zlib deflate options.
  14454. *
  14455. * The same as [[deflate]], but create gzip wrapper instead of
  14456. * deflate one.
  14457. **/
  14458. function gzip(input, options) {
  14459. options = options || {};
  14460. options.gzip = true;
  14461. return deflate(input, options);
  14462. }
  14463. exports.Deflate = Deflate;
  14464. exports.deflate = deflate;
  14465. exports.deflateRaw = deflateRaw;
  14466. exports.gzip = gzip;
  14467. },{"./utils/common":63,"./utils/strings":64,"./zlib/deflate.js":68,"./zlib/messages":73,"./zlib/zstream":75}],62:[function(require,module,exports){
  14468. 'use strict';
  14469. var zlib_inflate = require('./zlib/inflate.js');
  14470. var utils = require('./utils/common');
  14471. var strings = require('./utils/strings');
  14472. var c = require('./zlib/constants');
  14473. var msg = require('./zlib/messages');
  14474. var zstream = require('./zlib/zstream');
  14475. var gzheader = require('./zlib/gzheader');
  14476. /**
  14477. * class Inflate
  14478. *
  14479. * Generic JS-style wrapper for zlib calls. If you don't need
  14480. * streaming behaviour - use more simple functions: [[inflate]]
  14481. * and [[inflateRaw]].
  14482. **/
  14483. /* internal
  14484. * inflate.chunks -> Array
  14485. *
  14486. * Chunks of output data, if [[Inflate#onData]] not overriden.
  14487. **/
  14488. /**
  14489. * Inflate.result -> Uint8Array|Array|String
  14490. *
  14491. * Uncompressed result, generated by default [[Inflate#onData]]
  14492. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  14493. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  14494. **/
  14495. /**
  14496. * Inflate.err -> Number
  14497. *
  14498. * Error code after inflate finished. 0 (Z_OK) on success.
  14499. * Should be checked if broken data possible.
  14500. **/
  14501. /**
  14502. * Inflate.msg -> String
  14503. *
  14504. * Error message, if [[Inflate.err]] != 0
  14505. **/
  14506. /**
  14507. * new Inflate(options)
  14508. * - options (Object): zlib inflate options.
  14509. *
  14510. * Creates new inflator instance with specified params. Throws exception
  14511. * on bad params. Supported options:
  14512. *
  14513. * - `windowBits`
  14514. *
  14515. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14516. * for more information on these.
  14517. *
  14518. * Additional options, for internal needs:
  14519. *
  14520. * - `chunkSize` - size of generated data chunks (16K by default)
  14521. * - `raw` (Boolean) - do raw inflate
  14522. * - `to` (String) - if equal to 'string', then result will be converted
  14523. * from utf8 to utf16 (javascript) string. When string output requested,
  14524. * chunk length can differ from `chunkSize`, depending on content.
  14525. *
  14526. * By default, when no options set, autodetect deflate/gzip data format via
  14527. * wrapper header.
  14528. *
  14529. * ##### Example:
  14530. *
  14531. * ```javascript
  14532. * var pako = require('pako')
  14533. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14534. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14535. *
  14536. * var inflate = new pako.Inflate({ level: 3});
  14537. *
  14538. * inflate.push(chunk1, false);
  14539. * inflate.push(chunk2, true); // true -> last chunk
  14540. *
  14541. * if (inflate.err) { throw new Error(inflate.err); }
  14542. *
  14543. * console.log(inflate.result);
  14544. * ```
  14545. **/
  14546. var Inflate = function(options) {
  14547. this.options = utils.assign({
  14548. chunkSize: 16384,
  14549. windowBits: 0,
  14550. to: ''
  14551. }, options || {});
  14552. var opt = this.options;
  14553. // Force window size for `raw` data, if not set directly,
  14554. // because we have no header for autodetect.
  14555. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  14556. opt.windowBits = -opt.windowBits;
  14557. if (opt.windowBits === 0) { opt.windowBits = -15; }
  14558. }
  14559. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  14560. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  14561. !(options && options.windowBits)) {
  14562. opt.windowBits += 32;
  14563. }
  14564. // Gzip header has no info about windows size, we can do autodetect only
  14565. // for deflate. So, if window size not set, force it to max when gzip possible
  14566. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  14567. // bit 3 (16) -> gzipped data
  14568. // bit 4 (32) -> autodetect gzip/deflate
  14569. if ((opt.windowBits & 15) === 0) {
  14570. opt.windowBits |= 15;
  14571. }
  14572. }
  14573. this.err = 0; // error code, if happens (0 = Z_OK)
  14574. this.msg = ''; // error message
  14575. this.ended = false; // used to avoid multiple onEnd() calls
  14576. this.chunks = []; // chunks of compressed data
  14577. this.strm = new zstream();
  14578. this.strm.avail_out = 0;
  14579. var status = zlib_inflate.inflateInit2(
  14580. this.strm,
  14581. opt.windowBits
  14582. );
  14583. if (status !== c.Z_OK) {
  14584. throw new Error(msg[status]);
  14585. }
  14586. this.header = new gzheader();
  14587. zlib_inflate.inflateGetHeader(this.strm, this.header);
  14588. };
  14589. /**
  14590. * Inflate#push(data[, mode]) -> Boolean
  14591. * - data (Uint8Array|Array|String): input data
  14592. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14593. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14594. *
  14595. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  14596. * new output chunks. Returns `true` on success. The last data block must have
  14597. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  14598. * [[Inflate#onEnd]].
  14599. *
  14600. * On fail call [[Inflate#onEnd]] with error code and return false.
  14601. *
  14602. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14603. * format is detected automatically). Also, don't skip last param and always
  14604. * use the same type in your code (boolean or number). That will improve JS speed.
  14605. *
  14606. * For regular `Array`-s make sure all elements are [0..255].
  14607. *
  14608. * ##### Example
  14609. *
  14610. * ```javascript
  14611. * push(chunk, false); // push one of data chunks
  14612. * ...
  14613. * push(chunk, true); // push last chunk
  14614. * ```
  14615. **/
  14616. Inflate.prototype.push = function(data, mode) {
  14617. var strm = this.strm;
  14618. var chunkSize = this.options.chunkSize;
  14619. var status, _mode;
  14620. var next_out_utf8, tail, utf8str;
  14621. if (this.ended) { return false; }
  14622. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  14623. // Convert data if needed
  14624. if (typeof data === 'string') {
  14625. // Only binary strings can be decompressed on practice
  14626. strm.input = strings.binstring2buf(data);
  14627. } else {
  14628. strm.input = data;
  14629. }
  14630. strm.next_in = 0;
  14631. strm.avail_in = strm.input.length;
  14632. do {
  14633. if (strm.avail_out === 0) {
  14634. strm.output = new utils.Buf8(chunkSize);
  14635. strm.next_out = 0;
  14636. strm.avail_out = chunkSize;
  14637. }
  14638. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  14639. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  14640. this.onEnd(status);
  14641. this.ended = true;
  14642. return false;
  14643. }
  14644. if (strm.next_out) {
  14645. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  14646. if (this.options.to === 'string') {
  14647. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  14648. tail = strm.next_out - next_out_utf8;
  14649. utf8str = strings.buf2string(strm.output, next_out_utf8);
  14650. // move tail
  14651. strm.next_out = tail;
  14652. strm.avail_out = chunkSize - tail;
  14653. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  14654. this.onData(utf8str);
  14655. } else {
  14656. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14657. }
  14658. }
  14659. }
  14660. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  14661. if (status === c.Z_STREAM_END) {
  14662. _mode = c.Z_FINISH;
  14663. }
  14664. // Finalize on the last chunk.
  14665. if (_mode === c.Z_FINISH) {
  14666. status = zlib_inflate.inflateEnd(this.strm);
  14667. this.onEnd(status);
  14668. this.ended = true;
  14669. return status === c.Z_OK;
  14670. }
  14671. return true;
  14672. };
  14673. /**
  14674. * Inflate#onData(chunk) -> Void
  14675. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14676. * on js engine support. When string output requested, each chunk
  14677. * will be string.
  14678. *
  14679. * By default, stores data blocks in `chunks[]` property and glue
  14680. * those in `onEnd`. Override this handler, if you need another behaviour.
  14681. **/
  14682. Inflate.prototype.onData = function(chunk) {
  14683. this.chunks.push(chunk);
  14684. };
  14685. /**
  14686. * Inflate#onEnd(status) -> Void
  14687. * - status (Number): inflate status. 0 (Z_OK) on success,
  14688. * other if not.
  14689. *
  14690. * Called once after you tell inflate that input stream complete
  14691. * or error happenned. By default - join collected chunks,
  14692. * free memory and fill `results` / `err` properties.
  14693. **/
  14694. Inflate.prototype.onEnd = function(status) {
  14695. // On success - join
  14696. if (status === c.Z_OK) {
  14697. if (this.options.to === 'string') {
  14698. // Glue & convert here, until we teach pako to send
  14699. // utf8 alligned strings to onData
  14700. this.result = this.chunks.join('');
  14701. } else {
  14702. this.result = utils.flattenChunks(this.chunks);
  14703. }
  14704. }
  14705. this.chunks = [];
  14706. this.err = status;
  14707. this.msg = this.strm.msg;
  14708. };
  14709. /**
  14710. * inflate(data[, options]) -> Uint8Array|Array|String
  14711. * - data (Uint8Array|Array|String): input data to decompress.
  14712. * - options (Object): zlib inflate options.
  14713. *
  14714. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  14715. * format via wrapper header by default. That's why we don't provide
  14716. * separate `ungzip` method.
  14717. *
  14718. * Supported options are:
  14719. *
  14720. * - windowBits
  14721. *
  14722. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14723. * for more information.
  14724. *
  14725. * Sugar (options):
  14726. *
  14727. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14728. * negative windowBits implicitly.
  14729. * - `to` (String) - if equal to 'string', then result will be converted
  14730. * from utf8 to utf16 (javascript) string. When string output requested,
  14731. * chunk length can differ from `chunkSize`, depending on content.
  14732. *
  14733. *
  14734. * ##### Example:
  14735. *
  14736. * ```javascript
  14737. * var pako = require('pako')
  14738. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  14739. * , output;
  14740. *
  14741. * try {
  14742. * output = pako.inflate(input);
  14743. * } catch (err)
  14744. * console.log(err);
  14745. * }
  14746. * ```
  14747. **/
  14748. function inflate(input, options) {
  14749. var inflator = new Inflate(options);
  14750. inflator.push(input, true);
  14751. // That will never happens, if you don't cheat with options :)
  14752. if (inflator.err) { throw inflator.msg; }
  14753. return inflator.result;
  14754. }
  14755. /**
  14756. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  14757. * - data (Uint8Array|Array|String): input data to decompress.
  14758. * - options (Object): zlib inflate options.
  14759. *
  14760. * The same as [[inflate]], but creates raw data, without wrapper
  14761. * (header and adler32 crc).
  14762. **/
  14763. function inflateRaw(input, options) {
  14764. options = options || {};
  14765. options.raw = true;
  14766. return inflate(input, options);
  14767. }
  14768. /**
  14769. * ungzip(data[, options]) -> Uint8Array|Array|String
  14770. * - data (Uint8Array|Array|String): input data to decompress.
  14771. * - options (Object): zlib inflate options.
  14772. *
  14773. * Just shortcut to [[inflate]], because it autodetects format
  14774. * by header.content. Done for convenience.
  14775. **/
  14776. exports.Inflate = Inflate;
  14777. exports.inflate = inflate;
  14778. exports.inflateRaw = inflateRaw;
  14779. exports.ungzip = inflate;
  14780. },{"./utils/common":63,"./utils/strings":64,"./zlib/constants":66,"./zlib/gzheader":69,"./zlib/inflate.js":71,"./zlib/messages":73,"./zlib/zstream":75}],63:[function(require,module,exports){
  14781. 'use strict';
  14782. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  14783. (typeof Uint16Array !== 'undefined') &&
  14784. (typeof Int32Array !== 'undefined');
  14785. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  14786. var sources = Array.prototype.slice.call(arguments, 1);
  14787. while (sources.length) {
  14788. var source = sources.shift();
  14789. if (!source) { continue; }
  14790. if (typeof(source) !== 'object') {
  14791. throw new TypeError(source + 'must be non-object');
  14792. }
  14793. for (var p in source) {
  14794. if (source.hasOwnProperty(p)) {
  14795. obj[p] = source[p];
  14796. }
  14797. }
  14798. }
  14799. return obj;
  14800. };
  14801. // reduce buffer size, avoiding mem copy
  14802. exports.shrinkBuf = function (buf, size) {
  14803. if (buf.length === size) { return buf; }
  14804. if (buf.subarray) { return buf.subarray(0, size); }
  14805. buf.length = size;
  14806. return buf;
  14807. };
  14808. var fnTyped = {
  14809. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14810. if (src.subarray && dest.subarray) {
  14811. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  14812. return;
  14813. }
  14814. // Fallback to ordinary array
  14815. for(var i=0; i<len; i++) {
  14816. dest[dest_offs + i] = src[src_offs + i];
  14817. }
  14818. },
  14819. // Join array of chunks to single array.
  14820. flattenChunks: function(chunks) {
  14821. var i, l, len, pos, chunk, result;
  14822. // calculate data length
  14823. len = 0;
  14824. for (i=0, l=chunks.length; i<l; i++) {
  14825. len += chunks[i].length;
  14826. }
  14827. // join chunks
  14828. result = new Uint8Array(len);
  14829. pos = 0;
  14830. for (i=0, l=chunks.length; i<l; i++) {
  14831. chunk = chunks[i];
  14832. result.set(chunk, pos);
  14833. pos += chunk.length;
  14834. }
  14835. return result;
  14836. }
  14837. };
  14838. var fnUntyped = {
  14839. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14840. for(var i=0; i<len; i++) {
  14841. dest[dest_offs + i] = src[src_offs + i];
  14842. }
  14843. },
  14844. // Join array of chunks to single array.
  14845. flattenChunks: function(chunks) {
  14846. return [].concat.apply([], chunks);
  14847. }
  14848. };
  14849. // Enable/Disable typed arrays use, for testing
  14850. //
  14851. exports.setTyped = function (on) {
  14852. if (on) {
  14853. exports.Buf8 = Uint8Array;
  14854. exports.Buf16 = Uint16Array;
  14855. exports.Buf32 = Int32Array;
  14856. exports.assign(exports, fnTyped);
  14857. } else {
  14858. exports.Buf8 = Array;
  14859. exports.Buf16 = Array;
  14860. exports.Buf32 = Array;
  14861. exports.assign(exports, fnUntyped);
  14862. }
  14863. };
  14864. exports.setTyped(TYPED_OK);
  14865. },{}],64:[function(require,module,exports){
  14866. // String encode/decode helpers
  14867. 'use strict';
  14868. var utils = require('./common');
  14869. // Quick check if we can use fast array to bin string conversion
  14870. //
  14871. // - apply(Array) can fail on Android 2.2
  14872. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  14873. //
  14874. var STR_APPLY_OK = true;
  14875. var STR_APPLY_UIA_OK = true;
  14876. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  14877. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  14878. // Table with utf8 lengths (calculated by first byte of sequence)
  14879. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  14880. // because max possible codepoint is 0x10ffff
  14881. var _utf8len = new utils.Buf8(256);
  14882. for (var i=0; i<256; i++) {
  14883. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  14884. }
  14885. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  14886. // convert string to array (typed, when possible)
  14887. exports.string2buf = function (str) {
  14888. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  14889. // count binary size
  14890. for (m_pos = 0; m_pos < str_len; m_pos++) {
  14891. c = str.charCodeAt(m_pos);
  14892. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14893. c2 = str.charCodeAt(m_pos+1);
  14894. if ((c2 & 0xfc00) === 0xdc00) {
  14895. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14896. m_pos++;
  14897. }
  14898. }
  14899. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  14900. }
  14901. // allocate buffer
  14902. buf = new utils.Buf8(buf_len);
  14903. // convert
  14904. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  14905. c = str.charCodeAt(m_pos);
  14906. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14907. c2 = str.charCodeAt(m_pos+1);
  14908. if ((c2 & 0xfc00) === 0xdc00) {
  14909. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14910. m_pos++;
  14911. }
  14912. }
  14913. if (c < 0x80) {
  14914. /* one byte */
  14915. buf[i++] = c;
  14916. } else if (c < 0x800) {
  14917. /* two bytes */
  14918. buf[i++] = 0xC0 | (c >>> 6);
  14919. buf[i++] = 0x80 | (c & 0x3f);
  14920. } else if (c < 0x10000) {
  14921. /* three bytes */
  14922. buf[i++] = 0xE0 | (c >>> 12);
  14923. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14924. buf[i++] = 0x80 | (c & 0x3f);
  14925. } else {
  14926. /* four bytes */
  14927. buf[i++] = 0xf0 | (c >>> 18);
  14928. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  14929. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14930. buf[i++] = 0x80 | (c & 0x3f);
  14931. }
  14932. }
  14933. return buf;
  14934. };
  14935. // Helper (used in 2 places)
  14936. function buf2binstring(buf, len) {
  14937. // use fallback for big arrays to avoid stack overflow
  14938. if (len < 65537) {
  14939. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  14940. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  14941. }
  14942. }
  14943. var result = '';
  14944. for(var i=0; i < len; i++) {
  14945. result += String.fromCharCode(buf[i]);
  14946. }
  14947. return result;
  14948. }
  14949. // Convert byte array to binary string
  14950. exports.buf2binstring = function(buf) {
  14951. return buf2binstring(buf, buf.length);
  14952. };
  14953. // Convert binary string (typed, when possible)
  14954. exports.binstring2buf = function(str) {
  14955. var buf = new utils.Buf8(str.length);
  14956. for(var i=0, len=buf.length; i < len; i++) {
  14957. buf[i] = str.charCodeAt(i);
  14958. }
  14959. return buf;
  14960. };
  14961. // convert array to string
  14962. exports.buf2string = function (buf, max) {
  14963. var i, out, c, c_len;
  14964. var len = max || buf.length;
  14965. // Reserve max possible length (2 words per char)
  14966. // NB: by unknown reasons, Array is significantly faster for
  14967. // String.fromCharCode.apply than Uint16Array.
  14968. var utf16buf = new Array(len*2);
  14969. for (out=0, i=0; i<len;) {
  14970. c = buf[i++];
  14971. // quick process ascii
  14972. if (c < 0x80) { utf16buf[out++] = c; continue; }
  14973. c_len = _utf8len[c];
  14974. // skip 5 & 6 byte codes
  14975. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  14976. // apply mask on first byte
  14977. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  14978. // join the rest
  14979. while (c_len > 1 && i < len) {
  14980. c = (c << 6) | (buf[i++] & 0x3f);
  14981. c_len--;
  14982. }
  14983. // terminated by end of string?
  14984. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  14985. if (c < 0x10000) {
  14986. utf16buf[out++] = c;
  14987. } else {
  14988. c -= 0x10000;
  14989. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  14990. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  14991. }
  14992. }
  14993. return buf2binstring(utf16buf, out);
  14994. };
  14995. // Calculate max possible position in utf8 buffer,
  14996. // that will not break sequence. If that's not possible
  14997. // - (very small limits) return max size as is.
  14998. //
  14999. // buf[] - utf8 bytes array
  15000. // max - length limit (mandatory);
  15001. exports.utf8border = function(buf, max) {
  15002. var pos;
  15003. max = max || buf.length;
  15004. if (max > buf.length) { max = buf.length; }
  15005. // go back from last position, until start of sequence found
  15006. pos = max-1;
  15007. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15008. // Fuckup - very small and broken sequence,
  15009. // return max, because we should return something anyway.
  15010. if (pos < 0) { return max; }
  15011. // If we came to start of buffer - that means vuffer is too small,
  15012. // return max too.
  15013. if (pos === 0) { return max; }
  15014. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15015. };
  15016. },{"./common":63}],65:[function(require,module,exports){
  15017. 'use strict';
  15018. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15019. // It doesn't worth to make additional optimizationa as in original.
  15020. // Small size is preferable.
  15021. function adler32(adler, buf, len, pos) {
  15022. var s1 = (adler & 0xffff) |0
  15023. , s2 = ((adler >>> 16) & 0xffff) |0
  15024. , n = 0;
  15025. while (len !== 0) {
  15026. // Set limit ~ twice less than 5552, to keep
  15027. // s2 in 31-bits, because we force signed ints.
  15028. // in other case %= will fail.
  15029. n = len > 2000 ? 2000 : len;
  15030. len -= n;
  15031. do {
  15032. s1 = (s1 + buf[pos++]) |0;
  15033. s2 = (s2 + s1) |0;
  15034. } while (--n);
  15035. s1 %= 65521;
  15036. s2 %= 65521;
  15037. }
  15038. return (s1 | (s2 << 16)) |0;
  15039. }
  15040. module.exports = adler32;
  15041. },{}],66:[function(require,module,exports){
  15042. module.exports = {
  15043. /* Allowed flush values; see deflate() and inflate() below for details */
  15044. Z_NO_FLUSH: 0,
  15045. Z_PARTIAL_FLUSH: 1,
  15046. Z_SYNC_FLUSH: 2,
  15047. Z_FULL_FLUSH: 3,
  15048. Z_FINISH: 4,
  15049. Z_BLOCK: 5,
  15050. Z_TREES: 6,
  15051. /* Return codes for the compression/decompression functions. Negative values
  15052. * are errors, positive values are used for special but normal events.
  15053. */
  15054. Z_OK: 0,
  15055. Z_STREAM_END: 1,
  15056. Z_NEED_DICT: 2,
  15057. Z_ERRNO: -1,
  15058. Z_STREAM_ERROR: -2,
  15059. Z_DATA_ERROR: -3,
  15060. //Z_MEM_ERROR: -4,
  15061. Z_BUF_ERROR: -5,
  15062. //Z_VERSION_ERROR: -6,
  15063. /* compression levels */
  15064. Z_NO_COMPRESSION: 0,
  15065. Z_BEST_SPEED: 1,
  15066. Z_BEST_COMPRESSION: 9,
  15067. Z_DEFAULT_COMPRESSION: -1,
  15068. Z_FILTERED: 1,
  15069. Z_HUFFMAN_ONLY: 2,
  15070. Z_RLE: 3,
  15071. Z_FIXED: 4,
  15072. Z_DEFAULT_STRATEGY: 0,
  15073. /* Possible values of the data_type field (though see inflate()) */
  15074. Z_BINARY: 0,
  15075. Z_TEXT: 1,
  15076. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15077. Z_UNKNOWN: 2,
  15078. /* The deflate compression method */
  15079. Z_DEFLATED: 8
  15080. //Z_NULL: null // Use -1 or null inline, depending on var type
  15081. };
  15082. },{}],67:[function(require,module,exports){
  15083. 'use strict';
  15084. // Note: we can't get significant speed boost here.
  15085. // So write code to minimize size - no pregenerated tables
  15086. // and array tools dependencies.
  15087. // Use ordinary array, since untyped makes no boost here
  15088. function makeTable() {
  15089. var c, table = [];
  15090. for(var n =0; n < 256; n++){
  15091. c = n;
  15092. for(var k =0; k < 8; k++){
  15093. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15094. }
  15095. table[n] = c;
  15096. }
  15097. return table;
  15098. }
  15099. // Create table on load. Just 255 signed longs. Not a problem.
  15100. var crcTable = makeTable();
  15101. function crc32(crc, buf, len, pos) {
  15102. var t = crcTable
  15103. , end = pos + len;
  15104. crc = crc ^ (-1);
  15105. for (var i = pos; i < end; i++ ) {
  15106. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15107. }
  15108. return (crc ^ (-1)); // >>> 0;
  15109. }
  15110. module.exports = crc32;
  15111. },{}],68:[function(require,module,exports){
  15112. 'use strict';
  15113. var utils = require('../utils/common');
  15114. var trees = require('./trees');
  15115. var adler32 = require('./adler32');
  15116. var crc32 = require('./crc32');
  15117. var msg = require('./messages');
  15118. /* Public constants ==========================================================*/
  15119. /* ===========================================================================*/
  15120. /* Allowed flush values; see deflate() and inflate() below for details */
  15121. var Z_NO_FLUSH = 0;
  15122. var Z_PARTIAL_FLUSH = 1;
  15123. //var Z_SYNC_FLUSH = 2;
  15124. var Z_FULL_FLUSH = 3;
  15125. var Z_FINISH = 4;
  15126. var Z_BLOCK = 5;
  15127. //var Z_TREES = 6;
  15128. /* Return codes for the compression/decompression functions. Negative values
  15129. * are errors, positive values are used for special but normal events.
  15130. */
  15131. var Z_OK = 0;
  15132. var Z_STREAM_END = 1;
  15133. //var Z_NEED_DICT = 2;
  15134. //var Z_ERRNO = -1;
  15135. var Z_STREAM_ERROR = -2;
  15136. var Z_DATA_ERROR = -3;
  15137. //var Z_MEM_ERROR = -4;
  15138. var Z_BUF_ERROR = -5;
  15139. //var Z_VERSION_ERROR = -6;
  15140. /* compression levels */
  15141. //var Z_NO_COMPRESSION = 0;
  15142. //var Z_BEST_SPEED = 1;
  15143. //var Z_BEST_COMPRESSION = 9;
  15144. var Z_DEFAULT_COMPRESSION = -1;
  15145. var Z_FILTERED = 1;
  15146. var Z_HUFFMAN_ONLY = 2;
  15147. var Z_RLE = 3;
  15148. var Z_FIXED = 4;
  15149. var Z_DEFAULT_STRATEGY = 0;
  15150. /* Possible values of the data_type field (though see inflate()) */
  15151. //var Z_BINARY = 0;
  15152. //var Z_TEXT = 1;
  15153. //var Z_ASCII = 1; // = Z_TEXT
  15154. var Z_UNKNOWN = 2;
  15155. /* The deflate compression method */
  15156. var Z_DEFLATED = 8;
  15157. /*============================================================================*/
  15158. var MAX_MEM_LEVEL = 9;
  15159. /* Maximum value for memLevel in deflateInit2 */
  15160. var MAX_WBITS = 15;
  15161. /* 32K LZ77 window */
  15162. var DEF_MEM_LEVEL = 8;
  15163. var LENGTH_CODES = 29;
  15164. /* number of length codes, not counting the special END_BLOCK code */
  15165. var LITERALS = 256;
  15166. /* number of literal bytes 0..255 */
  15167. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15168. /* number of Literal or Length codes, including the END_BLOCK code */
  15169. var D_CODES = 30;
  15170. /* number of distance codes */
  15171. var BL_CODES = 19;
  15172. /* number of codes used to transfer the bit lengths */
  15173. var HEAP_SIZE = 2*L_CODES + 1;
  15174. /* maximum heap size */
  15175. var MAX_BITS = 15;
  15176. /* All codes must not exceed MAX_BITS bits */
  15177. var MIN_MATCH = 3;
  15178. var MAX_MATCH = 258;
  15179. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15180. var PRESET_DICT = 0x20;
  15181. var INIT_STATE = 42;
  15182. var EXTRA_STATE = 69;
  15183. var NAME_STATE = 73;
  15184. var COMMENT_STATE = 91;
  15185. var HCRC_STATE = 103;
  15186. var BUSY_STATE = 113;
  15187. var FINISH_STATE = 666;
  15188. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15189. var BS_BLOCK_DONE = 2; /* block flush performed */
  15190. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15191. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15192. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15193. function err(strm, errorCode) {
  15194. strm.msg = msg[errorCode];
  15195. return errorCode;
  15196. }
  15197. function rank(f) {
  15198. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15199. }
  15200. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15201. /* =========================================================================
  15202. * Flush as much pending output as possible. All deflate() output goes
  15203. * through this function so some applications may wish to modify it
  15204. * to avoid allocating a large strm->output buffer and copying into it.
  15205. * (See also read_buf()).
  15206. */
  15207. function flush_pending(strm) {
  15208. var s = strm.state;
  15209. //_tr_flush_bits(s);
  15210. var len = s.pending;
  15211. if (len > strm.avail_out) {
  15212. len = strm.avail_out;
  15213. }
  15214. if (len === 0) { return; }
  15215. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  15216. strm.next_out += len;
  15217. s.pending_out += len;
  15218. strm.total_out += len;
  15219. strm.avail_out -= len;
  15220. s.pending -= len;
  15221. if (s.pending === 0) {
  15222. s.pending_out = 0;
  15223. }
  15224. }
  15225. function flush_block_only (s, last) {
  15226. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  15227. s.block_start = s.strstart;
  15228. flush_pending(s.strm);
  15229. }
  15230. function put_byte(s, b) {
  15231. s.pending_buf[s.pending++] = b;
  15232. }
  15233. /* =========================================================================
  15234. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  15235. * IN assertion: the stream state is correct and there is enough room in
  15236. * pending_buf.
  15237. */
  15238. function putShortMSB(s, b) {
  15239. // put_byte(s, (Byte)(b >> 8));
  15240. // put_byte(s, (Byte)(b & 0xff));
  15241. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  15242. s.pending_buf[s.pending++] = b & 0xff;
  15243. }
  15244. /* ===========================================================================
  15245. * Read a new buffer from the current input stream, update the adler32
  15246. * and total number of bytes read. All deflate() input goes through
  15247. * this function so some applications may wish to modify it to avoid
  15248. * allocating a large strm->input buffer and copying from it.
  15249. * (See also flush_pending()).
  15250. */
  15251. function read_buf(strm, buf, start, size) {
  15252. var len = strm.avail_in;
  15253. if (len > size) { len = size; }
  15254. if (len === 0) { return 0; }
  15255. strm.avail_in -= len;
  15256. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  15257. if (strm.state.wrap === 1) {
  15258. strm.adler = adler32(strm.adler, buf, len, start);
  15259. }
  15260. else if (strm.state.wrap === 2) {
  15261. strm.adler = crc32(strm.adler, buf, len, start);
  15262. }
  15263. strm.next_in += len;
  15264. strm.total_in += len;
  15265. return len;
  15266. }
  15267. /* ===========================================================================
  15268. * Set match_start to the longest match starting at the given string and
  15269. * return its length. Matches shorter or equal to prev_length are discarded,
  15270. * in which case the result is equal to prev_length and match_start is
  15271. * garbage.
  15272. * IN assertions: cur_match is the head of the hash chain for the current
  15273. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  15274. * OUT assertion: the match length is not greater than s->lookahead.
  15275. */
  15276. function longest_match(s, cur_match) {
  15277. var chain_length = s.max_chain_length; /* max hash chain length */
  15278. var scan = s.strstart; /* current string */
  15279. var match; /* matched string */
  15280. var len; /* length of current match */
  15281. var best_len = s.prev_length; /* best match length so far */
  15282. var nice_match = s.nice_match; /* stop if match long enough */
  15283. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  15284. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  15285. var _win = s.window; // shortcut
  15286. var wmask = s.w_mask;
  15287. var prev = s.prev;
  15288. /* Stop when cur_match becomes <= limit. To simplify the code,
  15289. * we prevent matches with the string of window index 0.
  15290. */
  15291. var strend = s.strstart + MAX_MATCH;
  15292. var scan_end1 = _win[scan + best_len - 1];
  15293. var scan_end = _win[scan + best_len];
  15294. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  15295. * It is easy to get rid of this optimization if necessary.
  15296. */
  15297. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  15298. /* Do not waste too much time if we already have a good match: */
  15299. if (s.prev_length >= s.good_match) {
  15300. chain_length >>= 2;
  15301. }
  15302. /* Do not look for matches beyond the end of the input. This is necessary
  15303. * to make deflate deterministic.
  15304. */
  15305. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  15306. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  15307. do {
  15308. // Assert(cur_match < s->strstart, "no future");
  15309. match = cur_match;
  15310. /* Skip to next match if the match length cannot increase
  15311. * or if the match length is less than 2. Note that the checks below
  15312. * for insufficient lookahead only occur occasionally for performance
  15313. * reasons. Therefore uninitialized memory will be accessed, and
  15314. * conditional jumps will be made that depend on those values.
  15315. * However the length of the match is limited to the lookahead, so
  15316. * the output of deflate is not affected by the uninitialized values.
  15317. */
  15318. if (_win[match + best_len] !== scan_end ||
  15319. _win[match + best_len - 1] !== scan_end1 ||
  15320. _win[match] !== _win[scan] ||
  15321. _win[++match] !== _win[scan + 1]) {
  15322. continue;
  15323. }
  15324. /* The check at best_len-1 can be removed because it will be made
  15325. * again later. (This heuristic is not always a win.)
  15326. * It is not necessary to compare scan[2] and match[2] since they
  15327. * are always equal when the other bytes match, given that
  15328. * the hash keys are equal and that HASH_BITS >= 8.
  15329. */
  15330. scan += 2;
  15331. match++;
  15332. // Assert(*scan == *match, "match[2]?");
  15333. /* We check for insufficient lookahead only every 8th comparison;
  15334. * the 256th check will be made at strstart+258.
  15335. */
  15336. do {
  15337. /*jshint noempty:false*/
  15338. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15339. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15340. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15341. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15342. scan < strend);
  15343. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  15344. len = MAX_MATCH - (strend - scan);
  15345. scan = strend - MAX_MATCH;
  15346. if (len > best_len) {
  15347. s.match_start = cur_match;
  15348. best_len = len;
  15349. if (len >= nice_match) {
  15350. break;
  15351. }
  15352. scan_end1 = _win[scan + best_len - 1];
  15353. scan_end = _win[scan + best_len];
  15354. }
  15355. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  15356. if (best_len <= s.lookahead) {
  15357. return best_len;
  15358. }
  15359. return s.lookahead;
  15360. }
  15361. /* ===========================================================================
  15362. * Fill the window when the lookahead becomes insufficient.
  15363. * Updates strstart and lookahead.
  15364. *
  15365. * IN assertion: lookahead < MIN_LOOKAHEAD
  15366. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  15367. * At least one byte has been read, or avail_in == 0; reads are
  15368. * performed for at least two bytes (required for the zip translate_eol
  15369. * option -- not supported here).
  15370. */
  15371. function fill_window(s) {
  15372. var _w_size = s.w_size;
  15373. var p, n, m, more, str;
  15374. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  15375. do {
  15376. more = s.window_size - s.lookahead - s.strstart;
  15377. // JS ints have 32 bit, block below not needed
  15378. /* Deal with !@#$% 64K limit: */
  15379. //if (sizeof(int) <= 2) {
  15380. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  15381. // more = wsize;
  15382. //
  15383. // } else if (more == (unsigned)(-1)) {
  15384. // /* Very unlikely, but possible on 16 bit machine if
  15385. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  15386. // */
  15387. // more--;
  15388. // }
  15389. //}
  15390. /* If the window is almost full and there is insufficient lookahead,
  15391. * move the upper half to the lower one to make room in the upper half.
  15392. */
  15393. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  15394. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  15395. s.match_start -= _w_size;
  15396. s.strstart -= _w_size;
  15397. /* we now have strstart >= MAX_DIST */
  15398. s.block_start -= _w_size;
  15399. /* Slide the hash table (could be avoided with 32 bit values
  15400. at the expense of memory usage). We slide even when level == 0
  15401. to keep the hash table consistent if we switch back to level > 0
  15402. later. (Using level 0 permanently is not an optimal usage of
  15403. zlib, so we don't care about this pathological case.)
  15404. */
  15405. n = s.hash_size;
  15406. p = n;
  15407. do {
  15408. m = s.head[--p];
  15409. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  15410. } while (--n);
  15411. n = _w_size;
  15412. p = n;
  15413. do {
  15414. m = s.prev[--p];
  15415. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  15416. /* If n is not on any hash chain, prev[n] is garbage but
  15417. * its value will never be used.
  15418. */
  15419. } while (--n);
  15420. more += _w_size;
  15421. }
  15422. if (s.strm.avail_in === 0) {
  15423. break;
  15424. }
  15425. /* If there was no sliding:
  15426. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  15427. * more == window_size - lookahead - strstart
  15428. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  15429. * => more >= window_size - 2*WSIZE + 2
  15430. * In the BIG_MEM or MMAP case (not yet supported),
  15431. * window_size == input_size + MIN_LOOKAHEAD &&
  15432. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  15433. * Otherwise, window_size == 2*WSIZE so more >= 2.
  15434. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  15435. */
  15436. //Assert(more >= 2, "more < 2");
  15437. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  15438. s.lookahead += n;
  15439. /* Initialize the hash value now that we have some input: */
  15440. if (s.lookahead + s.insert >= MIN_MATCH) {
  15441. str = s.strstart - s.insert;
  15442. s.ins_h = s.window[str];
  15443. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  15444. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  15445. //#if MIN_MATCH != 3
  15446. // Call update_hash() MIN_MATCH-3 more times
  15447. //#endif
  15448. while (s.insert) {
  15449. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15450. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  15451. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15452. s.head[s.ins_h] = str;
  15453. str++;
  15454. s.insert--;
  15455. if (s.lookahead + s.insert < MIN_MATCH) {
  15456. break;
  15457. }
  15458. }
  15459. }
  15460. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  15461. * but this is not important since only literal bytes will be emitted.
  15462. */
  15463. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  15464. /* If the WIN_INIT bytes after the end of the current data have never been
  15465. * written, then zero those bytes in order to avoid memory check reports of
  15466. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  15467. * the longest match routines. Update the high water mark for the next
  15468. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  15469. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  15470. */
  15471. // if (s.high_water < s.window_size) {
  15472. // var curr = s.strstart + s.lookahead;
  15473. // var init = 0;
  15474. //
  15475. // if (s.high_water < curr) {
  15476. // /* Previous high water mark below current data -- zero WIN_INIT
  15477. // * bytes or up to end of window, whichever is less.
  15478. // */
  15479. // init = s.window_size - curr;
  15480. // if (init > WIN_INIT)
  15481. // init = WIN_INIT;
  15482. // zmemzero(s->window + curr, (unsigned)init);
  15483. // s->high_water = curr + init;
  15484. // }
  15485. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  15486. // /* High water mark at or above current data, but below current data
  15487. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  15488. // * to end of window, whichever is less.
  15489. // */
  15490. // init = (ulg)curr + WIN_INIT - s->high_water;
  15491. // if (init > s->window_size - s->high_water)
  15492. // init = s->window_size - s->high_water;
  15493. // zmemzero(s->window + s->high_water, (unsigned)init);
  15494. // s->high_water += init;
  15495. // }
  15496. // }
  15497. //
  15498. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15499. // "not enough room for search");
  15500. }
  15501. /* ===========================================================================
  15502. * Copy without compression as much as possible from the input stream, return
  15503. * the current block state.
  15504. * This function does not insert new strings in the dictionary since
  15505. * uncompressible data is probably not useful. This function is used
  15506. * only for the level=0 compression option.
  15507. * NOTE: this function should be optimized to avoid extra copying from
  15508. * window to pending_buf.
  15509. */
  15510. function deflate_stored(s, flush) {
  15511. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15512. * to pending_buf_size, and each stored block has a 5 byte header:
  15513. */
  15514. var max_block_size = 0xffff;
  15515. if (max_block_size > s.pending_buf_size - 5) {
  15516. max_block_size = s.pending_buf_size - 5;
  15517. }
  15518. /* Copy as much as possible from input to output: */
  15519. for (;;) {
  15520. /* Fill the window as much as possible: */
  15521. if (s.lookahead <= 1) {
  15522. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15523. // s->block_start >= (long)s->w_size, "slide too late");
  15524. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15525. // s.block_start >= s.w_size)) {
  15526. // throw new Error("slide too late");
  15527. // }
  15528. fill_window(s);
  15529. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  15530. return BS_NEED_MORE;
  15531. }
  15532. if (s.lookahead === 0) {
  15533. break;
  15534. }
  15535. /* flush the current block */
  15536. }
  15537. //Assert(s->block_start >= 0L, "block gone");
  15538. // if (s.block_start < 0) throw new Error("block gone");
  15539. s.strstart += s.lookahead;
  15540. s.lookahead = 0;
  15541. /* Emit a stored block if pending_buf will be full: */
  15542. var max_start = s.block_start + max_block_size;
  15543. if (s.strstart === 0 || s.strstart >= max_start) {
  15544. /* strstart == 0 is possible when wraparound on 16-bit machine */
  15545. s.lookahead = s.strstart - max_start;
  15546. s.strstart = max_start;
  15547. /*** FLUSH_BLOCK(s, 0); ***/
  15548. flush_block_only(s, false);
  15549. if (s.strm.avail_out === 0) {
  15550. return BS_NEED_MORE;
  15551. }
  15552. /***/
  15553. }
  15554. /* Flush if we may have to slide, otherwise block_start may become
  15555. * negative and the data will be gone:
  15556. */
  15557. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  15558. /*** FLUSH_BLOCK(s, 0); ***/
  15559. flush_block_only(s, false);
  15560. if (s.strm.avail_out === 0) {
  15561. return BS_NEED_MORE;
  15562. }
  15563. /***/
  15564. }
  15565. }
  15566. s.insert = 0;
  15567. if (flush === Z_FINISH) {
  15568. /*** FLUSH_BLOCK(s, 1); ***/
  15569. flush_block_only(s, true);
  15570. if (s.strm.avail_out === 0) {
  15571. return BS_FINISH_STARTED;
  15572. }
  15573. /***/
  15574. return BS_FINISH_DONE;
  15575. }
  15576. if (s.strstart > s.block_start) {
  15577. /*** FLUSH_BLOCK(s, 0); ***/
  15578. flush_block_only(s, false);
  15579. if (s.strm.avail_out === 0) {
  15580. return BS_NEED_MORE;
  15581. }
  15582. /***/
  15583. }
  15584. return BS_NEED_MORE;
  15585. }
  15586. /* ===========================================================================
  15587. * Compress as much as possible from the input stream, return the current
  15588. * block state.
  15589. * This function does not perform lazy evaluation of matches and inserts
  15590. * new strings in the dictionary only for unmatched strings or for short
  15591. * matches. It is used only for the fast compression options.
  15592. */
  15593. function deflate_fast(s, flush) {
  15594. var hash_head; /* head of the hash chain */
  15595. var bflush; /* set if current block must be flushed */
  15596. for (;;) {
  15597. /* Make sure that we always have enough lookahead, except
  15598. * at the end of the input file. We need MAX_MATCH bytes
  15599. * for the next match, plus MIN_MATCH bytes to insert the
  15600. * string following the next match.
  15601. */
  15602. if (s.lookahead < MIN_LOOKAHEAD) {
  15603. fill_window(s);
  15604. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15605. return BS_NEED_MORE;
  15606. }
  15607. if (s.lookahead === 0) {
  15608. break; /* flush the current block */
  15609. }
  15610. }
  15611. /* Insert the string window[strstart .. strstart+2] in the
  15612. * dictionary, and set hash_head to the head of the hash chain:
  15613. */
  15614. hash_head = 0/*NIL*/;
  15615. if (s.lookahead >= MIN_MATCH) {
  15616. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15617. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15618. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15619. s.head[s.ins_h] = s.strstart;
  15620. /***/
  15621. }
  15622. /* Find the longest match, discarding those <= prev_length.
  15623. * At this point we have always match_length < MIN_MATCH
  15624. */
  15625. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  15626. /* To simplify the code, we prevent matches with the string
  15627. * of window index 0 (in particular we have to avoid a match
  15628. * of the string with itself at the start of the input file).
  15629. */
  15630. s.match_length = longest_match(s, hash_head);
  15631. /* longest_match() sets match_start */
  15632. }
  15633. if (s.match_length >= MIN_MATCH) {
  15634. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  15635. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  15636. s.match_length - MIN_MATCH, bflush); ***/
  15637. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  15638. s.lookahead -= s.match_length;
  15639. /* Insert new strings in the hash table only if the match length
  15640. * is not too large. This saves time but degrades compression.
  15641. */
  15642. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  15643. s.match_length--; /* string at strstart already in table */
  15644. do {
  15645. s.strstart++;
  15646. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15647. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15648. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15649. s.head[s.ins_h] = s.strstart;
  15650. /***/
  15651. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  15652. * always MIN_MATCH bytes ahead.
  15653. */
  15654. } while (--s.match_length !== 0);
  15655. s.strstart++;
  15656. } else
  15657. {
  15658. s.strstart += s.match_length;
  15659. s.match_length = 0;
  15660. s.ins_h = s.window[s.strstart];
  15661. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  15662. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  15663. //#if MIN_MATCH != 3
  15664. // Call UPDATE_HASH() MIN_MATCH-3 more times
  15665. //#endif
  15666. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  15667. * matter since it will be recomputed at next deflate call.
  15668. */
  15669. }
  15670. } else {
  15671. /* No match, output a literal byte */
  15672. //Tracevv((stderr,"%c", s.window[s.strstart]));
  15673. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15674. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15675. s.lookahead--;
  15676. s.strstart++;
  15677. }
  15678. if (bflush) {
  15679. /*** FLUSH_BLOCK(s, 0); ***/
  15680. flush_block_only(s, false);
  15681. if (s.strm.avail_out === 0) {
  15682. return BS_NEED_MORE;
  15683. }
  15684. /***/
  15685. }
  15686. }
  15687. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  15688. if (flush === Z_FINISH) {
  15689. /*** FLUSH_BLOCK(s, 1); ***/
  15690. flush_block_only(s, true);
  15691. if (s.strm.avail_out === 0) {
  15692. return BS_FINISH_STARTED;
  15693. }
  15694. /***/
  15695. return BS_FINISH_DONE;
  15696. }
  15697. if (s.last_lit) {
  15698. /*** FLUSH_BLOCK(s, 0); ***/
  15699. flush_block_only(s, false);
  15700. if (s.strm.avail_out === 0) {
  15701. return BS_NEED_MORE;
  15702. }
  15703. /***/
  15704. }
  15705. return BS_BLOCK_DONE;
  15706. }
  15707. /* ===========================================================================
  15708. * Same as above, but achieves better compression. We use a lazy
  15709. * evaluation for matches: a match is finally adopted only if there is
  15710. * no better match at the next window position.
  15711. */
  15712. function deflate_slow(s, flush) {
  15713. var hash_head; /* head of hash chain */
  15714. var bflush; /* set if current block must be flushed */
  15715. var max_insert;
  15716. /* Process the input block. */
  15717. for (;;) {
  15718. /* Make sure that we always have enough lookahead, except
  15719. * at the end of the input file. We need MAX_MATCH bytes
  15720. * for the next match, plus MIN_MATCH bytes to insert the
  15721. * string following the next match.
  15722. */
  15723. if (s.lookahead < MIN_LOOKAHEAD) {
  15724. fill_window(s);
  15725. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15726. return BS_NEED_MORE;
  15727. }
  15728. if (s.lookahead === 0) { break; } /* flush the current block */
  15729. }
  15730. /* Insert the string window[strstart .. strstart+2] in the
  15731. * dictionary, and set hash_head to the head of the hash chain:
  15732. */
  15733. hash_head = 0/*NIL*/;
  15734. if (s.lookahead >= MIN_MATCH) {
  15735. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15736. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15737. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15738. s.head[s.ins_h] = s.strstart;
  15739. /***/
  15740. }
  15741. /* Find the longest match, discarding those <= prev_length.
  15742. */
  15743. s.prev_length = s.match_length;
  15744. s.prev_match = s.match_start;
  15745. s.match_length = MIN_MATCH-1;
  15746. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  15747. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  15748. /* To simplify the code, we prevent matches with the string
  15749. * of window index 0 (in particular we have to avoid a match
  15750. * of the string with itself at the start of the input file).
  15751. */
  15752. s.match_length = longest_match(s, hash_head);
  15753. /* longest_match() sets match_start */
  15754. if (s.match_length <= 5 &&
  15755. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  15756. /* If prev_match is also MIN_MATCH, match_start is garbage
  15757. * but we will ignore the current match anyway.
  15758. */
  15759. s.match_length = MIN_MATCH-1;
  15760. }
  15761. }
  15762. /* If there was a match at the previous step and the current
  15763. * match is not better, output the previous match:
  15764. */
  15765. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  15766. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  15767. /* Do not insert strings in hash table beyond this. */
  15768. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  15769. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  15770. s.prev_length - MIN_MATCH, bflush);***/
  15771. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  15772. /* Insert in hash table all strings up to the end of the match.
  15773. * strstart-1 and strstart are already inserted. If there is not
  15774. * enough lookahead, the last two strings are not inserted in
  15775. * the hash table.
  15776. */
  15777. s.lookahead -= s.prev_length-1;
  15778. s.prev_length -= 2;
  15779. do {
  15780. if (++s.strstart <= max_insert) {
  15781. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15782. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15783. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15784. s.head[s.ins_h] = s.strstart;
  15785. /***/
  15786. }
  15787. } while (--s.prev_length !== 0);
  15788. s.match_available = 0;
  15789. s.match_length = MIN_MATCH-1;
  15790. s.strstart++;
  15791. if (bflush) {
  15792. /*** FLUSH_BLOCK(s, 0); ***/
  15793. flush_block_only(s, false);
  15794. if (s.strm.avail_out === 0) {
  15795. return BS_NEED_MORE;
  15796. }
  15797. /***/
  15798. }
  15799. } else if (s.match_available) {
  15800. /* If there was no match at the previous position, output a
  15801. * single literal. If there was a match but the current match
  15802. * is longer, truncate the previous match to a single literal.
  15803. */
  15804. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15805. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15806. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15807. if (bflush) {
  15808. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  15809. flush_block_only(s, false);
  15810. /***/
  15811. }
  15812. s.strstart++;
  15813. s.lookahead--;
  15814. if (s.strm.avail_out === 0) {
  15815. return BS_NEED_MORE;
  15816. }
  15817. } else {
  15818. /* There is no previous match to compare with, wait for
  15819. * the next step to decide.
  15820. */
  15821. s.match_available = 1;
  15822. s.strstart++;
  15823. s.lookahead--;
  15824. }
  15825. }
  15826. //Assert (flush != Z_NO_FLUSH, "no flush?");
  15827. if (s.match_available) {
  15828. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15829. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15830. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15831. s.match_available = 0;
  15832. }
  15833. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  15834. if (flush === Z_FINISH) {
  15835. /*** FLUSH_BLOCK(s, 1); ***/
  15836. flush_block_only(s, true);
  15837. if (s.strm.avail_out === 0) {
  15838. return BS_FINISH_STARTED;
  15839. }
  15840. /***/
  15841. return BS_FINISH_DONE;
  15842. }
  15843. if (s.last_lit) {
  15844. /*** FLUSH_BLOCK(s, 0); ***/
  15845. flush_block_only(s, false);
  15846. if (s.strm.avail_out === 0) {
  15847. return BS_NEED_MORE;
  15848. }
  15849. /***/
  15850. }
  15851. return BS_BLOCK_DONE;
  15852. }
  15853. /* ===========================================================================
  15854. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  15855. * one. Do not maintain a hash table. (It will be regenerated if this run of
  15856. * deflate switches away from Z_RLE.)
  15857. */
  15858. function deflate_rle(s, flush) {
  15859. var bflush; /* set if current block must be flushed */
  15860. var prev; /* byte at distance one to match */
  15861. var scan, strend; /* scan goes up to strend for length of run */
  15862. var _win = s.window;
  15863. for (;;) {
  15864. /* Make sure that we always have enough lookahead, except
  15865. * at the end of the input file. We need MAX_MATCH bytes
  15866. * for the longest run, plus one for the unrolled loop.
  15867. */
  15868. if (s.lookahead <= MAX_MATCH) {
  15869. fill_window(s);
  15870. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  15871. return BS_NEED_MORE;
  15872. }
  15873. if (s.lookahead === 0) { break; } /* flush the current block */
  15874. }
  15875. /* See how many times the previous byte repeats */
  15876. s.match_length = 0;
  15877. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  15878. scan = s.strstart - 1;
  15879. prev = _win[scan];
  15880. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  15881. strend = s.strstart + MAX_MATCH;
  15882. do {
  15883. /*jshint noempty:false*/
  15884. } while (prev === _win[++scan] && prev === _win[++scan] &&
  15885. prev === _win[++scan] && prev === _win[++scan] &&
  15886. prev === _win[++scan] && prev === _win[++scan] &&
  15887. prev === _win[++scan] && prev === _win[++scan] &&
  15888. scan < strend);
  15889. s.match_length = MAX_MATCH - (strend - scan);
  15890. if (s.match_length > s.lookahead) {
  15891. s.match_length = s.lookahead;
  15892. }
  15893. }
  15894. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  15895. }
  15896. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  15897. if (s.match_length >= MIN_MATCH) {
  15898. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  15899. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  15900. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  15901. s.lookahead -= s.match_length;
  15902. s.strstart += s.match_length;
  15903. s.match_length = 0;
  15904. } else {
  15905. /* No match, output a literal byte */
  15906. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15907. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15908. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15909. s.lookahead--;
  15910. s.strstart++;
  15911. }
  15912. if (bflush) {
  15913. /*** FLUSH_BLOCK(s, 0); ***/
  15914. flush_block_only(s, false);
  15915. if (s.strm.avail_out === 0) {
  15916. return BS_NEED_MORE;
  15917. }
  15918. /***/
  15919. }
  15920. }
  15921. s.insert = 0;
  15922. if (flush === Z_FINISH) {
  15923. /*** FLUSH_BLOCK(s, 1); ***/
  15924. flush_block_only(s, true);
  15925. if (s.strm.avail_out === 0) {
  15926. return BS_FINISH_STARTED;
  15927. }
  15928. /***/
  15929. return BS_FINISH_DONE;
  15930. }
  15931. if (s.last_lit) {
  15932. /*** FLUSH_BLOCK(s, 0); ***/
  15933. flush_block_only(s, false);
  15934. if (s.strm.avail_out === 0) {
  15935. return BS_NEED_MORE;
  15936. }
  15937. /***/
  15938. }
  15939. return BS_BLOCK_DONE;
  15940. }
  15941. /* ===========================================================================
  15942. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  15943. * (It will be regenerated if this run of deflate switches away from Huffman.)
  15944. */
  15945. function deflate_huff(s, flush) {
  15946. var bflush; /* set if current block must be flushed */
  15947. for (;;) {
  15948. /* Make sure that we have a literal to write. */
  15949. if (s.lookahead === 0) {
  15950. fill_window(s);
  15951. if (s.lookahead === 0) {
  15952. if (flush === Z_NO_FLUSH) {
  15953. return BS_NEED_MORE;
  15954. }
  15955. break; /* flush the current block */
  15956. }
  15957. }
  15958. /* Output a literal byte */
  15959. s.match_length = 0;
  15960. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15961. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15962. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15963. s.lookahead--;
  15964. s.strstart++;
  15965. if (bflush) {
  15966. /*** FLUSH_BLOCK(s, 0); ***/
  15967. flush_block_only(s, false);
  15968. if (s.strm.avail_out === 0) {
  15969. return BS_NEED_MORE;
  15970. }
  15971. /***/
  15972. }
  15973. }
  15974. s.insert = 0;
  15975. if (flush === Z_FINISH) {
  15976. /*** FLUSH_BLOCK(s, 1); ***/
  15977. flush_block_only(s, true);
  15978. if (s.strm.avail_out === 0) {
  15979. return BS_FINISH_STARTED;
  15980. }
  15981. /***/
  15982. return BS_FINISH_DONE;
  15983. }
  15984. if (s.last_lit) {
  15985. /*** FLUSH_BLOCK(s, 0); ***/
  15986. flush_block_only(s, false);
  15987. if (s.strm.avail_out === 0) {
  15988. return BS_NEED_MORE;
  15989. }
  15990. /***/
  15991. }
  15992. return BS_BLOCK_DONE;
  15993. }
  15994. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  15995. * the desired pack level (0..9). The values given below have been tuned to
  15996. * exclude worst case performance for pathological files. Better values may be
  15997. * found for specific files.
  15998. */
  15999. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  16000. this.good_length = good_length;
  16001. this.max_lazy = max_lazy;
  16002. this.nice_length = nice_length;
  16003. this.max_chain = max_chain;
  16004. this.func = func;
  16005. };
  16006. var configuration_table;
  16007. configuration_table = [
  16008. /* good lazy nice chain */
  16009. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16010. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16011. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16012. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16013. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16014. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16015. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16016. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16017. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16018. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16019. ];
  16020. /* ===========================================================================
  16021. * Initialize the "longest match" routines for a new zlib stream
  16022. */
  16023. function lm_init(s) {
  16024. s.window_size = 2 * s.w_size;
  16025. /*** CLEAR_HASH(s); ***/
  16026. zero(s.head); // Fill with NIL (= 0);
  16027. /* Set the default configuration parameters:
  16028. */
  16029. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16030. s.good_match = configuration_table[s.level].good_length;
  16031. s.nice_match = configuration_table[s.level].nice_length;
  16032. s.max_chain_length = configuration_table[s.level].max_chain;
  16033. s.strstart = 0;
  16034. s.block_start = 0;
  16035. s.lookahead = 0;
  16036. s.insert = 0;
  16037. s.match_length = s.prev_length = MIN_MATCH - 1;
  16038. s.match_available = 0;
  16039. s.ins_h = 0;
  16040. }
  16041. function DeflateState() {
  16042. this.strm = null; /* pointer back to this zlib stream */
  16043. this.status = 0; /* as the name implies */
  16044. this.pending_buf = null; /* output still pending */
  16045. this.pending_buf_size = 0; /* size of pending_buf */
  16046. this.pending_out = 0; /* next pending byte to output to the stream */
  16047. this.pending = 0; /* nb of bytes in the pending buffer */
  16048. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16049. this.gzhead = null; /* gzip header information to write */
  16050. this.gzindex = 0; /* where in extra, name, or comment */
  16051. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16052. this.last_flush = -1; /* value of flush param for previous deflate call */
  16053. this.w_size = 0; /* LZ77 window size (32K by default) */
  16054. this.w_bits = 0; /* log2(w_size) (8..16) */
  16055. this.w_mask = 0; /* w_size - 1 */
  16056. this.window = null;
  16057. /* Sliding window. Input bytes are read into the second half of the window,
  16058. * and move to the first half later to keep a dictionary of at least wSize
  16059. * bytes. With this organization, matches are limited to a distance of
  16060. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16061. * performed with a length multiple of the block size.
  16062. */
  16063. this.window_size = 0;
  16064. /* Actual size of window: 2*wSize, except when the user input buffer
  16065. * is directly used as sliding window.
  16066. */
  16067. this.prev = null;
  16068. /* Link to older string with same hash index. To limit the size of this
  16069. * array to 64K, this link is maintained only for the last 32K strings.
  16070. * An index in this array is thus a window index modulo 32K.
  16071. */
  16072. this.head = null; /* Heads of the hash chains or NIL. */
  16073. this.ins_h = 0; /* hash index of string to be inserted */
  16074. this.hash_size = 0; /* number of elements in hash table */
  16075. this.hash_bits = 0; /* log2(hash_size) */
  16076. this.hash_mask = 0; /* hash_size-1 */
  16077. this.hash_shift = 0;
  16078. /* Number of bits by which ins_h must be shifted at each input
  16079. * step. It must be such that after MIN_MATCH steps, the oldest
  16080. * byte no longer takes part in the hash key, that is:
  16081. * hash_shift * MIN_MATCH >= hash_bits
  16082. */
  16083. this.block_start = 0;
  16084. /* Window position at the beginning of the current output block. Gets
  16085. * negative when the window is moved backwards.
  16086. */
  16087. this.match_length = 0; /* length of best match */
  16088. this.prev_match = 0; /* previous match */
  16089. this.match_available = 0; /* set if previous match exists */
  16090. this.strstart = 0; /* start of string to insert */
  16091. this.match_start = 0; /* start of matching string */
  16092. this.lookahead = 0; /* number of valid bytes ahead in window */
  16093. this.prev_length = 0;
  16094. /* Length of the best match at previous step. Matches not greater than this
  16095. * are discarded. This is used in the lazy match evaluation.
  16096. */
  16097. this.max_chain_length = 0;
  16098. /* To speed up deflation, hash chains are never searched beyond this
  16099. * length. A higher limit improves compression ratio but degrades the
  16100. * speed.
  16101. */
  16102. this.max_lazy_match = 0;
  16103. /* Attempt to find a better match only when the current match is strictly
  16104. * smaller than this value. This mechanism is used only for compression
  16105. * levels >= 4.
  16106. */
  16107. // That's alias to max_lazy_match, don't use directly
  16108. //this.max_insert_length = 0;
  16109. /* Insert new strings in the hash table only if the match length is not
  16110. * greater than this length. This saves time but degrades compression.
  16111. * max_insert_length is used only for compression levels <= 3.
  16112. */
  16113. this.level = 0; /* compression level (1..9) */
  16114. this.strategy = 0; /* favor or force Huffman coding*/
  16115. this.good_match = 0;
  16116. /* Use a faster search when the previous match is longer than this */
  16117. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16118. /* used by trees.c: */
  16119. /* Didn't use ct_data typedef below to suppress compiler warning */
  16120. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16121. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16122. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16123. // Use flat array of DOUBLE size, with interleaved fata,
  16124. // because JS does not support effective
  16125. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16126. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  16127. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  16128. zero(this.dyn_ltree);
  16129. zero(this.dyn_dtree);
  16130. zero(this.bl_tree);
  16131. this.l_desc = null; /* desc. for literal tree */
  16132. this.d_desc = null; /* desc. for distance tree */
  16133. this.bl_desc = null; /* desc. for bit length tree */
  16134. //ush bl_count[MAX_BITS+1];
  16135. this.bl_count = new utils.Buf16(MAX_BITS+1);
  16136. /* number of codes at each bit length for an optimal tree */
  16137. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16138. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  16139. zero(this.heap);
  16140. this.heap_len = 0; /* number of elements in the heap */
  16141. this.heap_max = 0; /* element of largest frequency */
  16142. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16143. * The same heap array is used to build all trees.
  16144. */
  16145. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  16146. zero(this.depth);
  16147. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16148. */
  16149. this.l_buf = 0; /* buffer index for literals or lengths */
  16150. this.lit_bufsize = 0;
  16151. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16152. * limiting lit_bufsize to 64K:
  16153. * - frequencies can be kept in 16 bit counters
  16154. * - if compression is not successful for the first block, all input
  16155. * data is still in the window so we can still emit a stored block even
  16156. * when input comes from standard input. (This can also be done for
  16157. * all blocks if lit_bufsize is not greater than 32K.)
  16158. * - if compression is not successful for a file smaller than 64K, we can
  16159. * even emit a stored file instead of a stored block (saving 5 bytes).
  16160. * This is applicable only for zip (not gzip or zlib).
  16161. * - creating new Huffman trees less frequently may not provide fast
  16162. * adaptation to changes in the input data statistics. (Take for
  16163. * example a binary file with poorly compressible code followed by
  16164. * a highly compressible string table.) Smaller buffer sizes give
  16165. * fast adaptation but have of course the overhead of transmitting
  16166. * trees more frequently.
  16167. * - I can't count above 4
  16168. */
  16169. this.last_lit = 0; /* running index in l_buf */
  16170. this.d_buf = 0;
  16171. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16172. * the same number of elements. To use different lengths, an extra flag
  16173. * array would be necessary.
  16174. */
  16175. this.opt_len = 0; /* bit length of current block with optimal trees */
  16176. this.static_len = 0; /* bit length of current block with static trees */
  16177. this.matches = 0; /* number of string matches in current block */
  16178. this.insert = 0; /* bytes at end of window left to insert */
  16179. this.bi_buf = 0;
  16180. /* Output buffer. bits are inserted starting at the bottom (least
  16181. * significant bits).
  16182. */
  16183. this.bi_valid = 0;
  16184. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16185. * are always zero.
  16186. */
  16187. // Used for window memory init. We safely ignore it for JS. That makes
  16188. // sense only for pointers and memory check tools.
  16189. //this.high_water = 0;
  16190. /* High water mark offset in window for initialized bytes -- bytes above
  16191. * this are set to zero in order to avoid memory check warnings when
  16192. * longest match routines access bytes past the input. This is then
  16193. * updated to the new high water mark.
  16194. */
  16195. }
  16196. function deflateResetKeep(strm) {
  16197. var s;
  16198. if (!strm || !strm.state) {
  16199. return err(strm, Z_STREAM_ERROR);
  16200. }
  16201. strm.total_in = strm.total_out = 0;
  16202. strm.data_type = Z_UNKNOWN;
  16203. s = strm.state;
  16204. s.pending = 0;
  16205. s.pending_out = 0;
  16206. if (s.wrap < 0) {
  16207. s.wrap = -s.wrap;
  16208. /* was made negative by deflate(..., Z_FINISH); */
  16209. }
  16210. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  16211. strm.adler = (s.wrap === 2) ?
  16212. 0 // crc32(0, Z_NULL, 0)
  16213. :
  16214. 1; // adler32(0, Z_NULL, 0)
  16215. s.last_flush = Z_NO_FLUSH;
  16216. trees._tr_init(s);
  16217. return Z_OK;
  16218. }
  16219. function deflateReset(strm) {
  16220. var ret = deflateResetKeep(strm);
  16221. if (ret === Z_OK) {
  16222. lm_init(strm.state);
  16223. }
  16224. return ret;
  16225. }
  16226. function deflateSetHeader(strm, head) {
  16227. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16228. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  16229. strm.state.gzhead = head;
  16230. return Z_OK;
  16231. }
  16232. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  16233. if (!strm) { // === Z_NULL
  16234. return Z_STREAM_ERROR;
  16235. }
  16236. var wrap = 1;
  16237. if (level === Z_DEFAULT_COMPRESSION) {
  16238. level = 6;
  16239. }
  16240. if (windowBits < 0) { /* suppress zlib wrapper */
  16241. wrap = 0;
  16242. windowBits = -windowBits;
  16243. }
  16244. else if (windowBits > 15) {
  16245. wrap = 2; /* write gzip wrapper instead */
  16246. windowBits -= 16;
  16247. }
  16248. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  16249. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  16250. strategy < 0 || strategy > Z_FIXED) {
  16251. return err(strm, Z_STREAM_ERROR);
  16252. }
  16253. if (windowBits === 8) {
  16254. windowBits = 9;
  16255. }
  16256. /* until 256-byte window bug fixed */
  16257. var s = new DeflateState();
  16258. strm.state = s;
  16259. s.strm = strm;
  16260. s.wrap = wrap;
  16261. s.gzhead = null;
  16262. s.w_bits = windowBits;
  16263. s.w_size = 1 << s.w_bits;
  16264. s.w_mask = s.w_size - 1;
  16265. s.hash_bits = memLevel + 7;
  16266. s.hash_size = 1 << s.hash_bits;
  16267. s.hash_mask = s.hash_size - 1;
  16268. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  16269. s.window = new utils.Buf8(s.w_size * 2);
  16270. s.head = new utils.Buf16(s.hash_size);
  16271. s.prev = new utils.Buf16(s.w_size);
  16272. // Don't need mem init magic for JS.
  16273. //s.high_water = 0; /* nothing written to s->window yet */
  16274. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  16275. s.pending_buf_size = s.lit_bufsize * 4;
  16276. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  16277. s.d_buf = s.lit_bufsize >> 1;
  16278. s.l_buf = (1 + 2) * s.lit_bufsize;
  16279. s.level = level;
  16280. s.strategy = strategy;
  16281. s.method = method;
  16282. return deflateReset(strm);
  16283. }
  16284. function deflateInit(strm, level) {
  16285. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  16286. }
  16287. function deflate(strm, flush) {
  16288. var old_flush, s;
  16289. var beg, val; // for gzip header write only
  16290. if (!strm || !strm.state ||
  16291. flush > Z_BLOCK || flush < 0) {
  16292. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  16293. }
  16294. s = strm.state;
  16295. if (!strm.output ||
  16296. (!strm.input && strm.avail_in !== 0) ||
  16297. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  16298. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  16299. }
  16300. s.strm = strm; /* just in case */
  16301. old_flush = s.last_flush;
  16302. s.last_flush = flush;
  16303. /* Write the header */
  16304. if (s.status === INIT_STATE) {
  16305. if (s.wrap === 2) { // GZIP header
  16306. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16307. put_byte(s, 31);
  16308. put_byte(s, 139);
  16309. put_byte(s, 8);
  16310. if (!s.gzhead) { // s->gzhead == Z_NULL
  16311. put_byte(s, 0);
  16312. put_byte(s, 0);
  16313. put_byte(s, 0);
  16314. put_byte(s, 0);
  16315. put_byte(s, 0);
  16316. put_byte(s, s.level === 9 ? 2 :
  16317. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16318. 4 : 0));
  16319. put_byte(s, OS_CODE);
  16320. s.status = BUSY_STATE;
  16321. }
  16322. else {
  16323. put_byte(s, (s.gzhead.text ? 1 : 0) +
  16324. (s.gzhead.hcrc ? 2 : 0) +
  16325. (!s.gzhead.extra ? 0 : 4) +
  16326. (!s.gzhead.name ? 0 : 8) +
  16327. (!s.gzhead.comment ? 0 : 16)
  16328. );
  16329. put_byte(s, s.gzhead.time & 0xff);
  16330. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  16331. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  16332. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  16333. put_byte(s, s.level === 9 ? 2 :
  16334. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16335. 4 : 0));
  16336. put_byte(s, s.gzhead.os & 0xff);
  16337. if (s.gzhead.extra && s.gzhead.extra.length) {
  16338. put_byte(s, s.gzhead.extra.length & 0xff);
  16339. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  16340. }
  16341. if (s.gzhead.hcrc) {
  16342. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  16343. }
  16344. s.gzindex = 0;
  16345. s.status = EXTRA_STATE;
  16346. }
  16347. }
  16348. else // DEFLATE header
  16349. {
  16350. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  16351. var level_flags = -1;
  16352. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  16353. level_flags = 0;
  16354. } else if (s.level < 6) {
  16355. level_flags = 1;
  16356. } else if (s.level === 6) {
  16357. level_flags = 2;
  16358. } else {
  16359. level_flags = 3;
  16360. }
  16361. header |= (level_flags << 6);
  16362. if (s.strstart !== 0) { header |= PRESET_DICT; }
  16363. header += 31 - (header % 31);
  16364. s.status = BUSY_STATE;
  16365. putShortMSB(s, header);
  16366. /* Save the adler32 of the preset dictionary: */
  16367. if (s.strstart !== 0) {
  16368. putShortMSB(s, strm.adler >>> 16);
  16369. putShortMSB(s, strm.adler & 0xffff);
  16370. }
  16371. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  16372. }
  16373. }
  16374. //#ifdef GZIP
  16375. if (s.status === EXTRA_STATE) {
  16376. if (s.gzhead.extra/* != Z_NULL*/) {
  16377. beg = s.pending; /* start of bytes to update crc */
  16378. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  16379. if (s.pending === s.pending_buf_size) {
  16380. if (s.gzhead.hcrc && s.pending > beg) {
  16381. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16382. }
  16383. flush_pending(strm);
  16384. beg = s.pending;
  16385. if (s.pending === s.pending_buf_size) {
  16386. break;
  16387. }
  16388. }
  16389. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  16390. s.gzindex++;
  16391. }
  16392. if (s.gzhead.hcrc && s.pending > beg) {
  16393. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16394. }
  16395. if (s.gzindex === s.gzhead.extra.length) {
  16396. s.gzindex = 0;
  16397. s.status = NAME_STATE;
  16398. }
  16399. }
  16400. else {
  16401. s.status = NAME_STATE;
  16402. }
  16403. }
  16404. if (s.status === NAME_STATE) {
  16405. if (s.gzhead.name/* != Z_NULL*/) {
  16406. beg = s.pending; /* start of bytes to update crc */
  16407. //int val;
  16408. do {
  16409. if (s.pending === s.pending_buf_size) {
  16410. if (s.gzhead.hcrc && s.pending > beg) {
  16411. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16412. }
  16413. flush_pending(strm);
  16414. beg = s.pending;
  16415. if (s.pending === s.pending_buf_size) {
  16416. val = 1;
  16417. break;
  16418. }
  16419. }
  16420. // JS specific: little magic to add zero terminator to end of string
  16421. if (s.gzindex < s.gzhead.name.length) {
  16422. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  16423. } else {
  16424. val = 0;
  16425. }
  16426. put_byte(s, val);
  16427. } while (val !== 0);
  16428. if (s.gzhead.hcrc && s.pending > beg){
  16429. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16430. }
  16431. if (val === 0) {
  16432. s.gzindex = 0;
  16433. s.status = COMMENT_STATE;
  16434. }
  16435. }
  16436. else {
  16437. s.status = COMMENT_STATE;
  16438. }
  16439. }
  16440. if (s.status === COMMENT_STATE) {
  16441. if (s.gzhead.comment/* != Z_NULL*/) {
  16442. beg = s.pending; /* start of bytes to update crc */
  16443. //int val;
  16444. do {
  16445. if (s.pending === s.pending_buf_size) {
  16446. if (s.gzhead.hcrc && s.pending > beg) {
  16447. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16448. }
  16449. flush_pending(strm);
  16450. beg = s.pending;
  16451. if (s.pending === s.pending_buf_size) {
  16452. val = 1;
  16453. break;
  16454. }
  16455. }
  16456. // JS specific: little magic to add zero terminator to end of string
  16457. if (s.gzindex < s.gzhead.comment.length) {
  16458. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  16459. } else {
  16460. val = 0;
  16461. }
  16462. put_byte(s, val);
  16463. } while (val !== 0);
  16464. if (s.gzhead.hcrc && s.pending > beg) {
  16465. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16466. }
  16467. if (val === 0) {
  16468. s.status = HCRC_STATE;
  16469. }
  16470. }
  16471. else {
  16472. s.status = HCRC_STATE;
  16473. }
  16474. }
  16475. if (s.status === HCRC_STATE) {
  16476. if (s.gzhead.hcrc) {
  16477. if (s.pending + 2 > s.pending_buf_size) {
  16478. flush_pending(strm);
  16479. }
  16480. if (s.pending + 2 <= s.pending_buf_size) {
  16481. put_byte(s, strm.adler & 0xff);
  16482. put_byte(s, (strm.adler >> 8) & 0xff);
  16483. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16484. s.status = BUSY_STATE;
  16485. }
  16486. }
  16487. else {
  16488. s.status = BUSY_STATE;
  16489. }
  16490. }
  16491. //#endif
  16492. /* Flush as much pending output as possible */
  16493. if (s.pending !== 0) {
  16494. flush_pending(strm);
  16495. if (strm.avail_out === 0) {
  16496. /* Since avail_out is 0, deflate will be called again with
  16497. * more output space, but possibly with both pending and
  16498. * avail_in equal to zero. There won't be anything to do,
  16499. * but this is not an error situation so make sure we
  16500. * return OK instead of BUF_ERROR at next call of deflate:
  16501. */
  16502. s.last_flush = -1;
  16503. return Z_OK;
  16504. }
  16505. /* Make sure there is something to do and avoid duplicate consecutive
  16506. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16507. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16508. */
  16509. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16510. flush !== Z_FINISH) {
  16511. return err(strm, Z_BUF_ERROR);
  16512. }
  16513. /* User must not provide more input after the first FINISH: */
  16514. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16515. return err(strm, Z_BUF_ERROR);
  16516. }
  16517. /* Start a new block or continue the current one.
  16518. */
  16519. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16520. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16521. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16522. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16523. configuration_table[s.level].func(s, flush));
  16524. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16525. s.status = FINISH_STATE;
  16526. }
  16527. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  16528. if (strm.avail_out === 0) {
  16529. s.last_flush = -1;
  16530. /* avoid BUF_ERROR next call, see above */
  16531. }
  16532. return Z_OK;
  16533. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  16534. * of deflate should use the same flush parameter to make sure
  16535. * that the flush is complete. So we don't have to output an
  16536. * empty block here, this will be done at next call. This also
  16537. * ensures that for a very small output buffer, we emit at most
  16538. * one empty block.
  16539. */
  16540. }
  16541. if (bstate === BS_BLOCK_DONE) {
  16542. if (flush === Z_PARTIAL_FLUSH) {
  16543. trees._tr_align(s);
  16544. }
  16545. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  16546. trees._tr_stored_block(s, 0, 0, false);
  16547. /* For a full flush, this empty block will be recognized
  16548. * as a special marker by inflate_sync().
  16549. */
  16550. if (flush === Z_FULL_FLUSH) {
  16551. /*** CLEAR_HASH(s); ***/ /* forget history */
  16552. zero(s.head); // Fill with NIL (= 0);
  16553. if (s.lookahead === 0) {
  16554. s.strstart = 0;
  16555. s.block_start = 0;
  16556. s.insert = 0;
  16557. }
  16558. }
  16559. }
  16560. flush_pending(strm);
  16561. if (strm.avail_out === 0) {
  16562. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  16563. return Z_OK;
  16564. }
  16565. }
  16566. }
  16567. //Assert(strm->avail_out > 0, "bug2");
  16568. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  16569. if (flush !== Z_FINISH) { return Z_OK; }
  16570. if (s.wrap <= 0) { return Z_STREAM_END; }
  16571. /* Write the trailer */
  16572. if (s.wrap === 2) {
  16573. put_byte(s, strm.adler & 0xff);
  16574. put_byte(s, (strm.adler >> 8) & 0xff);
  16575. put_byte(s, (strm.adler >> 16) & 0xff);
  16576. put_byte(s, (strm.adler >> 24) & 0xff);
  16577. put_byte(s, strm.total_in & 0xff);
  16578. put_byte(s, (strm.total_in >> 8) & 0xff);
  16579. put_byte(s, (strm.total_in >> 16) & 0xff);
  16580. put_byte(s, (strm.total_in >> 24) & 0xff);
  16581. }
  16582. else
  16583. {
  16584. putShortMSB(s, strm.adler >>> 16);
  16585. putShortMSB(s, strm.adler & 0xffff);
  16586. }
  16587. flush_pending(strm);
  16588. /* If avail_out is zero, the application will call deflate again
  16589. * to flush the rest.
  16590. */
  16591. if (s.wrap > 0) { s.wrap = -s.wrap; }
  16592. /* write the trailer only once! */
  16593. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  16594. }
  16595. function deflateEnd(strm) {
  16596. var status;
  16597. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  16598. return Z_STREAM_ERROR;
  16599. }
  16600. status = strm.state.status;
  16601. if (status !== INIT_STATE &&
  16602. status !== EXTRA_STATE &&
  16603. status !== NAME_STATE &&
  16604. status !== COMMENT_STATE &&
  16605. status !== HCRC_STATE &&
  16606. status !== BUSY_STATE &&
  16607. status !== FINISH_STATE
  16608. ) {
  16609. return err(strm, Z_STREAM_ERROR);
  16610. }
  16611. strm.state = null;
  16612. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  16613. }
  16614. /* =========================================================================
  16615. * Copy the source state to the destination state
  16616. */
  16617. //function deflateCopy(dest, source) {
  16618. //
  16619. //}
  16620. exports.deflateInit = deflateInit;
  16621. exports.deflateInit2 = deflateInit2;
  16622. exports.deflateReset = deflateReset;
  16623. exports.deflateResetKeep = deflateResetKeep;
  16624. exports.deflateSetHeader = deflateSetHeader;
  16625. exports.deflate = deflate;
  16626. exports.deflateEnd = deflateEnd;
  16627. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  16628. /* Not implemented
  16629. exports.deflateBound = deflateBound;
  16630. exports.deflateCopy = deflateCopy;
  16631. exports.deflateSetDictionary = deflateSetDictionary;
  16632. exports.deflateParams = deflateParams;
  16633. exports.deflatePending = deflatePending;
  16634. exports.deflatePrime = deflatePrime;
  16635. exports.deflateTune = deflateTune;
  16636. */
  16637. },{"../utils/common":63,"./adler32":65,"./crc32":67,"./messages":73,"./trees":74}],69:[function(require,module,exports){
  16638. 'use strict';
  16639. function GZheader() {
  16640. /* true if compressed data believed to be text */
  16641. this.text = 0;
  16642. /* modification time */
  16643. this.time = 0;
  16644. /* extra flags (not used when writing a gzip file) */
  16645. this.xflags = 0;
  16646. /* operating system */
  16647. this.os = 0;
  16648. /* pointer to extra field or Z_NULL if none */
  16649. this.extra = null;
  16650. /* extra field length (valid if extra != Z_NULL) */
  16651. this.extra_len = 0; // Actually, we don't need it in JS,
  16652. // but leave for few code modifications
  16653. //
  16654. // Setup limits is not necessary because in js we should not preallocate memory
  16655. // for inflate use constant limit in 65536 bytes
  16656. //
  16657. /* space at extra (only when reading header) */
  16658. // this.extra_max = 0;
  16659. /* pointer to zero-terminated file name or Z_NULL */
  16660. this.name = '';
  16661. /* space at name (only when reading header) */
  16662. // this.name_max = 0;
  16663. /* pointer to zero-terminated comment or Z_NULL */
  16664. this.comment = '';
  16665. /* space at comment (only when reading header) */
  16666. // this.comm_max = 0;
  16667. /* true if there was or will be a header crc */
  16668. this.hcrc = 0;
  16669. /* true when done reading gzip header (not used when writing a gzip file) */
  16670. this.done = false;
  16671. }
  16672. module.exports = GZheader;
  16673. },{}],70:[function(require,module,exports){
  16674. 'use strict';
  16675. // See state defs from inflate.js
  16676. var BAD = 30; /* got a data error -- remain here until reset */
  16677. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16678. /*
  16679. Decode literal, length, and distance codes and write out the resulting
  16680. literal and match bytes until either not enough input or output is
  16681. available, an end-of-block is encountered, or a data error is encountered.
  16682. When large enough input and output buffers are supplied to inflate(), for
  16683. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  16684. inflate execution time is spent in this routine.
  16685. Entry assumptions:
  16686. state.mode === LEN
  16687. strm.avail_in >= 6
  16688. strm.avail_out >= 258
  16689. start >= strm.avail_out
  16690. state.bits < 8
  16691. On return, state.mode is one of:
  16692. LEN -- ran out of enough output space or enough available input
  16693. TYPE -- reached end of block code, inflate() to interpret next block
  16694. BAD -- error in block data
  16695. Notes:
  16696. - The maximum input bits used by a length/distance pair is 15 bits for the
  16697. length code, 5 bits for the length extra, 15 bits for the distance code,
  16698. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  16699. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  16700. checking for available input while decoding.
  16701. - The maximum bytes that a single length/distance pair can output is 258
  16702. bytes, which is the maximum length that can be coded. inflate_fast()
  16703. requires strm.avail_out >= 258 for each loop to avoid checking for
  16704. output space.
  16705. */
  16706. module.exports = function inflate_fast(strm, start) {
  16707. var state;
  16708. var _in; /* local strm.input */
  16709. var last; /* have enough input while in < last */
  16710. var _out; /* local strm.output */
  16711. var beg; /* inflate()'s initial strm.output */
  16712. var end; /* while out < end, enough space available */
  16713. //#ifdef INFLATE_STRICT
  16714. var dmax; /* maximum distance from zlib header */
  16715. //#endif
  16716. var wsize; /* window size or zero if not using window */
  16717. var whave; /* valid bytes in the window */
  16718. var wnext; /* window write index */
  16719. var window; /* allocated sliding window, if wsize != 0 */
  16720. var hold; /* local strm.hold */
  16721. var bits; /* local strm.bits */
  16722. var lcode; /* local strm.lencode */
  16723. var dcode; /* local strm.distcode */
  16724. var lmask; /* mask for first level of length codes */
  16725. var dmask; /* mask for first level of distance codes */
  16726. var here; /* retrieved table entry */
  16727. var op; /* code bits, operation, extra bits, or */
  16728. /* window position, window bytes to copy */
  16729. var len; /* match length, unused bytes */
  16730. var dist; /* match distance */
  16731. var from; /* where to copy match from */
  16732. var from_source;
  16733. var input, output; // JS specific, because we have no pointers
  16734. /* copy state to local variables */
  16735. state = strm.state;
  16736. //here = state.here;
  16737. _in = strm.next_in;
  16738. input = strm.input;
  16739. last = _in + (strm.avail_in - 5);
  16740. _out = strm.next_out;
  16741. output = strm.output;
  16742. beg = _out - (start - strm.avail_out);
  16743. end = _out + (strm.avail_out - 257);
  16744. //#ifdef INFLATE_STRICT
  16745. dmax = state.dmax;
  16746. //#endif
  16747. wsize = state.wsize;
  16748. whave = state.whave;
  16749. wnext = state.wnext;
  16750. window = state.window;
  16751. hold = state.hold;
  16752. bits = state.bits;
  16753. lcode = state.lencode;
  16754. dcode = state.distcode;
  16755. lmask = (1 << state.lenbits) - 1;
  16756. dmask = (1 << state.distbits) - 1;
  16757. /* decode literals and length/distances until end-of-block or not enough
  16758. input data or output space */
  16759. top:
  16760. do {
  16761. if (bits < 15) {
  16762. hold += input[_in++] << bits;
  16763. bits += 8;
  16764. hold += input[_in++] << bits;
  16765. bits += 8;
  16766. }
  16767. here = lcode[hold & lmask];
  16768. dolen:
  16769. for (;;) { // Goto emulation
  16770. op = here >>> 24/*here.bits*/;
  16771. hold >>>= op;
  16772. bits -= op;
  16773. op = (here >>> 16) & 0xff/*here.op*/;
  16774. if (op === 0) { /* literal */
  16775. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16776. // "inflate: literal '%c'\n" :
  16777. // "inflate: literal 0x%02x\n", here.val));
  16778. output[_out++] = here & 0xffff/*here.val*/;
  16779. }
  16780. else if (op & 16) { /* length base */
  16781. len = here & 0xffff/*here.val*/;
  16782. op &= 15; /* number of extra bits */
  16783. if (op) {
  16784. if (bits < op) {
  16785. hold += input[_in++] << bits;
  16786. bits += 8;
  16787. }
  16788. len += hold & ((1 << op) - 1);
  16789. hold >>>= op;
  16790. bits -= op;
  16791. }
  16792. //Tracevv((stderr, "inflate: length %u\n", len));
  16793. if (bits < 15) {
  16794. hold += input[_in++] << bits;
  16795. bits += 8;
  16796. hold += input[_in++] << bits;
  16797. bits += 8;
  16798. }
  16799. here = dcode[hold & dmask];
  16800. dodist:
  16801. for (;;) { // goto emulation
  16802. op = here >>> 24/*here.bits*/;
  16803. hold >>>= op;
  16804. bits -= op;
  16805. op = (here >>> 16) & 0xff/*here.op*/;
  16806. if (op & 16) { /* distance base */
  16807. dist = here & 0xffff/*here.val*/;
  16808. op &= 15; /* number of extra bits */
  16809. if (bits < op) {
  16810. hold += input[_in++] << bits;
  16811. bits += 8;
  16812. if (bits < op) {
  16813. hold += input[_in++] << bits;
  16814. bits += 8;
  16815. }
  16816. }
  16817. dist += hold & ((1 << op) - 1);
  16818. //#ifdef INFLATE_STRICT
  16819. if (dist > dmax) {
  16820. strm.msg = 'invalid distance too far back';
  16821. state.mode = BAD;
  16822. break top;
  16823. }
  16824. //#endif
  16825. hold >>>= op;
  16826. bits -= op;
  16827. //Tracevv((stderr, "inflate: distance %u\n", dist));
  16828. op = _out - beg; /* max distance in output */
  16829. if (dist > op) { /* see if copy from window */
  16830. op = dist - op; /* distance back in window */
  16831. if (op > whave) {
  16832. if (state.sane) {
  16833. strm.msg = 'invalid distance too far back';
  16834. state.mode = BAD;
  16835. break top;
  16836. }
  16837. // (!) This block is disabled in zlib defailts,
  16838. // don't enable it for binary compatibility
  16839. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16840. // if (len <= op - whave) {
  16841. // do {
  16842. // output[_out++] = 0;
  16843. // } while (--len);
  16844. // continue top;
  16845. // }
  16846. // len -= op - whave;
  16847. // do {
  16848. // output[_out++] = 0;
  16849. // } while (--op > whave);
  16850. // if (op === 0) {
  16851. // from = _out - dist;
  16852. // do {
  16853. // output[_out++] = output[from++];
  16854. // } while (--len);
  16855. // continue top;
  16856. // }
  16857. //#endif
  16858. }
  16859. from = 0; // window index
  16860. from_source = window;
  16861. if (wnext === 0) { /* very common case */
  16862. from += wsize - op;
  16863. if (op < len) { /* some from window */
  16864. len -= op;
  16865. do {
  16866. output[_out++] = window[from++];
  16867. } while (--op);
  16868. from = _out - dist; /* rest from output */
  16869. from_source = output;
  16870. }
  16871. }
  16872. else if (wnext < op) { /* wrap around window */
  16873. from += wsize + wnext - op;
  16874. op -= wnext;
  16875. if (op < len) { /* some from end of window */
  16876. len -= op;
  16877. do {
  16878. output[_out++] = window[from++];
  16879. } while (--op);
  16880. from = 0;
  16881. if (wnext < len) { /* some from start of window */
  16882. op = wnext;
  16883. len -= op;
  16884. do {
  16885. output[_out++] = window[from++];
  16886. } while (--op);
  16887. from = _out - dist; /* rest from output */
  16888. from_source = output;
  16889. }
  16890. }
  16891. }
  16892. else { /* contiguous in window */
  16893. from += wnext - op;
  16894. if (op < len) { /* some from window */
  16895. len -= op;
  16896. do {
  16897. output[_out++] = window[from++];
  16898. } while (--op);
  16899. from = _out - dist; /* rest from output */
  16900. from_source = output;
  16901. }
  16902. }
  16903. while (len > 2) {
  16904. output[_out++] = from_source[from++];
  16905. output[_out++] = from_source[from++];
  16906. output[_out++] = from_source[from++];
  16907. len -= 3;
  16908. }
  16909. if (len) {
  16910. output[_out++] = from_source[from++];
  16911. if (len > 1) {
  16912. output[_out++] = from_source[from++];
  16913. }
  16914. }
  16915. }
  16916. else {
  16917. from = _out - dist; /* copy direct from output */
  16918. do { /* minimum length is three */
  16919. output[_out++] = output[from++];
  16920. output[_out++] = output[from++];
  16921. output[_out++] = output[from++];
  16922. len -= 3;
  16923. } while (len > 2);
  16924. if (len) {
  16925. output[_out++] = output[from++];
  16926. if (len > 1) {
  16927. output[_out++] = output[from++];
  16928. }
  16929. }
  16930. }
  16931. }
  16932. else if ((op & 64) === 0) { /* 2nd level distance code */
  16933. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16934. continue dodist;
  16935. }
  16936. else {
  16937. strm.msg = 'invalid distance code';
  16938. state.mode = BAD;
  16939. break top;
  16940. }
  16941. break; // need to emulate goto via "continue"
  16942. }
  16943. }
  16944. else if ((op & 64) === 0) { /* 2nd level length code */
  16945. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16946. continue dolen;
  16947. }
  16948. else if (op & 32) { /* end-of-block */
  16949. //Tracevv((stderr, "inflate: end of block\n"));
  16950. state.mode = TYPE;
  16951. break top;
  16952. }
  16953. else {
  16954. strm.msg = 'invalid literal/length code';
  16955. state.mode = BAD;
  16956. break top;
  16957. }
  16958. break; // need to emulate goto via "continue"
  16959. }
  16960. } while (_in < last && _out < end);
  16961. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  16962. len = bits >> 3;
  16963. _in -= len;
  16964. bits -= len << 3;
  16965. hold &= (1 << bits) - 1;
  16966. /* update state and return */
  16967. strm.next_in = _in;
  16968. strm.next_out = _out;
  16969. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  16970. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  16971. state.hold = hold;
  16972. state.bits = bits;
  16973. return;
  16974. };
  16975. },{}],71:[function(require,module,exports){
  16976. 'use strict';
  16977. var utils = require('../utils/common');
  16978. var adler32 = require('./adler32');
  16979. var crc32 = require('./crc32');
  16980. var inflate_fast = require('./inffast');
  16981. var inflate_table = require('./inftrees');
  16982. var CODES = 0;
  16983. var LENS = 1;
  16984. var DISTS = 2;
  16985. /* Public constants ==========================================================*/
  16986. /* ===========================================================================*/
  16987. /* Allowed flush values; see deflate() and inflate() below for details */
  16988. //var Z_NO_FLUSH = 0;
  16989. //var Z_PARTIAL_FLUSH = 1;
  16990. //var Z_SYNC_FLUSH = 2;
  16991. //var Z_FULL_FLUSH = 3;
  16992. var Z_FINISH = 4;
  16993. var Z_BLOCK = 5;
  16994. var Z_TREES = 6;
  16995. /* Return codes for the compression/decompression functions. Negative values
  16996. * are errors, positive values are used for special but normal events.
  16997. */
  16998. var Z_OK = 0;
  16999. var Z_STREAM_END = 1;
  17000. var Z_NEED_DICT = 2;
  17001. //var Z_ERRNO = -1;
  17002. var Z_STREAM_ERROR = -2;
  17003. var Z_DATA_ERROR = -3;
  17004. var Z_MEM_ERROR = -4;
  17005. var Z_BUF_ERROR = -5;
  17006. //var Z_VERSION_ERROR = -6;
  17007. /* The deflate compression method */
  17008. var Z_DEFLATED = 8;
  17009. /* STATES ====================================================================*/
  17010. /* ===========================================================================*/
  17011. var HEAD = 1; /* i: waiting for magic header */
  17012. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17013. var TIME = 3; /* i: waiting for modification time (gzip) */
  17014. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17015. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17016. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17017. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17018. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17019. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17020. var DICTID = 10; /* i: waiting for dictionary check value */
  17021. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17022. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17023. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17024. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17025. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17026. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17027. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17028. var LENLENS = 18; /* i: waiting for code length code lengths */
  17029. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17030. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17031. var LEN = 21; /* i: waiting for length/lit/eob code */
  17032. var LENEXT = 22; /* i: waiting for length extra bits */
  17033. var DIST = 23; /* i: waiting for distance code */
  17034. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17035. var MATCH = 25; /* o: waiting for output space to copy string */
  17036. var LIT = 26; /* o: waiting for output space to write literal */
  17037. var CHECK = 27; /* i: waiting for 32-bit check value */
  17038. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17039. var DONE = 29; /* finished check, done -- remain here until reset */
  17040. var BAD = 30; /* got a data error -- remain here until reset */
  17041. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17042. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17043. /* ===========================================================================*/
  17044. var ENOUGH_LENS = 852;
  17045. var ENOUGH_DISTS = 592;
  17046. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17047. var MAX_WBITS = 15;
  17048. /* 32K LZ77 window */
  17049. var DEF_WBITS = MAX_WBITS;
  17050. function ZSWAP32(q) {
  17051. return (((q >>> 24) & 0xff) +
  17052. ((q >>> 8) & 0xff00) +
  17053. ((q & 0xff00) << 8) +
  17054. ((q & 0xff) << 24));
  17055. }
  17056. function InflateState() {
  17057. this.mode = 0; /* current inflate mode */
  17058. this.last = false; /* true if processing last block */
  17059. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17060. this.havedict = false; /* true if dictionary provided */
  17061. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17062. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17063. this.check = 0; /* protected copy of check value */
  17064. this.total = 0; /* protected copy of output count */
  17065. // TODO: may be {}
  17066. this.head = null; /* where to save gzip header information */
  17067. /* sliding window */
  17068. this.wbits = 0; /* log base 2 of requested window size */
  17069. this.wsize = 0; /* window size or zero if not using window */
  17070. this.whave = 0; /* valid bytes in the window */
  17071. this.wnext = 0; /* window write index */
  17072. this.window = null; /* allocated sliding window, if needed */
  17073. /* bit accumulator */
  17074. this.hold = 0; /* input bit accumulator */
  17075. this.bits = 0; /* number of bits in "in" */
  17076. /* for string and stored block copying */
  17077. this.length = 0; /* literal or length of data to copy */
  17078. this.offset = 0; /* distance back to copy string from */
  17079. /* for table and code decoding */
  17080. this.extra = 0; /* extra bits needed */
  17081. /* fixed and dynamic code tables */
  17082. this.lencode = null; /* starting table for length/literal codes */
  17083. this.distcode = null; /* starting table for distance codes */
  17084. this.lenbits = 0; /* index bits for lencode */
  17085. this.distbits = 0; /* index bits for distcode */
  17086. /* dynamic table building */
  17087. this.ncode = 0; /* number of code length code lengths */
  17088. this.nlen = 0; /* number of length code lengths */
  17089. this.ndist = 0; /* number of distance code lengths */
  17090. this.have = 0; /* number of code lengths in lens[] */
  17091. this.next = null; /* next available space in codes[] */
  17092. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17093. this.work = new utils.Buf16(288); /* work area for code table building */
  17094. /*
  17095. because we don't have pointers in js, we use lencode and distcode directly
  17096. as buffers so we don't need codes
  17097. */
  17098. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17099. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17100. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17101. this.sane = 0; /* if false, allow invalid distance too far */
  17102. this.back = 0; /* bits back of last unprocessed length/lit */
  17103. this.was = 0; /* initial length of match */
  17104. }
  17105. function inflateResetKeep(strm) {
  17106. var state;
  17107. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17108. state = strm.state;
  17109. strm.total_in = strm.total_out = state.total = 0;
  17110. strm.msg = ''; /*Z_NULL*/
  17111. if (state.wrap) { /* to support ill-conceived Java test suite */
  17112. strm.adler = state.wrap & 1;
  17113. }
  17114. state.mode = HEAD;
  17115. state.last = 0;
  17116. state.havedict = 0;
  17117. state.dmax = 32768;
  17118. state.head = null/*Z_NULL*/;
  17119. state.hold = 0;
  17120. state.bits = 0;
  17121. //state.lencode = state.distcode = state.next = state.codes;
  17122. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17123. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17124. state.sane = 1;
  17125. state.back = -1;
  17126. //Tracev((stderr, "inflate: reset\n"));
  17127. return Z_OK;
  17128. }
  17129. function inflateReset(strm) {
  17130. var state;
  17131. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17132. state = strm.state;
  17133. state.wsize = 0;
  17134. state.whave = 0;
  17135. state.wnext = 0;
  17136. return inflateResetKeep(strm);
  17137. }
  17138. function inflateReset2(strm, windowBits) {
  17139. var wrap;
  17140. var state;
  17141. /* get the state */
  17142. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17143. state = strm.state;
  17144. /* extract wrap request from windowBits parameter */
  17145. if (windowBits < 0) {
  17146. wrap = 0;
  17147. windowBits = -windowBits;
  17148. }
  17149. else {
  17150. wrap = (windowBits >> 4) + 1;
  17151. if (windowBits < 48) {
  17152. windowBits &= 15;
  17153. }
  17154. }
  17155. /* set number of window bits, free window if different */
  17156. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  17157. return Z_STREAM_ERROR;
  17158. }
  17159. if (state.window !== null && state.wbits !== windowBits) {
  17160. state.window = null;
  17161. }
  17162. /* update state and reset the rest of it */
  17163. state.wrap = wrap;
  17164. state.wbits = windowBits;
  17165. return inflateReset(strm);
  17166. }
  17167. function inflateInit2(strm, windowBits) {
  17168. var ret;
  17169. var state;
  17170. if (!strm) { return Z_STREAM_ERROR; }
  17171. //strm.msg = Z_NULL; /* in case we return an error */
  17172. state = new InflateState();
  17173. //if (state === Z_NULL) return Z_MEM_ERROR;
  17174. //Tracev((stderr, "inflate: allocated\n"));
  17175. strm.state = state;
  17176. state.window = null/*Z_NULL*/;
  17177. ret = inflateReset2(strm, windowBits);
  17178. if (ret !== Z_OK) {
  17179. strm.state = null/*Z_NULL*/;
  17180. }
  17181. return ret;
  17182. }
  17183. function inflateInit(strm) {
  17184. return inflateInit2(strm, DEF_WBITS);
  17185. }
  17186. /*
  17187. Return state with length and distance decoding tables and index sizes set to
  17188. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  17189. If BUILDFIXED is defined, then instead this routine builds the tables the
  17190. first time it's called, and returns those tables the first time and
  17191. thereafter. This reduces the size of the code by about 2K bytes, in
  17192. exchange for a little execution time. However, BUILDFIXED should not be
  17193. used for threaded applications, since the rewriting of the tables and virgin
  17194. may not be thread-safe.
  17195. */
  17196. var virgin = true;
  17197. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  17198. function fixedtables(state) {
  17199. /* build fixed huffman tables if first call (may not be thread safe) */
  17200. if (virgin) {
  17201. var sym;
  17202. lenfix = new utils.Buf32(512);
  17203. distfix = new utils.Buf32(32);
  17204. /* literal/length table */
  17205. sym = 0;
  17206. while (sym < 144) { state.lens[sym++] = 8; }
  17207. while (sym < 256) { state.lens[sym++] = 9; }
  17208. while (sym < 280) { state.lens[sym++] = 7; }
  17209. while (sym < 288) { state.lens[sym++] = 8; }
  17210. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  17211. /* distance table */
  17212. sym = 0;
  17213. while (sym < 32) { state.lens[sym++] = 5; }
  17214. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  17215. /* do this just once */
  17216. virgin = false;
  17217. }
  17218. state.lencode = lenfix;
  17219. state.lenbits = 9;
  17220. state.distcode = distfix;
  17221. state.distbits = 5;
  17222. }
  17223. /*
  17224. Update the window with the last wsize (normally 32K) bytes written before
  17225. returning. If window does not exist yet, create it. This is only called
  17226. when a window is already in use, or when output has been written during this
  17227. inflate call, but the end of the deflate stream has not been reached yet.
  17228. It is also called to create a window for dictionary data when a dictionary
  17229. is loaded.
  17230. Providing output buffers larger than 32K to inflate() should provide a speed
  17231. advantage, since only the last 32K of output is copied to the sliding window
  17232. upon return from inflate(), and since all distances after the first 32K of
  17233. output will fall in the output data, making match copies simpler and faster.
  17234. The advantage may be dependent on the size of the processor's data caches.
  17235. */
  17236. function updatewindow(strm, src, end, copy) {
  17237. var dist;
  17238. var state = strm.state;
  17239. /* if it hasn't been done already, allocate space for the window */
  17240. if (state.window === null) {
  17241. state.wsize = 1 << state.wbits;
  17242. state.wnext = 0;
  17243. state.whave = 0;
  17244. state.window = new utils.Buf8(state.wsize);
  17245. }
  17246. /* copy state->wsize or less output bytes into the circular window */
  17247. if (copy >= state.wsize) {
  17248. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  17249. state.wnext = 0;
  17250. state.whave = state.wsize;
  17251. }
  17252. else {
  17253. dist = state.wsize - state.wnext;
  17254. if (dist > copy) {
  17255. dist = copy;
  17256. }
  17257. //zmemcpy(state->window + state->wnext, end - copy, dist);
  17258. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  17259. copy -= dist;
  17260. if (copy) {
  17261. //zmemcpy(state->window, end - copy, copy);
  17262. utils.arraySet(state.window,src, end - copy, copy, 0);
  17263. state.wnext = copy;
  17264. state.whave = state.wsize;
  17265. }
  17266. else {
  17267. state.wnext += dist;
  17268. if (state.wnext === state.wsize) { state.wnext = 0; }
  17269. if (state.whave < state.wsize) { state.whave += dist; }
  17270. }
  17271. }
  17272. return 0;
  17273. }
  17274. function inflate(strm, flush) {
  17275. var state;
  17276. var input, output; // input/output buffers
  17277. var next; /* next input INDEX */
  17278. var put; /* next output INDEX */
  17279. var have, left; /* available input and output */
  17280. var hold; /* bit buffer */
  17281. var bits; /* bits in bit buffer */
  17282. var _in, _out; /* save starting available input and output */
  17283. var copy; /* number of stored or match bytes to copy */
  17284. var from; /* where to copy match bytes from */
  17285. var from_source;
  17286. var here = 0; /* current decoding table entry */
  17287. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  17288. //var last; /* parent table entry */
  17289. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  17290. var len; /* length to copy for repeats, bits to drop */
  17291. var ret; /* return code */
  17292. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  17293. var opts;
  17294. var n; // temporary var for NEED_BITS
  17295. var order = /* permutation of code lengths */
  17296. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  17297. if (!strm || !strm.state || !strm.output ||
  17298. (!strm.input && strm.avail_in !== 0)) {
  17299. return Z_STREAM_ERROR;
  17300. }
  17301. state = strm.state;
  17302. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  17303. //--- LOAD() ---
  17304. put = strm.next_out;
  17305. output = strm.output;
  17306. left = strm.avail_out;
  17307. next = strm.next_in;
  17308. input = strm.input;
  17309. have = strm.avail_in;
  17310. hold = state.hold;
  17311. bits = state.bits;
  17312. //---
  17313. _in = have;
  17314. _out = left;
  17315. ret = Z_OK;
  17316. inf_leave: // goto emulation
  17317. for (;;) {
  17318. switch (state.mode) {
  17319. case HEAD:
  17320. if (state.wrap === 0) {
  17321. state.mode = TYPEDO;
  17322. break;
  17323. }
  17324. //=== NEEDBITS(16);
  17325. while (bits < 16) {
  17326. if (have === 0) { break inf_leave; }
  17327. have--;
  17328. hold += input[next++] << bits;
  17329. bits += 8;
  17330. }
  17331. //===//
  17332. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  17333. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  17334. //=== CRC2(state.check, hold);
  17335. hbuf[0] = hold & 0xff;
  17336. hbuf[1] = (hold >>> 8) & 0xff;
  17337. state.check = crc32(state.check, hbuf, 2, 0);
  17338. //===//
  17339. //=== INITBITS();
  17340. hold = 0;
  17341. bits = 0;
  17342. //===//
  17343. state.mode = FLAGS;
  17344. break;
  17345. }
  17346. state.flags = 0; /* expect zlib header */
  17347. if (state.head) {
  17348. state.head.done = false;
  17349. }
  17350. if (!(state.wrap & 1) || /* check if zlib header allowed */
  17351. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  17352. strm.msg = 'incorrect header check';
  17353. state.mode = BAD;
  17354. break;
  17355. }
  17356. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  17357. strm.msg = 'unknown compression method';
  17358. state.mode = BAD;
  17359. break;
  17360. }
  17361. //--- DROPBITS(4) ---//
  17362. hold >>>= 4;
  17363. bits -= 4;
  17364. //---//
  17365. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  17366. if (state.wbits === 0) {
  17367. state.wbits = len;
  17368. }
  17369. else if (len > state.wbits) {
  17370. strm.msg = 'invalid window size';
  17371. state.mode = BAD;
  17372. break;
  17373. }
  17374. state.dmax = 1 << len;
  17375. //Tracev((stderr, "inflate: zlib header ok\n"));
  17376. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17377. state.mode = hold & 0x200 ? DICTID : TYPE;
  17378. //=== INITBITS();
  17379. hold = 0;
  17380. bits = 0;
  17381. //===//
  17382. break;
  17383. case FLAGS:
  17384. //=== NEEDBITS(16); */
  17385. while (bits < 16) {
  17386. if (have === 0) { break inf_leave; }
  17387. have--;
  17388. hold += input[next++] << bits;
  17389. bits += 8;
  17390. }
  17391. //===//
  17392. state.flags = hold;
  17393. if ((state.flags & 0xff) !== Z_DEFLATED) {
  17394. strm.msg = 'unknown compression method';
  17395. state.mode = BAD;
  17396. break;
  17397. }
  17398. if (state.flags & 0xe000) {
  17399. strm.msg = 'unknown header flags set';
  17400. state.mode = BAD;
  17401. break;
  17402. }
  17403. if (state.head) {
  17404. state.head.text = ((hold >> 8) & 1);
  17405. }
  17406. if (state.flags & 0x0200) {
  17407. //=== CRC2(state.check, hold);
  17408. hbuf[0] = hold & 0xff;
  17409. hbuf[1] = (hold >>> 8) & 0xff;
  17410. state.check = crc32(state.check, hbuf, 2, 0);
  17411. //===//
  17412. }
  17413. //=== INITBITS();
  17414. hold = 0;
  17415. bits = 0;
  17416. //===//
  17417. state.mode = TIME;
  17418. /* falls through */
  17419. case TIME:
  17420. //=== NEEDBITS(32); */
  17421. while (bits < 32) {
  17422. if (have === 0) { break inf_leave; }
  17423. have--;
  17424. hold += input[next++] << bits;
  17425. bits += 8;
  17426. }
  17427. //===//
  17428. if (state.head) {
  17429. state.head.time = hold;
  17430. }
  17431. if (state.flags & 0x0200) {
  17432. //=== CRC4(state.check, hold)
  17433. hbuf[0] = hold & 0xff;
  17434. hbuf[1] = (hold >>> 8) & 0xff;
  17435. hbuf[2] = (hold >>> 16) & 0xff;
  17436. hbuf[3] = (hold >>> 24) & 0xff;
  17437. state.check = crc32(state.check, hbuf, 4, 0);
  17438. //===
  17439. }
  17440. //=== INITBITS();
  17441. hold = 0;
  17442. bits = 0;
  17443. //===//
  17444. state.mode = OS;
  17445. /* falls through */
  17446. case OS:
  17447. //=== NEEDBITS(16); */
  17448. while (bits < 16) {
  17449. if (have === 0) { break inf_leave; }
  17450. have--;
  17451. hold += input[next++] << bits;
  17452. bits += 8;
  17453. }
  17454. //===//
  17455. if (state.head) {
  17456. state.head.xflags = (hold & 0xff);
  17457. state.head.os = (hold >> 8);
  17458. }
  17459. if (state.flags & 0x0200) {
  17460. //=== CRC2(state.check, hold);
  17461. hbuf[0] = hold & 0xff;
  17462. hbuf[1] = (hold >>> 8) & 0xff;
  17463. state.check = crc32(state.check, hbuf, 2, 0);
  17464. //===//
  17465. }
  17466. //=== INITBITS();
  17467. hold = 0;
  17468. bits = 0;
  17469. //===//
  17470. state.mode = EXLEN;
  17471. /* falls through */
  17472. case EXLEN:
  17473. if (state.flags & 0x0400) {
  17474. //=== NEEDBITS(16); */
  17475. while (bits < 16) {
  17476. if (have === 0) { break inf_leave; }
  17477. have--;
  17478. hold += input[next++] << bits;
  17479. bits += 8;
  17480. }
  17481. //===//
  17482. state.length = hold;
  17483. if (state.head) {
  17484. state.head.extra_len = hold;
  17485. }
  17486. if (state.flags & 0x0200) {
  17487. //=== CRC2(state.check, hold);
  17488. hbuf[0] = hold & 0xff;
  17489. hbuf[1] = (hold >>> 8) & 0xff;
  17490. state.check = crc32(state.check, hbuf, 2, 0);
  17491. //===//
  17492. }
  17493. //=== INITBITS();
  17494. hold = 0;
  17495. bits = 0;
  17496. //===//
  17497. }
  17498. else if (state.head) {
  17499. state.head.extra = null/*Z_NULL*/;
  17500. }
  17501. state.mode = EXTRA;
  17502. /* falls through */
  17503. case EXTRA:
  17504. if (state.flags & 0x0400) {
  17505. copy = state.length;
  17506. if (copy > have) { copy = have; }
  17507. if (copy) {
  17508. if (state.head) {
  17509. len = state.head.extra_len - state.length;
  17510. if (!state.head.extra) {
  17511. // Use untyped array for more conveniend processing later
  17512. state.head.extra = new Array(state.head.extra_len);
  17513. }
  17514. utils.arraySet(
  17515. state.head.extra,
  17516. input,
  17517. next,
  17518. // extra field is limited to 65536 bytes
  17519. // - no need for additional size check
  17520. copy,
  17521. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17522. len
  17523. );
  17524. //zmemcpy(state.head.extra + len, next,
  17525. // len + copy > state.head.extra_max ?
  17526. // state.head.extra_max - len : copy);
  17527. }
  17528. if (state.flags & 0x0200) {
  17529. state.check = crc32(state.check, input, copy, next);
  17530. }
  17531. have -= copy;
  17532. next += copy;
  17533. state.length -= copy;
  17534. }
  17535. if (state.length) { break inf_leave; }
  17536. }
  17537. state.length = 0;
  17538. state.mode = NAME;
  17539. /* falls through */
  17540. case NAME:
  17541. if (state.flags & 0x0800) {
  17542. if (have === 0) { break inf_leave; }
  17543. copy = 0;
  17544. do {
  17545. // TODO: 2 or 1 bytes?
  17546. len = input[next + copy++];
  17547. /* use constant limit because in js we should not preallocate memory */
  17548. if (state.head && len &&
  17549. (state.length < 65536 /*state.head.name_max*/)) {
  17550. state.head.name += String.fromCharCode(len);
  17551. }
  17552. } while (len && copy < have);
  17553. if (state.flags & 0x0200) {
  17554. state.check = crc32(state.check, input, copy, next);
  17555. }
  17556. have -= copy;
  17557. next += copy;
  17558. if (len) { break inf_leave; }
  17559. }
  17560. else if (state.head) {
  17561. state.head.name = null;
  17562. }
  17563. state.length = 0;
  17564. state.mode = COMMENT;
  17565. /* falls through */
  17566. case COMMENT:
  17567. if (state.flags & 0x1000) {
  17568. if (have === 0) { break inf_leave; }
  17569. copy = 0;
  17570. do {
  17571. len = input[next + copy++];
  17572. /* use constant limit because in js we should not preallocate memory */
  17573. if (state.head && len &&
  17574. (state.length < 65536 /*state.head.comm_max*/)) {
  17575. state.head.comment += String.fromCharCode(len);
  17576. }
  17577. } while (len && copy < have);
  17578. if (state.flags & 0x0200) {
  17579. state.check = crc32(state.check, input, copy, next);
  17580. }
  17581. have -= copy;
  17582. next += copy;
  17583. if (len) { break inf_leave; }
  17584. }
  17585. else if (state.head) {
  17586. state.head.comment = null;
  17587. }
  17588. state.mode = HCRC;
  17589. /* falls through */
  17590. case HCRC:
  17591. if (state.flags & 0x0200) {
  17592. //=== NEEDBITS(16); */
  17593. while (bits < 16) {
  17594. if (have === 0) { break inf_leave; }
  17595. have--;
  17596. hold += input[next++] << bits;
  17597. bits += 8;
  17598. }
  17599. //===//
  17600. if (hold !== (state.check & 0xffff)) {
  17601. strm.msg = 'header crc mismatch';
  17602. state.mode = BAD;
  17603. break;
  17604. }
  17605. //=== INITBITS();
  17606. hold = 0;
  17607. bits = 0;
  17608. //===//
  17609. }
  17610. if (state.head) {
  17611. state.head.hcrc = ((state.flags >> 9) & 1);
  17612. state.head.done = true;
  17613. }
  17614. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  17615. state.mode = TYPE;
  17616. break;
  17617. case DICTID:
  17618. //=== NEEDBITS(32); */
  17619. while (bits < 32) {
  17620. if (have === 0) { break inf_leave; }
  17621. have--;
  17622. hold += input[next++] << bits;
  17623. bits += 8;
  17624. }
  17625. //===//
  17626. strm.adler = state.check = ZSWAP32(hold);
  17627. //=== INITBITS();
  17628. hold = 0;
  17629. bits = 0;
  17630. //===//
  17631. state.mode = DICT;
  17632. /* falls through */
  17633. case DICT:
  17634. if (state.havedict === 0) {
  17635. //--- RESTORE() ---
  17636. strm.next_out = put;
  17637. strm.avail_out = left;
  17638. strm.next_in = next;
  17639. strm.avail_in = have;
  17640. state.hold = hold;
  17641. state.bits = bits;
  17642. //---
  17643. return Z_NEED_DICT;
  17644. }
  17645. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17646. state.mode = TYPE;
  17647. /* falls through */
  17648. case TYPE:
  17649. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  17650. /* falls through */
  17651. case TYPEDO:
  17652. if (state.last) {
  17653. //--- BYTEBITS() ---//
  17654. hold >>>= bits & 7;
  17655. bits -= bits & 7;
  17656. //---//
  17657. state.mode = CHECK;
  17658. break;
  17659. }
  17660. //=== NEEDBITS(3); */
  17661. while (bits < 3) {
  17662. if (have === 0) { break inf_leave; }
  17663. have--;
  17664. hold += input[next++] << bits;
  17665. bits += 8;
  17666. }
  17667. //===//
  17668. state.last = (hold & 0x01)/*BITS(1)*/;
  17669. //--- DROPBITS(1) ---//
  17670. hold >>>= 1;
  17671. bits -= 1;
  17672. //---//
  17673. switch ((hold & 0x03)/*BITS(2)*/) {
  17674. case 0: /* stored block */
  17675. //Tracev((stderr, "inflate: stored block%s\n",
  17676. // state.last ? " (last)" : ""));
  17677. state.mode = STORED;
  17678. break;
  17679. case 1: /* fixed block */
  17680. fixedtables(state);
  17681. //Tracev((stderr, "inflate: fixed codes block%s\n",
  17682. // state.last ? " (last)" : ""));
  17683. state.mode = LEN_; /* decode codes */
  17684. if (flush === Z_TREES) {
  17685. //--- DROPBITS(2) ---//
  17686. hold >>>= 2;
  17687. bits -= 2;
  17688. //---//
  17689. break inf_leave;
  17690. }
  17691. break;
  17692. case 2: /* dynamic block */
  17693. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  17694. // state.last ? " (last)" : ""));
  17695. state.mode = TABLE;
  17696. break;
  17697. case 3:
  17698. strm.msg = 'invalid block type';
  17699. state.mode = BAD;
  17700. }
  17701. //--- DROPBITS(2) ---//
  17702. hold >>>= 2;
  17703. bits -= 2;
  17704. //---//
  17705. break;
  17706. case STORED:
  17707. //--- BYTEBITS() ---// /* go to byte boundary */
  17708. hold >>>= bits & 7;
  17709. bits -= bits & 7;
  17710. //---//
  17711. //=== NEEDBITS(32); */
  17712. while (bits < 32) {
  17713. if (have === 0) { break inf_leave; }
  17714. have--;
  17715. hold += input[next++] << bits;
  17716. bits += 8;
  17717. }
  17718. //===//
  17719. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  17720. strm.msg = 'invalid stored block lengths';
  17721. state.mode = BAD;
  17722. break;
  17723. }
  17724. state.length = hold & 0xffff;
  17725. //Tracev((stderr, "inflate: stored length %u\n",
  17726. // state.length));
  17727. //=== INITBITS();
  17728. hold = 0;
  17729. bits = 0;
  17730. //===//
  17731. state.mode = COPY_;
  17732. if (flush === Z_TREES) { break inf_leave; }
  17733. /* falls through */
  17734. case COPY_:
  17735. state.mode = COPY;
  17736. /* falls through */
  17737. case COPY:
  17738. copy = state.length;
  17739. if (copy) {
  17740. if (copy > have) { copy = have; }
  17741. if (copy > left) { copy = left; }
  17742. if (copy === 0) { break inf_leave; }
  17743. //--- zmemcpy(put, next, copy); ---
  17744. utils.arraySet(output, input, next, copy, put);
  17745. //---//
  17746. have -= copy;
  17747. next += copy;
  17748. left -= copy;
  17749. put += copy;
  17750. state.length -= copy;
  17751. break;
  17752. }
  17753. //Tracev((stderr, "inflate: stored end\n"));
  17754. state.mode = TYPE;
  17755. break;
  17756. case TABLE:
  17757. //=== NEEDBITS(14); */
  17758. while (bits < 14) {
  17759. if (have === 0) { break inf_leave; }
  17760. have--;
  17761. hold += input[next++] << bits;
  17762. bits += 8;
  17763. }
  17764. //===//
  17765. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  17766. //--- DROPBITS(5) ---//
  17767. hold >>>= 5;
  17768. bits -= 5;
  17769. //---//
  17770. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  17771. //--- DROPBITS(5) ---//
  17772. hold >>>= 5;
  17773. bits -= 5;
  17774. //---//
  17775. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  17776. //--- DROPBITS(4) ---//
  17777. hold >>>= 4;
  17778. bits -= 4;
  17779. //---//
  17780. //#ifndef PKZIP_BUG_WORKAROUND
  17781. if (state.nlen > 286 || state.ndist > 30) {
  17782. strm.msg = 'too many length or distance symbols';
  17783. state.mode = BAD;
  17784. break;
  17785. }
  17786. //#endif
  17787. //Tracev((stderr, "inflate: table sizes ok\n"));
  17788. state.have = 0;
  17789. state.mode = LENLENS;
  17790. /* falls through */
  17791. case LENLENS:
  17792. while (state.have < state.ncode) {
  17793. //=== NEEDBITS(3);
  17794. while (bits < 3) {
  17795. if (have === 0) { break inf_leave; }
  17796. have--;
  17797. hold += input[next++] << bits;
  17798. bits += 8;
  17799. }
  17800. //===//
  17801. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  17802. //--- DROPBITS(3) ---//
  17803. hold >>>= 3;
  17804. bits -= 3;
  17805. //---//
  17806. }
  17807. while (state.have < 19) {
  17808. state.lens[order[state.have++]] = 0;
  17809. }
  17810. // We have separate tables & no pointers. 2 commented lines below not needed.
  17811. //state.next = state.codes;
  17812. //state.lencode = state.next;
  17813. // Switch to use dynamic table
  17814. state.lencode = state.lendyn;
  17815. state.lenbits = 7;
  17816. opts = {bits: state.lenbits};
  17817. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  17818. state.lenbits = opts.bits;
  17819. if (ret) {
  17820. strm.msg = 'invalid code lengths set';
  17821. state.mode = BAD;
  17822. break;
  17823. }
  17824. //Tracev((stderr, "inflate: code lengths ok\n"));
  17825. state.have = 0;
  17826. state.mode = CODELENS;
  17827. /* falls through */
  17828. case CODELENS:
  17829. while (state.have < state.nlen + state.ndist) {
  17830. for (;;) {
  17831. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  17832. here_bits = here >>> 24;
  17833. here_op = (here >>> 16) & 0xff;
  17834. here_val = here & 0xffff;
  17835. if ((here_bits) <= bits) { break; }
  17836. //--- PULLBYTE() ---//
  17837. if (have === 0) { break inf_leave; }
  17838. have--;
  17839. hold += input[next++] << bits;
  17840. bits += 8;
  17841. //---//
  17842. }
  17843. if (here_val < 16) {
  17844. //--- DROPBITS(here.bits) ---//
  17845. hold >>>= here_bits;
  17846. bits -= here_bits;
  17847. //---//
  17848. state.lens[state.have++] = here_val;
  17849. }
  17850. else {
  17851. if (here_val === 16) {
  17852. //=== NEEDBITS(here.bits + 2);
  17853. n = here_bits + 2;
  17854. while (bits < n) {
  17855. if (have === 0) { break inf_leave; }
  17856. have--;
  17857. hold += input[next++] << bits;
  17858. bits += 8;
  17859. }
  17860. //===//
  17861. //--- DROPBITS(here.bits) ---//
  17862. hold >>>= here_bits;
  17863. bits -= here_bits;
  17864. //---//
  17865. if (state.have === 0) {
  17866. strm.msg = 'invalid bit length repeat';
  17867. state.mode = BAD;
  17868. break;
  17869. }
  17870. len = state.lens[state.have - 1];
  17871. copy = 3 + (hold & 0x03);//BITS(2);
  17872. //--- DROPBITS(2) ---//
  17873. hold >>>= 2;
  17874. bits -= 2;
  17875. //---//
  17876. }
  17877. else if (here_val === 17) {
  17878. //=== NEEDBITS(here.bits + 3);
  17879. n = here_bits + 3;
  17880. while (bits < n) {
  17881. if (have === 0) { break inf_leave; }
  17882. have--;
  17883. hold += input[next++] << bits;
  17884. bits += 8;
  17885. }
  17886. //===//
  17887. //--- DROPBITS(here.bits) ---//
  17888. hold >>>= here_bits;
  17889. bits -= here_bits;
  17890. //---//
  17891. len = 0;
  17892. copy = 3 + (hold & 0x07);//BITS(3);
  17893. //--- DROPBITS(3) ---//
  17894. hold >>>= 3;
  17895. bits -= 3;
  17896. //---//
  17897. }
  17898. else {
  17899. //=== NEEDBITS(here.bits + 7);
  17900. n = here_bits + 7;
  17901. while (bits < n) {
  17902. if (have === 0) { break inf_leave; }
  17903. have--;
  17904. hold += input[next++] << bits;
  17905. bits += 8;
  17906. }
  17907. //===//
  17908. //--- DROPBITS(here.bits) ---//
  17909. hold >>>= here_bits;
  17910. bits -= here_bits;
  17911. //---//
  17912. len = 0;
  17913. copy = 11 + (hold & 0x7f);//BITS(7);
  17914. //--- DROPBITS(7) ---//
  17915. hold >>>= 7;
  17916. bits -= 7;
  17917. //---//
  17918. }
  17919. if (state.have + copy > state.nlen + state.ndist) {
  17920. strm.msg = 'invalid bit length repeat';
  17921. state.mode = BAD;
  17922. break;
  17923. }
  17924. while (copy--) {
  17925. state.lens[state.have++] = len;
  17926. }
  17927. }
  17928. }
  17929. /* handle error breaks in while */
  17930. if (state.mode === BAD) { break; }
  17931. /* check for end-of-block code (better have one) */
  17932. if (state.lens[256] === 0) {
  17933. strm.msg = 'invalid code -- missing end-of-block';
  17934. state.mode = BAD;
  17935. break;
  17936. }
  17937. /* build code tables -- note: do not change the lenbits or distbits
  17938. values here (9 and 6) without reading the comments in inftrees.h
  17939. concerning the ENOUGH constants, which depend on those values */
  17940. state.lenbits = 9;
  17941. opts = {bits: state.lenbits};
  17942. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  17943. // We have separate tables & no pointers. 2 commented lines below not needed.
  17944. // state.next_index = opts.table_index;
  17945. state.lenbits = opts.bits;
  17946. // state.lencode = state.next;
  17947. if (ret) {
  17948. strm.msg = 'invalid literal/lengths set';
  17949. state.mode = BAD;
  17950. break;
  17951. }
  17952. state.distbits = 6;
  17953. //state.distcode.copy(state.codes);
  17954. // Switch to use dynamic table
  17955. state.distcode = state.distdyn;
  17956. opts = {bits: state.distbits};
  17957. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  17958. // We have separate tables & no pointers. 2 commented lines below not needed.
  17959. // state.next_index = opts.table_index;
  17960. state.distbits = opts.bits;
  17961. // state.distcode = state.next;
  17962. if (ret) {
  17963. strm.msg = 'invalid distances set';
  17964. state.mode = BAD;
  17965. break;
  17966. }
  17967. //Tracev((stderr, 'inflate: codes ok\n'));
  17968. state.mode = LEN_;
  17969. if (flush === Z_TREES) { break inf_leave; }
  17970. /* falls through */
  17971. case LEN_:
  17972. state.mode = LEN;
  17973. /* falls through */
  17974. case LEN:
  17975. if (have >= 6 && left >= 258) {
  17976. //--- RESTORE() ---
  17977. strm.next_out = put;
  17978. strm.avail_out = left;
  17979. strm.next_in = next;
  17980. strm.avail_in = have;
  17981. state.hold = hold;
  17982. state.bits = bits;
  17983. //---
  17984. inflate_fast(strm, _out);
  17985. //--- LOAD() ---
  17986. put = strm.next_out;
  17987. output = strm.output;
  17988. left = strm.avail_out;
  17989. next = strm.next_in;
  17990. input = strm.input;
  17991. have = strm.avail_in;
  17992. hold = state.hold;
  17993. bits = state.bits;
  17994. //---
  17995. if (state.mode === TYPE) {
  17996. state.back = -1;
  17997. }
  17998. break;
  17999. }
  18000. state.back = 0;
  18001. for (;;) {
  18002. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  18003. here_bits = here >>> 24;
  18004. here_op = (here >>> 16) & 0xff;
  18005. here_val = here & 0xffff;
  18006. if (here_bits <= bits) { break; }
  18007. //--- PULLBYTE() ---//
  18008. if (have === 0) { break inf_leave; }
  18009. have--;
  18010. hold += input[next++] << bits;
  18011. bits += 8;
  18012. //---//
  18013. }
  18014. if (here_op && (here_op & 0xf0) === 0) {
  18015. last_bits = here_bits;
  18016. last_op = here_op;
  18017. last_val = here_val;
  18018. for (;;) {
  18019. here = state.lencode[last_val +
  18020. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18021. here_bits = here >>> 24;
  18022. here_op = (here >>> 16) & 0xff;
  18023. here_val = here & 0xffff;
  18024. if ((last_bits + here_bits) <= bits) { break; }
  18025. //--- PULLBYTE() ---//
  18026. if (have === 0) { break inf_leave; }
  18027. have--;
  18028. hold += input[next++] << bits;
  18029. bits += 8;
  18030. //---//
  18031. }
  18032. //--- DROPBITS(last.bits) ---//
  18033. hold >>>= last_bits;
  18034. bits -= last_bits;
  18035. //---//
  18036. state.back += last_bits;
  18037. }
  18038. //--- DROPBITS(here.bits) ---//
  18039. hold >>>= here_bits;
  18040. bits -= here_bits;
  18041. //---//
  18042. state.back += here_bits;
  18043. state.length = here_val;
  18044. if (here_op === 0) {
  18045. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18046. // "inflate: literal '%c'\n" :
  18047. // "inflate: literal 0x%02x\n", here.val));
  18048. state.mode = LIT;
  18049. break;
  18050. }
  18051. if (here_op & 32) {
  18052. //Tracevv((stderr, "inflate: end of block\n"));
  18053. state.back = -1;
  18054. state.mode = TYPE;
  18055. break;
  18056. }
  18057. if (here_op & 64) {
  18058. strm.msg = 'invalid literal/length code';
  18059. state.mode = BAD;
  18060. break;
  18061. }
  18062. state.extra = here_op & 15;
  18063. state.mode = LENEXT;
  18064. /* falls through */
  18065. case LENEXT:
  18066. if (state.extra) {
  18067. //=== NEEDBITS(state.extra);
  18068. n = state.extra;
  18069. while (bits < n) {
  18070. if (have === 0) { break inf_leave; }
  18071. have--;
  18072. hold += input[next++] << bits;
  18073. bits += 8;
  18074. }
  18075. //===//
  18076. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18077. //--- DROPBITS(state.extra) ---//
  18078. hold >>>= state.extra;
  18079. bits -= state.extra;
  18080. //---//
  18081. state.back += state.extra;
  18082. }
  18083. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18084. state.was = state.length;
  18085. state.mode = DIST;
  18086. /* falls through */
  18087. case DIST:
  18088. for (;;) {
  18089. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  18090. here_bits = here >>> 24;
  18091. here_op = (here >>> 16) & 0xff;
  18092. here_val = here & 0xffff;
  18093. if ((here_bits) <= bits) { break; }
  18094. //--- PULLBYTE() ---//
  18095. if (have === 0) { break inf_leave; }
  18096. have--;
  18097. hold += input[next++] << bits;
  18098. bits += 8;
  18099. //---//
  18100. }
  18101. if ((here_op & 0xf0) === 0) {
  18102. last_bits = here_bits;
  18103. last_op = here_op;
  18104. last_val = here_val;
  18105. for (;;) {
  18106. here = state.distcode[last_val +
  18107. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18108. here_bits = here >>> 24;
  18109. here_op = (here >>> 16) & 0xff;
  18110. here_val = here & 0xffff;
  18111. if ((last_bits + here_bits) <= bits) { break; }
  18112. //--- PULLBYTE() ---//
  18113. if (have === 0) { break inf_leave; }
  18114. have--;
  18115. hold += input[next++] << bits;
  18116. bits += 8;
  18117. //---//
  18118. }
  18119. //--- DROPBITS(last.bits) ---//
  18120. hold >>>= last_bits;
  18121. bits -= last_bits;
  18122. //---//
  18123. state.back += last_bits;
  18124. }
  18125. //--- DROPBITS(here.bits) ---//
  18126. hold >>>= here_bits;
  18127. bits -= here_bits;
  18128. //---//
  18129. state.back += here_bits;
  18130. if (here_op & 64) {
  18131. strm.msg = 'invalid distance code';
  18132. state.mode = BAD;
  18133. break;
  18134. }
  18135. state.offset = here_val;
  18136. state.extra = (here_op) & 15;
  18137. state.mode = DISTEXT;
  18138. /* falls through */
  18139. case DISTEXT:
  18140. if (state.extra) {
  18141. //=== NEEDBITS(state.extra);
  18142. n = state.extra;
  18143. while (bits < n) {
  18144. if (have === 0) { break inf_leave; }
  18145. have--;
  18146. hold += input[next++] << bits;
  18147. bits += 8;
  18148. }
  18149. //===//
  18150. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18151. //--- DROPBITS(state.extra) ---//
  18152. hold >>>= state.extra;
  18153. bits -= state.extra;
  18154. //---//
  18155. state.back += state.extra;
  18156. }
  18157. //#ifdef INFLATE_STRICT
  18158. if (state.offset > state.dmax) {
  18159. strm.msg = 'invalid distance too far back';
  18160. state.mode = BAD;
  18161. break;
  18162. }
  18163. //#endif
  18164. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  18165. state.mode = MATCH;
  18166. /* falls through */
  18167. case MATCH:
  18168. if (left === 0) { break inf_leave; }
  18169. copy = _out - left;
  18170. if (state.offset > copy) { /* copy from window */
  18171. copy = state.offset - copy;
  18172. if (copy > state.whave) {
  18173. if (state.sane) {
  18174. strm.msg = 'invalid distance too far back';
  18175. state.mode = BAD;
  18176. break;
  18177. }
  18178. // (!) This block is disabled in zlib defailts,
  18179. // don't enable it for binary compatibility
  18180. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  18181. // Trace((stderr, "inflate.c too far\n"));
  18182. // copy -= state.whave;
  18183. // if (copy > state.length) { copy = state.length; }
  18184. // if (copy > left) { copy = left; }
  18185. // left -= copy;
  18186. // state.length -= copy;
  18187. // do {
  18188. // output[put++] = 0;
  18189. // } while (--copy);
  18190. // if (state.length === 0) { state.mode = LEN; }
  18191. // break;
  18192. //#endif
  18193. }
  18194. if (copy > state.wnext) {
  18195. copy -= state.wnext;
  18196. from = state.wsize - copy;
  18197. }
  18198. else {
  18199. from = state.wnext - copy;
  18200. }
  18201. if (copy > state.length) { copy = state.length; }
  18202. from_source = state.window;
  18203. }
  18204. else { /* copy from output */
  18205. from_source = output;
  18206. from = put - state.offset;
  18207. copy = state.length;
  18208. }
  18209. if (copy > left) { copy = left; }
  18210. left -= copy;
  18211. state.length -= copy;
  18212. do {
  18213. output[put++] = from_source[from++];
  18214. } while (--copy);
  18215. if (state.length === 0) { state.mode = LEN; }
  18216. break;
  18217. case LIT:
  18218. if (left === 0) { break inf_leave; }
  18219. output[put++] = state.length;
  18220. left--;
  18221. state.mode = LEN;
  18222. break;
  18223. case CHECK:
  18224. if (state.wrap) {
  18225. //=== NEEDBITS(32);
  18226. while (bits < 32) {
  18227. if (have === 0) { break inf_leave; }
  18228. have--;
  18229. // Use '|' insdead of '+' to make sure that result is signed
  18230. hold |= input[next++] << bits;
  18231. bits += 8;
  18232. }
  18233. //===//
  18234. _out -= left;
  18235. strm.total_out += _out;
  18236. state.total += _out;
  18237. if (_out) {
  18238. strm.adler = state.check =
  18239. /*UPDATE(state.check, put - _out, _out);*/
  18240. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  18241. }
  18242. _out = left;
  18243. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  18244. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  18245. strm.msg = 'incorrect data check';
  18246. state.mode = BAD;
  18247. break;
  18248. }
  18249. //=== INITBITS();
  18250. hold = 0;
  18251. bits = 0;
  18252. //===//
  18253. //Tracev((stderr, "inflate: check matches trailer\n"));
  18254. }
  18255. state.mode = LENGTH;
  18256. /* falls through */
  18257. case LENGTH:
  18258. if (state.wrap && state.flags) {
  18259. //=== NEEDBITS(32);
  18260. while (bits < 32) {
  18261. if (have === 0) { break inf_leave; }
  18262. have--;
  18263. hold += input[next++] << bits;
  18264. bits += 8;
  18265. }
  18266. //===//
  18267. if (hold !== (state.total & 0xffffffff)) {
  18268. strm.msg = 'incorrect length check';
  18269. state.mode = BAD;
  18270. break;
  18271. }
  18272. //=== INITBITS();
  18273. hold = 0;
  18274. bits = 0;
  18275. //===//
  18276. //Tracev((stderr, "inflate: length matches trailer\n"));
  18277. }
  18278. state.mode = DONE;
  18279. /* falls through */
  18280. case DONE:
  18281. ret = Z_STREAM_END;
  18282. break inf_leave;
  18283. case BAD:
  18284. ret = Z_DATA_ERROR;
  18285. break inf_leave;
  18286. case MEM:
  18287. return Z_MEM_ERROR;
  18288. case SYNC:
  18289. /* falls through */
  18290. default:
  18291. return Z_STREAM_ERROR;
  18292. }
  18293. }
  18294. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  18295. /*
  18296. Return from inflate(), updating the total counts and the check value.
  18297. If there was no progress during the inflate() call, return a buffer
  18298. error. Call updatewindow() to create and/or update the window state.
  18299. Note: a memory error from inflate() is non-recoverable.
  18300. */
  18301. //--- RESTORE() ---
  18302. strm.next_out = put;
  18303. strm.avail_out = left;
  18304. strm.next_in = next;
  18305. strm.avail_in = have;
  18306. state.hold = hold;
  18307. state.bits = bits;
  18308. //---
  18309. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  18310. (state.mode < CHECK || flush !== Z_FINISH))) {
  18311. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  18312. state.mode = MEM;
  18313. return Z_MEM_ERROR;
  18314. }
  18315. }
  18316. _in -= strm.avail_in;
  18317. _out -= strm.avail_out;
  18318. strm.total_in += _in;
  18319. strm.total_out += _out;
  18320. state.total += _out;
  18321. if (state.wrap && _out) {
  18322. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  18323. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  18324. }
  18325. strm.data_type = state.bits + (state.last ? 64 : 0) +
  18326. (state.mode === TYPE ? 128 : 0) +
  18327. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  18328. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  18329. ret = Z_BUF_ERROR;
  18330. }
  18331. return ret;
  18332. }
  18333. function inflateEnd(strm) {
  18334. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  18335. return Z_STREAM_ERROR;
  18336. }
  18337. var state = strm.state;
  18338. if (state.window) {
  18339. state.window = null;
  18340. }
  18341. strm.state = null;
  18342. return Z_OK;
  18343. }
  18344. function inflateGetHeader(strm, head) {
  18345. var state;
  18346. /* check state */
  18347. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18348. state = strm.state;
  18349. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  18350. /* save header structure */
  18351. state.head = head;
  18352. head.done = false;
  18353. return Z_OK;
  18354. }
  18355. exports.inflateReset = inflateReset;
  18356. exports.inflateReset2 = inflateReset2;
  18357. exports.inflateResetKeep = inflateResetKeep;
  18358. exports.inflateInit = inflateInit;
  18359. exports.inflateInit2 = inflateInit2;
  18360. exports.inflate = inflate;
  18361. exports.inflateEnd = inflateEnd;
  18362. exports.inflateGetHeader = inflateGetHeader;
  18363. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  18364. /* Not implemented
  18365. exports.inflateCopy = inflateCopy;
  18366. exports.inflateGetDictionary = inflateGetDictionary;
  18367. exports.inflateMark = inflateMark;
  18368. exports.inflatePrime = inflatePrime;
  18369. exports.inflateSetDictionary = inflateSetDictionary;
  18370. exports.inflateSync = inflateSync;
  18371. exports.inflateSyncPoint = inflateSyncPoint;
  18372. exports.inflateUndermine = inflateUndermine;
  18373. */
  18374. },{"../utils/common":63,"./adler32":65,"./crc32":67,"./inffast":70,"./inftrees":72}],72:[function(require,module,exports){
  18375. 'use strict';
  18376. var utils = require('../utils/common');
  18377. var MAXBITS = 15;
  18378. var ENOUGH_LENS = 852;
  18379. var ENOUGH_DISTS = 592;
  18380. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  18381. var CODES = 0;
  18382. var LENS = 1;
  18383. var DISTS = 2;
  18384. var lbase = [ /* Length codes 257..285 base */
  18385. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  18386. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  18387. ];
  18388. var lext = [ /* Length codes 257..285 extra */
  18389. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  18390. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  18391. ];
  18392. var dbase = [ /* Distance codes 0..29 base */
  18393. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  18394. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  18395. 8193, 12289, 16385, 24577, 0, 0
  18396. ];
  18397. var dext = [ /* Distance codes 0..29 extra */
  18398. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  18399. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  18400. 28, 28, 29, 29, 64, 64
  18401. ];
  18402. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  18403. {
  18404. var bits = opts.bits;
  18405. //here = opts.here; /* table entry for duplication */
  18406. var len = 0; /* a code's length in bits */
  18407. var sym = 0; /* index of code symbols */
  18408. var min = 0, max = 0; /* minimum and maximum code lengths */
  18409. var root = 0; /* number of index bits for root table */
  18410. var curr = 0; /* number of index bits for current table */
  18411. var drop = 0; /* code bits to drop for sub-table */
  18412. var left = 0; /* number of prefix codes available */
  18413. var used = 0; /* code entries in table used */
  18414. var huff = 0; /* Huffman code */
  18415. var incr; /* for incrementing code, index */
  18416. var fill; /* index for replicating entries */
  18417. var low; /* low bits for current root entry */
  18418. var mask; /* mask for low root bits */
  18419. var next; /* next available space in table */
  18420. var base = null; /* base value table to use */
  18421. var base_index = 0;
  18422. // var shoextra; /* extra bits table to use */
  18423. var end; /* use base and extra for symbol > end */
  18424. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  18425. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  18426. var extra = null;
  18427. var extra_index = 0;
  18428. var here_bits, here_op, here_val;
  18429. /*
  18430. Process a set of code lengths to create a canonical Huffman code. The
  18431. code lengths are lens[0..codes-1]. Each length corresponds to the
  18432. symbols 0..codes-1. The Huffman code is generated by first sorting the
  18433. symbols by length from short to long, and retaining the symbol order
  18434. for codes with equal lengths. Then the code starts with all zero bits
  18435. for the first code of the shortest length, and the codes are integer
  18436. increments for the same length, and zeros are appended as the length
  18437. increases. For the deflate format, these bits are stored backwards
  18438. from their more natural integer increment ordering, and so when the
  18439. decoding tables are built in the large loop below, the integer codes
  18440. are incremented backwards.
  18441. This routine assumes, but does not check, that all of the entries in
  18442. lens[] are in the range 0..MAXBITS. The caller must assure this.
  18443. 1..MAXBITS is interpreted as that code length. zero means that that
  18444. symbol does not occur in this code.
  18445. The codes are sorted by computing a count of codes for each length,
  18446. creating from that a table of starting indices for each length in the
  18447. sorted table, and then entering the symbols in order in the sorted
  18448. table. The sorted table is work[], with that space being provided by
  18449. the caller.
  18450. The length counts are used for other purposes as well, i.e. finding
  18451. the minimum and maximum length codes, determining if there are any
  18452. codes at all, checking for a valid set of lengths, and looking ahead
  18453. at length counts to determine sub-table sizes when building the
  18454. decoding tables.
  18455. */
  18456. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  18457. for (len = 0; len <= MAXBITS; len++) {
  18458. count[len] = 0;
  18459. }
  18460. for (sym = 0; sym < codes; sym++) {
  18461. count[lens[lens_index + sym]]++;
  18462. }
  18463. /* bound code lengths, force root to be within code lengths */
  18464. root = bits;
  18465. for (max = MAXBITS; max >= 1; max--) {
  18466. if (count[max] !== 0) { break; }
  18467. }
  18468. if (root > max) {
  18469. root = max;
  18470. }
  18471. if (max === 0) { /* no symbols to code at all */
  18472. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  18473. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  18474. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  18475. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18476. //table.op[opts.table_index] = 64;
  18477. //table.bits[opts.table_index] = 1;
  18478. //table.val[opts.table_index++] = 0;
  18479. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18480. opts.bits = 1;
  18481. return 0; /* no symbols, but wait for decoding to report error */
  18482. }
  18483. for (min = 1; min < max; min++) {
  18484. if (count[min] !== 0) { break; }
  18485. }
  18486. if (root < min) {
  18487. root = min;
  18488. }
  18489. /* check for an over-subscribed or incomplete set of lengths */
  18490. left = 1;
  18491. for (len = 1; len <= MAXBITS; len++) {
  18492. left <<= 1;
  18493. left -= count[len];
  18494. if (left < 0) {
  18495. return -1;
  18496. } /* over-subscribed */
  18497. }
  18498. if (left > 0 && (type === CODES || max !== 1)) {
  18499. return -1; /* incomplete set */
  18500. }
  18501. /* generate offsets into symbol table for each length for sorting */
  18502. offs[1] = 0;
  18503. for (len = 1; len < MAXBITS; len++) {
  18504. offs[len + 1] = offs[len] + count[len];
  18505. }
  18506. /* sort symbols by length, by symbol order within each length */
  18507. for (sym = 0; sym < codes; sym++) {
  18508. if (lens[lens_index + sym] !== 0) {
  18509. work[offs[lens[lens_index + sym]]++] = sym;
  18510. }
  18511. }
  18512. /*
  18513. Create and fill in decoding tables. In this loop, the table being
  18514. filled is at next and has curr index bits. The code being used is huff
  18515. with length len. That code is converted to an index by dropping drop
  18516. bits off of the bottom. For codes where len is less than drop + curr,
  18517. those top drop + curr - len bits are incremented through all values to
  18518. fill the table with replicated entries.
  18519. root is the number of index bits for the root table. When len exceeds
  18520. root, sub-tables are created pointed to by the root entry with an index
  18521. of the low root bits of huff. This is saved in low to check for when a
  18522. new sub-table should be started. drop is zero when the root table is
  18523. being filled, and drop is root when sub-tables are being filled.
  18524. When a new sub-table is needed, it is necessary to look ahead in the
  18525. code lengths to determine what size sub-table is needed. The length
  18526. counts are used for this, and so count[] is decremented as codes are
  18527. entered in the tables.
  18528. used keeps track of how many table entries have been allocated from the
  18529. provided *table space. It is checked for LENS and DIST tables against
  18530. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  18531. the initial root table size constants. See the comments in inftrees.h
  18532. for more information.
  18533. sym increments through all symbols, and the loop terminates when
  18534. all codes of length max, i.e. all codes, have been processed. This
  18535. routine permits incomplete codes, so another loop after this one fills
  18536. in the rest of the decoding tables with invalid code markers.
  18537. */
  18538. /* set up for code type */
  18539. // poor man optimization - use if-else instead of switch,
  18540. // to avoid deopts in old v8
  18541. if (type === CODES) {
  18542. base = extra = work; /* dummy value--not used */
  18543. end = 19;
  18544. } else if (type === LENS) {
  18545. base = lbase;
  18546. base_index -= 257;
  18547. extra = lext;
  18548. extra_index -= 257;
  18549. end = 256;
  18550. } else { /* DISTS */
  18551. base = dbase;
  18552. extra = dext;
  18553. end = -1;
  18554. }
  18555. /* initialize opts for loop */
  18556. huff = 0; /* starting code */
  18557. sym = 0; /* starting code symbol */
  18558. len = min; /* starting code length */
  18559. next = table_index; /* current table to fill in */
  18560. curr = root; /* current table index bits */
  18561. drop = 0; /* current bits to drop from code for index */
  18562. low = -1; /* trigger new sub-table when len > root */
  18563. used = 1 << root; /* use root table entries */
  18564. mask = used - 1; /* mask for comparing low */
  18565. /* check available table space */
  18566. if ((type === LENS && used > ENOUGH_LENS) ||
  18567. (type === DISTS && used > ENOUGH_DISTS)) {
  18568. return 1;
  18569. }
  18570. var i=0;
  18571. /* process all codes and make table entries */
  18572. for (;;) {
  18573. i++;
  18574. /* create table entry */
  18575. here_bits = len - drop;
  18576. if (work[sym] < end) {
  18577. here_op = 0;
  18578. here_val = work[sym];
  18579. }
  18580. else if (work[sym] > end) {
  18581. here_op = extra[extra_index + work[sym]];
  18582. here_val = base[base_index + work[sym]];
  18583. }
  18584. else {
  18585. here_op = 32 + 64; /* end of block */
  18586. here_val = 0;
  18587. }
  18588. /* replicate for those indices with low len bits equal to huff */
  18589. incr = 1 << (len - drop);
  18590. fill = 1 << curr;
  18591. min = fill; /* save offset to next table */
  18592. do {
  18593. fill -= incr;
  18594. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  18595. } while (fill !== 0);
  18596. /* backwards increment the len-bit code huff */
  18597. incr = 1 << (len - 1);
  18598. while (huff & incr) {
  18599. incr >>= 1;
  18600. }
  18601. if (incr !== 0) {
  18602. huff &= incr - 1;
  18603. huff += incr;
  18604. } else {
  18605. huff = 0;
  18606. }
  18607. /* go to next symbol, update count, len */
  18608. sym++;
  18609. if (--count[len] === 0) {
  18610. if (len === max) { break; }
  18611. len = lens[lens_index + work[sym]];
  18612. }
  18613. /* create new sub-table if needed */
  18614. if (len > root && (huff & mask) !== low) {
  18615. /* if first time, transition to sub-tables */
  18616. if (drop === 0) {
  18617. drop = root;
  18618. }
  18619. /* increment past last table */
  18620. next += min; /* here min is 1 << curr */
  18621. /* determine length of next table */
  18622. curr = len - drop;
  18623. left = 1 << curr;
  18624. while (curr + drop < max) {
  18625. left -= count[curr + drop];
  18626. if (left <= 0) { break; }
  18627. curr++;
  18628. left <<= 1;
  18629. }
  18630. /* check for enough space */
  18631. used += 1 << curr;
  18632. if ((type === LENS && used > ENOUGH_LENS) ||
  18633. (type === DISTS && used > ENOUGH_DISTS)) {
  18634. return 1;
  18635. }
  18636. /* point entry in root table to sub-table */
  18637. low = huff & mask;
  18638. /*table.op[low] = curr;
  18639. table.bits[low] = root;
  18640. table.val[low] = next - opts.table_index;*/
  18641. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  18642. }
  18643. }
  18644. /* fill in remaining table entry if code is incomplete (guaranteed to have
  18645. at most one remaining entry, since if the code is incomplete, the
  18646. maximum code length that was allowed to get this far is one bit) */
  18647. if (huff !== 0) {
  18648. //table.op[next + huff] = 64; /* invalid code marker */
  18649. //table.bits[next + huff] = len - drop;
  18650. //table.val[next + huff] = 0;
  18651. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  18652. }
  18653. /* set return parameters */
  18654. //opts.table_index += used;
  18655. opts.bits = root;
  18656. return 0;
  18657. };
  18658. },{"../utils/common":63}],73:[function(require,module,exports){
  18659. 'use strict';
  18660. module.exports = {
  18661. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  18662. '1': 'stream end', /* Z_STREAM_END 1 */
  18663. '0': '', /* Z_OK 0 */
  18664. '-1': 'file error', /* Z_ERRNO (-1) */
  18665. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  18666. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  18667. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  18668. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  18669. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  18670. };
  18671. },{}],74:[function(require,module,exports){
  18672. 'use strict';
  18673. var utils = require('../utils/common');
  18674. /* Public constants ==========================================================*/
  18675. /* ===========================================================================*/
  18676. //var Z_FILTERED = 1;
  18677. //var Z_HUFFMAN_ONLY = 2;
  18678. //var Z_RLE = 3;
  18679. var Z_FIXED = 4;
  18680. //var Z_DEFAULT_STRATEGY = 0;
  18681. /* Possible values of the data_type field (though see inflate()) */
  18682. var Z_BINARY = 0;
  18683. var Z_TEXT = 1;
  18684. //var Z_ASCII = 1; // = Z_TEXT
  18685. var Z_UNKNOWN = 2;
  18686. /*============================================================================*/
  18687. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18688. // From zutil.h
  18689. var STORED_BLOCK = 0;
  18690. var STATIC_TREES = 1;
  18691. var DYN_TREES = 2;
  18692. /* The three kinds of block type */
  18693. var MIN_MATCH = 3;
  18694. var MAX_MATCH = 258;
  18695. /* The minimum and maximum match lengths */
  18696. // From deflate.h
  18697. /* ===========================================================================
  18698. * Internal compression state.
  18699. */
  18700. var LENGTH_CODES = 29;
  18701. /* number of length codes, not counting the special END_BLOCK code */
  18702. var LITERALS = 256;
  18703. /* number of literal bytes 0..255 */
  18704. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18705. /* number of Literal or Length codes, including the END_BLOCK code */
  18706. var D_CODES = 30;
  18707. /* number of distance codes */
  18708. var BL_CODES = 19;
  18709. /* number of codes used to transfer the bit lengths */
  18710. var HEAP_SIZE = 2*L_CODES + 1;
  18711. /* maximum heap size */
  18712. var MAX_BITS = 15;
  18713. /* All codes must not exceed MAX_BITS bits */
  18714. var Buf_size = 16;
  18715. /* size of bit buffer in bi_buf */
  18716. /* ===========================================================================
  18717. * Constants
  18718. */
  18719. var MAX_BL_BITS = 7;
  18720. /* Bit length codes must not exceed MAX_BL_BITS bits */
  18721. var END_BLOCK = 256;
  18722. /* end of block literal code */
  18723. var REP_3_6 = 16;
  18724. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  18725. var REPZ_3_10 = 17;
  18726. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  18727. var REPZ_11_138 = 18;
  18728. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  18729. var extra_lbits = /* extra bits for each length code */
  18730. [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];
  18731. var extra_dbits = /* extra bits for each distance code */
  18732. [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];
  18733. var extra_blbits = /* extra bits for each bit length code */
  18734. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  18735. var bl_order =
  18736. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  18737. /* The lengths of the bit length codes are sent in order of decreasing
  18738. * probability, to avoid transmitting the lengths for unused bit length codes.
  18739. */
  18740. /* ===========================================================================
  18741. * Local data. These are initialized only once.
  18742. */
  18743. // We pre-fill arrays with 0 to avoid uninitialized gaps
  18744. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  18745. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  18746. var static_ltree = new Array((L_CODES+2) * 2);
  18747. zero(static_ltree);
  18748. /* The static literal tree. Since the bit lengths are imposed, there is no
  18749. * need for the L_CODES extra codes used during heap construction. However
  18750. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  18751. * below).
  18752. */
  18753. var static_dtree = new Array(D_CODES * 2);
  18754. zero(static_dtree);
  18755. /* The static distance tree. (Actually a trivial tree since all codes use
  18756. * 5 bits.)
  18757. */
  18758. var _dist_code = new Array(DIST_CODE_LEN);
  18759. zero(_dist_code);
  18760. /* Distance codes. The first 256 values correspond to the distances
  18761. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  18762. * the 15 bit distances.
  18763. */
  18764. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  18765. zero(_length_code);
  18766. /* length code for each normalized match length (0 == MIN_MATCH) */
  18767. var base_length = new Array(LENGTH_CODES);
  18768. zero(base_length);
  18769. /* First normalized length for each code (0 = MIN_MATCH) */
  18770. var base_dist = new Array(D_CODES);
  18771. zero(base_dist);
  18772. /* First normalized distance for each code (0 = distance of 1) */
  18773. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  18774. this.static_tree = static_tree; /* static tree or NULL */
  18775. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  18776. this.extra_base = extra_base; /* base index for extra_bits */
  18777. this.elems = elems; /* max number of elements in the tree */
  18778. this.max_length = max_length; /* max bit length for the codes */
  18779. // show if `static_tree` has data or dummy - needed for monomorphic objects
  18780. this.has_stree = static_tree && static_tree.length;
  18781. };
  18782. var static_l_desc;
  18783. var static_d_desc;
  18784. var static_bl_desc;
  18785. var TreeDesc = function(dyn_tree, stat_desc) {
  18786. this.dyn_tree = dyn_tree; /* the dynamic tree */
  18787. this.max_code = 0; /* largest code with non zero frequency */
  18788. this.stat_desc = stat_desc; /* the corresponding static tree */
  18789. };
  18790. function d_code(dist) {
  18791. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  18792. }
  18793. /* ===========================================================================
  18794. * Output a short LSB first on the stream.
  18795. * IN assertion: there is enough room in pendingBuf.
  18796. */
  18797. function put_short (s, w) {
  18798. // put_byte(s, (uch)((w) & 0xff));
  18799. // put_byte(s, (uch)((ush)(w) >> 8));
  18800. s.pending_buf[s.pending++] = (w) & 0xff;
  18801. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  18802. }
  18803. /* ===========================================================================
  18804. * Send a value on a given number of bits.
  18805. * IN assertion: length <= 16 and value fits in length bits.
  18806. */
  18807. function send_bits(s, value, length) {
  18808. if (s.bi_valid > (Buf_size - length)) {
  18809. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18810. put_short(s, s.bi_buf);
  18811. s.bi_buf = value >> (Buf_size - s.bi_valid);
  18812. s.bi_valid += length - Buf_size;
  18813. } else {
  18814. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18815. s.bi_valid += length;
  18816. }
  18817. }
  18818. function send_code(s, c, tree) {
  18819. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  18820. }
  18821. /* ===========================================================================
  18822. * Reverse the first len bits of a code, using straightforward code (a faster
  18823. * method would use a table)
  18824. * IN assertion: 1 <= len <= 15
  18825. */
  18826. function bi_reverse(code, len) {
  18827. var res = 0;
  18828. do {
  18829. res |= code & 1;
  18830. code >>>= 1;
  18831. res <<= 1;
  18832. } while (--len > 0);
  18833. return res >>> 1;
  18834. }
  18835. /* ===========================================================================
  18836. * Flush the bit buffer, keeping at most 7 bits in it.
  18837. */
  18838. function bi_flush(s) {
  18839. if (s.bi_valid === 16) {
  18840. put_short(s, s.bi_buf);
  18841. s.bi_buf = 0;
  18842. s.bi_valid = 0;
  18843. } else if (s.bi_valid >= 8) {
  18844. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  18845. s.bi_buf >>= 8;
  18846. s.bi_valid -= 8;
  18847. }
  18848. }
  18849. /* ===========================================================================
  18850. * Compute the optimal bit lengths for a tree and update the total bit length
  18851. * for the current block.
  18852. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  18853. * above are the tree nodes sorted by increasing frequency.
  18854. * OUT assertions: the field len is set to the optimal bit length, the
  18855. * array bl_count contains the frequencies for each bit length.
  18856. * The length opt_len is updated; static_len is also updated if stree is
  18857. * not null.
  18858. */
  18859. function gen_bitlen(s, desc)
  18860. // deflate_state *s;
  18861. // tree_desc *desc; /* the tree descriptor */
  18862. {
  18863. var tree = desc.dyn_tree;
  18864. var max_code = desc.max_code;
  18865. var stree = desc.stat_desc.static_tree;
  18866. var has_stree = desc.stat_desc.has_stree;
  18867. var extra = desc.stat_desc.extra_bits;
  18868. var base = desc.stat_desc.extra_base;
  18869. var max_length = desc.stat_desc.max_length;
  18870. var h; /* heap index */
  18871. var n, m; /* iterate over the tree elements */
  18872. var bits; /* bit length */
  18873. var xbits; /* extra bits */
  18874. var f; /* frequency */
  18875. var overflow = 0; /* number of elements with bit length too large */
  18876. for (bits = 0; bits <= MAX_BITS; bits++) {
  18877. s.bl_count[bits] = 0;
  18878. }
  18879. /* In a first pass, compute the optimal bit lengths (which may
  18880. * overflow in the case of the bit length tree).
  18881. */
  18882. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  18883. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  18884. n = s.heap[h];
  18885. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  18886. if (bits > max_length) {
  18887. bits = max_length;
  18888. overflow++;
  18889. }
  18890. tree[n*2 + 1]/*.Len*/ = bits;
  18891. /* We overwrite tree[n].Dad which is no longer needed */
  18892. if (n > max_code) { continue; } /* not a leaf node */
  18893. s.bl_count[bits]++;
  18894. xbits = 0;
  18895. if (n >= base) {
  18896. xbits = extra[n-base];
  18897. }
  18898. f = tree[n * 2]/*.Freq*/;
  18899. s.opt_len += f * (bits + xbits);
  18900. if (has_stree) {
  18901. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  18902. }
  18903. }
  18904. if (overflow === 0) { return; }
  18905. // Trace((stderr,"\nbit length overflow\n"));
  18906. /* This happens for example on obj2 and pic of the Calgary corpus */
  18907. /* Find the first bit length which could increase: */
  18908. do {
  18909. bits = max_length-1;
  18910. while (s.bl_count[bits] === 0) { bits--; }
  18911. s.bl_count[bits]--; /* move one leaf down the tree */
  18912. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  18913. s.bl_count[max_length]--;
  18914. /* The brother of the overflow item also moves one step up,
  18915. * but this does not affect bl_count[max_length]
  18916. */
  18917. overflow -= 2;
  18918. } while (overflow > 0);
  18919. /* Now recompute all bit lengths, scanning in increasing frequency.
  18920. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  18921. * lengths instead of fixing only the wrong ones. This idea is taken
  18922. * from 'ar' written by Haruhiko Okumura.)
  18923. */
  18924. for (bits = max_length; bits !== 0; bits--) {
  18925. n = s.bl_count[bits];
  18926. while (n !== 0) {
  18927. m = s.heap[--h];
  18928. if (m > max_code) { continue; }
  18929. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  18930. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  18931. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  18932. tree[m*2 + 1]/*.Len*/ = bits;
  18933. }
  18934. n--;
  18935. }
  18936. }
  18937. }
  18938. /* ===========================================================================
  18939. * Generate the codes for a given tree and bit counts (which need not be
  18940. * optimal).
  18941. * IN assertion: the array bl_count contains the bit length statistics for
  18942. * the given tree and the field len is set for all tree elements.
  18943. * OUT assertion: the field code is set for all tree elements of non
  18944. * zero code length.
  18945. */
  18946. function gen_codes(tree, max_code, bl_count)
  18947. // ct_data *tree; /* the tree to decorate */
  18948. // int max_code; /* largest code with non zero frequency */
  18949. // ushf *bl_count; /* number of codes at each bit length */
  18950. {
  18951. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  18952. var code = 0; /* running code value */
  18953. var bits; /* bit index */
  18954. var n; /* code index */
  18955. /* The distribution counts are first used to generate the code values
  18956. * without bit reversal.
  18957. */
  18958. for (bits = 1; bits <= MAX_BITS; bits++) {
  18959. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  18960. }
  18961. /* Check that the bit counts in bl_count are consistent. The last code
  18962. * must be all ones.
  18963. */
  18964. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  18965. // "inconsistent bit counts");
  18966. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  18967. for (n = 0; n <= max_code; n++) {
  18968. var len = tree[n*2 + 1]/*.Len*/;
  18969. if (len === 0) { continue; }
  18970. /* Now reverse the bits */
  18971. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  18972. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  18973. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  18974. }
  18975. }
  18976. /* ===========================================================================
  18977. * Initialize the various 'constant' tables.
  18978. */
  18979. function tr_static_init() {
  18980. var n; /* iterates over tree elements */
  18981. var bits; /* bit counter */
  18982. var length; /* length value */
  18983. var code; /* code value */
  18984. var dist; /* distance index */
  18985. var bl_count = new Array(MAX_BITS+1);
  18986. /* number of codes at each bit length for an optimal tree */
  18987. // do check in _tr_init()
  18988. //if (static_init_done) return;
  18989. /* For some embedded targets, global variables are not initialized: */
  18990. /*#ifdef NO_INIT_GLOBAL_POINTERS
  18991. static_l_desc.static_tree = static_ltree;
  18992. static_l_desc.extra_bits = extra_lbits;
  18993. static_d_desc.static_tree = static_dtree;
  18994. static_d_desc.extra_bits = extra_dbits;
  18995. static_bl_desc.extra_bits = extra_blbits;
  18996. #endif*/
  18997. /* Initialize the mapping length (0..255) -> length code (0..28) */
  18998. length = 0;
  18999. for (code = 0; code < LENGTH_CODES-1; code++) {
  19000. base_length[code] = length;
  19001. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  19002. _length_code[length++] = code;
  19003. }
  19004. }
  19005. //Assert (length == 256, "tr_static_init: length != 256");
  19006. /* Note that the length 255 (match length 258) can be represented
  19007. * in two different ways: code 284 + 5 bits or code 285, so we
  19008. * overwrite length_code[255] to use the best encoding:
  19009. */
  19010. _length_code[length-1] = code;
  19011. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19012. dist = 0;
  19013. for (code = 0 ; code < 16; code++) {
  19014. base_dist[code] = dist;
  19015. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  19016. _dist_code[dist++] = code;
  19017. }
  19018. }
  19019. //Assert (dist == 256, "tr_static_init: dist != 256");
  19020. dist >>= 7; /* from now on, all distances are divided by 128 */
  19021. for ( ; code < D_CODES; code++) {
  19022. base_dist[code] = dist << 7;
  19023. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  19024. _dist_code[256 + dist++] = code;
  19025. }
  19026. }
  19027. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19028. /* Construct the codes of the static literal tree */
  19029. for (bits = 0; bits <= MAX_BITS; bits++) {
  19030. bl_count[bits] = 0;
  19031. }
  19032. n = 0;
  19033. while (n <= 143) {
  19034. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19035. n++;
  19036. bl_count[8]++;
  19037. }
  19038. while (n <= 255) {
  19039. static_ltree[n*2 + 1]/*.Len*/ = 9;
  19040. n++;
  19041. bl_count[9]++;
  19042. }
  19043. while (n <= 279) {
  19044. static_ltree[n*2 + 1]/*.Len*/ = 7;
  19045. n++;
  19046. bl_count[7]++;
  19047. }
  19048. while (n <= 287) {
  19049. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19050. n++;
  19051. bl_count[8]++;
  19052. }
  19053. /* Codes 286 and 287 do not exist, but we must include them in the
  19054. * tree construction to get a canonical Huffman tree (longest code
  19055. * all ones)
  19056. */
  19057. gen_codes(static_ltree, L_CODES+1, bl_count);
  19058. /* The static distance tree is trivial: */
  19059. for (n = 0; n < D_CODES; n++) {
  19060. static_dtree[n*2 + 1]/*.Len*/ = 5;
  19061. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  19062. }
  19063. // Now data ready and we can init static trees
  19064. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  19065. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19066. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19067. //static_init_done = true;
  19068. }
  19069. /* ===========================================================================
  19070. * Initialize a new block.
  19071. */
  19072. function init_block(s) {
  19073. var n; /* iterates over tree elements */
  19074. /* Initialize the trees. */
  19075. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  19076. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  19077. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  19078. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  19079. s.opt_len = s.static_len = 0;
  19080. s.last_lit = s.matches = 0;
  19081. }
  19082. /* ===========================================================================
  19083. * Flush the bit buffer and align the output on a byte boundary
  19084. */
  19085. function bi_windup(s)
  19086. {
  19087. if (s.bi_valid > 8) {
  19088. put_short(s, s.bi_buf);
  19089. } else if (s.bi_valid > 0) {
  19090. //put_byte(s, (Byte)s->bi_buf);
  19091. s.pending_buf[s.pending++] = s.bi_buf;
  19092. }
  19093. s.bi_buf = 0;
  19094. s.bi_valid = 0;
  19095. }
  19096. /* ===========================================================================
  19097. * Copy a stored block, storing first the length and its
  19098. * one's complement if requested.
  19099. */
  19100. function copy_block(s, buf, len, header)
  19101. //DeflateState *s;
  19102. //charf *buf; /* the input data */
  19103. //unsigned len; /* its length */
  19104. //int header; /* true if block header must be written */
  19105. {
  19106. bi_windup(s); /* align on byte boundary */
  19107. if (header) {
  19108. put_short(s, len);
  19109. put_short(s, ~len);
  19110. }
  19111. // while (len--) {
  19112. // put_byte(s, *buf++);
  19113. // }
  19114. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  19115. s.pending += len;
  19116. }
  19117. /* ===========================================================================
  19118. * Compares to subtrees, using the tree depth as tie breaker when
  19119. * the subtrees have equal frequency. This minimizes the worst case length.
  19120. */
  19121. function smaller(tree, n, m, depth) {
  19122. var _n2 = n*2;
  19123. var _m2 = m*2;
  19124. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  19125. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  19126. }
  19127. /* ===========================================================================
  19128. * Restore the heap property by moving down the tree starting at node k,
  19129. * exchanging a node with the smallest of its two sons if necessary, stopping
  19130. * when the heap property is re-established (each father smaller than its
  19131. * two sons).
  19132. */
  19133. function pqdownheap(s, tree, k)
  19134. // deflate_state *s;
  19135. // ct_data *tree; /* the tree to restore */
  19136. // int k; /* node to move down */
  19137. {
  19138. var v = s.heap[k];
  19139. var j = k << 1; /* left son of k */
  19140. while (j <= s.heap_len) {
  19141. /* Set j to the smallest of the two sons: */
  19142. if (j < s.heap_len &&
  19143. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  19144. j++;
  19145. }
  19146. /* Exit if v is smaller than both sons */
  19147. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  19148. /* Exchange v with the smallest son */
  19149. s.heap[k] = s.heap[j];
  19150. k = j;
  19151. /* And continue down the tree, setting j to the left son of k */
  19152. j <<= 1;
  19153. }
  19154. s.heap[k] = v;
  19155. }
  19156. // inlined manually
  19157. // var SMALLEST = 1;
  19158. /* ===========================================================================
  19159. * Send the block data compressed using the given Huffman trees
  19160. */
  19161. function compress_block(s, ltree, dtree)
  19162. // deflate_state *s;
  19163. // const ct_data *ltree; /* literal tree */
  19164. // const ct_data *dtree; /* distance tree */
  19165. {
  19166. var dist; /* distance of matched string */
  19167. var lc; /* match length or unmatched char (if dist == 0) */
  19168. var lx = 0; /* running index in l_buf */
  19169. var code; /* the code to send */
  19170. var extra; /* number of extra bits to send */
  19171. if (s.last_lit !== 0) {
  19172. do {
  19173. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  19174. lc = s.pending_buf[s.l_buf + lx];
  19175. lx++;
  19176. if (dist === 0) {
  19177. send_code(s, lc, ltree); /* send a literal byte */
  19178. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  19179. } else {
  19180. /* Here, lc is the match length - MIN_MATCH */
  19181. code = _length_code[lc];
  19182. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  19183. extra = extra_lbits[code];
  19184. if (extra !== 0) {
  19185. lc -= base_length[code];
  19186. send_bits(s, lc, extra); /* send the extra length bits */
  19187. }
  19188. dist--; /* dist is now the match distance - 1 */
  19189. code = d_code(dist);
  19190. //Assert (code < D_CODES, "bad d_code");
  19191. send_code(s, code, dtree); /* send the distance code */
  19192. extra = extra_dbits[code];
  19193. if (extra !== 0) {
  19194. dist -= base_dist[code];
  19195. send_bits(s, dist, extra); /* send the extra distance bits */
  19196. }
  19197. } /* literal or match pair ? */
  19198. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  19199. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  19200. // "pendingBuf overflow");
  19201. } while (lx < s.last_lit);
  19202. }
  19203. send_code(s, END_BLOCK, ltree);
  19204. }
  19205. /* ===========================================================================
  19206. * Construct one Huffman tree and assigns the code bit strings and lengths.
  19207. * Update the total bit length for the current block.
  19208. * IN assertion: the field freq is set for all tree elements.
  19209. * OUT assertions: the fields len and code are set to the optimal bit length
  19210. * and corresponding code. The length opt_len is updated; static_len is
  19211. * also updated if stree is not null. The field max_code is set.
  19212. */
  19213. function build_tree(s, desc)
  19214. // deflate_state *s;
  19215. // tree_desc *desc; /* the tree descriptor */
  19216. {
  19217. var tree = desc.dyn_tree;
  19218. var stree = desc.stat_desc.static_tree;
  19219. var has_stree = desc.stat_desc.has_stree;
  19220. var elems = desc.stat_desc.elems;
  19221. var n, m; /* iterate over heap elements */
  19222. var max_code = -1; /* largest code with non zero frequency */
  19223. var node; /* new node being created */
  19224. /* Construct the initial heap, with least frequent element in
  19225. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  19226. * heap[0] is not used.
  19227. */
  19228. s.heap_len = 0;
  19229. s.heap_max = HEAP_SIZE;
  19230. for (n = 0; n < elems; n++) {
  19231. if (tree[n * 2]/*.Freq*/ !== 0) {
  19232. s.heap[++s.heap_len] = max_code = n;
  19233. s.depth[n] = 0;
  19234. } else {
  19235. tree[n*2 + 1]/*.Len*/ = 0;
  19236. }
  19237. }
  19238. /* The pkzip format requires that at least one distance code exists,
  19239. * and that at least one bit should be sent even if there is only one
  19240. * possible code. So to avoid special checks later on we force at least
  19241. * two codes of non zero frequency.
  19242. */
  19243. while (s.heap_len < 2) {
  19244. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  19245. tree[node * 2]/*.Freq*/ = 1;
  19246. s.depth[node] = 0;
  19247. s.opt_len--;
  19248. if (has_stree) {
  19249. s.static_len -= stree[node*2 + 1]/*.Len*/;
  19250. }
  19251. /* node is 0 or 1 so it does not have extra bits */
  19252. }
  19253. desc.max_code = max_code;
  19254. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  19255. * establish sub-heaps of increasing lengths:
  19256. */
  19257. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  19258. /* Construct the Huffman tree by repeatedly combining the least two
  19259. * frequent nodes.
  19260. */
  19261. node = elems; /* next internal node of the tree */
  19262. do {
  19263. //pqremove(s, tree, n); /* n = node of least frequency */
  19264. /*** pqremove ***/
  19265. n = s.heap[1/*SMALLEST*/];
  19266. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  19267. pqdownheap(s, tree, 1/*SMALLEST*/);
  19268. /***/
  19269. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  19270. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  19271. s.heap[--s.heap_max] = m;
  19272. /* Create a new node father of n and m */
  19273. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  19274. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  19275. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  19276. /* and insert the new node in the heap */
  19277. s.heap[1/*SMALLEST*/] = node++;
  19278. pqdownheap(s, tree, 1/*SMALLEST*/);
  19279. } while (s.heap_len >= 2);
  19280. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  19281. /* At this point, the fields freq and dad are set. We can now
  19282. * generate the bit lengths.
  19283. */
  19284. gen_bitlen(s, desc);
  19285. /* The field len is now set, we can generate the bit codes */
  19286. gen_codes(tree, max_code, s.bl_count);
  19287. }
  19288. /* ===========================================================================
  19289. * Scan a literal or distance tree to determine the frequencies of the codes
  19290. * in the bit length tree.
  19291. */
  19292. function scan_tree(s, tree, max_code)
  19293. // deflate_state *s;
  19294. // ct_data *tree; /* the tree to be scanned */
  19295. // int max_code; /* and its largest code of non zero frequency */
  19296. {
  19297. var n; /* iterates over all tree elements */
  19298. var prevlen = -1; /* last emitted length */
  19299. var curlen; /* length of current code */
  19300. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19301. var count = 0; /* repeat count of the current code */
  19302. var max_count = 7; /* max repeat count */
  19303. var min_count = 4; /* min repeat count */
  19304. if (nextlen === 0) {
  19305. max_count = 138;
  19306. min_count = 3;
  19307. }
  19308. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  19309. for (n = 0; n <= max_code; n++) {
  19310. curlen = nextlen;
  19311. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19312. if (++count < max_count && curlen === nextlen) {
  19313. continue;
  19314. } else if (count < min_count) {
  19315. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  19316. } else if (curlen !== 0) {
  19317. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  19318. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  19319. } else if (count <= 10) {
  19320. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  19321. } else {
  19322. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  19323. }
  19324. count = 0;
  19325. prevlen = curlen;
  19326. if (nextlen === 0) {
  19327. max_count = 138;
  19328. min_count = 3;
  19329. } else if (curlen === nextlen) {
  19330. max_count = 6;
  19331. min_count = 3;
  19332. } else {
  19333. max_count = 7;
  19334. min_count = 4;
  19335. }
  19336. }
  19337. }
  19338. /* ===========================================================================
  19339. * Send a literal or distance tree in compressed form, using the codes in
  19340. * bl_tree.
  19341. */
  19342. function send_tree(s, tree, max_code)
  19343. // deflate_state *s;
  19344. // ct_data *tree; /* the tree to be scanned */
  19345. // int max_code; /* and its largest code of non zero frequency */
  19346. {
  19347. var n; /* iterates over all tree elements */
  19348. var prevlen = -1; /* last emitted length */
  19349. var curlen; /* length of current code */
  19350. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19351. var count = 0; /* repeat count of the current code */
  19352. var max_count = 7; /* max repeat count */
  19353. var min_count = 4; /* min repeat count */
  19354. /* tree[max_code+1].Len = -1; */ /* guard already set */
  19355. if (nextlen === 0) {
  19356. max_count = 138;
  19357. min_count = 3;
  19358. }
  19359. for (n = 0; n <= max_code; n++) {
  19360. curlen = nextlen;
  19361. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19362. if (++count < max_count && curlen === nextlen) {
  19363. continue;
  19364. } else if (count < min_count) {
  19365. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  19366. } else if (curlen !== 0) {
  19367. if (curlen !== prevlen) {
  19368. send_code(s, curlen, s.bl_tree);
  19369. count--;
  19370. }
  19371. //Assert(count >= 3 && count <= 6, " 3_6?");
  19372. send_code(s, REP_3_6, s.bl_tree);
  19373. send_bits(s, count-3, 2);
  19374. } else if (count <= 10) {
  19375. send_code(s, REPZ_3_10, s.bl_tree);
  19376. send_bits(s, count-3, 3);
  19377. } else {
  19378. send_code(s, REPZ_11_138, s.bl_tree);
  19379. send_bits(s, count-11, 7);
  19380. }
  19381. count = 0;
  19382. prevlen = curlen;
  19383. if (nextlen === 0) {
  19384. max_count = 138;
  19385. min_count = 3;
  19386. } else if (curlen === nextlen) {
  19387. max_count = 6;
  19388. min_count = 3;
  19389. } else {
  19390. max_count = 7;
  19391. min_count = 4;
  19392. }
  19393. }
  19394. }
  19395. /* ===========================================================================
  19396. * Construct the Huffman tree for the bit lengths and return the index in
  19397. * bl_order of the last bit length code to send.
  19398. */
  19399. function build_bl_tree(s) {
  19400. var max_blindex; /* index of last bit length code of non zero freq */
  19401. /* Determine the bit length frequencies for literal and distance trees */
  19402. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  19403. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  19404. /* Build the bit length tree: */
  19405. build_tree(s, s.bl_desc);
  19406. /* opt_len now includes the length of the tree representations, except
  19407. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  19408. */
  19409. /* Determine the number of bit length codes to send. The pkzip format
  19410. * requires that at least 4 bit length codes be sent. (appnote.txt says
  19411. * 3 but the actual value used is 4.)
  19412. */
  19413. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  19414. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  19415. break;
  19416. }
  19417. }
  19418. /* Update opt_len to include the bit length tree and counts */
  19419. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  19420. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  19421. // s->opt_len, s->static_len));
  19422. return max_blindex;
  19423. }
  19424. /* ===========================================================================
  19425. * Send the header for a block using dynamic Huffman trees: the counts, the
  19426. * lengths of the bit length codes, the literal tree and the distance tree.
  19427. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  19428. */
  19429. function send_all_trees(s, lcodes, dcodes, blcodes)
  19430. // deflate_state *s;
  19431. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  19432. {
  19433. var rank; /* index in bl_order */
  19434. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  19435. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  19436. // "too many codes");
  19437. //Tracev((stderr, "\nbl counts: "));
  19438. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  19439. send_bits(s, dcodes-1, 5);
  19440. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  19441. for (rank = 0; rank < blcodes; rank++) {
  19442. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  19443. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  19444. }
  19445. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  19446. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  19447. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  19448. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  19449. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  19450. }
  19451. /* ===========================================================================
  19452. * Check if the data type is TEXT or BINARY, using the following algorithm:
  19453. * - TEXT if the two conditions below are satisfied:
  19454. * a) There are no non-portable control characters belonging to the
  19455. * "black list" (0..6, 14..25, 28..31).
  19456. * b) There is at least one printable character belonging to the
  19457. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  19458. * - BINARY otherwise.
  19459. * - The following partially-portable control characters form a
  19460. * "gray list" that is ignored in this detection algorithm:
  19461. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  19462. * IN assertion: the fields Freq of dyn_ltree are set.
  19463. */
  19464. function detect_data_type(s) {
  19465. /* black_mask is the bit mask of black-listed bytes
  19466. * set bits 0..6, 14..25, and 28..31
  19467. * 0xf3ffc07f = binary 11110011111111111100000001111111
  19468. */
  19469. var black_mask = 0xf3ffc07f;
  19470. var n;
  19471. /* Check for non-textual ("black-listed") bytes. */
  19472. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  19473. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  19474. return Z_BINARY;
  19475. }
  19476. }
  19477. /* Check for textual ("white-listed") bytes. */
  19478. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  19479. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  19480. return Z_TEXT;
  19481. }
  19482. for (n = 32; n < LITERALS; n++) {
  19483. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  19484. return Z_TEXT;
  19485. }
  19486. }
  19487. /* There are no "black-listed" or "white-listed" bytes:
  19488. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  19489. */
  19490. return Z_BINARY;
  19491. }
  19492. var static_init_done = false;
  19493. /* ===========================================================================
  19494. * Initialize the tree data structures for a new zlib stream.
  19495. */
  19496. function _tr_init(s)
  19497. {
  19498. if (!static_init_done) {
  19499. tr_static_init();
  19500. static_init_done = true;
  19501. }
  19502. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19503. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19504. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19505. s.bi_buf = 0;
  19506. s.bi_valid = 0;
  19507. /* Initialize the first block of the first file: */
  19508. init_block(s);
  19509. }
  19510. /* ===========================================================================
  19511. * Send a stored block
  19512. */
  19513. function _tr_stored_block(s, buf, stored_len, last)
  19514. //DeflateState *s;
  19515. //charf *buf; /* input block */
  19516. //ulg stored_len; /* length of input block */
  19517. //int last; /* one if this is the last block for a file */
  19518. {
  19519. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19520. copy_block(s, buf, stored_len, true); /* with header */
  19521. }
  19522. /* ===========================================================================
  19523. * Send one empty static block to give enough lookahead for inflate.
  19524. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19525. */
  19526. function _tr_align(s) {
  19527. send_bits(s, STATIC_TREES<<1, 3);
  19528. send_code(s, END_BLOCK, static_ltree);
  19529. bi_flush(s);
  19530. }
  19531. /* ===========================================================================
  19532. * Determine the best encoding for the current block: dynamic trees, static
  19533. * trees or store, and output the encoded block to the zip file.
  19534. */
  19535. function _tr_flush_block(s, buf, stored_len, last)
  19536. //DeflateState *s;
  19537. //charf *buf; /* input block, or NULL if too old */
  19538. //ulg stored_len; /* length of input block */
  19539. //int last; /* one if this is the last block for a file */
  19540. {
  19541. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  19542. var max_blindex = 0; /* index of last bit length code of non zero freq */
  19543. /* Build the Huffman trees unless a stored block is forced */
  19544. if (s.level > 0) {
  19545. /* Check if the file is binary or text */
  19546. if (s.strm.data_type === Z_UNKNOWN) {
  19547. s.strm.data_type = detect_data_type(s);
  19548. }
  19549. /* Construct the literal and distance trees */
  19550. build_tree(s, s.l_desc);
  19551. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  19552. // s->static_len));
  19553. build_tree(s, s.d_desc);
  19554. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  19555. // s->static_len));
  19556. /* At this point, opt_len and static_len are the total bit lengths of
  19557. * the compressed block data, excluding the tree representations.
  19558. */
  19559. /* Build the bit length tree for the above two trees, and get the index
  19560. * in bl_order of the last bit length code to send.
  19561. */
  19562. max_blindex = build_bl_tree(s);
  19563. /* Determine the best encoding. Compute the block lengths in bytes. */
  19564. opt_lenb = (s.opt_len+3+7) >>> 3;
  19565. static_lenb = (s.static_len+3+7) >>> 3;
  19566. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  19567. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  19568. // s->last_lit));
  19569. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  19570. } else {
  19571. // Assert(buf != (char*)0, "lost buf");
  19572. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  19573. }
  19574. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  19575. /* 4: two words for the lengths */
  19576. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  19577. * Otherwise we can't have processed more than WSIZE input bytes since
  19578. * the last block flush, because compression would have been
  19579. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  19580. * transform a block into a stored block.
  19581. */
  19582. _tr_stored_block(s, buf, stored_len, last);
  19583. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  19584. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  19585. compress_block(s, static_ltree, static_dtree);
  19586. } else {
  19587. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  19588. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  19589. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  19590. }
  19591. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  19592. /* The above check is made mod 2^32, for files larger than 512 MB
  19593. * and uLong implemented on 32 bits.
  19594. */
  19595. init_block(s);
  19596. if (last) {
  19597. bi_windup(s);
  19598. }
  19599. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  19600. // s->compressed_len-7*last));
  19601. }
  19602. /* ===========================================================================
  19603. * Save the match info and tally the frequency counts. Return true if
  19604. * the current block must be flushed.
  19605. */
  19606. function _tr_tally(s, dist, lc)
  19607. // deflate_state *s;
  19608. // unsigned dist; /* distance of matched string */
  19609. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  19610. {
  19611. //var out_length, in_length, dcode;
  19612. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  19613. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  19614. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  19615. s.last_lit++;
  19616. if (dist === 0) {
  19617. /* lc is the unmatched char */
  19618. s.dyn_ltree[lc*2]/*.Freq*/++;
  19619. } else {
  19620. s.matches++;
  19621. /* Here, lc is the match length - MIN_MATCH */
  19622. dist--; /* dist = match distance - 1 */
  19623. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  19624. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  19625. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  19626. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  19627. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  19628. }
  19629. // (!) This block is disabled in zlib defailts,
  19630. // don't enable it for binary compatibility
  19631. //#ifdef TRUNCATE_BLOCK
  19632. // /* Try to guess if it is profitable to stop the current block here */
  19633. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  19634. // /* Compute an upper bound for the compressed length */
  19635. // out_length = s.last_lit*8;
  19636. // in_length = s.strstart - s.block_start;
  19637. //
  19638. // for (dcode = 0; dcode < D_CODES; dcode++) {
  19639. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  19640. // }
  19641. // out_length >>>= 3;
  19642. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  19643. // // s->last_lit, in_length, out_length,
  19644. // // 100L - out_length*100L/in_length));
  19645. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  19646. // return true;
  19647. // }
  19648. // }
  19649. //#endif
  19650. return (s.last_lit === s.lit_bufsize-1);
  19651. /* We avoid equality with lit_bufsize because of wraparound at 64K
  19652. * on 16 bit machines and because stored blocks are restricted to
  19653. * 64K-1 bytes.
  19654. */
  19655. }
  19656. exports._tr_init = _tr_init;
  19657. exports._tr_stored_block = _tr_stored_block;
  19658. exports._tr_flush_block = _tr_flush_block;
  19659. exports._tr_tally = _tr_tally;
  19660. exports._tr_align = _tr_align;
  19661. },{"../utils/common":63}],75:[function(require,module,exports){
  19662. 'use strict';
  19663. function ZStream() {
  19664. /* next input byte */
  19665. this.input = null; // JS specific, because we have no pointers
  19666. this.next_in = 0;
  19667. /* number of bytes available at input */
  19668. this.avail_in = 0;
  19669. /* total number of input bytes read so far */
  19670. this.total_in = 0;
  19671. /* next output byte should be put there */
  19672. this.output = null; // JS specific, because we have no pointers
  19673. this.next_out = 0;
  19674. /* remaining free space at output */
  19675. this.avail_out = 0;
  19676. /* total number of bytes output so far */
  19677. this.total_out = 0;
  19678. /* last error message, NULL if no error */
  19679. this.msg = ''/*Z_NULL*/;
  19680. /* not visible by applications */
  19681. this.state = null;
  19682. /* best guess about the data type: binary or text */
  19683. this.data_type = 2/*Z_UNKNOWN*/;
  19684. /* adler32 value of the uncompressed data */
  19685. this.adler = 0;
  19686. }
  19687. module.exports = ZStream;
  19688. },{}],76:[function(require,module,exports){
  19689. var MediaStreamType = {
  19690. VIDEO_TYPE: "Video",
  19691. AUDIO_TYPE: "Audio"
  19692. };
  19693. module.exports = MediaStreamType;
  19694. },{}],77:[function(require,module,exports){
  19695. var RTCBrowserType = {
  19696. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  19697. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  19698. };
  19699. module.exports = RTCBrowserType;
  19700. },{}],78:[function(require,module,exports){
  19701. var RTCEvents = {
  19702. LASTN_CHANGED: "rtc.lastn_changed",
  19703. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  19704. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  19705. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  19706. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  19707. SIMULCAST_START: "rtc.simlcast_start",
  19708. SIMULCAST_STOP: "rtc.simlcast_stop"
  19709. };
  19710. module.exports = RTCEvents;
  19711. },{}],79:[function(require,module,exports){
  19712. var StreamEventTypes = {
  19713. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  19714. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  19715. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  19716. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  19717. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  19718. };
  19719. module.exports = StreamEventTypes;
  19720. },{}],80:[function(require,module,exports){
  19721. var UIEvents = {
  19722. NICKNAME_CHANGED: "UI.nickname_changed",
  19723. SELECTED_ENDPOINT: "UI.selected_endpoint",
  19724. PINNED_ENDPOINT: "UI.pinned_endpoint"
  19725. };
  19726. module.exports = UIEvents;
  19727. },{}],81:[function(require,module,exports){
  19728. var CQEvents = {
  19729. LOCALSTATS_UPDATED: "cq.localstats_updated",
  19730. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  19731. STOP: "cq.stop"
  19732. };
  19733. module.exports = CQEvents;
  19734. },{}],82:[function(require,module,exports){
  19735. var DesktopSharingEventTypes = {
  19736. INIT: "ds.init",
  19737. SWITCHING_DONE: "ds.switching_done",
  19738. NEW_STREAM_CREATED: "ds.new_stream_created"
  19739. };
  19740. module.exports = DesktopSharingEventTypes;
  19741. },{}],83:[function(require,module,exports){
  19742. var XMPPEvents = {
  19743. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  19744. CALL_TERMINATED: "xmpp.callterminated.jingle",
  19745. CALL_INCOMING: "xmpp.callincoming.jingle",
  19746. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  19747. KICKED: "xmpp.kicked",
  19748. BRIDGE_DOWN: "xmpp.bridge_down",
  19749. USER_ID_CHANGED: "xmpp.user_id_changed",
  19750. CHANGED_STREAMS: "xmpp.changed_streams",
  19751. MUC_JOINED: "xmpp.muc_joined",
  19752. MUC_ENTER: "xmpp.muc_enter",
  19753. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  19754. MUC_LEFT: "xmpp.muc_left",
  19755. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  19756. REMOTE_STATS: "xmpp.remote_stats",
  19757. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  19758. PRESENCE_STATUS: "xmpp.presence_status",
  19759. SUBJECT_CHANGED: "xmpp.subject_changed",
  19760. MESSAGE_RECEIVED: "xmpp.message_received",
  19761. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  19762. PASSWORD_REQUIRED: "xmpp.password_required",
  19763. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  19764. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  19765. ETHERPAD: "xmpp.etherpad"
  19766. };
  19767. module.exports = XMPPEvents;
  19768. },{}],84:[function(require,module,exports){
  19769. // Copyright Joyent, Inc. and other Node contributors.
  19770. //
  19771. // Permission is hereby granted, free of charge, to any person obtaining a
  19772. // copy of this software and associated documentation files (the
  19773. // "Software"), to deal in the Software without restriction, including
  19774. // without limitation the rights to use, copy, modify, merge, publish,
  19775. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19776. // persons to whom the Software is furnished to do so, subject to the
  19777. // following conditions:
  19778. //
  19779. // The above copyright notice and this permission notice shall be included
  19780. // in all copies or substantial portions of the Software.
  19781. //
  19782. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19783. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19784. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19785. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19786. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19787. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19788. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19789. function EventEmitter() {
  19790. this._events = this._events || {};
  19791. this._maxListeners = this._maxListeners || undefined;
  19792. }
  19793. module.exports = EventEmitter;
  19794. // Backwards-compat with node 0.10.x
  19795. EventEmitter.EventEmitter = EventEmitter;
  19796. EventEmitter.prototype._events = undefined;
  19797. EventEmitter.prototype._maxListeners = undefined;
  19798. // By default EventEmitters will print a warning if more than 10 listeners are
  19799. // added to it. This is a useful default which helps finding memory leaks.
  19800. EventEmitter.defaultMaxListeners = 10;
  19801. // Obviously not all Emitters should be limited to 10. This function allows
  19802. // that to be increased. Set to zero for unlimited.
  19803. EventEmitter.prototype.setMaxListeners = function(n) {
  19804. if (!isNumber(n) || n < 0 || isNaN(n))
  19805. throw TypeError('n must be a positive number');
  19806. this._maxListeners = n;
  19807. return this;
  19808. };
  19809. EventEmitter.prototype.emit = function(type) {
  19810. var er, handler, len, args, i, listeners;
  19811. if (!this._events)
  19812. this._events = {};
  19813. // If there is no 'error' event listener then throw.
  19814. if (type === 'error') {
  19815. if (!this._events.error ||
  19816. (isObject(this._events.error) && !this._events.error.length)) {
  19817. er = arguments[1];
  19818. if (er instanceof Error) {
  19819. throw er; // Unhandled 'error' event
  19820. }
  19821. throw TypeError('Uncaught, unspecified "error" event.');
  19822. }
  19823. }
  19824. handler = this._events[type];
  19825. if (isUndefined(handler))
  19826. return false;
  19827. if (isFunction(handler)) {
  19828. switch (arguments.length) {
  19829. // fast cases
  19830. case 1:
  19831. handler.call(this);
  19832. break;
  19833. case 2:
  19834. handler.call(this, arguments[1]);
  19835. break;
  19836. case 3:
  19837. handler.call(this, arguments[1], arguments[2]);
  19838. break;
  19839. // slower
  19840. default:
  19841. len = arguments.length;
  19842. args = new Array(len - 1);
  19843. for (i = 1; i < len; i++)
  19844. args[i - 1] = arguments[i];
  19845. handler.apply(this, args);
  19846. }
  19847. } else if (isObject(handler)) {
  19848. len = arguments.length;
  19849. args = new Array(len - 1);
  19850. for (i = 1; i < len; i++)
  19851. args[i - 1] = arguments[i];
  19852. listeners = handler.slice();
  19853. len = listeners.length;
  19854. for (i = 0; i < len; i++)
  19855. listeners[i].apply(this, args);
  19856. }
  19857. return true;
  19858. };
  19859. EventEmitter.prototype.addListener = function(type, listener) {
  19860. var m;
  19861. if (!isFunction(listener))
  19862. throw TypeError('listener must be a function');
  19863. if (!this._events)
  19864. this._events = {};
  19865. // To avoid recursion in the case that type === "newListener"! Before
  19866. // adding it to the listeners, first emit "newListener".
  19867. if (this._events.newListener)
  19868. this.emit('newListener', type,
  19869. isFunction(listener.listener) ?
  19870. listener.listener : listener);
  19871. if (!this._events[type])
  19872. // Optimize the case of one listener. Don't need the extra array object.
  19873. this._events[type] = listener;
  19874. else if (isObject(this._events[type]))
  19875. // If we've already got an array, just append.
  19876. this._events[type].push(listener);
  19877. else
  19878. // Adding the second element, need to change to array.
  19879. this._events[type] = [this._events[type], listener];
  19880. // Check for listener leak
  19881. if (isObject(this._events[type]) && !this._events[type].warned) {
  19882. var m;
  19883. if (!isUndefined(this._maxListeners)) {
  19884. m = this._maxListeners;
  19885. } else {
  19886. m = EventEmitter.defaultMaxListeners;
  19887. }
  19888. if (m && m > 0 && this._events[type].length > m) {
  19889. this._events[type].warned = true;
  19890. console.error('(node) warning: possible EventEmitter memory ' +
  19891. 'leak detected. %d listeners added. ' +
  19892. 'Use emitter.setMaxListeners() to increase limit.',
  19893. this._events[type].length);
  19894. if (typeof console.trace === 'function') {
  19895. // not supported in IE 10
  19896. console.trace();
  19897. }
  19898. }
  19899. }
  19900. return this;
  19901. };
  19902. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  19903. EventEmitter.prototype.once = function(type, listener) {
  19904. if (!isFunction(listener))
  19905. throw TypeError('listener must be a function');
  19906. var fired = false;
  19907. function g() {
  19908. this.removeListener(type, g);
  19909. if (!fired) {
  19910. fired = true;
  19911. listener.apply(this, arguments);
  19912. }
  19913. }
  19914. g.listener = listener;
  19915. this.on(type, g);
  19916. return this;
  19917. };
  19918. // emits a 'removeListener' event iff the listener was removed
  19919. EventEmitter.prototype.removeListener = function(type, listener) {
  19920. var list, position, length, i;
  19921. if (!isFunction(listener))
  19922. throw TypeError('listener must be a function');
  19923. if (!this._events || !this._events[type])
  19924. return this;
  19925. list = this._events[type];
  19926. length = list.length;
  19927. position = -1;
  19928. if (list === listener ||
  19929. (isFunction(list.listener) && list.listener === listener)) {
  19930. delete this._events[type];
  19931. if (this._events.removeListener)
  19932. this.emit('removeListener', type, listener);
  19933. } else if (isObject(list)) {
  19934. for (i = length; i-- > 0;) {
  19935. if (list[i] === listener ||
  19936. (list[i].listener && list[i].listener === listener)) {
  19937. position = i;
  19938. break;
  19939. }
  19940. }
  19941. if (position < 0)
  19942. return this;
  19943. if (list.length === 1) {
  19944. list.length = 0;
  19945. delete this._events[type];
  19946. } else {
  19947. list.splice(position, 1);
  19948. }
  19949. if (this._events.removeListener)
  19950. this.emit('removeListener', type, listener);
  19951. }
  19952. return this;
  19953. };
  19954. EventEmitter.prototype.removeAllListeners = function(type) {
  19955. var key, listeners;
  19956. if (!this._events)
  19957. return this;
  19958. // not listening for removeListener, no need to emit
  19959. if (!this._events.removeListener) {
  19960. if (arguments.length === 0)
  19961. this._events = {};
  19962. else if (this._events[type])
  19963. delete this._events[type];
  19964. return this;
  19965. }
  19966. // emit removeListener for all listeners on all events
  19967. if (arguments.length === 0) {
  19968. for (key in this._events) {
  19969. if (key === 'removeListener') continue;
  19970. this.removeAllListeners(key);
  19971. }
  19972. this.removeAllListeners('removeListener');
  19973. this._events = {};
  19974. return this;
  19975. }
  19976. listeners = this._events[type];
  19977. if (isFunction(listeners)) {
  19978. this.removeListener(type, listeners);
  19979. } else {
  19980. // LIFO order
  19981. while (listeners.length)
  19982. this.removeListener(type, listeners[listeners.length - 1]);
  19983. }
  19984. delete this._events[type];
  19985. return this;
  19986. };
  19987. EventEmitter.prototype.listeners = function(type) {
  19988. var ret;
  19989. if (!this._events || !this._events[type])
  19990. ret = [];
  19991. else if (isFunction(this._events[type]))
  19992. ret = [this._events[type]];
  19993. else
  19994. ret = this._events[type].slice();
  19995. return ret;
  19996. };
  19997. EventEmitter.listenerCount = function(emitter, type) {
  19998. var ret;
  19999. if (!emitter._events || !emitter._events[type])
  20000. ret = 0;
  20001. else if (isFunction(emitter._events[type]))
  20002. ret = 1;
  20003. else
  20004. ret = emitter._events[type].length;
  20005. return ret;
  20006. };
  20007. function isFunction(arg) {
  20008. return typeof arg === 'function';
  20009. }
  20010. function isNumber(arg) {
  20011. return typeof arg === 'number';
  20012. }
  20013. function isObject(arg) {
  20014. return typeof arg === 'object' && arg !== null;
  20015. }
  20016. function isUndefined(arg) {
  20017. return arg === void 0;
  20018. }
  20019. },{}]},{},[1])(1)
  20020. });