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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* 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. this.translation = require("./modules/translation/translation");
  17. this.settings = require("./modules/settings/Settings");
  18. }
  19. };
  20. function init() {
  21. APP.RTC.start();
  22. APP.xmpp.start();
  23. APP.statistics.start();
  24. APP.connectionquality.init();
  25. // Set default desktop sharing method
  26. APP.desktopsharing.init();
  27. APP.keyboardshortcut.init();
  28. }
  29. $(document).ready(function () {
  30. APP.init();
  31. APP.translation.init();
  32. if(APP.API.isEnabled())
  33. APP.API.init();
  34. APP.UI.start(init);
  35. });
  36. $(window).bind('beforeunload', function () {
  37. if(APP.API.isEnabled())
  38. APP.API.dispose();
  39. });
  40. module.exports = APP;
  41. },{"./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/settings/Settings":38,"./modules/simulcast/simulcast":43,"./modules/statistics/statistics":46,"./modules/translation/translation":47,"./modules/xmpp/xmpp":61}],2:[function(require,module,exports){
  42. /**
  43. * Implements API class that communicates with external api class
  44. * and provides interface to access Jitsi Meet features by external
  45. * applications that embed Jitsi Meet
  46. */
  47. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  48. /**
  49. * List of the available commands.
  50. * @type {{
  51. * displayName: inputDisplayNameHandler,
  52. * muteAudio: toggleAudio,
  53. * muteVideo: toggleVideo,
  54. * filmStrip: toggleFilmStrip
  55. * }}
  56. */
  57. var commands =
  58. {
  59. displayName: APP.UI.inputDisplayNameHandler,
  60. muteAudio: APP.UI.toggleAudio,
  61. muteVideo: APP.UI.toggleVideo,
  62. toggleFilmStrip: APP.UI.toggleFilmStrip,
  63. toggleChat: APP.UI.toggleChat,
  64. toggleContactList: APP.UI.toggleContactList
  65. };
  66. /**
  67. * Maps the supported events and their status
  68. * (true it the event is enabled and false if it is disabled)
  69. * @type {{
  70. * incomingMessage: boolean,
  71. * outgoingMessage: boolean,
  72. * displayNameChange: boolean,
  73. * participantJoined: boolean,
  74. * participantLeft: boolean
  75. * }}
  76. */
  77. var events =
  78. {
  79. incomingMessage: false,
  80. outgoingMessage:false,
  81. displayNameChange: false,
  82. participantJoined: false,
  83. participantLeft: false
  84. };
  85. var displayName = {};
  86. /**
  87. * Processes commands from external applicaiton.
  88. * @param message the object with the command
  89. */
  90. function processCommand(message)
  91. {
  92. if(message.action != "execute")
  93. {
  94. console.error("Unknown action of the message");
  95. return;
  96. }
  97. for(var key in message)
  98. {
  99. if(commands[key])
  100. commands[key].apply(null, message[key]);
  101. }
  102. }
  103. /**
  104. * Processes events objects from external applications
  105. * @param event the event
  106. */
  107. function processEvent(event) {
  108. if(!event.action)
  109. {
  110. console.error("Event with no action is received.");
  111. return;
  112. }
  113. var i = 0;
  114. switch(event.action)
  115. {
  116. case "add":
  117. for(; i < event.events.length; i++)
  118. {
  119. events[event.events[i]] = true;
  120. }
  121. break;
  122. case "remove":
  123. for(; i < event.events.length; i++)
  124. {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event)
  144. {
  145. var message;
  146. try {
  147. message = JSON.parse(event.data);
  148. } catch (e) {}
  149. if(!message.type)
  150. return;
  151. switch (message.type)
  152. {
  153. case "command":
  154. processCommand(message);
  155. break;
  156. case "event":
  157. processEvent(message);
  158. break;
  159. default:
  160. console.error("Unknown type of the message");
  161. return;
  162. }
  163. }
  164. function setupListeners() {
  165. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  166. API.triggerEvent("participantJoined", {jid: from});
  167. });
  168. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  169. if (from != myjid)
  170. API.triggerEvent("incomingMessage",
  171. {"from": from, "nick": nick, "message": txt});
  172. });
  173. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  174. API.triggerEvent("participantLeft", {jid: jid});
  175. });
  176. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  177. name = displayName[jid];
  178. if(!name || name != newDisplayName) {
  179. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  180. displayName[jid] = newDisplayName;
  181. }
  182. });
  183. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  184. APP.API.triggerEvent("outgoingMessage", {"message": body});
  185. });
  186. }
  187. var API = {
  188. /**
  189. * Check whether the API should be enabled or not.
  190. * @returns {boolean}
  191. */
  192. isEnabled: function () {
  193. var hash = location.hash;
  194. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  195. return true;
  196. return false;
  197. },
  198. /**
  199. * Initializes the APIConnector. Setups message event listeners that will
  200. * receive information from external applications that embed Jitsi Meet.
  201. * It also sends a message to the external application that APIConnector
  202. * is initialized.
  203. */
  204. init: function () {
  205. if (window.addEventListener)
  206. {
  207. window.addEventListener('message',
  208. processMessage, false);
  209. }
  210. else
  211. {
  212. window.attachEvent('onmessage', processMessage);
  213. }
  214. sendMessage({type: "system", loaded: true});
  215. setupListeners();
  216. },
  217. /**
  218. * Checks whether the event is enabled ot not.
  219. * @param name the name of the event.
  220. * @returns {*}
  221. */
  222. isEventEnabled: function (name) {
  223. return events[name];
  224. },
  225. /**
  226. * Sends event object to the external application that has been subscribed
  227. * for that event.
  228. * @param name the name event
  229. * @param object data associated with the event
  230. */
  231. triggerEvent: function (name, object) {
  232. if(this.isEnabled() && this.isEventEnabled(name))
  233. sendMessage({
  234. type: "event", action: "result", event: name, result: object});
  235. },
  236. /**
  237. * Removes the listeners.
  238. */
  239. dispose: function () {
  240. if(window.removeEventListener)
  241. {
  242. window.removeEventListener("message",
  243. processMessage, false);
  244. }
  245. else
  246. {
  247. window.detachEvent('onmessage', processMessage);
  248. }
  249. }
  250. };
  251. module.exports = API;
  252. },{"../../service/xmpp/XMPPEvents":98}],3:[function(require,module,exports){
  253. /* global Strophe, focusedVideoSrc*/
  254. // cache datachannels to avoid garbage collection
  255. // https://code.google.com/p/chromium/issues/detail?id=405545
  256. var RTCEvents = require("../../service/RTC/RTCEvents");
  257. var _dataChannels = [];
  258. var eventEmitter = null;
  259. var DataChannels =
  260. {
  261. /**
  262. * Callback triggered by PeerConnection when new data channel is opened
  263. * on the bridge.
  264. * @param event the event info object.
  265. */
  266. onDataChannel: function (event)
  267. {
  268. var dataChannel = event.channel;
  269. dataChannel.onopen = function () {
  270. console.info("Data channel opened by the Videobridge!", dataChannel);
  271. // Code sample for sending string and/or binary data
  272. // Sends String message to the bridge
  273. //dataChannel.send("Hello bridge!");
  274. // Sends 12 bytes binary message to the bridge
  275. //dataChannel.send(new ArrayBuffer(12));
  276. // when the data channel becomes available, tell the bridge about video
  277. // selections so that it can do adaptive simulcast,
  278. // we want the notification to trigger even if userJid is undefined,
  279. // or null.
  280. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  281. // we want the notification to trigger even if userJid is undefined,
  282. // or null.
  283. onSelectedEndpointChanged(userJid);
  284. };
  285. dataChannel.onerror = function (error) {
  286. console.error("Data Channel Error:", error, dataChannel);
  287. };
  288. dataChannel.onmessage = function (event) {
  289. var data = event.data;
  290. // JSON
  291. var obj;
  292. try {
  293. obj = JSON.parse(data);
  294. }
  295. catch (e) {
  296. console.error(
  297. "Failed to parse data channel message as JSON: ",
  298. data,
  299. dataChannel);
  300. }
  301. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  302. var colibriClass = obj.colibriClass;
  303. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  304. // Endpoint ID from the Videobridge.
  305. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  306. console.info(
  307. "Data channel new dominant speaker event: ",
  308. dominantSpeakerEndpoint);
  309. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  310. }
  311. else if ("InLastNChangeEvent" === colibriClass)
  312. {
  313. var oldValue = obj.oldValue;
  314. var newValue = obj.newValue;
  315. // Make sure that oldValue and newValue are of type boolean.
  316. var type;
  317. if ((type = typeof oldValue) !== 'boolean') {
  318. if (type === 'string') {
  319. oldValue = (oldValue == "true");
  320. } else {
  321. oldValue = new Boolean(oldValue).valueOf();
  322. }
  323. }
  324. if ((type = typeof newValue) !== 'boolean') {
  325. if (type === 'string') {
  326. newValue = (newValue == "true");
  327. } else {
  328. newValue = new Boolean(newValue).valueOf();
  329. }
  330. }
  331. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  332. }
  333. else if ("LastNEndpointsChangeEvent" === colibriClass)
  334. {
  335. // The new/latest list of last-n endpoint IDs.
  336. var lastNEndpoints = obj.lastNEndpoints;
  337. // The list of endpoint IDs which are entering the list of
  338. // last-n at this time i.e. were not in the old list of last-n
  339. // endpoint IDs.
  340. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  341. var stream = obj.stream;
  342. console.log(
  343. "Data channel new last-n event: ",
  344. lastNEndpoints, endpointsEnteringLastN, obj);
  345. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  346. lastNEndpoints, endpointsEnteringLastN, obj);
  347. }
  348. else if ("SimulcastLayersChangedEvent" === colibriClass)
  349. {
  350. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  351. obj.endpointSimulcastLayers);
  352. }
  353. else if ("SimulcastLayersChangingEvent" === colibriClass)
  354. {
  355. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  356. obj.endpointSimulcastLayers);
  357. }
  358. else if ("StartSimulcastLayerEvent" === colibriClass)
  359. {
  360. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  361. }
  362. else if ("StopSimulcastLayerEvent" === colibriClass)
  363. {
  364. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  365. }
  366. else
  367. {
  368. console.debug("Data channel JSON-formatted message: ", obj);
  369. }
  370. }
  371. };
  372. dataChannel.onclose = function ()
  373. {
  374. console.info("The Data Channel closed", dataChannel);
  375. var idx = _dataChannels.indexOf(dataChannel);
  376. if (idx > -1)
  377. _dataChannels = _dataChannels.splice(idx, 1);
  378. };
  379. _dataChannels.push(dataChannel);
  380. },
  381. /**
  382. * Binds "ondatachannel" event listener to given PeerConnection instance.
  383. * @param peerConnection WebRTC peer connection instance.
  384. */
  385. init: function (peerConnection, emitter) {
  386. if(!config.openSctp)
  387. return;
  388. peerConnection.ondatachannel = this.onDataChannel;
  389. eventEmitter = emitter;
  390. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  391. // Although it's not a requirement to open separate channels from both bridge
  392. // and peer as single channel can be used for sending and receiving data.
  393. // So either channel opened by the bridge or the one opened here is enough
  394. // for communication with the bridge.
  395. /*var dataChannelOptions =
  396. {
  397. reliable: true
  398. };
  399. var dataChannel
  400. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  401. // Can be used only when is in open state
  402. dataChannel.onopen = function ()
  403. {
  404. dataChannel.send("My channel !!!");
  405. };
  406. dataChannel.onmessage = function (event)
  407. {
  408. var msgData = event.data;
  409. console.info("Got My Data Channel Message:", msgData, dataChannel);
  410. };*/
  411. },
  412. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  413. handlePinnedEndpointEvent: onPinnedEndpointChanged
  414. };
  415. function onSelectedEndpointChanged(userResource)
  416. {
  417. console.log('selected endpoint changed: ', userResource);
  418. if (_dataChannels && _dataChannels.length != 0)
  419. {
  420. _dataChannels.some(function (dataChannel) {
  421. if (dataChannel.readyState == 'open')
  422. {
  423. console.log('sending selected endpoint changed '
  424. + 'notification to the bridge: ', userResource);
  425. dataChannel.send(JSON.stringify({
  426. 'colibriClass': 'SelectedEndpointChangedEvent',
  427. 'selectedEndpoint':
  428. (!userResource || userResource === null)?
  429. null : userResource
  430. }));
  431. return true;
  432. }
  433. });
  434. }
  435. }
  436. function onPinnedEndpointChanged(userResource)
  437. {
  438. console.log('pinned endpoint changed: ', userResource);
  439. if (_dataChannels && _dataChannels.length != 0)
  440. {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open')
  443. {
  444. dataChannel.send(JSON.stringify({
  445. 'colibriClass': 'PinnedEndpointChangedEvent',
  446. 'pinnedEndpoint':
  447. (!userResource || userResource == null)?
  448. null : userResource
  449. }));
  450. return true;
  451. }
  452. });
  453. }
  454. }
  455. module.exports = DataChannels;
  456. },{"../../service/RTC/RTCEvents":90}],4:[function(require,module,exports){
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. function LocalStream(stream, type, eventEmitter, videoType)
  459. {
  460. this.stream = stream;
  461. this.eventEmitter = eventEmitter;
  462. this.type = type;
  463. this.videoType = videoType;
  464. var self = this;
  465. if(type == "audio")
  466. {
  467. this.getTracks = function () {
  468. return self.stream.getAudioTracks();
  469. };
  470. }
  471. else
  472. {
  473. this.getTracks = function () {
  474. return self.stream.getVideoTracks();
  475. };
  476. }
  477. this.stream.onended = function()
  478. {
  479. self.streamEnded();
  480. };
  481. }
  482. LocalStream.prototype.streamEnded = function () {
  483. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  484. }
  485. LocalStream.prototype.getOriginalStream = function()
  486. {
  487. return this.stream;
  488. }
  489. LocalStream.prototype.isAudioStream = function () {
  490. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  491. };
  492. LocalStream.prototype.mute = function()
  493. {
  494. var ismuted = false;
  495. var tracks = this.getTracks();
  496. for (var idx = 0; idx < tracks.length; idx++) {
  497. ismuted = !tracks[idx].enabled;
  498. tracks[idx].enabled = ismuted;
  499. }
  500. return ismuted;
  501. };
  502. LocalStream.prototype.setMute = function(mute)
  503. {
  504. if(window.location.protocol != "https:" ||
  505. this.isAudioStream() || this.videoType === "screen")
  506. {
  507. var tracks = this.getTracks();
  508. for (var idx = 0; idx < tracks.length; idx++) {
  509. tracks[idx].enabled = mute;
  510. }
  511. }
  512. else
  513. {
  514. if(mute === false) {
  515. APP.xmpp.removeStream(this.stream);
  516. this.stream.stop();
  517. }
  518. else
  519. {
  520. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(["video"],
  521. function (stream) {
  522. APP.RTC.changeLocalVideo(stream, false, function () {});
  523. });
  524. }
  525. }
  526. };
  527. LocalStream.prototype.isMuted = function () {
  528. var tracks = [];
  529. if(this.type == "audio")
  530. {
  531. tracks = this.stream.getAudioTracks();
  532. }
  533. else
  534. {
  535. if(this.stream.ended)
  536. return true;
  537. tracks = this.stream.getVideoTracks();
  538. }
  539. for (var idx = 0; idx < tracks.length; idx++) {
  540. if(tracks[idx].enabled)
  541. return false;
  542. }
  543. return true;
  544. }
  545. LocalStream.prototype.getId = function () {
  546. return this.stream.getTracks()[0].id;
  547. }
  548. module.exports = LocalStream;
  549. },{"../../service/RTC/StreamEventTypes.js":92}],5:[function(require,module,exports){
  550. ////These lines should be uncommented when require works in app.js
  551. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  552. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  553. /**
  554. * Creates a MediaStream object for the given data, session id and ssrc.
  555. * It is a wrapper class for the MediaStream.
  556. *
  557. * @param data the data object from which we obtain the stream,
  558. * the peerjid, etc.
  559. * @param sid the session id
  560. * @param ssrc the ssrc corresponding to this MediaStream
  561. *
  562. * @constructor
  563. */
  564. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  565. // XXX(gp) to minimize headaches in the future, we should build our
  566. // abstractions around tracks and not streams. ORTC is track based API.
  567. // Mozilla expects m-lines to represent media tracks.
  568. //
  569. // Practically, what I'm saying is that we should have a MediaTrack class
  570. // and not a MediaStream class.
  571. //
  572. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  573. // a track might have an associated RTX and FEC sources.
  574. this.sid = sid;
  575. this.stream = data.stream;
  576. this.peerjid = data.peerjid;
  577. this.ssrc = ssrc;
  578. this.type = (this.stream.getVideoTracks().length > 0)?
  579. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  580. this.videoType = null;
  581. this.muted = false;
  582. this.eventEmitter = eventEmitter;
  583. }
  584. MediaStream.prototype.getOriginalStream = function()
  585. {
  586. return this.stream;
  587. };
  588. MediaStream.prototype.setMute = function (value)
  589. {
  590. this.stream.muted = value;
  591. this.muted = value;
  592. };
  593. MediaStream.prototype.setVideoType = function (value) {
  594. if(this.videoType === value)
  595. return;
  596. this.videoType = value;
  597. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  598. this.peerjid);
  599. };
  600. module.exports = MediaStream;
  601. },{"../../service/RTC/MediaStreamTypes":88,"../../service/RTC/StreamEventTypes":92}],6:[function(require,module,exports){
  602. var EventEmitter = require("events");
  603. var RTCUtils = require("./RTCUtils.js");
  604. var LocalStream = require("./LocalStream.js");
  605. var DataChannels = require("./DataChannels");
  606. var MediaStream = require("./MediaStream.js");
  607. var DesktopSharingEventTypes
  608. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  609. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  610. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  611. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  612. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  613. var UIEvents = require("../../service/UI/UIEvents");
  614. var eventEmitter = new EventEmitter();
  615. var RTC = {
  616. rtcUtils: null,
  617. devices: {
  618. audio: false,
  619. video: false
  620. },
  621. localStreams: [],
  622. remoteStreams: {},
  623. localAudio: null,
  624. localVideo: null,
  625. addStreamListener: function (listener, eventType) {
  626. eventEmitter.on(eventType, listener);
  627. },
  628. addListener: function (type, listener) {
  629. eventEmitter.on(type, listener);
  630. },
  631. removeStreamListener: function (listener, eventType) {
  632. if(!(eventType instanceof StreamEventTypes))
  633. throw "Illegal argument";
  634. eventEmitter.removeListener(eventType, listener);
  635. },
  636. createLocalStream: function (stream, type, change, videoType) {
  637. var localStream = new LocalStream(stream, type, eventEmitter, videoType);
  638. //in firefox we have only one stream object
  639. if(this.localStreams.length == 0 ||
  640. this.localStreams[0].getOriginalStream() != stream)
  641. this.localStreams.push(localStream);
  642. if(type == "audio")
  643. {
  644. this.localAudio = localStream;
  645. }
  646. else
  647. {
  648. this.localVideo = localStream;
  649. }
  650. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  651. if(change)
  652. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  653. eventEmitter.emit(eventType, localStream);
  654. return localStream;
  655. },
  656. removeLocalStream: function (stream) {
  657. for(var i = 0; i < this.localStreams.length; i++)
  658. {
  659. if(this.localStreams[i].getOriginalStream() === stream) {
  660. delete this.localStreams[i];
  661. return;
  662. }
  663. }
  664. },
  665. createRemoteStream: function (data, sid, thessrc) {
  666. var remoteStream = new MediaStream(data, sid, thessrc,
  667. this.getBrowserType(), eventEmitter);
  668. var jid = data.peerjid || APP.xmpp.myJid();
  669. if(!this.remoteStreams[jid]) {
  670. this.remoteStreams[jid] = {};
  671. }
  672. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  673. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  674. return remoteStream;
  675. },
  676. getBrowserType: function () {
  677. return this.rtcUtils.browser;
  678. },
  679. getPCConstraints: function () {
  680. return this.rtcUtils.pc_constraints;
  681. },
  682. getUserMediaWithConstraints:function(um, success_callback,
  683. failure_callback, resolution,
  684. bandwidth, fps, desktopStream)
  685. {
  686. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  687. failure_callback, resolution, bandwidth, fps, desktopStream);
  688. },
  689. attachMediaStream: function (element, stream) {
  690. this.rtcUtils.attachMediaStream(element, stream);
  691. },
  692. getStreamID: function (stream) {
  693. return this.rtcUtils.getStreamID(stream);
  694. },
  695. getVideoSrc: function (element) {
  696. return this.rtcUtils.getVideoSrc(element);
  697. },
  698. setVideoSrc: function (element, src) {
  699. this.rtcUtils.setVideoSrc(element, src);
  700. },
  701. dispose: function() {
  702. if (this.rtcUtils) {
  703. this.rtcUtils = null;
  704. }
  705. },
  706. stop: function () {
  707. this.dispose();
  708. },
  709. start: function () {
  710. var self = this;
  711. APP.desktopsharing.addListener(
  712. function (stream, isUsingScreenStream, callback) {
  713. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  714. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  715. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  716. for(var i = 0; i < changedStreams.length; i++) {
  717. var type = changedStreams[i].type;
  718. if (type != "audio") {
  719. var peerStreams = self.remoteStreams[jid];
  720. if(!peerStreams)
  721. continue;
  722. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  723. if(!videoStream)
  724. continue;
  725. videoStream.setVideoType(changedStreams[i].type);
  726. }
  727. }
  728. });
  729. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  730. DataChannels.init(event.peerconnection, eventEmitter);
  731. });
  732. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  733. DataChannels.handleSelectedEndpointEvent);
  734. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  735. DataChannels.handlePinnedEndpointEvent);
  736. this.rtcUtils = new RTCUtils(this);
  737. this.rtcUtils.obtainAudioAndVideoPermissions();
  738. },
  739. muteRemoteVideoStream: function (jid, value) {
  740. var stream;
  741. if(this.remoteStreams[jid] &&
  742. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  743. {
  744. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  745. }
  746. if(!stream)
  747. return true;
  748. if (value != stream.muted) {
  749. stream.setMute(value);
  750. return true;
  751. }
  752. return false;
  753. },
  754. switchVideoStreams: function (new_stream) {
  755. this.localVideo.stream = new_stream;
  756. this.localStreams = [];
  757. //in firefox we have only one stream object
  758. if (this.localAudio.getOriginalStream() != new_stream)
  759. this.localStreams.push(this.localAudio);
  760. this.localStreams.push(this.localVideo);
  761. },
  762. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  763. var oldStream = this.localVideo.getOriginalStream();
  764. var type = (isUsingScreenStream? "screen" : "video");
  765. var localCallback = callback;
  766. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  767. {
  768. localCallback = function() {
  769. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  770. callback();
  771. };
  772. }
  773. var videoStream = this.rtcUtils.createVideoStream(stream);
  774. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  775. // Stop the stream to trigger onended event for old stream
  776. oldStream.stop();
  777. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  778. },
  779. /**
  780. * Checks if video identified by given src is desktop stream.
  781. * @param videoSrc eg.
  782. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  783. * @returns {boolean}
  784. */
  785. isVideoSrcDesktop: function (jid) {
  786. if(!jid)
  787. return false;
  788. var isDesktop = false;
  789. var stream = null;
  790. if (APP.xmpp.myJid() === jid) {
  791. // local video
  792. stream = this.localVideo;
  793. } else {
  794. var peerStreams = this.remoteStreams[jid];
  795. if(!peerStreams)
  796. return false;
  797. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  798. }
  799. if(stream)
  800. isDesktop = (stream.videoType === "screen");
  801. return isDesktop;
  802. },
  803. setVideoMute: function(mute, callback, options) {
  804. if(!this.localVideo)
  805. return;
  806. if (mute == APP.RTC.localVideo.isMuted())
  807. {
  808. APP.xmpp.sendVideoInfoPresence(mute);
  809. if(callback)
  810. callback();
  811. }
  812. else
  813. {
  814. APP.RTC.localVideo.setMute(!mute);
  815. APP.xmpp.setVideoMute(
  816. mute,
  817. callback,
  818. options);
  819. }
  820. },
  821. setDeviceAvailability: function (devices) {
  822. if(!devices)
  823. return;
  824. if(devices.audio === true || devices.audio === false)
  825. this.devices.audio = devices.audio;
  826. if(devices.video === true || devices.video === false)
  827. this.devices.video = devices.video;
  828. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  829. }
  830. };
  831. module.exports = RTC;
  832. },{"../../service/RTC/MediaStreamTypes":88,"../../service/RTC/RTCEvents.js":90,"../../service/RTC/StreamEventTypes.js":92,"../../service/UI/UIEvents":93,"../../service/desktopsharing/DesktopSharingEventTypes":96,"../../service/xmpp/XMPPEvents":98,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":62}],7:[function(require,module,exports){
  833. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  834. var Resolutions = require("../../service/RTC/Resolutions");
  835. var currentResolution = null;
  836. function getPreviousResolution(resolution) {
  837. if(!Resolutions[resolution])
  838. return null;
  839. var order = Resolutions[resolution].order;
  840. var res = null;
  841. var resName = null;
  842. for(var i in Resolutions)
  843. {
  844. var tmp = Resolutions[i];
  845. if(res == null || (res.order < tmp.order && tmp.order < order))
  846. {
  847. resName = i;
  848. res = tmp;
  849. }
  850. }
  851. return resName;
  852. }
  853. function setResolutionConstraints(constraints, resolution, isAndroid)
  854. {
  855. if (resolution && !constraints.video || isAndroid) {
  856. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  857. }
  858. if(Resolutions[resolution])
  859. {
  860. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  861. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  862. }
  863. else
  864. {
  865. if (isAndroid) {
  866. constraints.video.mandatory.minWidth = 320;
  867. constraints.video.mandatory.minHeight = 240;
  868. constraints.video.mandatory.maxFrameRate = 15;
  869. }
  870. }
  871. if (constraints.video.mandatory.minWidth)
  872. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  873. if (constraints.video.mandatory.minHeight)
  874. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  875. }
  876. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  877. {
  878. var constraints = {audio: false, video: false};
  879. if (um.indexOf('video') >= 0) {
  880. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  881. }
  882. if (um.indexOf('audio') >= 0) {
  883. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  884. }
  885. if (um.indexOf('screen') >= 0) {
  886. constraints.video = {
  887. mandatory: {
  888. chromeMediaSource: "screen",
  889. googLeakyBucket: true,
  890. maxWidth: window.screen.width,
  891. maxHeight: window.screen.height,
  892. maxFrameRate: 3
  893. },
  894. optional: []
  895. };
  896. }
  897. if (um.indexOf('desktop') >= 0) {
  898. constraints.video = {
  899. mandatory: {
  900. chromeMediaSource: "desktop",
  901. chromeMediaSourceId: desktopStream,
  902. googLeakyBucket: true,
  903. maxWidth: window.screen.width,
  904. maxHeight: window.screen.height,
  905. maxFrameRate: 3
  906. },
  907. optional: []
  908. };
  909. }
  910. if (constraints.audio) {
  911. // if it is good enough for hangouts...
  912. constraints.audio.optional.push(
  913. {googEchoCancellation: true},
  914. {googAutoGainControl: true},
  915. {googNoiseSupression: true},
  916. {googHighpassFilter: true},
  917. {googNoisesuppression2: true},
  918. {googEchoCancellation2: true},
  919. {googAutoGainControl2: true}
  920. );
  921. }
  922. if (constraints.video) {
  923. constraints.video.optional.push(
  924. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  925. );
  926. if (um.indexOf('video') >= 0) {
  927. constraints.video.optional.push(
  928. {googLeakyBucket: true}
  929. );
  930. }
  931. }
  932. if (um.indexOf('video') >= 0) {
  933. setResolutionConstraints(constraints, resolution, isAndroid);
  934. }
  935. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  936. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  937. constraints.video.optional.push({bandwidth: bandwidth});
  938. }
  939. if (fps) { // for some cameras it might be necessary to request 30fps
  940. // so they choose 30fps mjpg over 10fps yuy2
  941. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  942. constraints.video.mandatory.minFrameRate = fps;
  943. }
  944. return constraints;
  945. }
  946. function RTCUtils(RTCService)
  947. {
  948. this.service = RTCService;
  949. if (navigator.mozGetUserMedia) {
  950. console.log('This appears to be Firefox');
  951. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  952. if (version >= 38
  953. && !config.enableSimulcast && config.useBundle && config.useRtcpMux) {
  954. this.peerconnection = mozRTCPeerConnection;
  955. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  956. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  957. this.pc_constraints = {};
  958. this.attachMediaStream = function (element, stream) {
  959. // srcObject is being standardized and FF will eventually
  960. // support that unprefixed. FF also supports the
  961. // "element.src = URL.createObjectURL(...)" combo, but that
  962. // will be deprecated in favour of srcObject.
  963. //
  964. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  965. // https://github.com/webrtc/samples/issues/302
  966. element[0].mozSrcObject = stream;
  967. element[0].play();
  968. };
  969. this.getStreamID = function (stream) {
  970. var tracks = stream.getVideoTracks();
  971. if(!tracks || tracks.length == 0)
  972. {
  973. tracks = stream.getAudioTracks();
  974. }
  975. return tracks[0].id.replace(/[\{,\}]/g,"");
  976. };
  977. this.getVideoSrc = function (element) {
  978. return element.mozSrcObject;
  979. };
  980. this.setVideoSrc = function (element, src) {
  981. element.mozSrcObject = src;
  982. };
  983. RTCSessionDescription = mozRTCSessionDescription;
  984. RTCIceCandidate = mozRTCIceCandidate;
  985. } else {
  986. window.location.href = 'unsupported_browser.html';
  987. return;
  988. }
  989. } else if (navigator.webkitGetUserMedia) {
  990. console.log('This appears to be Chrome');
  991. this.peerconnection = webkitRTCPeerConnection;
  992. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  993. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  994. this.attachMediaStream = function (element, stream) {
  995. element.attr('src', webkitURL.createObjectURL(stream));
  996. };
  997. this.getStreamID = function (stream) {
  998. // streams from FF endpoints have the characters '{' and '}'
  999. // that make jQuery choke.
  1000. return stream.id.replace(/[\{,\}]/g,"");
  1001. };
  1002. this.getVideoSrc = function (element) {
  1003. return element.getAttribute("src");
  1004. };
  1005. this.setVideoSrc = function (element, src) {
  1006. element.setAttribute("src", src);
  1007. };
  1008. // DTLS should now be enabled by default but..
  1009. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1010. if (navigator.userAgent.indexOf('Android') != -1) {
  1011. this.pc_constraints = {}; // disable DTLS on Android
  1012. }
  1013. if (!webkitMediaStream.prototype.getVideoTracks) {
  1014. webkitMediaStream.prototype.getVideoTracks = function () {
  1015. return this.videoTracks;
  1016. };
  1017. }
  1018. if (!webkitMediaStream.prototype.getAudioTracks) {
  1019. webkitMediaStream.prototype.getAudioTracks = function () {
  1020. return this.audioTracks;
  1021. };
  1022. }
  1023. }
  1024. else
  1025. {
  1026. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1027. window.location.href = 'unsupported_browser.html';
  1028. return;
  1029. }
  1030. }
  1031. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1032. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1033. desktopStream)
  1034. {
  1035. currentResolution = resolution;
  1036. // Check if we are running on Android device
  1037. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1038. var constraints = getConstraints(
  1039. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1040. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1041. var self = this;
  1042. try {
  1043. if (config.enableSimulcast
  1044. && constraints.video
  1045. && constraints.video.chromeMediaSource !== 'screen'
  1046. && constraints.video.chromeMediaSource !== 'desktop'
  1047. && !isAndroid
  1048. // We currently do not support FF, as it doesn't have multistream support.
  1049. && !isFF) {
  1050. APP.simulcast.getUserMedia(constraints, function (stream) {
  1051. console.log('onUserMediaSuccess');
  1052. self.setAvailableDevices(um, true);
  1053. success_callback(stream);
  1054. },
  1055. function (error) {
  1056. console.warn('Failed to get access to local media. Error ', error);
  1057. self.setAvailableDevices(um, false);
  1058. if (failure_callback) {
  1059. failure_callback(error);
  1060. }
  1061. });
  1062. } else {
  1063. this.getUserMedia(constraints,
  1064. function (stream) {
  1065. console.log('onUserMediaSuccess');
  1066. self.setAvailableDevices(um, true);
  1067. success_callback(stream);
  1068. },
  1069. function (error) {
  1070. self.setAvailableDevices(um, false);
  1071. console.warn('Failed to get access to local media. Error ',
  1072. error, constraints);
  1073. if (failure_callback) {
  1074. failure_callback(error);
  1075. }
  1076. });
  1077. }
  1078. } catch (e) {
  1079. console.error('GUM failed: ', e);
  1080. if(failure_callback) {
  1081. failure_callback(e);
  1082. }
  1083. }
  1084. };
  1085. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1086. var devices = {};
  1087. if(um.indexOf("video") != -1)
  1088. {
  1089. devices.video = available;
  1090. }
  1091. if(um.indexOf("audio") != -1)
  1092. {
  1093. devices.audio = available;
  1094. }
  1095. this.service.setDeviceAvailability(devices);
  1096. }
  1097. /**
  1098. * We ask for audio and video combined stream in order to get permissions and
  1099. * not to ask twice.
  1100. */
  1101. RTCUtils.prototype.obtainAudioAndVideoPermissions = function(devices, callback) {
  1102. var self = this;
  1103. // Get AV
  1104. if(!devices)
  1105. devices = ['audio', 'video'];
  1106. this.getUserMediaWithConstraints(
  1107. devices,
  1108. function (stream) {
  1109. if(callback)
  1110. callback(stream);
  1111. else
  1112. self.successCallback(stream);
  1113. },
  1114. function (error) {
  1115. self.errorCallback(error);
  1116. },
  1117. config.resolution || '360');
  1118. }
  1119. RTCUtils.prototype.successCallback = function (stream) {
  1120. if(stream)
  1121. console.log('got', stream, stream.getAudioTracks().length,
  1122. stream.getVideoTracks().length);
  1123. this.handleLocalStream(stream);
  1124. };
  1125. RTCUtils.prototype.errorCallback = function (error) {
  1126. var self = this;
  1127. console.error('failed to obtain audio/video stream - trying audio only', error);
  1128. var resolution = getPreviousResolution(currentResolution);
  1129. if(typeof error == "object" && error.constraintName && error.name
  1130. && (error.name == "ConstraintNotSatisfiedError" ||
  1131. error.name == "OverconstrainedError") &&
  1132. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1133. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1134. && resolution != null)
  1135. {
  1136. self.getUserMediaWithConstraints(['audio', 'video'],
  1137. function (stream) {
  1138. return self.successCallback(stream);
  1139. }, function (error) {
  1140. return self.errorCallback(error);
  1141. }, resolution);
  1142. }
  1143. else
  1144. {
  1145. self.getUserMediaWithConstraints(
  1146. ['audio'],
  1147. function (stream) {
  1148. return self.successCallback(stream);
  1149. },
  1150. function (error) {
  1151. console.error('failed to obtain audio/video stream - stop',
  1152. error);
  1153. return self.successCallback(null);
  1154. }
  1155. );
  1156. }
  1157. }
  1158. RTCUtils.prototype.handleLocalStream = function(stream)
  1159. {
  1160. if(window.webkitMediaStream)
  1161. {
  1162. var audioStream = new webkitMediaStream();
  1163. var videoStream = new webkitMediaStream();
  1164. if(stream) {
  1165. var audioTracks = stream.getAudioTracks();
  1166. for (var i = 0; i < audioTracks.length; i++) {
  1167. audioStream.addTrack(audioTracks[i]);
  1168. }
  1169. var videoTracks = stream.getVideoTracks();
  1170. for (i = 0; i < videoTracks.length; i++) {
  1171. videoStream.addTrack(videoTracks[i]);
  1172. }
  1173. }
  1174. this.service.createLocalStream(audioStream, "audio");
  1175. this.service.createLocalStream(videoStream, "video");
  1176. }
  1177. else
  1178. {//firefox
  1179. this.service.createLocalStream(stream, "stream");
  1180. }
  1181. };
  1182. RTCUtils.prototype.createVideoStream = function(stream)
  1183. {
  1184. var videoStream = null;
  1185. if(window.webkitMediaStream)
  1186. {
  1187. videoStream = new webkitMediaStream();
  1188. if(stream)
  1189. {
  1190. var videoTracks = stream.getVideoTracks();
  1191. for (i = 0; i < videoTracks.length; i++) {
  1192. videoStream.addTrack(videoTracks[i]);
  1193. }
  1194. }
  1195. }
  1196. else
  1197. videoStream = stream;
  1198. return videoStream;
  1199. };
  1200. module.exports = RTCUtils;
  1201. },{"../../service/RTC/RTCBrowserType.js":89,"../../service/RTC/Resolutions":91}],8:[function(require,module,exports){
  1202. var UI = {};
  1203. var VideoLayout = require("./videolayout/VideoLayout.js");
  1204. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1205. var Prezi = require("./prezi/Prezi.js");
  1206. var Etherpad = require("./etherpad/Etherpad.js");
  1207. var Chat = require("./side_pannels/chat/Chat.js");
  1208. var Toolbar = require("./toolbars/Toolbar");
  1209. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1210. var BottomToolbar = require("./toolbars/BottomToolbar");
  1211. var ContactList = require("./side_pannels/contactlist/ContactList");
  1212. var Avatar = require("./avatar/Avatar");
  1213. var EventEmitter = require("events");
  1214. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1215. var Settings = require("./../settings/Settings");
  1216. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1217. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1218. UI.messageHandler = require("./util/MessageHandler");
  1219. var messageHandler = UI.messageHandler;
  1220. var Authentication = require("./authentication/Authentication");
  1221. var UIUtil = require("./util/UIUtil");
  1222. var NicknameHandler = require("./util/NicknameHandler");
  1223. var CQEvents = require("../../service/connectionquality/CQEvents");
  1224. var DesktopSharingEventTypes
  1225. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1226. var RTCEvents = require("../../service/RTC/RTCEvents");
  1227. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1228. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1229. var eventEmitter = new EventEmitter();
  1230. var roomName = null;
  1231. function setupPrezi()
  1232. {
  1233. $("#reloadPresentationLink").click(function()
  1234. {
  1235. Prezi.reloadPresentation();
  1236. });
  1237. }
  1238. function setupChat()
  1239. {
  1240. Chat.init();
  1241. $("#toggle_smileys").click(function() {
  1242. Chat.toggleSmileys();
  1243. });
  1244. }
  1245. function setupToolbars() {
  1246. Toolbar.init(UI);
  1247. Toolbar.setupButtonsFromConfig();
  1248. BottomToolbar.init();
  1249. }
  1250. function streamHandler(stream) {
  1251. switch (stream.type)
  1252. {
  1253. case "audio":
  1254. VideoLayout.changeLocalAudio(stream);
  1255. break;
  1256. case "video":
  1257. VideoLayout.changeLocalVideo(stream);
  1258. break;
  1259. case "stream":
  1260. VideoLayout.changeLocalStream(stream);
  1261. break;
  1262. }
  1263. }
  1264. function onDisposeConference(unload) {
  1265. Toolbar.showAuthenticateButton(false);
  1266. };
  1267. function onDisplayNameChanged(jid, displayName) {
  1268. ContactList.onDisplayNameChange(jid, displayName);
  1269. SettingsMenu.onDisplayNameChange(jid, displayName);
  1270. VideoLayout.onDisplayNameChanged(jid, displayName);
  1271. }
  1272. function registerListeners() {
  1273. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1274. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1275. APP.RTC.addStreamListener(function (stream) {
  1276. VideoLayout.onRemoteStreamAdded(stream);
  1277. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1278. APP.RTC.addStreamListener(function (jid) {
  1279. VideoLayout.onVideoTypeChanged(jid);
  1280. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1281. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1282. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1283. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1284. });
  1285. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1286. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1287. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1288. endpointsEnteringLastN, stream);
  1289. });
  1290. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1291. function (endpointSimulcastLayers) {
  1292. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1293. });
  1294. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1295. function (endpointSimulcastLayers) {
  1296. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1297. });
  1298. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1299. function (devices) {
  1300. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1301. })
  1302. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1303. {
  1304. var resourceJid;
  1305. if(jid === APP.statistics.LOCAL_JID)
  1306. {
  1307. resourceJid = AudioLevels.LOCAL_LEVEL;
  1308. if(APP.RTC.localAudio.isMuted())
  1309. {
  1310. audioLevel = 0;
  1311. }
  1312. }
  1313. else
  1314. {
  1315. resourceJid = Strophe.getResourceFromJid(jid);
  1316. }
  1317. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1318. UI.getLargeVideoState().userResourceJid);
  1319. });
  1320. APP.desktopsharing.addListener(function () {
  1321. ToolbarToggler.showDesktopSharingButton();
  1322. }, DesktopSharingEventTypes.INIT);
  1323. APP.desktopsharing.addListener(
  1324. Toolbar.changeDesktopSharingButtonState,
  1325. DesktopSharingEventTypes.SWITCHING_DONE);
  1326. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1327. VideoLayout.updateLocalConnectionStats);
  1328. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1329. VideoLayout.updateConnectionStats);
  1330. APP.connectionquality.addListener(CQEvents.STOP,
  1331. VideoLayout.onStatsStop);
  1332. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1333. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1334. messageHandler.openMessageDialog(
  1335. 'dialog.serviceUnavailable',
  1336. 'dialog.gracefulShutdown'
  1337. );
  1338. });
  1339. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1340. var title = APP.translation.generateTranslatonHTML(
  1341. "dialog.reservationError");
  1342. var message = APP.translation.generateTranslatonHTML(
  1343. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1344. messageHandler.openDialog(
  1345. title,
  1346. message,
  1347. true, {},
  1348. function (event, value, message, formVals)
  1349. {
  1350. return false;
  1351. }
  1352. );
  1353. });
  1354. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1355. messageHandler.openMessageDialog("dialog.sessTerminated",
  1356. "dialog.kickMessage");
  1357. });
  1358. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1359. //FIXME: use Session Terminated from translation, but
  1360. // 'reason' text comes from XMPP packet and is not translated
  1361. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1362. messageHandler.openDialog(
  1363. title, reason, true, {},
  1364. function (event, value, message, formVals)
  1365. {
  1366. return false;
  1367. }
  1368. );
  1369. });
  1370. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1371. messageHandler.showError("dialog.error",
  1372. "dialog.bridgeUnavailable");
  1373. });
  1374. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1375. Avatar.setUserAvatar(from, id);
  1376. });
  1377. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1378. for(stream in changedStreams)
  1379. {
  1380. // might need to update the direction if participant just went from sendrecv to recvonly
  1381. if (stream.type === 'video' || stream.type === 'screen') {
  1382. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1383. switch (stream.direction) {
  1384. case 'sendrecv':
  1385. el.show();
  1386. break;
  1387. case 'recvonly':
  1388. el.hide();
  1389. // FIXME: Check if we have to change large video
  1390. //VideoLayout.updateLargeVideo(el);
  1391. break;
  1392. }
  1393. }
  1394. }
  1395. });
  1396. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1397. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1398. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1399. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1400. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1401. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1402. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1403. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1404. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1405. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1406. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1407. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1408. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1409. onAuthenticationRequired);
  1410. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1411. function (resource, devices) {
  1412. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1413. });
  1414. }
  1415. /**
  1416. * Mutes/unmutes the local video.
  1417. *
  1418. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1419. * @param options an object which specifies optional arguments such as the
  1420. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1421. * specifies whether the method was initiated in response to a user command (in
  1422. * contrast to an automatic decision taken by the application logic)
  1423. */
  1424. function setVideoMute(mute, options) {
  1425. APP.RTC.setVideoMute(mute,
  1426. UI.setVideoMuteButtonsState,
  1427. options);
  1428. }
  1429. function bindEvents()
  1430. {
  1431. /**
  1432. * Resizes and repositions videos in full screen mode.
  1433. */
  1434. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1435. function () {
  1436. VideoLayout.resizeLargeVideoContainer();
  1437. VideoLayout.positionLarge();
  1438. }
  1439. );
  1440. $(window).resize(function () {
  1441. VideoLayout.resizeLargeVideoContainer();
  1442. VideoLayout.positionLarge();
  1443. });
  1444. }
  1445. UI.start = function (init) {
  1446. document.title = interfaceConfig.APP_NAME;
  1447. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1448. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1449. {
  1450. $("#videoconference_page").hide();
  1451. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1452. setupWelcomePage();
  1453. return;
  1454. }
  1455. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1456. var leftWatermarkDiv
  1457. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1458. leftWatermarkDiv.css({display: 'block'});
  1459. leftWatermarkDiv.parent().get(0).href
  1460. = interfaceConfig.JITSI_WATERMARK_LINK;
  1461. }
  1462. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1463. var rightWatermarkDiv
  1464. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1465. rightWatermarkDiv.css({display: 'block'});
  1466. rightWatermarkDiv.parent().get(0).href
  1467. = interfaceConfig.BRAND_WATERMARK_LINK;
  1468. rightWatermarkDiv.get(0).style.backgroundImage
  1469. = "url(images/rightwatermark.png)";
  1470. }
  1471. if (interfaceConfig.SHOW_POWERED_BY) {
  1472. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1473. }
  1474. $("#welcome_page").hide();
  1475. VideoLayout.resizeLargeVideoContainer();
  1476. $("#videospace").mousemove(function () {
  1477. return ToolbarToggler.showToolbar();
  1478. });
  1479. // Set the defaults for prompt dialogs.
  1480. jQuery.prompt.setDefaults({persistent: false});
  1481. VideoLayout.init(eventEmitter);
  1482. AudioLevels.init();
  1483. NicknameHandler.init(eventEmitter);
  1484. registerListeners();
  1485. bindEvents();
  1486. setupPrezi();
  1487. setupToolbars();
  1488. setupChat();
  1489. document.title = interfaceConfig.APP_NAME;
  1490. $("#downloadlog").click(function (event) {
  1491. dump(event.target);
  1492. });
  1493. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1494. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1495. {
  1496. $("#videoconference_page").hide();
  1497. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1498. setupWelcomePage();
  1499. return;
  1500. }
  1501. $("#welcome_page").hide();
  1502. // Display notice message at the top of the toolbar
  1503. if (config.noticeMessage) {
  1504. $('#noticeText').text(config.noticeMessage);
  1505. $('#notice').css({display: 'block'});
  1506. }
  1507. document.getElementById('largeVideo').volume = 0;
  1508. if (!$('#settings').is(':visible')) {
  1509. console.log('init');
  1510. init();
  1511. } else {
  1512. loginInfo.onsubmit = function (e) {
  1513. if (e.preventDefault) e.preventDefault();
  1514. $('#settings').hide();
  1515. init();
  1516. };
  1517. }
  1518. toastr.options = {
  1519. "closeButton": true,
  1520. "debug": false,
  1521. "positionClass": "notification-bottom-right",
  1522. "onclick": null,
  1523. "showDuration": "300",
  1524. "hideDuration": "1000",
  1525. "timeOut": "2000",
  1526. "extendedTimeOut": "1000",
  1527. "showEasing": "swing",
  1528. "hideEasing": "linear",
  1529. "showMethod": "fadeIn",
  1530. "hideMethod": "fadeOut",
  1531. "reposition": function() {
  1532. if(PanelToggler.isVisible()) {
  1533. $("#toast-container").addClass("notification-bottom-right-center");
  1534. } else {
  1535. $("#toast-container").removeClass("notification-bottom-right-center");
  1536. }
  1537. },
  1538. "newestOnTop": false
  1539. };
  1540. SettingsMenu.init();
  1541. };
  1542. function chatAddError(errorMessage, originalText)
  1543. {
  1544. return Chat.chatAddError(errorMessage, originalText);
  1545. };
  1546. function chatSetSubject(text)
  1547. {
  1548. return Chat.chatSetSubject(text);
  1549. };
  1550. function updateChatConversation(from, displayName, message) {
  1551. return Chat.updateChatConversation(from, displayName, message);
  1552. };
  1553. function onMucJoined(jid, info) {
  1554. Toolbar.updateRoomUrl(window.location.href);
  1555. var meHTML = APP.translation.generateTranslatonHTML("me");
  1556. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1557. var settings = Settings.getSettings();
  1558. // Add myself to the contact list.
  1559. ContactList.addContact(jid, settings.email || settings.uid);
  1560. // Once we've joined the muc show the toolbar
  1561. ToolbarToggler.showToolbar();
  1562. var displayName = !config.displayJids
  1563. ? info.displayName : Strophe.getResourceFromJid(jid);
  1564. if (displayName)
  1565. onDisplayNameChanged('localVideoContainer', displayName);
  1566. }
  1567. function initEtherpad(name) {
  1568. Etherpad.init(name);
  1569. };
  1570. function onMucLeft(jid) {
  1571. console.log('left.muc', jid);
  1572. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1573. '>.displayname').html();
  1574. messageHandler.notify(displayName,'notify.somebody',
  1575. 'disconnected',
  1576. 'notify.disconnected');
  1577. // Need to call this with a slight delay, otherwise the element couldn't be
  1578. // found for some reason.
  1579. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1580. window.setTimeout(function () {
  1581. var container = document.getElementById(
  1582. 'participant_' + Strophe.getResourceFromJid(jid));
  1583. if (container) {
  1584. ContactList.removeContact(jid);
  1585. VideoLayout.removeConnectionIndicator(jid);
  1586. // hide here, wait for video to close before removing
  1587. $(container).hide();
  1588. VideoLayout.resizeThumbnails();
  1589. }
  1590. }, 10);
  1591. VideoLayout.participantLeft(jid);
  1592. };
  1593. function onLocalRoleChange(jid, info, pres, isModerator)
  1594. {
  1595. console.info("My role changed, new role: " + info.role);
  1596. onModeratorStatusChanged(isModerator);
  1597. VideoLayout.showModeratorIndicator();
  1598. if (isModerator) {
  1599. Authentication.closeAuthenticationWindow();
  1600. messageHandler.notify(null, "notify.me",
  1601. 'connected', "notify.moderator");
  1602. }
  1603. }
  1604. function onModeratorStatusChanged(isModerator) {
  1605. Toolbar.showSipCallButton(isModerator);
  1606. Toolbar.showRecordingButton(
  1607. isModerator); //&&
  1608. // FIXME:
  1609. // Recording visible if
  1610. // there are at least 2(+ 1 focus) participants
  1611. //Object.keys(connection.emuc.members).length >= 3);
  1612. if (isModerator && config.etherpad_base) {
  1613. Etherpad.init();
  1614. }
  1615. };
  1616. function onPasswordReqiured(callback) {
  1617. // password is required
  1618. Toolbar.lockLockButton();
  1619. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1620. message += APP.translation.translateString(
  1621. "dialog.passwordRequired");
  1622. message += '</h2>' +
  1623. '<input name="lockKey" type="text" data-i18n=' +
  1624. '"[placeholder]dialog.password" placeholder="' +
  1625. APP.translation.translateString("dialog.password") +
  1626. '" autofocus>';
  1627. messageHandler.openTwoButtonDialog(null, null, null, message,
  1628. true,
  1629. "dialog.Ok",
  1630. function (e, v, m, f) {},
  1631. null,
  1632. function (e, v, m, f) {
  1633. if (v) {
  1634. var lockKey = f.lockKey;
  1635. if (lockKey) {
  1636. Toolbar.setSharedKey(lockKey);
  1637. callback(lockKey);
  1638. }
  1639. }
  1640. },
  1641. ':input:first'
  1642. );
  1643. }
  1644. function onMucEntered(jid, id, displayName) {
  1645. messageHandler.notify(displayName,'notify.somebody',
  1646. 'connected',
  1647. 'notify.connected');
  1648. // Add Peer's container
  1649. VideoLayout.ensurePeerContainerExists(jid,id);
  1650. }
  1651. function onMucPresenceStatus( jid, info) {
  1652. VideoLayout.setPresenceStatus(
  1653. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1654. }
  1655. function onMucRoleChanged(role, displayName) {
  1656. VideoLayout.showModeratorIndicator();
  1657. if (role === 'moderator') {
  1658. var messageKey, messageOptions = {};
  1659. if (!displayName) {
  1660. messageKey = "notify.grantedToUnknown";
  1661. }
  1662. else
  1663. {
  1664. messageKey = "notify.grantedTo";
  1665. messageOptions = {to: displayName};
  1666. }
  1667. messageHandler.notify(
  1668. displayName,'notify.somebody',
  1669. 'connected', messageKey,
  1670. messageOptions);
  1671. }
  1672. }
  1673. function onAuthenticationRequired(intervalCallback) {
  1674. Authentication.openAuthenticationDialog(
  1675. roomName, intervalCallback, function () {
  1676. Toolbar.authenticateClicked();
  1677. });
  1678. };
  1679. function onLastNChanged(oldValue, newValue) {
  1680. if (config.muteLocalVideoIfNotInLastN) {
  1681. setVideoMute(!newValue, { 'byUser': false });
  1682. }
  1683. }
  1684. UI.toggleSmileys = function () {
  1685. Chat.toggleSmileys();
  1686. };
  1687. UI.getSettings = function () {
  1688. return Settings.getSettings();
  1689. };
  1690. UI.toggleFilmStrip = function () {
  1691. return BottomToolbar.toggleFilmStrip();
  1692. };
  1693. UI.toggleChat = function () {
  1694. return BottomToolbar.toggleChat();
  1695. };
  1696. UI.toggleContactList = function () {
  1697. return BottomToolbar.toggleContactList();
  1698. };
  1699. UI.inputDisplayNameHandler = function (value) {
  1700. VideoLayout.inputDisplayNameHandler(value);
  1701. };
  1702. UI.getLargeVideoState = function()
  1703. {
  1704. return VideoLayout.getLargeVideoState();
  1705. };
  1706. UI.generateRoomName = function() {
  1707. if(roomName)
  1708. return roomName;
  1709. var roomnode = null;
  1710. var path = window.location.pathname;
  1711. // determinde the room node from the url
  1712. // TODO: just the roomnode or the whole bare jid?
  1713. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1714. // custom function might be responsible for doing the pushstate
  1715. roomnode = config.getroomnode(path);
  1716. } else {
  1717. /* fall back to default strategy
  1718. * this is making assumptions about how the URL->room mapping happens.
  1719. * It currently assumes deployment at root, with a rewrite like the
  1720. * following one (for nginx):
  1721. location ~ ^/([a-zA-Z0-9]+)$ {
  1722. rewrite ^/(.*)$ / break;
  1723. }
  1724. */
  1725. if (path.length > 1) {
  1726. roomnode = path.substr(1).toLowerCase();
  1727. } else {
  1728. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1729. roomnode = word.toLowerCase();
  1730. window.history.pushState('VideoChat',
  1731. 'Room: ' + word, window.location.pathname + word);
  1732. }
  1733. }
  1734. roomName = roomnode + '@' + config.hosts.muc;
  1735. return roomName;
  1736. };
  1737. UI.connectionIndicatorShowMore = function(id)
  1738. {
  1739. return VideoLayout.connectionIndicators[id].showMore();
  1740. };
  1741. UI.showLoginPopup = function(callback)
  1742. {
  1743. console.log('password is required');
  1744. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1745. message += APP.translation.translateString(
  1746. "dialog.passwordRequired");
  1747. message += '</h2>' +
  1748. '<input name="username" type="text" ' +
  1749. 'placeholder="user@domain.net" autofocus>' +
  1750. '<input name="password" ' +
  1751. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1752. ' placeholder="user password">';
  1753. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1754. true,
  1755. "dialog.Ok",
  1756. function (e, v, m, f) {
  1757. if (v) {
  1758. if (f.username !== null && f.password != null) {
  1759. callback(f.username, f.password);
  1760. }
  1761. }
  1762. },
  1763. null, null, ':input:first'
  1764. );
  1765. }
  1766. UI.checkForNicknameAndJoin = function () {
  1767. Authentication.closeAuthenticationDialog();
  1768. Authentication.stopInterval();
  1769. var nick = null;
  1770. if (config.useNicks) {
  1771. nick = window.prompt('Your nickname (optional)');
  1772. }
  1773. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1774. };
  1775. function dump(elem, filename) {
  1776. elem = elem.parentNode;
  1777. elem.download = filename || 'meetlog.json';
  1778. elem.href = 'data:application/json;charset=utf-8,\n';
  1779. var data = APP.xmpp.populateData();
  1780. var metadata = {};
  1781. metadata.time = new Date();
  1782. metadata.url = window.location.href;
  1783. metadata.ua = navigator.userAgent;
  1784. var log = APP.xmpp.getLogger();
  1785. if (log) {
  1786. metadata.xmpp = log;
  1787. }
  1788. data.metadata = metadata;
  1789. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1790. return false;
  1791. }
  1792. UI.getRoomName = function () {
  1793. return roomName;
  1794. };
  1795. /**
  1796. * Mutes/unmutes the local video.
  1797. */
  1798. UI.toggleVideo = function () {
  1799. setVideoMute(!APP.RTC.localVideo.isMuted());
  1800. };
  1801. /**
  1802. * Mutes / unmutes audio for the local participant.
  1803. */
  1804. UI.toggleAudio = function() {
  1805. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1806. };
  1807. /**
  1808. * Sets muted audio state for the local participant.
  1809. */
  1810. UI.setAudioMuted = function (mute) {
  1811. if(!APP.xmpp.setAudioMute(mute, function () {
  1812. VideoLayout.showLocalAudioIndicator(mute);
  1813. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1814. }))
  1815. {
  1816. // We still click the button.
  1817. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1818. return;
  1819. }
  1820. }
  1821. UI.addListener = function (type, listener) {
  1822. eventEmitter.on(type, listener);
  1823. }
  1824. UI.clickOnVideo = function (videoNumber) {
  1825. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1826. if (remoteVideos.length > videoNumber) {
  1827. remoteVideos[videoNumber].click();
  1828. }
  1829. }
  1830. //Used by torture
  1831. UI.showToolbar = function () {
  1832. return ToolbarToggler.showToolbar();
  1833. }
  1834. //Used by torture
  1835. UI.dockToolbar = function (isDock) {
  1836. return ToolbarToggler.dockToolbar(isDock);
  1837. }
  1838. UI.setVideoMuteButtonsState = function (mute) {
  1839. var video = $('#video');
  1840. var communicativeClass = "icon-camera";
  1841. var muteClass = "icon-camera icon-camera-disabled";
  1842. if (mute) {
  1843. video.removeClass(communicativeClass);
  1844. video.addClass(muteClass);
  1845. } else {
  1846. video.removeClass(muteClass);
  1847. video.addClass(communicativeClass);
  1848. }
  1849. }
  1850. module.exports = UI;
  1851. },{"../../service/RTC/RTCEvents":90,"../../service/RTC/StreamEventTypes":92,"../../service/connectionquality/CQEvents":95,"../../service/desktopsharing/DesktopSharingEventTypes":96,"../../service/xmpp/XMPPEvents":98,"./../settings/Settings":38,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":13,"./etherpad/Etherpad.js":14,"./prezi/Prezi.js":15,"./side_pannels/SidePanelToggler":17,"./side_pannels/chat/Chat.js":18,"./side_pannels/contactlist/ContactList":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":62}],9:[function(require,module,exports){
  1852. var CanvasUtil = require("./CanvasUtils");
  1853. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1854. function initActiveSpeakerAudioLevels() {
  1855. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1856. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1857. // Draw a circle.
  1858. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1859. // Add a shadow around the circle
  1860. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1861. ASDrawContext.shadowOffsetX = 0;
  1862. ASDrawContext.shadowOffsetY = 0;
  1863. }
  1864. /**
  1865. * The audio Levels plugin.
  1866. */
  1867. var AudioLevels = (function(my) {
  1868. var audioLevelCanvasCache = {};
  1869. my.LOCAL_LEVEL = 'local';
  1870. my.init = function () {
  1871. initActiveSpeakerAudioLevels();
  1872. }
  1873. /**
  1874. * Updates the audio level canvas for the given peerJid. If the canvas
  1875. * didn't exist we create it.
  1876. */
  1877. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1878. var resourceJid = null;
  1879. var videoSpanId = null;
  1880. if (!peerJid)
  1881. videoSpanId = 'localVideoContainer';
  1882. else {
  1883. resourceJid = Strophe.getResourceFromJid(peerJid);
  1884. videoSpanId = 'participant_' + resourceJid;
  1885. }
  1886. var videoSpan = document.getElementById(videoSpanId);
  1887. if (!videoSpan) {
  1888. if (resourceJid)
  1889. console.error("No video element for jid", resourceJid);
  1890. else
  1891. console.error("No video element for local video.");
  1892. return;
  1893. }
  1894. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1895. var videoSpaceWidth = $('#remoteVideos').width();
  1896. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1897. var thumbnailWidth = thumbnailSize[0];
  1898. var thumbnailHeight = thumbnailSize[1];
  1899. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1900. audioLevelCanvas = document.createElement('canvas');
  1901. audioLevelCanvas.className = "audiolevel";
  1902. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1903. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1904. resizeAudioLevelCanvas( audioLevelCanvas,
  1905. thumbnailWidth,
  1906. thumbnailHeight);
  1907. videoSpan.appendChild(audioLevelCanvas);
  1908. } else {
  1909. audioLevelCanvas = audioLevelCanvas.get(0);
  1910. resizeAudioLevelCanvas( audioLevelCanvas,
  1911. thumbnailWidth,
  1912. thumbnailHeight);
  1913. }
  1914. };
  1915. /**
  1916. * Updates the audio level UI for the given resourceJid.
  1917. *
  1918. * @param resourceJid the resource jid indicating the video element for
  1919. * which we draw the audio level
  1920. * @param audioLevel the newAudio level to render
  1921. */
  1922. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1923. drawAudioLevelCanvas(resourceJid, audioLevel);
  1924. var videoSpanId = getVideoSpanId(resourceJid);
  1925. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1926. if (!audioLevelCanvas)
  1927. return;
  1928. var drawContext = audioLevelCanvas.getContext('2d');
  1929. var canvasCache = audioLevelCanvasCache[resourceJid];
  1930. drawContext.clearRect (0, 0,
  1931. audioLevelCanvas.width, audioLevelCanvas.height);
  1932. drawContext.drawImage(canvasCache, 0, 0);
  1933. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1934. if(!APP.xmpp.myJid()) {
  1935. return;
  1936. }
  1937. resourceJid = APP.xmpp.myResource();
  1938. }
  1939. if(resourceJid === largeVideoResourceJid) {
  1940. window.requestAnimationFrame(function () {
  1941. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1942. });
  1943. }
  1944. };
  1945. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1946. if($("#activeSpeaker").css("visibility") == "hidden")
  1947. return;
  1948. ASDrawContext.clearRect(0, 0, 300, 300);
  1949. if(audioLevel == 0)
  1950. return;
  1951. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1952. // Fill the shape.
  1953. ASDrawContext.fill();
  1954. };
  1955. /**
  1956. * Resizes the given audio level canvas to match the given thumbnail size.
  1957. */
  1958. function resizeAudioLevelCanvas(audioLevelCanvas,
  1959. thumbnailWidth,
  1960. thumbnailHeight) {
  1961. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1962. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1963. }
  1964. /**
  1965. * Draws the audio level canvas into the cached canvas object.
  1966. *
  1967. * @param resourceJid the resource jid indicating the video element for
  1968. * which we draw the audio level
  1969. * @param audioLevel the newAudio level to render
  1970. */
  1971. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1972. if (!audioLevelCanvasCache[resourceJid]) {
  1973. var videoSpanId = getVideoSpanId(resourceJid);
  1974. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1975. /*
  1976. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1977. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1978. * error. Since audio levels are frequently updated, the errors have
  1979. * been observed to pile into the console, strain the CPU.
  1980. */
  1981. if (audioLevelCanvasOrig)
  1982. {
  1983. audioLevelCanvasCache[resourceJid]
  1984. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1985. }
  1986. }
  1987. var canvas = audioLevelCanvasCache[resourceJid];
  1988. if (!canvas)
  1989. return;
  1990. var drawContext = canvas.getContext('2d');
  1991. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1992. var shadowLevel = getShadowLevel(audioLevel);
  1993. if (shadowLevel > 0)
  1994. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1995. CanvasUtil.drawRoundRectGlow( drawContext,
  1996. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1997. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1998. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1999. interfaceConfig.CANVAS_RADIUS,
  2000. interfaceConfig.SHADOW_COLOR,
  2001. shadowLevel);
  2002. }
  2003. /**
  2004. * Returns the shadow/glow level for the given audio level.
  2005. *
  2006. * @param audioLevel the audio level from which we determine the shadow
  2007. * level
  2008. */
  2009. function getShadowLevel (audioLevel) {
  2010. var shadowLevel = 0;
  2011. if (audioLevel <= 0.3) {
  2012. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2013. }
  2014. else if (audioLevel <= 0.6) {
  2015. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2016. }
  2017. else {
  2018. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2019. }
  2020. return shadowLevel;
  2021. }
  2022. /**
  2023. * Returns the video span id corresponding to the given resourceJid or local
  2024. * user.
  2025. */
  2026. function getVideoSpanId(resourceJid) {
  2027. var videoSpanId = null;
  2028. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2029. || (APP.xmpp.myResource() && resourceJid
  2030. === APP.xmpp.myResource()))
  2031. videoSpanId = 'localVideoContainer';
  2032. else
  2033. videoSpanId = 'participant_' + resourceJid;
  2034. return videoSpanId;
  2035. }
  2036. /**
  2037. * Indicates that the remote video has been resized.
  2038. */
  2039. $(document).bind('remotevideo.resized', function (event, width, height) {
  2040. var resized = false;
  2041. $('#remoteVideos>span>canvas').each(function() {
  2042. var canvas = $(this).get(0);
  2043. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2044. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2045. resized = true;
  2046. }
  2047. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2048. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2049. resized = true;
  2050. }
  2051. });
  2052. if (resized)
  2053. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2054. audioLevelCanvasCache[resourceJid].width
  2055. = width + interfaceConfig.CANVAS_EXTRA;
  2056. audioLevelCanvasCache[resourceJid].height
  2057. = height + interfaceConfig.CANVAS_EXTRA;
  2058. });
  2059. });
  2060. return my;
  2061. })(AudioLevels || {});
  2062. module.exports = AudioLevels;
  2063. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  2064. /**
  2065. * Utility class for drawing canvas shapes.
  2066. */
  2067. var CanvasUtil = (function(my) {
  2068. /**
  2069. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2070. * of the glow.
  2071. *
  2072. * @param drawContext the context of the canvas to draw to
  2073. * @param x the x coordinate of the round rectangle
  2074. * @param y the y coordinate of the round rectangle
  2075. * @param w the width of the round rectangle
  2076. * @param h the height of the round rectangle
  2077. * @param glowColor the color of the glow
  2078. * @param glowWidth the width of the glow
  2079. */
  2080. my.drawRoundRectGlow
  2081. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2082. // Save the previous state of the context.
  2083. drawContext.save();
  2084. if (w < 2 * r) r = w / 2;
  2085. if (h < 2 * r) r = h / 2;
  2086. // Draw a round rectangle.
  2087. drawContext.beginPath();
  2088. drawContext.moveTo(x+r, y);
  2089. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2090. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2091. drawContext.arcTo(x, y+h, x, y, r);
  2092. drawContext.arcTo(x, y, x+w, y, r);
  2093. drawContext.closePath();
  2094. // Add a shadow around the rectangle
  2095. drawContext.shadowColor = glowColor;
  2096. drawContext.shadowBlur = glowWidth;
  2097. drawContext.shadowOffsetX = 0;
  2098. drawContext.shadowOffsetY = 0;
  2099. // Fill the shape.
  2100. drawContext.fill();
  2101. drawContext.save();
  2102. drawContext.restore();
  2103. // 1) Uncomment this line to use Composite Operation, which is doing the
  2104. // same as the clip function below and is also antialiasing the round
  2105. // border, but is said to be less fast performance wise.
  2106. // drawContext.globalCompositeOperation='destination-out';
  2107. drawContext.beginPath();
  2108. drawContext.moveTo(x+r, y);
  2109. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2110. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2111. drawContext.arcTo(x, y+h, x, y, r);
  2112. drawContext.arcTo(x, y, x+w, y, r);
  2113. drawContext.closePath();
  2114. // 2) Uncomment this line to use Composite Operation, which is doing the
  2115. // same as the clip function below and is also antialiasing the round
  2116. // border, but is said to be less fast performance wise.
  2117. // drawContext.fill();
  2118. // Comment these two lines if choosing to do the same with composite
  2119. // operation above 1 and 2.
  2120. drawContext.clip();
  2121. drawContext.clearRect(0, 0, 277, 200);
  2122. // Restore the previous context state.
  2123. drawContext.restore();
  2124. };
  2125. /**
  2126. * Clones the given canvas.
  2127. *
  2128. * @return the new cloned canvas.
  2129. */
  2130. my.cloneCanvas = function (oldCanvas) {
  2131. /*
  2132. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2133. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2134. * levels are frequently updated, the errors have been observed to pile
  2135. * into the console, strain the CPU.
  2136. */
  2137. if (!oldCanvas)
  2138. return oldCanvas;
  2139. //create a new canvas
  2140. var newCanvas = document.createElement('canvas');
  2141. var context = newCanvas.getContext('2d');
  2142. //set dimensions
  2143. newCanvas.width = oldCanvas.width;
  2144. newCanvas.height = oldCanvas.height;
  2145. //apply the old canvas to the new one
  2146. context.drawImage(oldCanvas, 0, 0);
  2147. //return the new canvas
  2148. return newCanvas;
  2149. };
  2150. return my;
  2151. })(CanvasUtil || {});
  2152. module.exports = CanvasUtil;
  2153. },{}],11:[function(require,module,exports){
  2154. /* global $, APP*/
  2155. var LoginDialog = require('./LoginDialog');
  2156. var Moderator = require('../../xmpp/moderator');
  2157. /* Initial "authentication required" dialog */
  2158. var authDialog = null;
  2159. /* Loop retry ID that wits for other user to create the room */
  2160. var authRetryId = null;
  2161. var authenticationWindow = null;
  2162. var Authentication = {
  2163. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2164. // This is the loop that will wait for the room to be created by
  2165. // someone else. 'auth_required.moderator' will bring us back here.
  2166. authRetryId = window.setTimeout(intervalCallback, 5000);
  2167. // Show prompt only if it's not open
  2168. if (authDialog !== null) {
  2169. return;
  2170. }
  2171. // extract room name from 'room@muc.server.net'
  2172. var room = roomName.substr(0, roomName.indexOf('@'));
  2173. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2174. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2175. {room: room});
  2176. var buttonTxt
  2177. = APP.translation.generateTranslatonHTML("dialog.Authenticate");
  2178. var buttons = [];
  2179. buttons.push({title: buttonTxt, value: "authNow"});
  2180. authDialog = APP.UI.messageHandler.openDialog(
  2181. title,
  2182. msg,
  2183. true,
  2184. buttons,
  2185. function (onSubmitEvent, submitValue) {
  2186. // Do not close the dialog yet
  2187. onSubmitEvent.preventDefault();
  2188. // Open login popup
  2189. if (submitValue === 'authNow') {
  2190. callback();
  2191. }
  2192. }
  2193. );
  2194. },
  2195. closeAuthenticationWindow: function () {
  2196. if (authenticationWindow) {
  2197. authenticationWindow.close();
  2198. authenticationWindow = null;
  2199. }
  2200. },
  2201. xmppAuthenticate: function () {
  2202. var loginDialog = LoginDialog.show(
  2203. function (connection, state) {
  2204. if (!state) {
  2205. // User cancelled
  2206. loginDialog.close();
  2207. return;
  2208. } else if (state == APP.xmpp.Status.CONNECTED) {
  2209. loginDialog.close();
  2210. Authentication.stopInterval();
  2211. Authentication.closeAuthenticationDialog();
  2212. // Close the connection as anonymous one will be used
  2213. // to create the conference. Session-id will authorize
  2214. // the request.
  2215. connection.disconnect();
  2216. var roomName = APP.UI.generateRoomName();
  2217. Moderator.allocateConferenceFocus(roomName, function () {
  2218. // If it's not "on the fly" authentication now join
  2219. // the conference room
  2220. if (!APP.xmpp.getMUCJoined()) {
  2221. APP.UI.checkForNicknameAndJoin();
  2222. }
  2223. });
  2224. }
  2225. }, true);
  2226. },
  2227. focusAuthenticationWindow: function () {
  2228. // If auth window exists just bring it to the front
  2229. if (authenticationWindow) {
  2230. authenticationWindow.focus();
  2231. return;
  2232. }
  2233. },
  2234. closeAuthenticationDialog: function () {
  2235. // Close authentication dialog if opened
  2236. if (authDialog) {
  2237. authDialog.close();
  2238. authDialog = null;
  2239. }
  2240. },
  2241. createAuthenticationWindow: function (callback, url) {
  2242. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2243. url, 910, 660,
  2244. // On closed
  2245. function () {
  2246. // Close authentication dialog if opened
  2247. Authentication.closeAuthenticationDialog();
  2248. callback();
  2249. authenticationWindow = null;
  2250. });
  2251. return authenticationWindow;
  2252. },
  2253. stopInterval: function () {
  2254. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2255. if (authRetryId) {
  2256. window.clearTimeout(authRetryId);
  2257. authRetryId = null;
  2258. }
  2259. }
  2260. };
  2261. module.exports = Authentication;
  2262. },{"../../xmpp/moderator":53,"./LoginDialog":12}],12:[function(require,module,exports){
  2263. /* global $, APP, config*/
  2264. var XMPP = require('../../xmpp/xmpp');
  2265. var Moderator = require('../../xmpp/moderator');
  2266. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2267. // anonymous domain is not enabled
  2268. /**
  2269. * Creates new <tt>Dialog</tt> instance.
  2270. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2271. * when we either fail to connect or succeed(check Strophe.Status).
  2272. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2273. * in order to create session-id after the connection is established.
  2274. * @constructor
  2275. */
  2276. function Dialog(callback, obtainSession) {
  2277. var self = this;
  2278. var stop = false;
  2279. var connection = APP.xmpp.createConnection();
  2280. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2281. message += APP.translation.translateString("dialog.passwordRequired");
  2282. message += '</h2>' +
  2283. '<input name="username" type="text" ' +
  2284. 'placeholder="user@domain.net" autofocus>' +
  2285. '<input name="password" ' +
  2286. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2287. ' placeholder="user password">';
  2288. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2289. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2290. var states = {
  2291. login: {
  2292. html: message,
  2293. buttons: [
  2294. { title: okButton, value: true},
  2295. { title: cancelButton, value: false}
  2296. ],
  2297. focus: ':input:first',
  2298. submit: function (e, v, m, f) {
  2299. e.preventDefault();
  2300. if (v) {
  2301. var jid = f.username;
  2302. var password = f.password;
  2303. if (jid && password) {
  2304. stop = false;
  2305. connection.reset();
  2306. connDialog.goToState('connecting');
  2307. connection.connect(jid, password, stateHandler);
  2308. }
  2309. } else {
  2310. // User cancelled
  2311. stop = true;
  2312. callback();
  2313. }
  2314. }
  2315. },
  2316. connecting: {
  2317. title: APP.translation.translateString('dialog.connecting'),
  2318. html: '<div id="connectionStatus"></div>',
  2319. buttons: [],
  2320. defaultButton: 0
  2321. },
  2322. finished: {
  2323. title: APP.translation.translateString('dialog.error'),
  2324. html: '<div id="errorMessage"></div>',
  2325. buttons: [
  2326. {
  2327. title: APP.translation.translateString('dialog.retry'),
  2328. value: 'retry'
  2329. },
  2330. {
  2331. title: APP.translation.translateString('dialog.Cancel'),
  2332. value: 'cancel'
  2333. },
  2334. ],
  2335. defaultButton: 0,
  2336. submit: function (e, v, m, f) {
  2337. e.preventDefault();
  2338. if (v === 'retry')
  2339. connDialog.goToState('login');
  2340. else
  2341. callback();
  2342. }
  2343. }
  2344. };
  2345. var connDialog
  2346. = APP.UI.messageHandler.openDialogWithStates(states,
  2347. { persistent: true, closeText: '' }, null);
  2348. var stateHandler = function (status, message) {
  2349. if (stop) {
  2350. return;
  2351. }
  2352. var translateKey = "connection." + XMPP.getStatusString(status);
  2353. var statusStr = APP.translation.translateString(translateKey);
  2354. // Display current state
  2355. var connectionStatus =
  2356. connDialog.getState('connecting').find('#connectionStatus');
  2357. connectionStatus.text(statusStr);
  2358. switch (status) {
  2359. case XMPP.Status.CONNECTED:
  2360. stop = true;
  2361. if (!obtainSession) {
  2362. callback(connection, status);
  2363. return;
  2364. }
  2365. // Obtaining session-id status
  2366. connectionStatus.text(
  2367. APP.translation.translateString(
  2368. 'connection.FETCH_SESSION_ID'));
  2369. // Authenticate with Jicofo and obtain session-id
  2370. var roomName = APP.UI.generateRoomName();
  2371. // Jicofo will return new session-id when connected
  2372. // from authenticated domain
  2373. connection.sendIQ(
  2374. Moderator.createConferenceIq(roomName),
  2375. function (result) {
  2376. connectionStatus.text(
  2377. APP.translation.translateString(
  2378. 'connection.GOT_SESSION_ID'));
  2379. stop = true;
  2380. // Parse session-id
  2381. Moderator.parseSessionId(result);
  2382. callback(connection, status);
  2383. },
  2384. function (error) {
  2385. console.error("Auth on the fly failed", error);
  2386. stop = true;
  2387. var errorMsg =
  2388. APP.translation.translateString(
  2389. 'connection.GET_SESSION_ID_ERROR') +
  2390. $(error).find('>error').attr('code');
  2391. self.displayError(errorMsg);
  2392. connection.disconnect();
  2393. });
  2394. break;
  2395. case XMPP.Status.AUTHFAIL:
  2396. case XMPP.Status.CONNFAIL:
  2397. case XMPP.Status.DISCONNECTED:
  2398. stop = true;
  2399. callback(connection, status);
  2400. var errorMessage = statusStr;
  2401. if (message)
  2402. {
  2403. errorMessage += ': ' + message;
  2404. }
  2405. self.displayError(errorMessage);
  2406. break;
  2407. default:
  2408. break;
  2409. }
  2410. };
  2411. /**
  2412. * Displays error message in 'finished' state which allows either to cancel
  2413. * or retry.
  2414. * @param message the final message to be displayed.
  2415. */
  2416. this.displayError = function (message) {
  2417. var finishedState = connDialog.getState('finished');
  2418. var errorMessageElem = finishedState.find('#errorMessage');
  2419. errorMessageElem.text(message);
  2420. connDialog.goToState('finished');
  2421. };
  2422. /**
  2423. * Closes LoginDialog.
  2424. */
  2425. this.close = function () {
  2426. stop = true;
  2427. connDialog.close();
  2428. };
  2429. }
  2430. var LoginDialog = {
  2431. /**
  2432. * Displays login prompt used to establish new XMPP connection. Given
  2433. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2434. * called when we connect successfully(status === CONNECTED) or when we fail
  2435. * to do so. On connection failure program can call Dialog.close() method in
  2436. * order to cancel or do nothing to let the user retry.
  2437. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2438. * called when we either fail to connect or succeed(check
  2439. * Strophe.Status).
  2440. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2441. * Jicofo in order to create session-id after the connection is
  2442. * established.
  2443. * @returns {Dialog}
  2444. */
  2445. show: function (callback, obtainSession) {
  2446. return new Dialog(callback, obtainSession);
  2447. }
  2448. };
  2449. module.exports = LoginDialog;
  2450. },{"../../xmpp/moderator":53,"../../xmpp/xmpp":61}],13:[function(require,module,exports){
  2451. var Settings = require("../../settings/Settings");
  2452. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2453. var users = {};
  2454. var activeSpeakerJid;
  2455. function setVisibility(selector, show) {
  2456. if (selector && selector.length > 0) {
  2457. selector.css("visibility", show ? "visible" : "hidden");
  2458. }
  2459. }
  2460. function isUserMuted(jid) {
  2461. // XXX(gp) we may want to rename this method to something like
  2462. // isUserStreaming, for example.
  2463. if (jid && jid != APP.xmpp.myJid()) {
  2464. var resource = Strophe.getResourceFromJid(jid);
  2465. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2466. return true;
  2467. }
  2468. }
  2469. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2470. return null;
  2471. }
  2472. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2473. }
  2474. function getGravatarUrl(id, size) {
  2475. if(id === APP.xmpp.myJid() || !id) {
  2476. id = Settings.getSettings().uid;
  2477. }
  2478. return 'https://www.gravatar.com/avatar/' +
  2479. MD5.hexdigest(id.trim().toLowerCase()) +
  2480. "?d=wavatar&size=" + (size || "30");
  2481. }
  2482. var Avatar = {
  2483. /**
  2484. * Sets the user's avatar in the settings menu(if local user), contact list
  2485. * and thumbnail
  2486. * @param jid jid of the user
  2487. * @param id email or userID to be used as a hash
  2488. */
  2489. setUserAvatar: function (jid, id) {
  2490. if (id) {
  2491. if (users[jid] === id) {
  2492. return;
  2493. }
  2494. users[jid] = id;
  2495. }
  2496. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2497. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2498. var resourceJid = Strophe.getResourceFromJid(jid);
  2499. var thumbnail = $('#participant_' + resourceJid);
  2500. var avatar = $('#avatar_' + resourceJid);
  2501. // set the avatar in the settings menu if it is local user and get the
  2502. // local video container
  2503. if (jid === APP.xmpp.myJid()) {
  2504. $('#avatar').get(0).src = thumbUrl;
  2505. thumbnail = $('#localVideoContainer');
  2506. }
  2507. // set the avatar in the contact list
  2508. var contact = $('#' + resourceJid + '>img');
  2509. if (contact && contact.length > 0) {
  2510. contact.get(0).src = contactListUrl;
  2511. }
  2512. // set the avatar in the thumbnail
  2513. if (avatar && avatar.length > 0) {
  2514. avatar[0].src = thumbUrl;
  2515. } else {
  2516. if (thumbnail && thumbnail.length > 0) {
  2517. avatar = document.createElement('img');
  2518. avatar.id = 'avatar_' + resourceJid;
  2519. avatar.className = 'userAvatar';
  2520. avatar.src = thumbUrl;
  2521. thumbnail.append(avatar);
  2522. }
  2523. }
  2524. //if the user is the current active speaker - update the active speaker
  2525. // avatar
  2526. if (jid === activeSpeakerJid) {
  2527. this.updateActiveSpeakerAvatarSrc(jid);
  2528. }
  2529. },
  2530. /**
  2531. * Hides or shows the user's avatar
  2532. * @param jid jid of the user
  2533. * @param show whether we should show the avatar or not
  2534. * video because there is no dominant speaker and no focused speaker
  2535. */
  2536. showUserAvatar: function (jid, show) {
  2537. if (users[jid]) {
  2538. var resourceJid = Strophe.getResourceFromJid(jid);
  2539. var video = $('#participant_' + resourceJid + '>video');
  2540. var avatar = $('#avatar_' + resourceJid);
  2541. if (jid === APP.xmpp.myJid()) {
  2542. video = $('#localVideoWrapper>video');
  2543. }
  2544. if (show === undefined || show === null) {
  2545. show = isUserMuted(jid);
  2546. }
  2547. //if the user is the currently focused, the dominant speaker or if
  2548. //there is no focused and no dominant speaker and the large video is
  2549. //currently shown
  2550. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2551. setVisibility($("#largeVideo"), !show);
  2552. setVisibility($('#activeSpeaker'), show);
  2553. setVisibility(avatar, false);
  2554. setVisibility(video, false);
  2555. } else {
  2556. if (video && video.length > 0) {
  2557. setVisibility(video, !show);
  2558. setVisibility(avatar, show);
  2559. }
  2560. }
  2561. }
  2562. },
  2563. /**
  2564. * Updates the src of the active speaker avatar
  2565. * @param jid of the current active speaker
  2566. */
  2567. updateActiveSpeakerAvatarSrc: function (jid) {
  2568. if (!jid) {
  2569. jid = APP.xmpp.findJidFromResource(
  2570. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2571. }
  2572. var avatar = $("#activeSpeakerAvatar")[0];
  2573. var url = getGravatarUrl(users[jid],
  2574. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2575. if (jid === activeSpeakerJid && avatar.src === url) {
  2576. return;
  2577. }
  2578. activeSpeakerJid = jid;
  2579. var isMuted = isUserMuted(jid);
  2580. if (jid && isMuted !== null) {
  2581. avatar.src = url;
  2582. setVisibility($("#largeVideo"), !isMuted);
  2583. Avatar.showUserAvatar(jid, isMuted);
  2584. }
  2585. }
  2586. };
  2587. module.exports = Avatar;
  2588. },{"../../../service/RTC/MediaStreamTypes":88,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2589. /* global $, config,
  2590. setLargeVideoVisible, Util */
  2591. var VideoLayout = require("../videolayout/VideoLayout");
  2592. var Prezi = require("../prezi/Prezi");
  2593. var UIUtil = require("../util/UIUtil");
  2594. var etherpadName = null;
  2595. var etherpadIFrame = null;
  2596. var domain = null;
  2597. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2598. /**
  2599. * Resizes the etherpad.
  2600. */
  2601. function resize() {
  2602. if ($('#etherpad>iframe').length) {
  2603. var remoteVideos = $('#remoteVideos');
  2604. var availableHeight
  2605. = window.innerHeight - remoteVideos.outerHeight();
  2606. var availableWidth = UIUtil.getAvailableVideoWidth();
  2607. $('#etherpad>iframe').width(availableWidth);
  2608. $('#etherpad>iframe').height(availableHeight);
  2609. }
  2610. }
  2611. /**
  2612. * Shares the Etherpad name with other participants.
  2613. */
  2614. function shareEtherpad() {
  2615. APP.xmpp.addToPresence("etherpad", etherpadName);
  2616. }
  2617. /**
  2618. * Creates the Etherpad button and adds it to the toolbar.
  2619. */
  2620. function enableEtherpadButton() {
  2621. if (!$('#etherpadButton').is(":visible"))
  2622. $('#etherpadButton').css({display: 'inline-block'});
  2623. }
  2624. /**
  2625. * Creates the IFrame for the etherpad.
  2626. */
  2627. function createIFrame() {
  2628. etherpadIFrame = document.createElement('iframe');
  2629. etherpadIFrame.src = domain + etherpadName + options;
  2630. etherpadIFrame.frameBorder = 0;
  2631. etherpadIFrame.scrolling = "no";
  2632. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2633. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2634. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2635. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2636. etherpadIFrame.onload = function() {
  2637. document.domain = document.domain;
  2638. bubbleIframeMouseMove(etherpadIFrame);
  2639. setTimeout(function() {
  2640. // the iframes inside of the etherpad are
  2641. // not yet loaded when the etherpad iframe is loaded
  2642. var outer = etherpadIFrame.
  2643. contentDocument.getElementsByName("ace_outer")[0];
  2644. bubbleIframeMouseMove(outer);
  2645. var inner = outer.
  2646. contentDocument.getElementsByName("ace_inner")[0];
  2647. bubbleIframeMouseMove(inner);
  2648. }, 2000);
  2649. };
  2650. }
  2651. function bubbleIframeMouseMove(iframe){
  2652. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2653. iframe.contentWindow.onmousemove = function(e){
  2654. if(existingOnMouseMove) existingOnMouseMove(e);
  2655. var evt = document.createEvent("MouseEvents");
  2656. var boundingClientRect = iframe.getBoundingClientRect();
  2657. evt.initMouseEvent(
  2658. "mousemove",
  2659. true, // bubbles
  2660. false, // not cancelable
  2661. window,
  2662. e.detail,
  2663. e.screenX,
  2664. e.screenY,
  2665. e.clientX + boundingClientRect.left,
  2666. e.clientY + boundingClientRect.top,
  2667. e.ctrlKey,
  2668. e.altKey,
  2669. e.shiftKey,
  2670. e.metaKey,
  2671. e.button,
  2672. null // no related element
  2673. );
  2674. iframe.dispatchEvent(evt);
  2675. };
  2676. }
  2677. /**
  2678. * On video selected event.
  2679. */
  2680. $(document).bind('video.selected', function (event, isPresentation) {
  2681. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2682. Etherpad.toggleEtherpad(isPresentation);
  2683. });
  2684. var Etherpad = {
  2685. /**
  2686. * Initializes the etherpad.
  2687. */
  2688. init: function (name) {
  2689. if (config.etherpad_base && !etherpadName) {
  2690. domain = config.etherpad_base;
  2691. if (!name) {
  2692. // In case we're the focus we generate the name.
  2693. etherpadName = Math.random().toString(36).substring(7) +
  2694. '_' + (new Date().getTime()).toString();
  2695. shareEtherpad();
  2696. }
  2697. else
  2698. etherpadName = name;
  2699. enableEtherpadButton();
  2700. /**
  2701. * Resizes the etherpad, when the window is resized.
  2702. */
  2703. $(window).resize(function () {
  2704. resize();
  2705. });
  2706. }
  2707. },
  2708. /**
  2709. * Opens/hides the Etherpad.
  2710. */
  2711. toggleEtherpad: function (isPresentation) {
  2712. if (!etherpadIFrame)
  2713. createIFrame();
  2714. var largeVideo = null;
  2715. if (Prezi.isPresentationVisible())
  2716. largeVideo = $('#presentation>iframe');
  2717. else
  2718. largeVideo = $('#largeVideo');
  2719. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2720. $('#activeSpeaker').css('visibility', 'hidden');
  2721. largeVideo.fadeOut(300, function () {
  2722. if (Prezi.isPresentationVisible()) {
  2723. largeVideo.css({opacity: '0'});
  2724. } else {
  2725. VideoLayout.setLargeVideoVisible(false);
  2726. }
  2727. });
  2728. $('#etherpad>iframe').fadeIn(300, function () {
  2729. document.body.style.background = '#eeeeee';
  2730. $('#etherpad>iframe').css({visibility: 'visible'});
  2731. $('#etherpad').css({zIndex: 2});
  2732. });
  2733. }
  2734. else if ($('#etherpad>iframe')) {
  2735. $('#etherpad>iframe').fadeOut(300, function () {
  2736. $('#etherpad>iframe').css({visibility: 'hidden'});
  2737. $('#etherpad').css({zIndex: 0});
  2738. document.body.style.background = 'black';
  2739. });
  2740. if (!isPresentation) {
  2741. $('#largeVideo').fadeIn(300, function () {
  2742. VideoLayout.setLargeVideoVisible(true);
  2743. });
  2744. }
  2745. }
  2746. resize();
  2747. },
  2748. isVisible: function() {
  2749. var etherpadIframe = $('#etherpad>iframe');
  2750. return etherpadIframe && etherpadIframe.is(':visible');
  2751. }
  2752. };
  2753. module.exports = Etherpad;
  2754. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2755. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2756. var UIUtil = require("../util/UIUtil");
  2757. var VideoLayout = require("../videolayout/VideoLayout");
  2758. var messageHandler = require("../util/MessageHandler");
  2759. var PreziPlayer = require("./PreziPlayer");
  2760. var preziPlayer = null;
  2761. var Prezi = {
  2762. /**
  2763. * Reloads the current presentation.
  2764. */
  2765. reloadPresentation: function() {
  2766. var iframe = document.getElementById(preziPlayer.options.preziId);
  2767. iframe.src = iframe.src;
  2768. },
  2769. /**
  2770. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2771. * otherwise.
  2772. */
  2773. isPresentationVisible: function () {
  2774. return ($('#presentation>iframe') != null
  2775. && $('#presentation>iframe').css('opacity') == 1);
  2776. },
  2777. /**
  2778. * Opens the Prezi dialog, from which the user could choose a presentation
  2779. * to load.
  2780. */
  2781. openPreziDialog: function() {
  2782. var myprezi = APP.xmpp.getPrezi();
  2783. if (myprezi) {
  2784. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2785. null,
  2786. "dialog.removePreziMsg",
  2787. null,
  2788. false,
  2789. "dialog.Remove",
  2790. function(e,v,m,f) {
  2791. if(v) {
  2792. APP.xmpp.removePreziFromPresence();
  2793. }
  2794. }
  2795. );
  2796. }
  2797. else if (preziPlayer != null) {
  2798. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2799. null, "dialog.sharePreziMsg",
  2800. null,
  2801. false,
  2802. "dialog.Ok",
  2803. function(e,v,m,f) {
  2804. $.prompt.close();
  2805. }
  2806. );
  2807. }
  2808. else {
  2809. var html = APP.translation.generateTranslatonHTML(
  2810. "dialog.sharePreziTitle");
  2811. var cancelButton = APP.translation.generateTranslatonHTML(
  2812. "dialog.Cancel");
  2813. var shareButton = APP.translation.generateTranslatonHTML(
  2814. "dialog.Share");
  2815. var backButton = APP.translation.generateTranslatonHTML(
  2816. "dialog.Back");
  2817. var buttons = [];
  2818. var buttons1 = [];
  2819. // Cancel button to both states
  2820. buttons.push({title: cancelButton, value: false});
  2821. buttons1.push({title: cancelButton, value: false});
  2822. // Share button
  2823. buttons.push({title: shareButton, value: true});
  2824. // Back button
  2825. buttons1.push({title: backButton, value: true});
  2826. var linkError = APP.translation.generateTranslatonHTML(
  2827. "dialog.preziLinkError");
  2828. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2829. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2830. var openPreziState = {
  2831. state0: {
  2832. html: '<h2>' + html + '</h2>' +
  2833. '<input name="preziUrl" type="text" ' +
  2834. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  2835. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  2836. '\' placeholder="' + defaultUrl + '" autofocus>',
  2837. persistent: false,
  2838. buttons: buttons,
  2839. focus: ':input:first',
  2840. defaultButton: 0,
  2841. submit: function (e, v, m, f) {
  2842. e.preventDefault();
  2843. if(v)
  2844. {
  2845. var preziUrl = f.preziUrl;
  2846. if (preziUrl)
  2847. {
  2848. var urlValue
  2849. = encodeURI(UIUtil.escapeHtml(preziUrl));
  2850. if (urlValue.indexOf('http://prezi.com/') != 0
  2851. && urlValue.indexOf('https://prezi.com/') != 0)
  2852. {
  2853. $.prompt.goToState('state1');
  2854. return false;
  2855. }
  2856. else {
  2857. var presIdTmp = urlValue.substring(
  2858. urlValue.indexOf("prezi.com/") + 10);
  2859. if (!isAlphanumeric(presIdTmp)
  2860. || presIdTmp.indexOf('/') < 2) {
  2861. $.prompt.goToState('state1');
  2862. return false;
  2863. }
  2864. else {
  2865. APP.xmpp.addToPresence("prezi", urlValue);
  2866. $.prompt.close();
  2867. }
  2868. }
  2869. }
  2870. }
  2871. else
  2872. $.prompt.close();
  2873. }
  2874. },
  2875. state1: {
  2876. html: '<h2>' + html + '</h2>' +
  2877. linkError,
  2878. persistent: false,
  2879. buttons: buttons1,
  2880. focus: ':input:first',
  2881. defaultButton: 1,
  2882. submit: function (e, v, m, f) {
  2883. e.preventDefault();
  2884. if (v === 0)
  2885. $.prompt.close();
  2886. else
  2887. $.prompt.goToState('state0');
  2888. }
  2889. }
  2890. };
  2891. messageHandler.openDialogWithStates(openPreziState);
  2892. }
  2893. }
  2894. };
  2895. /**
  2896. * A new presentation has been added.
  2897. *
  2898. * @param event the event indicating the add of a presentation
  2899. * @param jid the jid from which the presentation was added
  2900. * @param presUrl url of the presentation
  2901. * @param currentSlide the current slide to which we should move
  2902. */
  2903. function presentationAdded(event, jid, presUrl, currentSlide) {
  2904. console.log("presentation added", presUrl);
  2905. var presId = getPresentationId(presUrl);
  2906. var elementId = 'participant_'
  2907. + Strophe.getResourceFromJid(jid)
  2908. + '_' + presId;
  2909. // We explicitly don't specify the peer jid here, because we don't want
  2910. // this video to be dealt with as a peer related one (for example we
  2911. // don't want to show a mute/kick menu for this one, etc.).
  2912. VideoLayout.addRemoteVideoContainer(null, elementId);
  2913. VideoLayout.resizeThumbnails();
  2914. var controlsEnabled = false;
  2915. if (jid === APP.xmpp.myJid())
  2916. controlsEnabled = true;
  2917. setPresentationVisible(true);
  2918. $('#largeVideoContainer').hover(
  2919. function (event) {
  2920. if (Prezi.isPresentationVisible()) {
  2921. var reloadButtonRight = window.innerWidth
  2922. - $('#presentation>iframe').offset().left
  2923. - $('#presentation>iframe').width();
  2924. $('#reloadPresentation').css({ right: reloadButtonRight,
  2925. display:'inline-block'});
  2926. }
  2927. },
  2928. function (event) {
  2929. if (!Prezi.isPresentationVisible())
  2930. $('#reloadPresentation').css({display:'none'});
  2931. else {
  2932. var e = event.toElement || event.relatedTarget;
  2933. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2934. $('#reloadPresentation').css({display:'none'});
  2935. }
  2936. });
  2937. preziPlayer = new PreziPlayer(
  2938. 'presentation',
  2939. {preziId: presId,
  2940. width: getPresentationWidth(),
  2941. height: getPresentationHeihgt(),
  2942. controls: controlsEnabled,
  2943. debug: true
  2944. });
  2945. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2946. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2947. console.log("prezi status", event.value);
  2948. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2949. if (jid != APP.xmpp.myJid())
  2950. preziPlayer.flyToStep(currentSlide);
  2951. }
  2952. });
  2953. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2954. console.log("event value", event.value);
  2955. APP.xmpp.addToPresence("preziSlide", event.value);
  2956. });
  2957. $("#" + elementId).css( 'background-image',
  2958. 'url(../images/avatarprezi.png)');
  2959. $("#" + elementId).click(
  2960. function () {
  2961. setPresentationVisible(true);
  2962. }
  2963. );
  2964. };
  2965. /**
  2966. * A presentation has been removed.
  2967. *
  2968. * @param event the event indicating the remove of a presentation
  2969. * @param jid the jid for which the presentation was removed
  2970. * @param the url of the presentation
  2971. */
  2972. function presentationRemoved(event, jid, presUrl) {
  2973. console.log('presentation removed', presUrl);
  2974. var presId = getPresentationId(presUrl);
  2975. setPresentationVisible(false);
  2976. $('#participant_'
  2977. + Strophe.getResourceFromJid(jid)
  2978. + '_' + presId).remove();
  2979. $('#presentation>iframe').remove();
  2980. if (preziPlayer != null) {
  2981. preziPlayer.destroy();
  2982. preziPlayer = null;
  2983. }
  2984. };
  2985. /**
  2986. * Indicates if the given string is an alphanumeric string.
  2987. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2988. * purpose of checking URIs.
  2989. */
  2990. function isAlphanumeric(unsafeText) {
  2991. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2992. return regex.test(unsafeText);
  2993. }
  2994. /**
  2995. * Returns the presentation id from the given url.
  2996. */
  2997. function getPresentationId (presUrl) {
  2998. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2999. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  3000. }
  3001. /**
  3002. * Returns the presentation width.
  3003. */
  3004. function getPresentationWidth() {
  3005. var availableWidth = UIUtil.getAvailableVideoWidth();
  3006. var availableHeight = getPresentationHeihgt();
  3007. var aspectRatio = 16.0 / 9.0;
  3008. if (availableHeight < availableWidth / aspectRatio) {
  3009. availableWidth = Math.floor(availableHeight * aspectRatio);
  3010. }
  3011. return availableWidth;
  3012. }
  3013. /**
  3014. * Returns the presentation height.
  3015. */
  3016. function getPresentationHeihgt() {
  3017. var remoteVideos = $('#remoteVideos');
  3018. return window.innerHeight - remoteVideos.outerHeight();
  3019. }
  3020. /**
  3021. * Resizes the presentation iframe.
  3022. */
  3023. function resize() {
  3024. if ($('#presentation>iframe')) {
  3025. $('#presentation>iframe').width(getPresentationWidth());
  3026. $('#presentation>iframe').height(getPresentationHeihgt());
  3027. }
  3028. }
  3029. /**
  3030. * Shows/hides a presentation.
  3031. */
  3032. function setPresentationVisible(visible) {
  3033. var prezi = $('#presentation>iframe');
  3034. if (visible) {
  3035. // Trigger the video.selected event to indicate a change in the
  3036. // large video.
  3037. $(document).trigger("video.selected", [true]);
  3038. $('#largeVideo').fadeOut(300);
  3039. prezi.fadeIn(300, function() {
  3040. prezi.css({opacity:'1'});
  3041. ToolbarToggler.dockToolbar(true);
  3042. VideoLayout.setLargeVideoVisible(false);
  3043. });
  3044. $('#activeSpeaker').css('visibility', 'hidden');
  3045. }
  3046. else {
  3047. if (prezi.css('opacity') == '1') {
  3048. prezi.fadeOut(300, function () {
  3049. prezi.css({opacity:'0'});
  3050. $('#reloadPresentation').css({display:'none'});
  3051. $('#largeVideo').fadeIn(300, function() {
  3052. VideoLayout.setLargeVideoVisible(true);
  3053. ToolbarToggler.dockToolbar(false);
  3054. });
  3055. });
  3056. }
  3057. }
  3058. }
  3059. /**
  3060. * Presentation has been removed.
  3061. */
  3062. $(document).bind('presentationremoved.muc', presentationRemoved);
  3063. /**
  3064. * Presentation has been added.
  3065. */
  3066. $(document).bind('presentationadded.muc', presentationAdded);
  3067. /*
  3068. * Indicates presentation slide change.
  3069. */
  3070. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3071. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3072. preziPlayer.flyToStep(current);
  3073. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3074. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3075. preziPlayer.flyToStep(current, i);
  3076. }
  3077. }
  3078. });
  3079. /**
  3080. * On video selected event.
  3081. */
  3082. $(document).bind('video.selected', function (event, isPresentation) {
  3083. if (!isPresentation && $('#presentation>iframe')) {
  3084. setPresentationVisible(false);
  3085. }
  3086. });
  3087. $(window).resize(function () {
  3088. resize();
  3089. });
  3090. module.exports = Prezi;
  3091. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  3092. (function() {
  3093. "use strict";
  3094. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3095. window.PreziPlayer = (function() {
  3096. PreziPlayer.API_VERSION = 1;
  3097. PreziPlayer.CURRENT_STEP = 'currentStep';
  3098. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3099. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3100. PreziPlayer.STATUS_LOADING = 'loading';
  3101. PreziPlayer.STATUS_READY = 'ready';
  3102. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3103. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3104. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3105. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3106. PreziPlayer.EVENT_STATUS = "statusChange";
  3107. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3108. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3109. PreziPlayer.domain = "https://prezi.com";
  3110. PreziPlayer.path = "/player/";
  3111. PreziPlayer.players = {};
  3112. PreziPlayer.binded_methods = ['changesHandler'];
  3113. PreziPlayer.createMultiplePlayers = function(optionArray){
  3114. for(var i=0; i<optionArray.length; i++) {
  3115. var optionSet = optionArray[i];
  3116. new PreziPlayer(optionSet.id, optionSet);
  3117. };
  3118. };
  3119. PreziPlayer.messageReceived = function(event){
  3120. var message, item, player;
  3121. try {
  3122. message = JSON.parse(event.data);
  3123. if (message.id && (player = PreziPlayer.players[message.id])) {
  3124. if (player.options.debug === true) {
  3125. if (console && console.log)
  3126. console.log('received', message);
  3127. }
  3128. if (message.type === "changes") {
  3129. player.changesHandler(message);
  3130. }
  3131. for (var i = 0; i < player.callbacks.length; i++) {
  3132. item = player.callbacks[i];
  3133. if (item && message.type === item.event) {
  3134. item.callback(message);
  3135. }
  3136. }
  3137. }
  3138. } catch (e) { }
  3139. };
  3140. function PreziPlayer(id, options) {
  3141. var params, paramString = "", _this = this;
  3142. if (PreziPlayer.players[id]){
  3143. PreziPlayer.players[id].destroy();
  3144. }
  3145. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3146. var method_name = PreziPlayer.binded_methods[i];
  3147. _this[method_name] = __bind(_this[method_name], _this);
  3148. };
  3149. options = options || {};
  3150. this.options = options;
  3151. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3152. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3153. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3154. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3155. this.callbacks = [];
  3156. this.id = id;
  3157. this.embedTo = document.getElementById(id);
  3158. if (!this.embedTo) {
  3159. throw "The element id is not available.";
  3160. }
  3161. this.iframe = document.createElement('iframe');
  3162. params = [
  3163. { name: 'oid', value: options.preziId },
  3164. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3165. { name: 'controls', value: options.controls ? 1 : 0 }
  3166. ];
  3167. for(var i=0; i<params.length; i++) {
  3168. var param = params[i];
  3169. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3170. };
  3171. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3172. this.iframe.frameBorder = 0;
  3173. this.iframe.scrolling = "no";
  3174. this.iframe.width = options.width || 640;
  3175. this.iframe.height = options.height || 480;
  3176. this.embedTo.innerHTML = '';
  3177. // JITSI: IN CASE SOMETHING GOES WRONG.
  3178. try {
  3179. this.embedTo.appendChild(this.iframe);
  3180. }
  3181. catch (err) {
  3182. console.log("CATCH ERROR");
  3183. }
  3184. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3185. // crashes for us.
  3186. this.initPollInterval = setInterval(function(){
  3187. _this.sendMessage({'action': 'init'});
  3188. }, 500);
  3189. PreziPlayer.players[id] = this;
  3190. }
  3191. PreziPlayer.prototype.changesHandler = function(message) {
  3192. var key, value, j, item;
  3193. if (this.initPollInterval) {
  3194. clearInterval(this.initPollInterval);
  3195. this.initPollInterval = false;
  3196. }
  3197. for (key in message.data) {
  3198. if (message.data.hasOwnProperty(key)){
  3199. value = message.data[key];
  3200. this.values[key] = value;
  3201. for (j=0; j<this.callbacks.length; j++) {
  3202. item = this.callbacks[j];
  3203. if (item && item.event === key + "Change"){
  3204. item.callback({type: item.event, value: value});
  3205. }
  3206. }
  3207. }
  3208. }
  3209. };
  3210. PreziPlayer.prototype.destroy = function() {
  3211. if (this.initPollInterval) {
  3212. clearInterval(this.initPollInterval);
  3213. this.initPollInterval = false;
  3214. }
  3215. this.embedTo.innerHTML = '';
  3216. };
  3217. PreziPlayer.prototype.sendMessage = function(message) {
  3218. if (this.options.debug === true) {
  3219. if (console && console.log) console.log('sent', message);
  3220. }
  3221. message.version = PreziPlayer.API_VERSION;
  3222. message.id = this.id;
  3223. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3224. };
  3225. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3226. PreziPlayer.prototype.flyToNextStep = function() {
  3227. return this.sendMessage({
  3228. 'action': 'present',
  3229. 'data': ['moveToNextStep']
  3230. });
  3231. };
  3232. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3233. PreziPlayer.prototype.flyToPreviousStep = function() {
  3234. return this.sendMessage({
  3235. 'action': 'present',
  3236. 'data': ['moveToPrevStep']
  3237. });
  3238. };
  3239. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3240. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3241. var obj = this;
  3242. // check animation_step
  3243. if (animation_step > 0 &&
  3244. obj.values.animationCountOnSteps &&
  3245. obj.values.animationCountOnSteps[step] <= animation_step) {
  3246. animation_step = obj.values.animationCountOnSteps[step];
  3247. }
  3248. // jump to animation steps by calling flyToNextStep()
  3249. function doAnimationSteps() {
  3250. if (obj.values.isMoving == true) {
  3251. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3252. return;
  3253. }
  3254. while (animation_step-- > 0) {
  3255. obj.flyToNextStep(); // do the animation steps
  3256. }
  3257. }
  3258. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3259. // jump to the step
  3260. return this.sendMessage({
  3261. 'action': 'present',
  3262. 'data': ['moveToStep', step]
  3263. });
  3264. };
  3265. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3266. PreziPlayer.prototype.flyToObject = function(objectId) {
  3267. return this.sendMessage({
  3268. 'action': 'present',
  3269. 'data': ['moveToObject', objectId]
  3270. });
  3271. };
  3272. PreziPlayer.prototype.play = function(defaultDelay) {
  3273. return this.sendMessage({
  3274. 'action': 'present',
  3275. 'data': ['startAutoPlay', defaultDelay]
  3276. });
  3277. };
  3278. PreziPlayer.prototype.stop = function() {
  3279. return this.sendMessage({
  3280. 'action': 'present',
  3281. 'data': ['stopAutoPlay']
  3282. });
  3283. };
  3284. PreziPlayer.prototype.pause = function(defaultDelay) {
  3285. return this.sendMessage({
  3286. 'action': 'present',
  3287. 'data': ['pauseAutoPlay', defaultDelay]
  3288. });
  3289. };
  3290. PreziPlayer.prototype.getCurrentStep = function() {
  3291. return this.values.currentStep;
  3292. };
  3293. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3294. return this.values.currentAnimationStep;
  3295. };
  3296. PreziPlayer.prototype.getCurrentObject = function() {
  3297. return this.values.currentObject;
  3298. };
  3299. PreziPlayer.prototype.getStatus = function() {
  3300. return this.values.status;
  3301. };
  3302. PreziPlayer.prototype.isPlaying = function() {
  3303. return this.values.isAutoPlaying;
  3304. };
  3305. PreziPlayer.prototype.getStepCount = function() {
  3306. return this.values.stepCount;
  3307. };
  3308. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3309. return this.values.animationCountOnSteps;
  3310. };
  3311. PreziPlayer.prototype.getTitle = function() {
  3312. return this.values.title;
  3313. };
  3314. PreziPlayer.prototype.setDimensions = function(dims) {
  3315. for (var parameter in dims) {
  3316. this.iframe[parameter] = dims[parameter];
  3317. }
  3318. }
  3319. PreziPlayer.prototype.getDimensions = function() {
  3320. return {
  3321. width: parseInt(this.iframe.width, 10),
  3322. height: parseInt(this.iframe.height, 10)
  3323. }
  3324. }
  3325. PreziPlayer.prototype.on = function(event, callback) {
  3326. this.callbacks.push({
  3327. event: event,
  3328. callback: callback
  3329. });
  3330. };
  3331. PreziPlayer.prototype.off = function(event, callback) {
  3332. var j, item;
  3333. if (event === undefined) {
  3334. this.callbacks = [];
  3335. }
  3336. j = this.callbacks.length;
  3337. while (j--) {
  3338. item = this.callbacks[j];
  3339. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3340. this.callbacks.splice(j, 1);
  3341. }
  3342. }
  3343. };
  3344. if (window.addEventListener) {
  3345. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3346. } else {
  3347. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3348. }
  3349. return PreziPlayer;
  3350. })();
  3351. })();
  3352. module.exports = PreziPlayer;
  3353. },{}],17:[function(require,module,exports){
  3354. var Chat = require("./chat/Chat");
  3355. var ContactList = require("./contactlist/ContactList");
  3356. var Settings = require("./../../settings/Settings");
  3357. var SettingsMenu = require("./settings/SettingsMenu");
  3358. var VideoLayout = require("../videolayout/VideoLayout");
  3359. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3360. var UIUtil = require("../util/UIUtil");
  3361. /**
  3362. * Toggler for the chat, contact list, settings menu, etc..
  3363. */
  3364. var PanelToggler = (function(my) {
  3365. var currentlyOpen = null;
  3366. var buttons = {
  3367. '#chatspace': '#chatBottomButton',
  3368. '#contactlist': '#contactListButton',
  3369. '#settingsmenu': '#settingsButton'
  3370. };
  3371. /**
  3372. * Resizes the video area
  3373. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3374. * @param completeFunction a function to be called when the video space is resized
  3375. */
  3376. var resizeVideoArea = function(isClosing, completeFunction) {
  3377. var videospace = $('#videospace');
  3378. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3379. var videospaceWidth = window.innerWidth - panelSize[0];
  3380. var videospaceHeight = window.innerHeight;
  3381. var videoSize
  3382. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3383. var videoWidth = videoSize[0];
  3384. var videoHeight = videoSize[1];
  3385. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3386. videoHeight,
  3387. videospaceWidth,
  3388. videospaceHeight);
  3389. var horizontalIndent = videoPosition[0];
  3390. var verticalIndent = videoPosition[1];
  3391. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3392. var thumbnailsWidth = thumbnailSize[0];
  3393. var thumbnailsHeight = thumbnailSize[1];
  3394. //for chat
  3395. videospace.animate({
  3396. right: panelSize[0],
  3397. width: videospaceWidth,
  3398. height: videospaceHeight
  3399. },
  3400. {
  3401. queue: false,
  3402. duration: 500,
  3403. complete: completeFunction
  3404. });
  3405. $('#remoteVideos').animate({
  3406. height: thumbnailsHeight
  3407. },
  3408. {
  3409. queue: false,
  3410. duration: 500
  3411. });
  3412. $('#remoteVideos>span').animate({
  3413. height: thumbnailsHeight,
  3414. width: thumbnailsWidth
  3415. },
  3416. {
  3417. queue: false,
  3418. duration: 500,
  3419. complete: function () {
  3420. $(document).trigger(
  3421. "remotevideo.resized",
  3422. [thumbnailsWidth,
  3423. thumbnailsHeight]);
  3424. }
  3425. });
  3426. $('#largeVideoContainer').animate({
  3427. width: videospaceWidth,
  3428. height: videospaceHeight
  3429. },
  3430. {
  3431. queue: false,
  3432. duration: 500
  3433. });
  3434. $('#largeVideo').animate({
  3435. width: videoWidth,
  3436. height: videoHeight,
  3437. top: verticalIndent,
  3438. bottom: verticalIndent,
  3439. left: horizontalIndent,
  3440. right: horizontalIndent
  3441. },
  3442. {
  3443. queue: false,
  3444. duration: 500
  3445. });
  3446. };
  3447. /**
  3448. * Toggles the windows in the side panel
  3449. * @param object the window that should be shown
  3450. * @param selector the selector for the element containing the panel
  3451. * @param onOpenComplete function to be called when the panel is opened
  3452. * @param onOpen function to be called if the window is going to be opened
  3453. * @param onClose function to be called if the window is going to be closed
  3454. */
  3455. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3456. UIUtil.buttonClick(buttons[selector], "active");
  3457. if (object.isVisible()) {
  3458. $("#toast-container").animate({
  3459. right: '5px'
  3460. },
  3461. {
  3462. queue: false,
  3463. duration: 500
  3464. });
  3465. $(selector).hide("slide", {
  3466. direction: "right",
  3467. queue: false,
  3468. duration: 500
  3469. });
  3470. if(typeof onClose === "function") {
  3471. onClose();
  3472. }
  3473. currentlyOpen = null;
  3474. }
  3475. else {
  3476. // Undock the toolbar when the chat is shown and if we're in a
  3477. // video mode.
  3478. if (VideoLayout.isLargeVideoVisible()) {
  3479. ToolbarToggler.dockToolbar(false);
  3480. }
  3481. if(currentlyOpen) {
  3482. var current = $(currentlyOpen);
  3483. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3484. current.css('z-index', 4);
  3485. setTimeout(function () {
  3486. current.css('display', 'none');
  3487. current.css('z-index', 5);
  3488. }, 500);
  3489. }
  3490. $("#toast-container").animate({
  3491. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3492. },
  3493. {
  3494. queue: false,
  3495. duration: 500
  3496. });
  3497. $(selector).show("slide", {
  3498. direction: "right",
  3499. queue: false,
  3500. duration: 500,
  3501. complete: onOpenComplete
  3502. });
  3503. if(typeof onOpen === "function") {
  3504. onOpen();
  3505. }
  3506. currentlyOpen = selector;
  3507. }
  3508. };
  3509. /**
  3510. * Opens / closes the chat area.
  3511. */
  3512. my.toggleChat = function() {
  3513. var chatCompleteFunction = Chat.isVisible() ?
  3514. function() {} : function () {
  3515. Chat.scrollChatToBottom();
  3516. $('#chatspace').trigger('shown');
  3517. };
  3518. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3519. toggle(Chat,
  3520. '#chatspace',
  3521. function () {
  3522. // Request the focus in the nickname field or the chat input field.
  3523. if ($('#nickname').css('visibility') === 'visible') {
  3524. $('#nickinput').focus();
  3525. } else {
  3526. $('#usermsg').focus();
  3527. }
  3528. },
  3529. null,
  3530. Chat.resizeChat,
  3531. null);
  3532. };
  3533. /**
  3534. * Opens / closes the contact list area.
  3535. */
  3536. my.toggleContactList = function () {
  3537. var completeFunction = ContactList.isVisible() ?
  3538. function() {} : function () { $('#contactlist').trigger('shown');};
  3539. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3540. toggle(ContactList,
  3541. '#contactlist',
  3542. null,
  3543. function() {
  3544. ContactList.setVisualNotification(false);
  3545. },
  3546. null);
  3547. };
  3548. /**
  3549. * Opens / closes the settings menu
  3550. */
  3551. my.toggleSettingsMenu = function() {
  3552. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3553. toggle(SettingsMenu,
  3554. '#settingsmenu',
  3555. null,
  3556. function() {
  3557. var settings = Settings.getSettings();
  3558. $('#setDisplayName').get(0).value = settings.displayName;
  3559. $('#setEmail').get(0).value = settings.email;
  3560. },
  3561. null);
  3562. };
  3563. /**
  3564. * Returns the size of the side panel.
  3565. */
  3566. my.getPanelSize = function () {
  3567. var availableHeight = window.innerHeight;
  3568. var availableWidth = window.innerWidth;
  3569. var panelWidth = 200;
  3570. if (availableWidth * 0.2 < 200) {
  3571. panelWidth = availableWidth * 0.2;
  3572. }
  3573. return [panelWidth, availableHeight];
  3574. };
  3575. my.isVisible = function() {
  3576. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3577. };
  3578. return my;
  3579. }(PanelToggler || {}));
  3580. module.exports = PanelToggler;
  3581. },{"../toolbars/ToolbarToggler":26,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./../../settings/Settings":38,"./chat/Chat":18,"./contactlist/ContactList":22,"./settings/SettingsMenu":23}],18:[function(require,module,exports){
  3582. /* global $, Util, nickname:true */
  3583. var Replacement = require("./Replacement");
  3584. var CommandsProcessor = require("./Commands");
  3585. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3586. var smileys = require("./smileys.json").smileys;
  3587. var NicknameHandler = require("../../util/NicknameHandler");
  3588. var UIUtil = require("../../util/UIUtil");
  3589. var UIEvents = require("../../../../service/UI/UIEvents");
  3590. var notificationInterval = false;
  3591. var unreadMessages = 0;
  3592. /**
  3593. * Shows/hides a visual notification, indicating that a message has arrived.
  3594. */
  3595. function setVisualNotification(show) {
  3596. var unreadMsgElement = document.getElementById('unreadMessages');
  3597. var unreadMsgBottomElement
  3598. = document.getElementById('bottomUnreadMessages');
  3599. var glower = $('#chatButton');
  3600. var bottomGlower = $('#chatBottomButton');
  3601. if (unreadMessages) {
  3602. unreadMsgElement.innerHTML = unreadMessages.toString();
  3603. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3604. ToolbarToggler.dockToolbar(true);
  3605. var chatButtonElement
  3606. = document.getElementById('chatButton').parentNode;
  3607. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3608. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3609. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3610. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3611. unreadMsgElement.setAttribute(
  3612. 'style',
  3613. 'top:' + topIndent +
  3614. '; left:' + leftIndent + ';');
  3615. var chatBottomButtonElement
  3616. = document.getElementById('chatBottomButton').parentNode;
  3617. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3618. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3619. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3620. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3621. unreadMsgBottomElement.setAttribute(
  3622. 'style',
  3623. 'top:' + bottomTopIndent +
  3624. '; left:' + bottomLeftIndent + ';');
  3625. if (!glower.hasClass('icon-chat-simple')) {
  3626. glower.removeClass('icon-chat');
  3627. glower.addClass('icon-chat-simple');
  3628. }
  3629. }
  3630. else {
  3631. unreadMsgElement.innerHTML = '';
  3632. unreadMsgBottomElement.innerHTML = '';
  3633. glower.removeClass('icon-chat-simple');
  3634. glower.addClass('icon-chat');
  3635. }
  3636. if (show && !notificationInterval) {
  3637. notificationInterval = window.setInterval(function () {
  3638. glower.toggleClass('active');
  3639. bottomGlower.toggleClass('active glowing');
  3640. }, 800);
  3641. }
  3642. else if (!show && notificationInterval) {
  3643. window.clearInterval(notificationInterval);
  3644. notificationInterval = false;
  3645. glower.removeClass('active');
  3646. bottomGlower.removeClass('glowing');
  3647. bottomGlower.addClass('active');
  3648. }
  3649. }
  3650. /**
  3651. * Returns the current time in the format it is shown to the user
  3652. * @returns {string}
  3653. */
  3654. function getCurrentTime() {
  3655. var now = new Date();
  3656. var hour = now.getHours();
  3657. var minute = now.getMinutes();
  3658. var second = now.getSeconds();
  3659. if(hour.toString().length === 1) {
  3660. hour = '0'+hour;
  3661. }
  3662. if(minute.toString().length === 1) {
  3663. minute = '0'+minute;
  3664. }
  3665. if(second.toString().length === 1) {
  3666. second = '0'+second;
  3667. }
  3668. return hour+':'+minute+':'+second;
  3669. }
  3670. function toggleSmileys()
  3671. {
  3672. var smileys = $('#smileysContainer');
  3673. if(!smileys.is(':visible')) {
  3674. smileys.show("slide", { direction: "down", duration: 300});
  3675. } else {
  3676. smileys.hide("slide", { direction: "down", duration: 300});
  3677. }
  3678. $('#usermsg').focus();
  3679. }
  3680. function addClickFunction(smiley, number) {
  3681. smiley.onclick = function addSmileyToMessage() {
  3682. var usermsg = $('#usermsg');
  3683. var message = usermsg.val();
  3684. message += smileys['smiley' + number];
  3685. usermsg.val(message);
  3686. usermsg.get(0).setSelectionRange(message.length, message.length);
  3687. toggleSmileys();
  3688. usermsg.focus();
  3689. };
  3690. }
  3691. /**
  3692. * Adds the smileys container to the chat
  3693. */
  3694. function addSmileys() {
  3695. var smileysContainer = document.createElement('div');
  3696. smileysContainer.id = 'smileysContainer';
  3697. for(var i = 1; i <= 21; i++) {
  3698. var smileyContainer = document.createElement('div');
  3699. smileyContainer.id = 'smiley' + i;
  3700. smileyContainer.className = 'smileyContainer';
  3701. var smiley = document.createElement('img');
  3702. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3703. smiley.className = 'smiley';
  3704. addClickFunction(smiley, i);
  3705. smileyContainer.appendChild(smiley);
  3706. smileysContainer.appendChild(smileyContainer);
  3707. }
  3708. $("#chatspace").append(smileysContainer);
  3709. }
  3710. /**
  3711. * Resizes the chat conversation.
  3712. */
  3713. function resizeChatConversation() {
  3714. var msgareaHeight = $('#usermsg').outerHeight();
  3715. var chatspace = $('#chatspace');
  3716. var width = chatspace.width();
  3717. var chat = $('#chatconversation');
  3718. var smileys = $('#smileysarea');
  3719. smileys.height(msgareaHeight);
  3720. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3721. $('#smileysContainer').css('bottom', msgareaHeight);
  3722. chat.width(width - 10);
  3723. chat.height(window.innerHeight - 15 - msgareaHeight);
  3724. }
  3725. /**
  3726. * Chat related user interface.
  3727. */
  3728. var Chat = (function (my) {
  3729. /**
  3730. * Initializes chat related interface.
  3731. */
  3732. my.init = function () {
  3733. if(NicknameHandler.getNickname())
  3734. Chat.setChatConversationMode(true);
  3735. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3736. function (nickname) {
  3737. Chat.setChatConversationMode(true);
  3738. });
  3739. $('#nickinput').keydown(function (event) {
  3740. if (event.keyCode === 13) {
  3741. event.preventDefault();
  3742. var val = UIUtil.escapeHtml(this.value);
  3743. this.value = '';
  3744. if (!NicknameHandler.getNickname()) {
  3745. NicknameHandler.setNickname(val);
  3746. return;
  3747. }
  3748. }
  3749. });
  3750. $('#usermsg').keydown(function (event) {
  3751. if (event.keyCode === 13) {
  3752. event.preventDefault();
  3753. var value = this.value;
  3754. $('#usermsg').val('').trigger('autosize.resize');
  3755. this.focus();
  3756. var command = new CommandsProcessor(value);
  3757. if(command.isCommand())
  3758. {
  3759. command.processCommand();
  3760. }
  3761. else
  3762. {
  3763. var message = UIUtil.escapeHtml(value);
  3764. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3765. }
  3766. }
  3767. });
  3768. var onTextAreaResize = function () {
  3769. resizeChatConversation();
  3770. Chat.scrollChatToBottom();
  3771. };
  3772. $('#usermsg').autosize({callback: onTextAreaResize});
  3773. $("#chatspace").bind("shown",
  3774. function () {
  3775. unreadMessages = 0;
  3776. setVisualNotification(false);
  3777. });
  3778. addSmileys();
  3779. };
  3780. /**
  3781. * Appends the given message to the chat conversation.
  3782. */
  3783. my.updateChatConversation = function (from, displayName, message) {
  3784. var divClassName = '';
  3785. if (APP.xmpp.myJid() === from) {
  3786. divClassName = "localuser";
  3787. }
  3788. else {
  3789. divClassName = "remoteuser";
  3790. if (!Chat.isVisible()) {
  3791. unreadMessages++;
  3792. UIUtil.playSoundNotification('chatNotification');
  3793. setVisualNotification(true);
  3794. }
  3795. }
  3796. // replace links and smileys
  3797. // Strophe already escapes special symbols on sending,
  3798. // so we escape here only tags to avoid double &amp;
  3799. var escMessage = message.replace(/</g, '&lt;').
  3800. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3801. var escDisplayName = UIUtil.escapeHtml(displayName);
  3802. message = Replacement.processReplacements(escMessage);
  3803. var messageContainer =
  3804. '<div class="chatmessage">'+
  3805. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3806. '<div class="username ' + divClassName +'">' + escDisplayName +
  3807. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3808. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3809. '</div>';
  3810. $('#chatconversation').append(messageContainer);
  3811. $('#chatconversation').animate(
  3812. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3813. };
  3814. /**
  3815. * Appends error message to the conversation
  3816. * @param errorMessage the received error message.
  3817. * @param originalText the original message.
  3818. */
  3819. my.chatAddError = function(errorMessage, originalText)
  3820. {
  3821. errorMessage = UIUtil.escapeHtml(errorMessage);
  3822. originalText = UIUtil.escapeHtml(originalText);
  3823. $('#chatconversation').append(
  3824. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3825. (originalText? (' \"'+ originalText + '\"') : "") +
  3826. ' was not sent.' +
  3827. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3828. $('#chatconversation').animate(
  3829. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3830. };
  3831. /**
  3832. * Sets the subject to the UI
  3833. * @param subject the subject
  3834. */
  3835. my.chatSetSubject = function(subject)
  3836. {
  3837. if(subject)
  3838. subject = subject.trim();
  3839. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3840. if(subject === "")
  3841. {
  3842. $("#subject").css({display: "none"});
  3843. }
  3844. else
  3845. {
  3846. $("#subject").css({display: "block"});
  3847. }
  3848. };
  3849. /**
  3850. * Sets the chat conversation mode.
  3851. */
  3852. my.setChatConversationMode = function (isConversationMode) {
  3853. if (isConversationMode) {
  3854. $('#nickname').css({visibility: 'hidden'});
  3855. $('#chatconversation').css({visibility: 'visible'});
  3856. $('#usermsg').css({visibility: 'visible'});
  3857. $('#smileysarea').css({visibility: 'visible'});
  3858. $('#usermsg').focus();
  3859. }
  3860. };
  3861. /**
  3862. * Resizes the chat area.
  3863. */
  3864. my.resizeChat = function () {
  3865. var chatSize = require("../SidePanelToggler").getPanelSize();
  3866. $('#chatspace').width(chatSize[0]);
  3867. $('#chatspace').height(chatSize[1]);
  3868. resizeChatConversation();
  3869. };
  3870. /**
  3871. * Indicates if the chat is currently visible.
  3872. */
  3873. my.isVisible = function () {
  3874. return $('#chatspace').is(":visible");
  3875. };
  3876. /**
  3877. * Shows and hides the window with the smileys
  3878. */
  3879. my.toggleSmileys = toggleSmileys;
  3880. /**
  3881. * Scrolls chat to the bottom.
  3882. */
  3883. my.scrollChatToBottom = function() {
  3884. setTimeout(function () {
  3885. $('#chatconversation').scrollTop(
  3886. $('#chatconversation')[0].scrollHeight);
  3887. }, 5);
  3888. };
  3889. return my;
  3890. }(Chat || {}));
  3891. module.exports = Chat;
  3892. },{"../../../../service/UI/UIEvents":93,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":17,"./Commands":19,"./Replacement":20,"./smileys.json":21}],19:[function(require,module,exports){
  3893. var UIUtil = require("../../util/UIUtil");
  3894. /**
  3895. * List with supported commands. The keys are the names of the commands and
  3896. * the value is the function that processes the message.
  3897. * @type {{String: function}}
  3898. */
  3899. var commands = {
  3900. "topic" : processTopic
  3901. };
  3902. /**
  3903. * Extracts the command from the message.
  3904. * @param message the received message
  3905. * @returns {string} the command
  3906. */
  3907. function getCommand(message)
  3908. {
  3909. if(message)
  3910. {
  3911. for(var command in commands)
  3912. {
  3913. if(message.indexOf("/" + command) == 0)
  3914. return command;
  3915. }
  3916. }
  3917. return "";
  3918. };
  3919. /**
  3920. * Processes the data for topic command.
  3921. * @param commandArguments the arguments of the topic command.
  3922. */
  3923. function processTopic(commandArguments)
  3924. {
  3925. var topic = UIUtil.escapeHtml(commandArguments);
  3926. APP.xmpp.setSubject(topic);
  3927. }
  3928. /**
  3929. * Constructs new CommandProccessor instance from a message that
  3930. * handles commands received via chat messages.
  3931. * @param message the message
  3932. * @constructor
  3933. */
  3934. function CommandsProcessor(message)
  3935. {
  3936. var command = getCommand(message);
  3937. /**
  3938. * Returns the name of the command.
  3939. * @returns {String} the command
  3940. */
  3941. this.getCommand = function()
  3942. {
  3943. return command;
  3944. };
  3945. var messageArgument = message.substr(command.length + 2);
  3946. /**
  3947. * Returns the arguments of the command.
  3948. * @returns {string}
  3949. */
  3950. this.getArgument = function()
  3951. {
  3952. return messageArgument;
  3953. };
  3954. }
  3955. /**
  3956. * Checks whether this instance is valid command or not.
  3957. * @returns {boolean}
  3958. */
  3959. CommandsProcessor.prototype.isCommand = function()
  3960. {
  3961. if(this.getCommand())
  3962. return true;
  3963. return false;
  3964. };
  3965. /**
  3966. * Processes the command.
  3967. */
  3968. CommandsProcessor.prototype.processCommand = function()
  3969. {
  3970. if(!this.isCommand())
  3971. return;
  3972. commands[this.getCommand()](this.getArgument());
  3973. };
  3974. module.exports = CommandsProcessor;
  3975. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3976. var Smileys = require("./smileys.json");
  3977. /**
  3978. * Processes links and smileys in "body"
  3979. */
  3980. function processReplacements(body)
  3981. {
  3982. //make links clickable
  3983. body = linkify(body);
  3984. //add smileys
  3985. body = smilify(body);
  3986. return body;
  3987. }
  3988. /**
  3989. * Finds and replaces all links in the links in "body"
  3990. * with their <a href=""></a>
  3991. */
  3992. function linkify(inputText)
  3993. {
  3994. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3995. //URLs starting with http://, https://, or ftp://
  3996. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3997. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3998. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3999. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  4000. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4001. //Change email addresses to mailto:: links.
  4002. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4003. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4004. return replacedText;
  4005. }
  4006. /**
  4007. * Replaces common smiley strings with images
  4008. */
  4009. function smilify(body)
  4010. {
  4011. if(!body) {
  4012. return body;
  4013. }
  4014. var regexs = Smileys["regexs"];
  4015. for(var smiley in regexs) {
  4016. if(regexs.hasOwnProperty(smiley)) {
  4017. body = body.replace(regexs[smiley],
  4018. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4019. }
  4020. }
  4021. return body;
  4022. }
  4023. module.exports = {
  4024. processReplacements: processReplacements,
  4025. linkify: linkify
  4026. };
  4027. },{"./smileys.json":21}],21:[function(require,module,exports){
  4028. module.exports={
  4029. "smileys": {
  4030. "smiley1": ":)",
  4031. "smiley2": ":(",
  4032. "smiley3": ":D",
  4033. "smiley4": "(y)",
  4034. "smiley5": " :P",
  4035. "smiley6": "(wave)",
  4036. "smiley7": "(blush)",
  4037. "smiley8": "(chuckle)",
  4038. "smiley9": "(shocked)",
  4039. "smiley10": ":*",
  4040. "smiley11": "(n)",
  4041. "smiley12": "(search)",
  4042. "smiley13": " <3",
  4043. "smiley14": "(oops)",
  4044. "smiley15": "(angry)",
  4045. "smiley16": "(angel)",
  4046. "smiley17": "(sick)",
  4047. "smiley18": ";(",
  4048. "smiley19": "(bomb)",
  4049. "smiley20": "(clap)",
  4050. "smiley21": " ;)"
  4051. },
  4052. "regexs": {
  4053. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4054. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4055. "smiley1": /(:-\)|:\))/gi,
  4056. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4057. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4058. "smiley6": /(\(wave\))/gi,
  4059. "smiley7": /(\(blush\))/gi,
  4060. "smiley8": /(\(chuckle\))/gi,
  4061. "smiley9": /(:-0|\(shocked\))/gi,
  4062. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4063. "smiley11": /(\(n\))/gi,
  4064. "smiley12": /(\(search\))/g,
  4065. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4066. "smiley14": /(\(oops\))/gi,
  4067. "smiley15": /(\(angry\))/gi,
  4068. "smiley16": /(\(angel\))/gi,
  4069. "smiley17": /(\(sick\))/gi,
  4070. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4071. "smiley19": /(\(bomb\))/gi,
  4072. "smiley20": /(\(clap\))/gi,
  4073. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4074. }
  4075. }
  4076. },{}],22:[function(require,module,exports){
  4077. var numberOfContacts = 0;
  4078. var notificationInterval;
  4079. /**
  4080. * Updates the number of participants in the contact list button and sets
  4081. * the glow
  4082. * @param delta indicates whether a new user has joined (1) or someone has
  4083. * left(-1)
  4084. */
  4085. function updateNumberOfParticipants(delta) {
  4086. //when the user is alone we don't show the number of participants
  4087. if(numberOfContacts === 0) {
  4088. $("#numberOfParticipants").text('');
  4089. numberOfContacts += delta;
  4090. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4091. ContactList.setVisualNotification(true);
  4092. numberOfContacts += delta;
  4093. $("#numberOfParticipants").text(numberOfContacts);
  4094. }
  4095. }
  4096. /**
  4097. * Creates the avatar element.
  4098. *
  4099. * @return the newly created avatar element
  4100. */
  4101. function createAvatar(id) {
  4102. var avatar = document.createElement('img');
  4103. avatar.className = "icon-avatar avatar";
  4104. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4105. return avatar;
  4106. }
  4107. /**
  4108. * Creates the display name paragraph.
  4109. *
  4110. * @param displayName the display name to set
  4111. */
  4112. function createDisplayNameParagraph(key, displayName) {
  4113. var p = document.createElement('p');
  4114. if(displayName)
  4115. p.innerText = displayName;
  4116. else if(key)
  4117. {
  4118. p.setAttribute("data-i18n",key);
  4119. p.innerText = APP.translation.translateString(key);
  4120. }
  4121. return p;
  4122. }
  4123. function stopGlowing(glower) {
  4124. window.clearInterval(notificationInterval);
  4125. notificationInterval = false;
  4126. glower.removeClass('glowing');
  4127. if (!ContactList.isVisible()) {
  4128. glower.removeClass('active');
  4129. }
  4130. }
  4131. /**
  4132. * Contact list.
  4133. */
  4134. var ContactList = {
  4135. /**
  4136. * Indicates if the chat is currently visible.
  4137. *
  4138. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4139. * otherwise
  4140. */
  4141. isVisible: function () {
  4142. return $('#contactlist').is(":visible");
  4143. },
  4144. /**
  4145. * Adds a contact for the given peerJid if such doesn't yet exist.
  4146. *
  4147. * @param peerJid the peerJid corresponding to the contact
  4148. * @param id the user's email or userId used to get the user's avatar
  4149. */
  4150. ensureAddContact: function (peerJid, id) {
  4151. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4152. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4153. if (!contact || contact.length <= 0)
  4154. ContactList.addContact(peerJid, id);
  4155. },
  4156. /**
  4157. * Adds a contact for the given peer jid.
  4158. *
  4159. * @param peerJid the jid of the contact to add
  4160. * @param id the email or userId of the user
  4161. */
  4162. addContact: function (peerJid, id) {
  4163. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4164. var contactlist = $('#contactlist>ul');
  4165. var newContact = document.createElement('li');
  4166. newContact.id = resourceJid;
  4167. newContact.className = "clickable";
  4168. newContact.onclick = function (event) {
  4169. if (event.currentTarget.className === "clickable") {
  4170. $(ContactList).trigger('contactclicked', [peerJid]);
  4171. }
  4172. };
  4173. newContact.appendChild(createAvatar(id));
  4174. newContact.appendChild(createDisplayNameParagraph("participant"));
  4175. var clElement = contactlist.get(0);
  4176. if (resourceJid === APP.xmpp.myResource()
  4177. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4178. clElement.insertBefore(newContact,
  4179. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4180. }
  4181. else {
  4182. clElement.appendChild(newContact);
  4183. }
  4184. updateNumberOfParticipants(1);
  4185. },
  4186. /**
  4187. * Removes a contact for the given peer jid.
  4188. *
  4189. * @param peerJid the peerJid corresponding to the contact to remove
  4190. */
  4191. removeContact: function (peerJid) {
  4192. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4193. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4194. if (contact && contact.length > 0) {
  4195. var contactlist = $('#contactlist>ul');
  4196. contactlist.get(0).removeChild(contact.get(0));
  4197. updateNumberOfParticipants(-1);
  4198. }
  4199. },
  4200. setVisualNotification: function (show, stopGlowingIn) {
  4201. var glower = $('#contactListButton');
  4202. if (show && !notificationInterval) {
  4203. notificationInterval = window.setInterval(function () {
  4204. glower.toggleClass('active glowing');
  4205. }, 800);
  4206. }
  4207. else if (!show && notificationInterval) {
  4208. stopGlowing(glower);
  4209. }
  4210. if (stopGlowingIn) {
  4211. setTimeout(function () {
  4212. stopGlowing(glower);
  4213. }, stopGlowingIn);
  4214. }
  4215. },
  4216. setClickable: function (resourceJid, isClickable) {
  4217. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4218. if (isClickable) {
  4219. contact.addClass('clickable');
  4220. } else {
  4221. contact.removeClass('clickable');
  4222. }
  4223. },
  4224. onDisplayNameChange: function (peerJid, displayName) {
  4225. if (peerJid === 'localVideoContainer')
  4226. peerJid = APP.xmpp.myJid();
  4227. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4228. var contactName = $('#contactlist #' + resourceJid + '>p');
  4229. if (contactName && displayName && displayName.length > 0)
  4230. contactName.html(displayName);
  4231. }
  4232. };
  4233. module.exports = ContactList;
  4234. },{}],23:[function(require,module,exports){
  4235. var Avatar = require("../../avatar/Avatar");
  4236. var Settings = require("./../../../settings/Settings");
  4237. var UIUtil = require("../../util/UIUtil");
  4238. var languages = require("../../../../service/translation/languages");
  4239. function generateLanguagesSelectBox()
  4240. {
  4241. var currentLang = APP.translation.getCurrentLanguage();
  4242. var html = "<select id=\"languages_selectbox\">";
  4243. var langArray = languages.getLanguages();
  4244. for(var i = 0; i < langArray.length; i++)
  4245. {
  4246. var lang = langArray[i];
  4247. html += "<option ";
  4248. if(lang === currentLang)
  4249. html += "selected ";
  4250. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4251. html += "</option>";
  4252. }
  4253. return html + "</select>";
  4254. }
  4255. var SettingsMenu = {
  4256. init: function () {
  4257. $("#updateSettings").before(generateLanguagesSelectBox());
  4258. APP.translation.translateElement($("#languages_selectbox"));
  4259. $('#settingsmenu>input').keyup(function(event){
  4260. if(event.keyCode === 13) {//enter
  4261. SettingsMenu.update();
  4262. }
  4263. });
  4264. $("#updateSettings").click(function () {
  4265. SettingsMenu.update();
  4266. });
  4267. },
  4268. update: function() {
  4269. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4270. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4271. if(newDisplayName) {
  4272. var displayName = Settings.setDisplayName(newDisplayName);
  4273. APP.xmpp.addToPresence("displayName", displayName, true);
  4274. }
  4275. var language = $("#languages_selectbox").val();
  4276. APP.translation.setLanguage(language);
  4277. Settings.setLanguage(language);
  4278. APP.xmpp.addToPresence("email", newEmail);
  4279. var email = Settings.setEmail(newEmail);
  4280. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4281. },
  4282. isVisible: function() {
  4283. return $('#settingsmenu').is(':visible');
  4284. },
  4285. setDisplayName: function(newDisplayName) {
  4286. var displayName = Settings.setDisplayName(newDisplayName);
  4287. $('#setDisplayName').get(0).value = displayName;
  4288. },
  4289. onDisplayNameChange: function(peerJid, newDisplayName) {
  4290. if(peerJid === 'localVideoContainer' ||
  4291. peerJid === APP.xmpp.myJid()) {
  4292. this.setDisplayName(newDisplayName);
  4293. }
  4294. }
  4295. };
  4296. module.exports = SettingsMenu;
  4297. },{"../../../../service/translation/languages":97,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4298. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4299. var buttonHandlers = {
  4300. "bottom_toolbar_contact_list": function () {
  4301. BottomToolbar.toggleContactList();
  4302. },
  4303. "bottom_toolbar_film_strip": function () {
  4304. BottomToolbar.toggleFilmStrip();
  4305. },
  4306. "bottom_toolbar_chat": function () {
  4307. BottomToolbar.toggleChat();
  4308. }
  4309. };
  4310. var BottomToolbar = (function (my) {
  4311. my.init = function () {
  4312. for(var k in buttonHandlers)
  4313. $("#" + k).click(buttonHandlers[k]);
  4314. };
  4315. my.toggleChat = function() {
  4316. PanelToggler.toggleChat();
  4317. };
  4318. my.toggleContactList = function() {
  4319. PanelToggler.toggleContactList();
  4320. };
  4321. my.toggleFilmStrip = function() {
  4322. var filmstrip = $("#remoteVideos");
  4323. filmstrip.toggleClass("hidden");
  4324. };
  4325. $(document).bind("remotevideo.resized", function (event, width, height) {
  4326. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4327. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4328. });
  4329. return my;
  4330. }(BottomToolbar || {}));
  4331. module.exports = BottomToolbar;
  4332. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4333. /* global APP,$, buttonClick, config, lockRoom,
  4334. setSharedKey, Util */
  4335. var messageHandler = require("../util/MessageHandler");
  4336. var BottomToolbar = require("./BottomToolbar");
  4337. var Prezi = require("../prezi/Prezi");
  4338. var Etherpad = require("../etherpad/Etherpad");
  4339. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4340. var Authentication = require("../authentication/Authentication");
  4341. var UIUtil = require("../util/UIUtil");
  4342. var AuthenticationEvents
  4343. = require("../../../service/authentication/AuthenticationEvents");
  4344. var roomUrl = null;
  4345. var sharedKey = '';
  4346. var UI = null;
  4347. var buttonHandlers =
  4348. {
  4349. "toolbar_button_mute": function () {
  4350. return APP.UI.toggleAudio();
  4351. },
  4352. "toolbar_button_camera": function () {
  4353. return APP.UI.toggleVideo();
  4354. },
  4355. /*"toolbar_button_authentication": function () {
  4356. return Toolbar.authenticateClicked();
  4357. },*/
  4358. "toolbar_button_record": function () {
  4359. return toggleRecording();
  4360. },
  4361. "toolbar_button_security": function () {
  4362. return Toolbar.openLockDialog();
  4363. },
  4364. "toolbar_button_link": function () {
  4365. return Toolbar.openLinkDialog();
  4366. },
  4367. "toolbar_button_chat": function () {
  4368. return BottomToolbar.toggleChat();
  4369. },
  4370. "toolbar_button_prezi": function () {
  4371. return Prezi.openPreziDialog();
  4372. },
  4373. "toolbar_button_etherpad": function () {
  4374. return Etherpad.toggleEtherpad(0);
  4375. },
  4376. "toolbar_button_desktopsharing": function () {
  4377. return APP.desktopsharing.toggleScreenSharing();
  4378. },
  4379. "toolbar_button_fullScreen": function()
  4380. {
  4381. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4382. return Toolbar.toggleFullScreen();
  4383. },
  4384. "toolbar_button_sip": function () {
  4385. return callSipButtonClicked();
  4386. },
  4387. "toolbar_button_settings": function () {
  4388. PanelToggler.toggleSettingsMenu();
  4389. },
  4390. "toolbar_button_hangup": function () {
  4391. return hangup();
  4392. },
  4393. "toolbar_button_login": function () {
  4394. Toolbar.authenticateClicked();
  4395. },
  4396. "toolbar_button_logout": function () {
  4397. // Ask for confirmation
  4398. messageHandler.openTwoButtonDialog(
  4399. "dialog.logoutTitle",
  4400. null,
  4401. "dialog.logoutQuestion",
  4402. null,
  4403. false,
  4404. "dialog.Yes",
  4405. function (evt, yes) {
  4406. if (yes) {
  4407. APP.xmpp.logout(function (url) {
  4408. if (url) {
  4409. window.location.href = url;
  4410. } else {
  4411. hangup();
  4412. }
  4413. });
  4414. }
  4415. });
  4416. }
  4417. };
  4418. function hangup() {
  4419. APP.xmpp.disposeConference();
  4420. if(config.enableWelcomePage)
  4421. {
  4422. setTimeout(function()
  4423. {
  4424. window.localStorage.welcomePageDisabled = false;
  4425. window.location.pathname = "/";
  4426. }, 10000);
  4427. }
  4428. var title = APP.translation.generateTranslatonHTML(
  4429. "dialog.sessTerminated");
  4430. var msg = APP.translation.generateTranslatonHTML(
  4431. "dialog.hungUp");
  4432. var button = APP.translation.generateTranslatonHTML(
  4433. "dialog.joinAgain");
  4434. var buttons = [];
  4435. buttons.push({title: button, value: true});
  4436. UI.messageHandler.openDialog(
  4437. title,
  4438. msg,
  4439. true,
  4440. buttons,
  4441. function(event, value, message, formVals)
  4442. {
  4443. window.location.reload();
  4444. return false;
  4445. }
  4446. );
  4447. }
  4448. /**
  4449. * Starts or stops the recording for the conference.
  4450. */
  4451. function toggleRecording() {
  4452. APP.xmpp.toggleRecording(function (callback) {
  4453. var msg = APP.translation.generateTranslatonHTML(
  4454. "dialog.recordingToken");
  4455. var token = APP.translation.translateString("dialog.token");
  4456. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4457. '<h2>' + msg + '</h2>' +
  4458. '<input name="recordingToken" type="text" ' +
  4459. ' data-i18n="[placeholder]dialog.token" ' +
  4460. 'placeholder="' + token + '" autofocus>',
  4461. false,
  4462. "dialog.Save",
  4463. function (e, v, m, f) {
  4464. if (v) {
  4465. var token = f.recordingToken;
  4466. if (token) {
  4467. callback(UIUtil.escapeHtml(token));
  4468. }
  4469. }
  4470. },
  4471. null,
  4472. function () { },
  4473. ':input:first'
  4474. );
  4475. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4476. }
  4477. /**
  4478. * Locks / unlocks the room.
  4479. */
  4480. function lockRoom(lock) {
  4481. var currentSharedKey = '';
  4482. if (lock)
  4483. currentSharedKey = sharedKey;
  4484. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4485. // password is required
  4486. if (sharedKey)
  4487. {
  4488. console.log('set room password');
  4489. Toolbar.lockLockButton();
  4490. }
  4491. else
  4492. {
  4493. console.log('removed room password');
  4494. Toolbar.unlockLockButton();
  4495. }
  4496. }, function (err) {
  4497. console.warn('setting password failed', err);
  4498. messageHandler.showError("dialog.lockTitle",
  4499. "dialog.lockMessage");
  4500. Toolbar.setSharedKey('');
  4501. }, function () {
  4502. console.warn('room passwords not supported');
  4503. messageHandler.showError("dialog.warning",
  4504. "dialog.passwordNotSupported");
  4505. Toolbar.setSharedKey('');
  4506. });
  4507. };
  4508. /**
  4509. * Invite participants to conference.
  4510. */
  4511. function inviteParticipants() {
  4512. if (roomUrl === null)
  4513. return;
  4514. var sharedKeyText = "";
  4515. if (sharedKey && sharedKey.length > 0) {
  4516. sharedKeyText =
  4517. APP.translation.translateString("email.sharedKey",
  4518. {sharedKey: sharedKey});
  4519. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4520. }
  4521. var supportedBrowsers = "Chromium, Google Chrome " +
  4522. APP.translation.translateString("email.and") + " Opera";
  4523. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4524. var subject = APP.translation.translateString("email.subject",
  4525. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4526. var body = APP.translation.translateString("email.body",
  4527. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4528. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4529. body = body.replace(/\n/g, "%0D%0A");
  4530. if (window.localStorage.displayname) {
  4531. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4532. }
  4533. if (interfaceConfig.INVITATION_POWERED_BY) {
  4534. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4535. }
  4536. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4537. }
  4538. function callSipButtonClicked()
  4539. {
  4540. var defaultNumber
  4541. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4542. var sipMsg = APP.translation.generateTranslatonHTML(
  4543. "dialog.sipMsg");
  4544. messageHandler.openTwoButtonDialog(null, null, null,
  4545. '<h2>' + sipMsg + '</h2>' +
  4546. '<input name="sipNumber" type="text"' +
  4547. ' value="' + defaultNumber + '" autofocus>',
  4548. false,
  4549. "dialog.Dial",
  4550. function (e, v, m, f) {
  4551. if (v) {
  4552. var numberInput = f.sipNumber;
  4553. if (numberInput) {
  4554. APP.xmpp.dial(
  4555. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4556. }
  4557. }
  4558. },
  4559. null, null, ':input:first'
  4560. );
  4561. }
  4562. var Toolbar = (function (my) {
  4563. my.init = function (ui) {
  4564. for(var k in buttonHandlers)
  4565. $("#" + k).click(buttonHandlers[k]);
  4566. UI = ui;
  4567. // Update login info
  4568. APP.xmpp.addListener(
  4569. AuthenticationEvents.IDENTITY_UPDATED,
  4570. function (authenticationEnabled, userIdentity) {
  4571. var loggedIn = false;
  4572. if (userIdentity) {
  4573. loggedIn = true;
  4574. }
  4575. Toolbar.showAuthenticateButton(authenticationEnabled);
  4576. if (authenticationEnabled) {
  4577. Toolbar.setAuthenticatedIdentity(userIdentity);
  4578. Toolbar.showLoginButton(!loggedIn);
  4579. Toolbar.showLogoutButton(loggedIn);
  4580. }
  4581. }
  4582. );
  4583. },
  4584. /**
  4585. * Sets shared key
  4586. * @param sKey the shared key
  4587. */
  4588. my.setSharedKey = function (sKey) {
  4589. sharedKey = sKey;
  4590. };
  4591. my.authenticateClicked = function () {
  4592. Authentication.focusAuthenticationWindow();
  4593. if (!APP.xmpp.isExternalAuthEnabled()) {
  4594. Authentication.xmppAuthenticate();
  4595. return;
  4596. }
  4597. // Get authentication URL
  4598. if (!APP.xmpp.getMUCJoined()) {
  4599. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4600. // If conference has not been started yet - redirect to login page
  4601. window.location.href = url;
  4602. });
  4603. } else {
  4604. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4605. // Otherwise - open popup with authentication URL
  4606. var authenticationWindow = Authentication.createAuthenticationWindow(
  4607. function () {
  4608. // On popup closed - retry room allocation
  4609. APP.xmpp.allocateConferenceFocus(
  4610. APP.UI.getRoomName(),
  4611. function () { console.info("AUTH DONE"); }
  4612. );
  4613. }, url);
  4614. if (!authenticationWindow) {
  4615. messageHandler.openMessageDialog(
  4616. null, "dialog.popupError");
  4617. }
  4618. });
  4619. }
  4620. };
  4621. /**
  4622. * Updates the room invite url.
  4623. */
  4624. my.updateRoomUrl = function (newRoomUrl) {
  4625. roomUrl = newRoomUrl;
  4626. // If the invite dialog has been already opened we update the information.
  4627. var inviteLink = document.getElementById('inviteLinkRef');
  4628. if (inviteLink) {
  4629. inviteLink.value = roomUrl;
  4630. inviteLink.select();
  4631. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4632. }
  4633. };
  4634. /**
  4635. * Disables and enables some of the buttons.
  4636. */
  4637. my.setupButtonsFromConfig = function () {
  4638. if (config.disablePrezi)
  4639. {
  4640. $("#prezi_button").css({display: "none"});
  4641. }
  4642. };
  4643. /**
  4644. * Opens the lock room dialog.
  4645. */
  4646. my.openLockDialog = function () {
  4647. // Only the focus is able to set a shared key.
  4648. if (!APP.xmpp.isModerator()) {
  4649. if (sharedKey) {
  4650. messageHandler.openMessageDialog(null,
  4651. "dialog.passwordError");
  4652. } else {
  4653. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4654. }
  4655. } else {
  4656. if (sharedKey) {
  4657. messageHandler.openTwoButtonDialog(null, null,
  4658. "dialog.passwordCheck",
  4659. null,
  4660. false,
  4661. "dialog.Remove",
  4662. function (e, v) {
  4663. if (v) {
  4664. Toolbar.setSharedKey('');
  4665. lockRoom(false);
  4666. }
  4667. });
  4668. } else {
  4669. var msg = APP.translation.generateTranslatonHTML(
  4670. "dialog.passwordMsg");
  4671. var yourPassword = APP.translation.translateString(
  4672. "dialog.yourPassword");
  4673. messageHandler.openTwoButtonDialog(null, null, null,
  4674. '<h2>' + msg + '</h2>' +
  4675. '<input name="lockKey" type="text"' +
  4676. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4677. 'placeholder="' + yourPassword + '" autofocus>',
  4678. false,
  4679. "dialog.Save",
  4680. function (e, v, m, f) {
  4681. if (v) {
  4682. var lockKey = f.lockKey;
  4683. if (lockKey) {
  4684. Toolbar.setSharedKey(
  4685. UIUtil.escapeHtml(lockKey));
  4686. lockRoom(true);
  4687. }
  4688. }
  4689. },
  4690. null, null, 'input:first'
  4691. );
  4692. }
  4693. }
  4694. };
  4695. /**
  4696. * Opens the invite link dialog.
  4697. */
  4698. my.openLinkDialog = function () {
  4699. var inviteAttreibutes;
  4700. if (roomUrl === null) {
  4701. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4702. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4703. } else {
  4704. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4705. }
  4706. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4707. null, null,
  4708. '<input id="inviteLinkRef" type="text" ' +
  4709. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4710. false,
  4711. "dialog.Invite",
  4712. function (e, v) {
  4713. if (v) {
  4714. if (roomUrl) {
  4715. inviteParticipants();
  4716. }
  4717. }
  4718. },
  4719. function () {
  4720. if (roomUrl) {
  4721. document.getElementById('inviteLinkRef').select();
  4722. } else {
  4723. document.getElementById('jqi_state0_buttonInvite')
  4724. .disabled = true;
  4725. }
  4726. }
  4727. );
  4728. };
  4729. /**
  4730. * Opens the settings dialog.
  4731. * FIXME: not used ?
  4732. */
  4733. my.openSettingsDialog = function () {
  4734. var settings1 = APP.translation.generateTranslatonHTML(
  4735. "dialog.settings1");
  4736. var settings2 = APP.translation.generateTranslatonHTML(
  4737. "dialog.settings2");
  4738. var settings3 = APP.translation.generateTranslatonHTML(
  4739. "dialog.settings3");
  4740. var yourPassword = APP.translation.translateString(
  4741. "dialog.yourPassword");
  4742. messageHandler.openTwoButtonDialog(null,
  4743. '<h2>' + settings1 + '</h2>' +
  4744. '<input type="checkbox" id="initMuted">' +
  4745. settings2 + '<br/>' +
  4746. '<input type="checkbox" id="requireNicknames">' +
  4747. settings3 +
  4748. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4749. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4750. null,
  4751. null,
  4752. false,
  4753. "dialog.Save",
  4754. function () {
  4755. document.getElementById('lockKey').focus();
  4756. },
  4757. function (e, v) {
  4758. if (v) {
  4759. if ($('#initMuted').is(":checked")) {
  4760. // it is checked
  4761. }
  4762. if ($('#requireNicknames').is(":checked")) {
  4763. // it is checked
  4764. }
  4765. /*
  4766. var lockKey = document.getElementById('lockKey');
  4767. if (lockKey.value) {
  4768. setSharedKey(lockKey.value);
  4769. lockRoom(true);
  4770. }
  4771. */
  4772. }
  4773. }
  4774. );
  4775. };
  4776. /**
  4777. * Toggles the application in and out of full screen mode
  4778. * (a.k.a. presentation mode in Chrome).
  4779. */
  4780. my.toggleFullScreen = function () {
  4781. var fsElement = document.documentElement;
  4782. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4783. //Enter Full Screen
  4784. if (fsElement.mozRequestFullScreen) {
  4785. fsElement.mozRequestFullScreen();
  4786. }
  4787. else {
  4788. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4789. }
  4790. } else {
  4791. //Exit Full Screen
  4792. if (document.mozCancelFullScreen) {
  4793. document.mozCancelFullScreen();
  4794. } else {
  4795. document.webkitCancelFullScreen();
  4796. }
  4797. }
  4798. };
  4799. /**
  4800. * Unlocks the lock button state.
  4801. */
  4802. my.unlockLockButton = function () {
  4803. if ($("#lockIcon").hasClass("icon-security-locked"))
  4804. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4805. };
  4806. /**
  4807. * Updates the lock button state to locked.
  4808. */
  4809. my.lockLockButton = function () {
  4810. if ($("#lockIcon").hasClass("icon-security"))
  4811. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4812. };
  4813. /**
  4814. * Shows or hides authentication button
  4815. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4816. */
  4817. my.showAuthenticateButton = function (show) {
  4818. if (show) {
  4819. $('#authentication').css({display: "inline"});
  4820. }
  4821. else {
  4822. $('#authentication').css({display: "none"});
  4823. }
  4824. };
  4825. // Shows or hides the 'recording' button.
  4826. my.showRecordingButton = function (show) {
  4827. if (!config.enableRecording) {
  4828. return;
  4829. }
  4830. if (show) {
  4831. $('#recording').css({display: "inline"});
  4832. }
  4833. else {
  4834. $('#recording').css({display: "none"});
  4835. }
  4836. };
  4837. // Sets the state of the recording button
  4838. my.setRecordingButtonState = function (isRecording) {
  4839. if (isRecording) {
  4840. $('#recordButton').removeClass("icon-recEnable");
  4841. $('#recordButton').addClass("icon-recEnable active");
  4842. } else {
  4843. $('#recordButton').removeClass("icon-recEnable active");
  4844. $('#recordButton').addClass("icon-recEnable");
  4845. }
  4846. };
  4847. // Shows or hides SIP calls button
  4848. my.showSipCallButton = function (show) {
  4849. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4850. $('#sipCallButton').css({display: "inline-block"});
  4851. } else {
  4852. $('#sipCallButton').css({display: "none"});
  4853. }
  4854. };
  4855. /**
  4856. * Displays user authenticated identity name(login).
  4857. * @param authIdentity identity name to be displayed.
  4858. */
  4859. my.setAuthenticatedIdentity = function (authIdentity) {
  4860. if (authIdentity) {
  4861. $('#toolbar_auth_identity').css({display: "list-item"});
  4862. $('#toolbar_auth_identity').text(authIdentity);
  4863. } else {
  4864. $('#toolbar_auth_identity').css({display: "none"});
  4865. }
  4866. };
  4867. /**
  4868. * Shows/hides login button.
  4869. * @param show <tt>true</tt> to show
  4870. */
  4871. my.showLoginButton = function (show) {
  4872. if (show) {
  4873. $('#toolbar_button_login').css({display: "list-item"});
  4874. } else {
  4875. $('#toolbar_button_login').css({display: "none"});
  4876. }
  4877. };
  4878. /**
  4879. * Shows/hides logout button.
  4880. * @param show <tt>true</tt> to show
  4881. */
  4882. my.showLogoutButton = function (show) {
  4883. if (show) {
  4884. $('#toolbar_button_logout').css({display: "list-item"});
  4885. } else {
  4886. $('#toolbar_button_logout').css({display: "none"});
  4887. }
  4888. };
  4889. /**
  4890. * Sets the state of the button. The button has blue glow if desktop
  4891. * streaming is active.
  4892. * @param active the state of the desktop streaming.
  4893. */
  4894. my.changeDesktopSharingButtonState = function (active) {
  4895. var button = $("#desktopsharing > a");
  4896. if (active)
  4897. {
  4898. button.addClass("glow");
  4899. }
  4900. else
  4901. {
  4902. button.removeClass("glow");
  4903. }
  4904. };
  4905. return my;
  4906. }(Toolbar || {}));
  4907. module.exports = Toolbar;
  4908. },{"../../../service/authentication/AuthenticationEvents":94,"../authentication/Authentication":11,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/SidePanelToggler":17,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){
  4909. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4910. var toolbarTimeoutObject,
  4911. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4912. function showDesktopSharingButton() {
  4913. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4914. $('#desktopsharing').css({display: "inline"});
  4915. } else {
  4916. $('#desktopsharing').css({display: "none"});
  4917. }
  4918. }
  4919. /**
  4920. * Hides the toolbar.
  4921. */
  4922. function hideToolbar() {
  4923. var header = $("#header"),
  4924. bottomToolbar = $("#bottomToolbar");
  4925. var isToolbarHover = false;
  4926. header.find('*').each(function () {
  4927. var id = $(this).attr('id');
  4928. if ($("#" + id + ":hover").length > 0) {
  4929. isToolbarHover = true;
  4930. }
  4931. });
  4932. if ($("#bottomToolbar:hover").length > 0) {
  4933. isToolbarHover = true;
  4934. }
  4935. clearTimeout(toolbarTimeoutObject);
  4936. toolbarTimeoutObject = null;
  4937. if (!isToolbarHover) {
  4938. header.hide("slide", { direction: "up", duration: 300});
  4939. $('#subject').animate({top: "-=40"}, 300);
  4940. if ($("#remoteVideos").hasClass("hidden")) {
  4941. bottomToolbar.hide(
  4942. "slide", {direction: "right", duration: 300});
  4943. }
  4944. }
  4945. else {
  4946. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4947. }
  4948. }
  4949. var ToolbarToggler = {
  4950. /**
  4951. * Shows the main toolbar.
  4952. */
  4953. showToolbar: function () {
  4954. var header = $("#header"),
  4955. bottomToolbar = $("#bottomToolbar");
  4956. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4957. header.show("slide", { direction: "up", duration: 300});
  4958. $('#subject').animate({top: "+=40"}, 300);
  4959. if (!bottomToolbar.is(":visible")) {
  4960. bottomToolbar.show(
  4961. "slide", {direction: "right", duration: 300});
  4962. }
  4963. if (toolbarTimeoutObject) {
  4964. clearTimeout(toolbarTimeoutObject);
  4965. toolbarTimeoutObject = null;
  4966. }
  4967. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4968. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4969. }
  4970. if (APP.xmpp.isModerator())
  4971. {
  4972. // TODO: Enable settings functionality.
  4973. // Need to uncomment the settings button in index.html.
  4974. // $('#settingsButton').css({visibility:"visible"});
  4975. }
  4976. // Show/hide desktop sharing button
  4977. showDesktopSharingButton();
  4978. },
  4979. /**
  4980. * Docks/undocks the toolbar.
  4981. *
  4982. * @param isDock indicates what operation to perform
  4983. */
  4984. dockToolbar: function (isDock) {
  4985. if (isDock) {
  4986. // First make sure the toolbar is shown.
  4987. if (!$('#header').is(':visible')) {
  4988. this.showToolbar();
  4989. }
  4990. // Then clear the time out, to dock the toolbar.
  4991. if (toolbarTimeoutObject) {
  4992. clearTimeout(toolbarTimeoutObject);
  4993. toolbarTimeoutObject = null;
  4994. }
  4995. }
  4996. else {
  4997. if (!$('#header').is(':visible')) {
  4998. this.showToolbar();
  4999. }
  5000. else {
  5001. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5002. }
  5003. }
  5004. },
  5005. showDesktopSharingButton: showDesktopSharingButton
  5006. };
  5007. module.exports = ToolbarToggler;
  5008. },{}],27:[function(require,module,exports){
  5009. var JitsiPopover = (function () {
  5010. /**
  5011. * Constructs new JitsiPopover and attaches it to the element
  5012. * @param element jquery selector
  5013. * @param options the options for the popover.
  5014. * @constructor
  5015. */
  5016. function JitsiPopover(element, options)
  5017. {
  5018. this.options = {
  5019. skin: "white",
  5020. content: ""
  5021. };
  5022. if(options)
  5023. {
  5024. if(options.skin)
  5025. this.options.skin = options.skin;
  5026. if(options.content)
  5027. this.options.content = options.content;
  5028. }
  5029. this.elementIsHovered = false;
  5030. this.popoverIsHovered = false;
  5031. this.popoverShown = false;
  5032. element.data("jitsi_popover", this);
  5033. this.element = element;
  5034. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5035. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5036. '<div class="jitsiPopupmenuPadding"></div></div>';
  5037. var self = this;
  5038. this.element.on("mouseenter", function () {
  5039. self.elementIsHovered = true;
  5040. self.show();
  5041. }).on("mouseleave", function () {
  5042. self.elementIsHovered = false;
  5043. setTimeout(function () {
  5044. self.hide();
  5045. }, 10);
  5046. });
  5047. }
  5048. /**
  5049. * Shows the popover
  5050. */
  5051. JitsiPopover.prototype.show = function () {
  5052. this.createPopover();
  5053. this.popoverShown = true;
  5054. };
  5055. /**
  5056. * Hides the popover
  5057. */
  5058. JitsiPopover.prototype.hide = function () {
  5059. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5060. {
  5061. this.forceHide();
  5062. }
  5063. };
  5064. /**
  5065. * Hides the popover
  5066. */
  5067. JitsiPopover.prototype.forceHide = function () {
  5068. $(".jitsipopover").remove();
  5069. this.popoverShown = false;
  5070. };
  5071. /**
  5072. * Creates the popover html
  5073. */
  5074. JitsiPopover.prototype.createPopover = function () {
  5075. $("body").append(this.template);
  5076. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5077. var self = this;
  5078. $(".jitsipopover").on("mouseenter", function () {
  5079. self.popoverIsHovered = true;
  5080. }).on("mouseleave", function () {
  5081. self.popoverIsHovered = false;
  5082. self.hide();
  5083. });
  5084. this.refreshPosition();
  5085. };
  5086. /**
  5087. * Refreshes the position of the popover
  5088. */
  5089. JitsiPopover.prototype.refreshPosition = function () {
  5090. $(".jitsipopover").position({
  5091. my: "bottom",
  5092. at: "top",
  5093. collision: "fit",
  5094. of: this.element,
  5095. using: function (position, elements) {
  5096. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5097. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5098. $(".jitsipopover > .arrow").css({left: calcLeft});
  5099. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5100. }
  5101. });
  5102. };
  5103. /**
  5104. * Updates the content of popover.
  5105. * @param content new content
  5106. */
  5107. JitsiPopover.prototype.updateContent = function (content) {
  5108. this.options.content = content;
  5109. if(!this.popoverShown)
  5110. return;
  5111. $(".jitsipopover").remove();
  5112. this.createPopover();
  5113. };
  5114. return JitsiPopover;
  5115. })();
  5116. module.exports = JitsiPopover;
  5117. },{}],28:[function(require,module,exports){
  5118. /* global $, APP, jQuery, toastr */
  5119. var messageHandler = (function(my) {
  5120. /**
  5121. * Shows a message to the user.
  5122. *
  5123. * @param titleString the title of the message
  5124. * @param messageString the text of the message
  5125. */
  5126. my.openMessageDialog = function(titleKey, messageKey) {
  5127. var title = null;
  5128. if(titleKey)
  5129. {
  5130. title = APP.translation.generateTranslatonHTML(titleKey);
  5131. }
  5132. var message = APP.translation.generateTranslatonHTML(messageKey);
  5133. $.prompt(message,
  5134. {
  5135. title: title,
  5136. persistent: false
  5137. }
  5138. );
  5139. };
  5140. /**
  5141. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5142. *
  5143. * @param titleString the title of the message
  5144. * @param msgString the text of the message
  5145. * @param persistent boolean value which determines whether the message is persistent or not
  5146. * @param leftButton the fist button's text
  5147. * @param submitFunction function to be called on submit
  5148. * @param loadedFunction function to be called after the prompt is fully loaded
  5149. * @param closeFunction function to be called after the prompt is closed
  5150. * @param focus optional focus selector or button index to be focused after
  5151. * the dialog is opened
  5152. * @param defaultButton index of default button which will be activated when
  5153. * the user press 'enter'. Indexed from 0.
  5154. */
  5155. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5156. persistent, leftButtonKey, submitFunction, loadedFunction,
  5157. closeFunction, focus, defaultButton)
  5158. {
  5159. var buttons = [];
  5160. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5161. buttons.push({ title: leftButton, value: true});
  5162. var cancelButton
  5163. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5164. buttons.push({title: cancelButton, value: false});
  5165. var message = msgString, title = titleString;
  5166. if (titleKey)
  5167. {
  5168. title = APP.translation.generateTranslatonHTML(titleKey);
  5169. }
  5170. if (msgKey) {
  5171. message = APP.translation.generateTranslatonHTML(msgKey);
  5172. }
  5173. $.prompt(message, {
  5174. title: title,
  5175. persistent: false,
  5176. buttons: buttons,
  5177. defaultButton: defaultButton,
  5178. focus: focus,
  5179. loaded: loadedFunction,
  5180. submit: submitFunction,
  5181. close: closeFunction
  5182. });
  5183. };
  5184. /**
  5185. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5186. *
  5187. * @param titleString the title of the message
  5188. * @param msgString the text of the message
  5189. * @param persistent boolean value which determines whether the message is persistent or not
  5190. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5191. * that will be passed to submitFunction
  5192. * @param submitFunction function to be called on submit
  5193. * @param loadedFunction function to be called after the prompt is fully loaded
  5194. */
  5195. my.openDialog = function (titleString, msgString, persistent, buttons,
  5196. submitFunction, loadedFunction) {
  5197. var args = {
  5198. title: titleString,
  5199. persistent: persistent,
  5200. buttons: buttons,
  5201. defaultButton: 1,
  5202. loaded: loadedFunction,
  5203. submit: submitFunction
  5204. };
  5205. if (persistent) {
  5206. args.closeText = '';
  5207. }
  5208. return new Impromptu(msgString, args);
  5209. };
  5210. /**
  5211. * Closes currently opened dialog.
  5212. */
  5213. my.closeDialog = function () {
  5214. $.prompt.close();
  5215. };
  5216. /**
  5217. * Shows a dialog with different states to the user.
  5218. *
  5219. * @param statesObject object containing all the states of the dialog
  5220. */
  5221. my.openDialogWithStates = function (statesObject, options) {
  5222. return new Impromptu(statesObject, options);
  5223. };
  5224. /**
  5225. * Opens new popup window for given <tt>url</tt> centered over current
  5226. * window.
  5227. *
  5228. * @param url the URL to be displayed in the popup window
  5229. * @param w the width of the popup window
  5230. * @param h the height of the popup window
  5231. * @param onPopupClosed optional callback function called when popup window
  5232. * has been closed.
  5233. *
  5234. * @returns popup window object if opened successfully or undefined
  5235. * in case we failed to open it(popup blocked)
  5236. */
  5237. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5238. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5239. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5240. var popup = window.open(
  5241. url, '_blank',
  5242. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5243. if (popup && onPopupClosed) {
  5244. var pollTimer = window.setInterval(function () {
  5245. if (popup.closed !== false) {
  5246. window.clearInterval(pollTimer);
  5247. onPopupClosed();
  5248. }
  5249. }, 200);
  5250. }
  5251. return popup;
  5252. };
  5253. /**
  5254. * Shows a dialog prompting the user to send an error report.
  5255. *
  5256. * @param titleString the title of the message
  5257. * @param msgString the text of the message
  5258. * @param error the error that is being reported
  5259. */
  5260. my.openReportDialog = function(titleKey, msgKey, error) {
  5261. my.openMessageDialog(titleKey, msgKey);
  5262. console.log(error);
  5263. //FIXME send the error to the server
  5264. };
  5265. /**
  5266. * Shows an error dialog to the user.
  5267. * @param title the title of the message
  5268. * @param message the text of the messafe
  5269. */
  5270. my.showError = function(titleKey, msgKey) {
  5271. if(!titleKey) {
  5272. titleKey = "dialog.oops";
  5273. }
  5274. if(!msgKey)
  5275. {
  5276. msgKey = "dialog.defaultError";
  5277. }
  5278. messageHandler.openMessageDialog(titleKey, msgKey);
  5279. };
  5280. my.notify = function(displayName, displayNameKey,
  5281. cls, messageKey, messageArguments) {
  5282. var displayNameSpan = '<span class="nickname" ';
  5283. if(displayName)
  5284. {
  5285. displayNameSpan += ">" + displayName;
  5286. }
  5287. else
  5288. {
  5289. displayNameSpan += "data-i18n='" + displayNameKey +
  5290. "'>" + APP.translation.translateString(displayNameKey);
  5291. }
  5292. displayNameSpan += "</span>";
  5293. toastr.info(
  5294. displayNameSpan + '<br>' +
  5295. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5296. (messageArguments?
  5297. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5298. : "") + ">" +
  5299. APP.translation.translateString(messageKey,
  5300. messageArguments) +
  5301. '</span>');
  5302. };
  5303. return my;
  5304. }(messageHandler || {}));
  5305. module.exports = messageHandler;
  5306. },{}],29:[function(require,module,exports){
  5307. var UIEvents = require("../../../service/UI/UIEvents");
  5308. var nickname = null;
  5309. var eventEmitter = null;
  5310. var NickanameHandler = {
  5311. init: function (emitter) {
  5312. eventEmitter = emitter;
  5313. var storedDisplayName = window.localStorage.displayname;
  5314. if (storedDisplayName) {
  5315. nickname = storedDisplayName;
  5316. }
  5317. },
  5318. setNickname: function (newNickname) {
  5319. if (!newNickname || nickname === newNickname)
  5320. return;
  5321. nickname = newNickname;
  5322. window.localStorage.displayname = nickname;
  5323. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5324. },
  5325. getNickname: function () {
  5326. return nickname;
  5327. },
  5328. addListener: function (type, listener) {
  5329. eventEmitter.on(type, listener);
  5330. }
  5331. };
  5332. module.exports = NickanameHandler;
  5333. },{"../../../service/UI/UIEvents":93}],30:[function(require,module,exports){
  5334. /**
  5335. * Created by hristo on 12/22/14.
  5336. */
  5337. module.exports = {
  5338. /**
  5339. * Returns the available video width.
  5340. */
  5341. getAvailableVideoWidth: function () {
  5342. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5343. var rightPanelWidth
  5344. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5345. return window.innerWidth - rightPanelWidth;
  5346. },
  5347. /**
  5348. * Changes the style class of the element given by id.
  5349. */
  5350. buttonClick: function(id, classname) {
  5351. $(id).toggleClass(classname); // add the class to the clicked element
  5352. },
  5353. /**
  5354. * Returns the text width for the given element.
  5355. *
  5356. * @param el the element
  5357. */
  5358. getTextWidth: function (el) {
  5359. return (el.clientWidth + 1);
  5360. },
  5361. /**
  5362. * Returns the text height for the given element.
  5363. *
  5364. * @param el the element
  5365. */
  5366. getTextHeight: function (el) {
  5367. return (el.clientHeight + 1);
  5368. },
  5369. /**
  5370. * Plays the sound given by id.
  5371. *
  5372. * @param id the identifier of the audio element.
  5373. */
  5374. playSoundNotification: function (id) {
  5375. document.getElementById(id).play();
  5376. },
  5377. /**
  5378. * Escapes the given text.
  5379. */
  5380. escapeHtml: function (unsafeText) {
  5381. return $('<div/>').text(unsafeText).html();
  5382. },
  5383. imageToGrayScale: function (canvas) {
  5384. var context = canvas.getContext('2d');
  5385. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5386. var pixels = imgData.data;
  5387. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5388. var grayscale
  5389. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5390. pixels[i ] = grayscale; // red
  5391. pixels[i+1] = grayscale; // green
  5392. pixels[i+2] = grayscale; // blue
  5393. // pixels[i+3] is alpha
  5394. }
  5395. // redraw the image in black & white
  5396. context.putImageData(imgData, 0, 0);
  5397. },
  5398. setTooltip: function (element, key, position) {
  5399. element.setAttribute("data-i18n", "[data-content]" + key);
  5400. element.setAttribute("data-toggle", "popover");
  5401. element.setAttribute("data-placement", position);
  5402. element.setAttribute("data-html", true);
  5403. element.setAttribute("data-container", "body");
  5404. }
  5405. };
  5406. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5407. var JitsiPopover = require("../util/JitsiPopover");
  5408. /**
  5409. * Constructs new connection indicator.
  5410. * @param videoContainer the video container associated with the indicator.
  5411. * @constructor
  5412. */
  5413. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5414. {
  5415. this.videoContainer = videoContainer;
  5416. this.bandwidth = null;
  5417. this.packetLoss = null;
  5418. this.bitrate = null;
  5419. this.showMoreValue = false;
  5420. this.resolution = null;
  5421. this.transport = [];
  5422. this.popover = null;
  5423. this.jid = jid;
  5424. this.create();
  5425. this.videoLayout = VideoLayout;
  5426. }
  5427. /**
  5428. * Values for the connection quality
  5429. * @type {{98: string,
  5430. * 81: string,
  5431. * 64: string,
  5432. * 47: string,
  5433. * 30: string,
  5434. * 0: string}}
  5435. */
  5436. ConnectionIndicator.connectionQualityValues = {
  5437. 98: "18px", //full
  5438. 81: "15px",//4 bars
  5439. 64: "11px",//3 bars
  5440. 47: "7px",//2 bars
  5441. 30: "3px",//1 bar
  5442. 0: "0px"//empty
  5443. };
  5444. ConnectionIndicator.getIP = function(value)
  5445. {
  5446. return value.substring(0, value.lastIndexOf(":"));
  5447. };
  5448. ConnectionIndicator.getPort = function(value)
  5449. {
  5450. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5451. };
  5452. ConnectionIndicator.getStringFromArray = function (array) {
  5453. var res = "";
  5454. for(var i = 0; i < array.length; i++)
  5455. {
  5456. res += (i === 0? "" : ", ") + array[i];
  5457. }
  5458. return res;
  5459. };
  5460. /**
  5461. * Generates the html content.
  5462. * @returns {string} the html content.
  5463. */
  5464. ConnectionIndicator.prototype.generateText = function () {
  5465. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5466. var translate = APP.translation.translateString;
  5467. if(this.bitrate === null)
  5468. {
  5469. downloadBitrate = "N/A";
  5470. uploadBitrate = "N/A";
  5471. }
  5472. else
  5473. {
  5474. downloadBitrate =
  5475. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5476. uploadBitrate =
  5477. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5478. }
  5479. if(this.packetLoss === null)
  5480. {
  5481. packetLoss = "N/A";
  5482. }
  5483. else
  5484. {
  5485. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5486. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5487. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5488. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5489. }
  5490. var resolutionValue = null;
  5491. if(this.resolution && this.jid != null)
  5492. {
  5493. var keys = Object.keys(this.resolution);
  5494. if(keys.length == 1)
  5495. {
  5496. for(var ssrc in this.resolution)
  5497. {
  5498. resolutionValue = this.resolution[ssrc];
  5499. }
  5500. }
  5501. else if(keys.length > 1)
  5502. {
  5503. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5504. resolutionValue = this.resolution[displayedSsrc];
  5505. }
  5506. }
  5507. if(this.jid === null)
  5508. {
  5509. resolution = "";
  5510. if(this.resolution === null || !Object.keys(this.resolution) ||
  5511. Object.keys(this.resolution).length === 0)
  5512. {
  5513. resolution = "N/A";
  5514. }
  5515. else
  5516. for(i in this.resolution)
  5517. {
  5518. resolutionValue = this.resolution[i];
  5519. if(resolutionValue)
  5520. {
  5521. if(resolutionValue.height &&
  5522. resolutionValue.width)
  5523. {
  5524. resolution += (resolution === ""? "" : ", ") +
  5525. resolutionValue.width + "x" +
  5526. resolutionValue.height;
  5527. }
  5528. }
  5529. }
  5530. }
  5531. else if(!resolutionValue ||
  5532. !resolutionValue.height ||
  5533. !resolutionValue.width)
  5534. {
  5535. resolution = "N/A";
  5536. }
  5537. else
  5538. {
  5539. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5540. }
  5541. var result = "<table style='width:100%'>" +
  5542. "<tr>" +
  5543. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5544. translate("connectionindicator.bitrate") + "</span></td>" +
  5545. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5546. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5547. uploadBitrate + "</td>" +
  5548. "</tr><tr>" +
  5549. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5550. translate("connectionindicator.packetloss") + "</span></td>" +
  5551. "<td>" + packetLoss + "</td>" +
  5552. "</tr><tr>" +
  5553. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5554. translate("connectionindicator.resolution") + "</span></td>" +
  5555. "<td>" + resolution + "</td></tr></table>";
  5556. if(this.videoContainer.id == "localVideoContainer") {
  5557. result += "<div class=\"jitsipopover_showmore\" " +
  5558. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5559. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5560. (this.showMoreValue ? "less" : "more") + "'>" +
  5561. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5562. "</div><br />";
  5563. }
  5564. if(this.showMoreValue)
  5565. {
  5566. var downloadBandwidth, uploadBandwidth, transport;
  5567. if(this.bandwidth === null)
  5568. {
  5569. downloadBandwidth = "N/A";
  5570. uploadBandwidth = "N/A";
  5571. }
  5572. else
  5573. {
  5574. downloadBandwidth = this.bandwidth.download?
  5575. this.bandwidth.download + " Kbps" :
  5576. "N/A";
  5577. uploadBandwidth = this.bandwidth.upload?
  5578. this.bandwidth.upload + " Kbps" :
  5579. "N/A";
  5580. }
  5581. if(!this.transport || this.transport.length === 0)
  5582. {
  5583. transport = "<tr>" +
  5584. "<td><span class='jitsipopover_blue' " +
  5585. "data-i18n='connectionindicator.address'>" +
  5586. translate("connectionindicator.address") + "</span></td>" +
  5587. "<td> N/A</td></tr>";
  5588. }
  5589. else
  5590. {
  5591. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5592. for(i = 0; i < this.transport.length; i++)
  5593. {
  5594. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5595. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5596. var localIP =
  5597. ConnectionIndicator.getIP(this.transport[i].localip);
  5598. var localPort =
  5599. ConnectionIndicator.getPort(this.transport[i].localip);
  5600. if(data.remoteIP.indexOf(ip) == -1)
  5601. {
  5602. data.remoteIP.push(ip);
  5603. }
  5604. if(data.remotePort.indexOf(port) == -1)
  5605. {
  5606. data.remotePort.push(port);
  5607. }
  5608. if(data.localIP.indexOf(localIP) == -1)
  5609. {
  5610. data.localIP.push(localIP);
  5611. }
  5612. if(data.localPort.indexOf(localPort) == -1)
  5613. {
  5614. data.localPort.push(localPort);
  5615. }
  5616. }
  5617. var local_address_key = "connectionindicator.localaddress";
  5618. var remote_address_key = "connectionindicator.remoteaddress";
  5619. var localTransport =
  5620. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5621. local_address_key +"' data-i18n-options='" +
  5622. JSON.stringify({count: data.localIP.length}) + "'>" +
  5623. translate(local_address_key, {count: data.localIP.length}) +
  5624. "</span></td><td> " +
  5625. ConnectionIndicator.getStringFromArray(data.localIP) +
  5626. "</td></tr>";
  5627. transport =
  5628. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5629. remote_address_key + "' data-i18n-options='" +
  5630. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5631. translate(remote_address_key,
  5632. {count: data.remoteIP.length}) +
  5633. "</span></td><td> " +
  5634. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5635. "</td></tr>";
  5636. var key_remote = "connectionindicator.remoteport",
  5637. key_local = "connectionindicator.localport";
  5638. transport += "<tr>" +
  5639. "<td>" +
  5640. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5641. "' data-i18n-options='" +
  5642. JSON.stringify({count: this.transport.length}) + "'>" +
  5643. translate(key_remote, {count: this.transport.length}) +
  5644. "</span></td><td>";
  5645. localTransport += "<tr>" +
  5646. "<td>" +
  5647. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5648. "' data-i18n-options='" +
  5649. JSON.stringify({count: this.transport.length}) + "'>" +
  5650. translate(key_local, {count: this.transport.length}) +
  5651. "</span></td><td>";
  5652. transport +=
  5653. ConnectionIndicator.getStringFromArray(data.remotePort);
  5654. localTransport +=
  5655. ConnectionIndicator.getStringFromArray(data.localPort);
  5656. transport += "</td></tr>";
  5657. transport += localTransport + "</td></tr>";
  5658. transport +="<tr>" +
  5659. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5660. translate("connectionindicator.transport") + "</span></td>" +
  5661. "<td>" + this.transport[0].type + "</td></tr>";
  5662. }
  5663. result += "<table style='width:100%'>" +
  5664. "<tr>" +
  5665. "<td>" +
  5666. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5667. translate("connectionindicator.bandwidth") + "</span>" +
  5668. "</td><td>" +
  5669. "<span class='jitsipopover_green'>&darr;</span>" +
  5670. downloadBandwidth +
  5671. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5672. uploadBandwidth + "</td></tr>";
  5673. result += transport + "</table>";
  5674. }
  5675. return result;
  5676. };
  5677. /**
  5678. * Shows or hide the additional information.
  5679. */
  5680. ConnectionIndicator.prototype.showMore = function () {
  5681. this.showMoreValue = !this.showMoreValue;
  5682. this.updatePopoverData();
  5683. };
  5684. function createIcon(classes)
  5685. {
  5686. var icon = document.createElement("span");
  5687. for(var i in classes)
  5688. {
  5689. icon.classList.add(classes[i]);
  5690. }
  5691. icon.appendChild(
  5692. document.createElement("i")).classList.add("icon-connection");
  5693. return icon;
  5694. }
  5695. /**
  5696. * Creates the indicator
  5697. */
  5698. ConnectionIndicator.prototype.create = function () {
  5699. this.connectionIndicatorContainer = document.createElement("div");
  5700. this.connectionIndicatorContainer.className = "connectionindicator";
  5701. this.connectionIndicatorContainer.style.display = "none";
  5702. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5703. this.popover = new JitsiPopover(
  5704. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5705. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5706. APP.translation.translateString("connectionindicator.na") + "</div>",
  5707. skin: "black"});
  5708. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5709. createIcon(["connection", "connection_empty"]));
  5710. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5711. createIcon(["connection", "connection_full"]));
  5712. };
  5713. /**
  5714. * Removes the indicator
  5715. */
  5716. ConnectionIndicator.prototype.remove = function()
  5717. {
  5718. this.connectionIndicatorContainer.remove();
  5719. this.popover.forceHide();
  5720. };
  5721. /**
  5722. * Updates the data of the indicator
  5723. * @param percent the percent of connection quality
  5724. * @param object the statistics data.
  5725. */
  5726. ConnectionIndicator.prototype.updateConnectionQuality =
  5727. function (percent, object) {
  5728. if(percent === null)
  5729. {
  5730. this.connectionIndicatorContainer.style.display = "none";
  5731. this.popover.forceHide();
  5732. return;
  5733. }
  5734. else
  5735. {
  5736. if(this.connectionIndicatorContainer.style.display == "none") {
  5737. this.connectionIndicatorContainer.style.display = "block";
  5738. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5739. }
  5740. }
  5741. this.bandwidth = object.bandwidth;
  5742. this.bitrate = object.bitrate;
  5743. this.packetLoss = object.packetLoss;
  5744. this.transport = object.transport;
  5745. if(object.resolution)
  5746. {
  5747. this.resolution = object.resolution;
  5748. }
  5749. for(var quality in ConnectionIndicator.connectionQualityValues)
  5750. {
  5751. if(percent >= quality)
  5752. {
  5753. this.fullIcon.style.width =
  5754. ConnectionIndicator.connectionQualityValues[quality];
  5755. }
  5756. }
  5757. this.updatePopoverData();
  5758. };
  5759. /**
  5760. * Updates the resolution
  5761. * @param resolution the new resolution
  5762. */
  5763. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5764. this.resolution = resolution;
  5765. this.updatePopoverData();
  5766. };
  5767. /**
  5768. * Updates the content of the popover
  5769. */
  5770. ConnectionIndicator.prototype.updatePopoverData = function () {
  5771. this.popover.updateContent(
  5772. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5773. APP.translation.translateElement($(".connection_info"));
  5774. };
  5775. /**
  5776. * Hides the popover
  5777. */
  5778. ConnectionIndicator.prototype.hide = function () {
  5779. this.popover.forceHide();
  5780. };
  5781. /**
  5782. * Hides the indicator
  5783. */
  5784. ConnectionIndicator.prototype.hideIndicator = function () {
  5785. this.connectionIndicatorContainer.style.display = "none";
  5786. if(this.popover)
  5787. this.popover.forceHide();
  5788. };
  5789. module.exports = ConnectionIndicator;
  5790. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5791. var AudioLevels = require("../audio_levels/AudioLevels");
  5792. var Avatar = require("../avatar/Avatar");
  5793. var Chat = require("../side_pannels/chat/Chat");
  5794. var ContactList = require("../side_pannels/contactlist/ContactList");
  5795. var UIUtil = require("../util/UIUtil");
  5796. var ConnectionIndicator = require("./ConnectionIndicator");
  5797. var NicknameHandler = require("../util/NicknameHandler");
  5798. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5799. var UIEvents = require("../../../service/UI/UIEvents");
  5800. var currentDominantSpeaker = null;
  5801. var lastNCount = config.channelLastN;
  5802. var localLastNCount = config.channelLastN;
  5803. var localLastNSet = [];
  5804. var lastNEndpointsCache = [];
  5805. var lastNPickupJid = null;
  5806. var largeVideoState = {
  5807. updateInProgress: false,
  5808. newSrc: ''
  5809. };
  5810. var eventEmitter = null;
  5811. /**
  5812. * Currently focused video "src"(displayed in large video).
  5813. * @type {String}
  5814. */
  5815. var focusedVideoInfo = null;
  5816. /**
  5817. * Indicates if we have muted our audio before the conference has started.
  5818. * @type {boolean}
  5819. */
  5820. var preMuted = false;
  5821. var mutedAudios = {};
  5822. var flipXLocalVideo = true;
  5823. var currentVideoWidth = null;
  5824. var currentVideoHeight = null;
  5825. var localVideoSrc = null;
  5826. function videoactive( videoelem) {
  5827. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5828. // ignore mixedmslabela0 and v0
  5829. videoelem.show();
  5830. VideoLayout.resizeThumbnails();
  5831. var videoParent = videoelem.parent();
  5832. var parentResourceJid = null;
  5833. if (videoParent)
  5834. parentResourceJid
  5835. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5836. // Update the large video to the last added video only if there's no
  5837. // current dominant, focused speaker or prezi playing or update it to
  5838. // the current dominant speaker.
  5839. if ((!focusedVideoInfo &&
  5840. !VideoLayout.getDominantSpeakerResourceJid() &&
  5841. !require("../prezi/Prezi").isPresentationVisible()) ||
  5842. (parentResourceJid &&
  5843. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5844. VideoLayout.updateLargeVideo(
  5845. APP.RTC.getVideoSrc(videoelem[0]),
  5846. 1,
  5847. parentResourceJid);
  5848. }
  5849. VideoLayout.showModeratorIndicator();
  5850. }
  5851. }
  5852. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5853. // XXX(gp) so, every call to this function is *always* preceded by a call
  5854. // to the RTC.attachMediaStream() function but that call is *not* followed
  5855. // by an update to the videoSrcToSsrc map!
  5856. //
  5857. // The above way of doing things results in video SRCs that don't correspond
  5858. // to any SSRC for a short period of time (to be more precise, for as long
  5859. // the waitForRemoteVideo takes to complete). This causes problems (see
  5860. // bellow).
  5861. //
  5862. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5863. // a second time in here and only then update the videoSrcToSsrc map? Why
  5864. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5865. // is called the first time? I actually do that in the lastN changed event
  5866. // handler because the "orphan" video SRC is causing troubles there. The
  5867. // purpose of this method would then be to fire the "videoactive.jingle".
  5868. //
  5869. // Food for though I guess :-)
  5870. if (selector.removed || !selector.parent().is(":visible")) {
  5871. console.warn("Media removed before had started", selector);
  5872. return;
  5873. }
  5874. if (stream.id === 'mixedmslabel') return;
  5875. if (selector[0].currentTime > 0) {
  5876. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5877. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5878. videoactive(selector);
  5879. } else {
  5880. setTimeout(function () {
  5881. waitForRemoteVideo(selector, ssrc, stream, jid);
  5882. }, 250);
  5883. }
  5884. }
  5885. /**
  5886. * Returns an array of the video horizontal and vertical indents,
  5887. * so that if fits its parent.
  5888. *
  5889. * @return an array with 2 elements, the horizontal indent and the vertical
  5890. * indent
  5891. */
  5892. function getCameraVideoPosition(videoWidth,
  5893. videoHeight,
  5894. videoSpaceWidth,
  5895. videoSpaceHeight) {
  5896. // Parent height isn't completely calculated when we position the video in
  5897. // full screen mode and this is why we use the screen height in this case.
  5898. // Need to think it further at some point and implement it properly.
  5899. var isFullScreen = document.fullScreen ||
  5900. document.mozFullScreen ||
  5901. document.webkitIsFullScreen;
  5902. if (isFullScreen)
  5903. videoSpaceHeight = window.innerHeight;
  5904. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5905. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5906. return [horizontalIndent, verticalIndent];
  5907. }
  5908. /**
  5909. * Returns an array of the video horizontal and vertical indents.
  5910. * Centers horizontally and top aligns vertically.
  5911. *
  5912. * @return an array with 2 elements, the horizontal indent and the vertical
  5913. * indent
  5914. */
  5915. function getDesktopVideoPosition(videoWidth,
  5916. videoHeight,
  5917. videoSpaceWidth,
  5918. videoSpaceHeight) {
  5919. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5920. var verticalIndent = 0;// Top aligned
  5921. return [horizontalIndent, verticalIndent];
  5922. }
  5923. /**
  5924. * Returns an array of the video dimensions, so that it covers the screen.
  5925. * It leaves no empty areas, but some parts of the video might not be visible.
  5926. *
  5927. * @return an array with 2 elements, the video width and the video height
  5928. */
  5929. function getCameraVideoSize(videoWidth,
  5930. videoHeight,
  5931. videoSpaceWidth,
  5932. videoSpaceHeight) {
  5933. if (!videoWidth)
  5934. videoWidth = currentVideoWidth;
  5935. if (!videoHeight)
  5936. videoHeight = currentVideoHeight;
  5937. var aspectRatio = videoWidth / videoHeight;
  5938. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5939. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5940. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5941. availableHeight = videoSpaceHeight;
  5942. availableWidth = availableHeight * aspectRatio;
  5943. }
  5944. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5945. availableWidth = videoSpaceWidth;
  5946. availableHeight = availableWidth / aspectRatio;
  5947. }
  5948. return [availableWidth, availableHeight];
  5949. }
  5950. /**
  5951. * Sets the display name for the given video span id.
  5952. */
  5953. function setDisplayName(videoSpanId, displayName, key) {
  5954. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5955. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  5956. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  5957. // If we already have a display name for this video.
  5958. if (nameSpan.length > 0) {
  5959. var nameSpanElement = nameSpan.get(0);
  5960. if (nameSpanElement.id === 'localDisplayName' &&
  5961. $('#localDisplayName').text() !== displayName) {
  5962. if (displayName && displayName.length > 0)
  5963. {
  5964. var meHTML = APP.translation.generateTranslatonHTML("me");
  5965. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  5966. }
  5967. else
  5968. $('#localDisplayName').html(defaultLocalDisplayName);
  5969. } else {
  5970. if (displayName && displayName.length > 0)
  5971. {
  5972. $('#' + videoSpanId + '_name').html(displayName);
  5973. }
  5974. else if (key && key.length > 0)
  5975. {
  5976. var nameHtml = APP.translation.generateTranslatonHTML(key);
  5977. $('#' + videoSpanId + '_name').html(nameHtml);
  5978. }
  5979. else
  5980. $('#' + videoSpanId + '_name').text(
  5981. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5982. }
  5983. } else {
  5984. var editButton = null;
  5985. nameSpan = document.createElement('span');
  5986. nameSpan.className = 'displayname';
  5987. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5988. if (videoSpanId === 'localVideoContainer') {
  5989. editButton = createEditDisplayNameButton();
  5990. if (displayName && displayName.length > 0) {
  5991. var meHTML = APP.translation.generateTranslatonHTML("me");
  5992. nameSpan.innerHTML = displayName + meHTML;
  5993. }
  5994. else
  5995. nameSpan.innerHTML = defaultLocalDisplayName;
  5996. }
  5997. else {
  5998. if (displayName && displayName.length > 0) {
  5999. nameSpan.innerText = displayName;
  6000. }
  6001. else
  6002. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  6003. }
  6004. if (!editButton) {
  6005. nameSpan.id = videoSpanId + '_name';
  6006. } else {
  6007. nameSpan.id = 'localDisplayName';
  6008. $('#' + videoSpanId)[0].appendChild(editButton);
  6009. //translates popover of edit button
  6010. APP.translation.translateElement($("a.displayname"));
  6011. var editableText = document.createElement('input');
  6012. editableText.className = 'displayname';
  6013. editableText.type = 'text';
  6014. editableText.id = 'editDisplayName';
  6015. if (displayName && displayName.length) {
  6016. editableText.value
  6017. = displayName;
  6018. }
  6019. var defaultNickname = APP.translation.translateString(
  6020. "defaultNickname", {name: "Jane Pink"});
  6021. editableText.setAttribute('style', 'display:none;');
  6022. editableText.setAttribute('data-18n',
  6023. '[placeholder]defaultNickname');
  6024. editableText.setAttribute("data-i18n-options",
  6025. JSON.stringify({name: "Jane Pink"}));
  6026. editableText.setAttribute("placeholder", defaultNickname);
  6027. $('#' + videoSpanId)[0].appendChild(editableText);
  6028. $('#localVideoContainer .displayname')
  6029. .bind("click", function (e) {
  6030. e.preventDefault();
  6031. e.stopPropagation();
  6032. $('#localDisplayName').hide();
  6033. $('#editDisplayName').show();
  6034. $('#editDisplayName').focus();
  6035. $('#editDisplayName').select();
  6036. $('#editDisplayName').one("focusout", function (e) {
  6037. VideoLayout.inputDisplayNameHandler(this.value);
  6038. });
  6039. $('#editDisplayName').on('keydown', function (e) {
  6040. if (e.keyCode === 13) {
  6041. e.preventDefault();
  6042. VideoLayout.inputDisplayNameHandler(this.value);
  6043. }
  6044. });
  6045. });
  6046. }
  6047. }
  6048. }
  6049. /**
  6050. * Gets the selector of video thumbnail container for the user identified by
  6051. * given <tt>userJid</tt>
  6052. * @param resourceJid user's Jid for whom we want to get the video container.
  6053. */
  6054. function getParticipantContainer(resourceJid)
  6055. {
  6056. if (!resourceJid)
  6057. return null;
  6058. if (resourceJid === APP.xmpp.myResource())
  6059. return $("#localVideoContainer");
  6060. else
  6061. return $("#participant_" + resourceJid);
  6062. }
  6063. /**
  6064. * Sets the size and position of the given video element.
  6065. *
  6066. * @param video the video element to position
  6067. * @param width the desired video width
  6068. * @param height the desired video height
  6069. * @param horizontalIndent the left and right indent
  6070. * @param verticalIndent the top and bottom indent
  6071. */
  6072. function positionVideo(video,
  6073. width,
  6074. height,
  6075. horizontalIndent,
  6076. verticalIndent) {
  6077. video.width(width);
  6078. video.height(height);
  6079. video.css({ top: verticalIndent + 'px',
  6080. bottom: verticalIndent + 'px',
  6081. left: horizontalIndent + 'px',
  6082. right: horizontalIndent + 'px'});
  6083. }
  6084. /**
  6085. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6086. * given <tt>parentElement</tt>.
  6087. *
  6088. * @param jid the jid indicating the video for which we're adding a menu.
  6089. * @param parentElement the parent element where this menu will be added
  6090. */
  6091. function addRemoteVideoMenu(jid, parentElement) {
  6092. var spanElement = document.createElement('span');
  6093. spanElement.className = 'remotevideomenu';
  6094. parentElement.appendChild(spanElement);
  6095. var menuElement = document.createElement('i');
  6096. menuElement.className = 'fa fa-angle-down';
  6097. menuElement.title = 'Remote user controls';
  6098. spanElement.appendChild(menuElement);
  6099. // <ul class="popupmenu">
  6100. // <li><a href="#">Mute</a></li>
  6101. // <li><a href="#">Eject</a></li>
  6102. // </ul>
  6103. var popupmenuElement = document.createElement('ul');
  6104. popupmenuElement.className = 'popupmenu';
  6105. popupmenuElement.id
  6106. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6107. spanElement.appendChild(popupmenuElement);
  6108. var muteMenuItem = document.createElement('li');
  6109. var muteLinkItem = document.createElement('a');
  6110. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6111. if (!mutedAudios[jid]) {
  6112. muteLinkItem.innerHTML = mutedIndicator +
  6113. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6114. muteLinkItem.className = 'mutelink';
  6115. }
  6116. else {
  6117. muteLinkItem.innerHTML = mutedIndicator +
  6118. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6119. muteLinkItem.className = 'mutelink disabled';
  6120. }
  6121. muteLinkItem.onclick = function(){
  6122. if ($(this).attr('disabled') != undefined) {
  6123. event.preventDefault();
  6124. }
  6125. var isMute = mutedAudios[jid] == true;
  6126. APP.xmpp.setMute(jid, !isMute);
  6127. popupmenuElement.setAttribute('style', 'display:none;');
  6128. if (isMute) {
  6129. this.innerHTML = mutedIndicator +
  6130. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6131. this.className = 'mutelink disabled';
  6132. }
  6133. else {
  6134. this.innerHTML = mutedIndicator +
  6135. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6136. this.className = 'mutelink';
  6137. }
  6138. };
  6139. muteMenuItem.appendChild(muteLinkItem);
  6140. popupmenuElement.appendChild(muteMenuItem);
  6141. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6142. var ejectMenuItem = document.createElement('li');
  6143. var ejectLinkItem = document.createElement('a');
  6144. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6145. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6146. ejectLinkItem.onclick = function(){
  6147. APP.xmpp.eject(jid);
  6148. popupmenuElement.setAttribute('style', 'display:none;');
  6149. };
  6150. ejectMenuItem.appendChild(ejectLinkItem);
  6151. popupmenuElement.appendChild(ejectMenuItem);
  6152. var paddingSpan = document.createElement('span');
  6153. paddingSpan.className = 'popupmenuPadding';
  6154. popupmenuElement.appendChild(paddingSpan);
  6155. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6156. }
  6157. /**
  6158. * Removes remote video menu element from video element identified by
  6159. * given <tt>videoElementId</tt>.
  6160. *
  6161. * @param videoElementId the id of local or remote video element.
  6162. */
  6163. function removeRemoteVideoMenu(videoElementId) {
  6164. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6165. if (menuSpan.length) {
  6166. menuSpan.remove();
  6167. }
  6168. }
  6169. /**
  6170. * Updates the data for the indicator
  6171. * @param id the id of the indicator
  6172. * @param percent the percent for connection quality
  6173. * @param object the data
  6174. */
  6175. function updateStatsIndicator(id, percent, object) {
  6176. if(VideoLayout.connectionIndicators[id])
  6177. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6178. }
  6179. /**
  6180. * Returns an array of the video dimensions, so that it keeps it's aspect
  6181. * ratio and fits available area with it's larger dimension. This method
  6182. * ensures that whole video will be visible and can leave empty areas.
  6183. *
  6184. * @return an array with 2 elements, the video width and the video height
  6185. */
  6186. function getDesktopVideoSize(videoWidth,
  6187. videoHeight,
  6188. videoSpaceWidth,
  6189. videoSpaceHeight) {
  6190. if (!videoWidth)
  6191. videoWidth = currentVideoWidth;
  6192. if (!videoHeight)
  6193. videoHeight = currentVideoHeight;
  6194. var aspectRatio = videoWidth / videoHeight;
  6195. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6196. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6197. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6198. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6199. {
  6200. availableHeight = videoSpaceHeight;
  6201. availableWidth = availableHeight * aspectRatio;
  6202. }
  6203. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6204. {
  6205. availableWidth = videoSpaceWidth;
  6206. availableHeight = availableWidth / aspectRatio;
  6207. }
  6208. return [availableWidth, availableHeight];
  6209. }
  6210. /**
  6211. * Creates the edit display name button.
  6212. *
  6213. * @returns the edit button
  6214. */
  6215. function createEditDisplayNameButton() {
  6216. var editButton = document.createElement('a');
  6217. editButton.className = 'displayname';
  6218. UIUtil.setTooltip(editButton,
  6219. "videothumbnail.editnickname",
  6220. "top");
  6221. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6222. return editButton;
  6223. }
  6224. /**
  6225. * Creates the element indicating the moderator(owner) of the conference.
  6226. *
  6227. * @param parentElement the parent element where the owner indicator will
  6228. * be added
  6229. */
  6230. function createModeratorIndicatorElement(parentElement) {
  6231. var moderatorIndicator = document.createElement('i');
  6232. moderatorIndicator.className = 'fa fa-star';
  6233. parentElement.appendChild(moderatorIndicator);
  6234. UIUtil.setTooltip(parentElement,
  6235. "videothumbnail.moderator",
  6236. "top");
  6237. }
  6238. var VideoLayout = (function (my) {
  6239. my.connectionIndicators = {};
  6240. // By default we use camera
  6241. my.getVideoSize = getCameraVideoSize;
  6242. my.getVideoPosition = getCameraVideoPosition;
  6243. my.init = function (emitter) {
  6244. // Listen for large video size updates
  6245. document.getElementById('largeVideo')
  6246. .addEventListener('loadedmetadata', function (e) {
  6247. currentVideoWidth = this.videoWidth;
  6248. currentVideoHeight = this.videoHeight;
  6249. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6250. });
  6251. eventEmitter = emitter;
  6252. };
  6253. my.isInLastN = function(resource) {
  6254. return lastNCount < 0 // lastN is disabled, return true
  6255. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6256. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6257. };
  6258. my.changeLocalStream = function (stream) {
  6259. VideoLayout.changeLocalVideo(stream);
  6260. };
  6261. my.changeLocalAudio = function(stream) {
  6262. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6263. document.getElementById('localAudio').autoplay = true;
  6264. document.getElementById('localAudio').volume = 0;
  6265. if (preMuted) {
  6266. if(!APP.UI.setAudioMuted(true))
  6267. {
  6268. preMuted = mute;
  6269. }
  6270. preMuted = false;
  6271. }
  6272. };
  6273. my.changeLocalVideo = function(stream) {
  6274. var flipX = true;
  6275. if(stream.videoType == "screen")
  6276. flipX = false;
  6277. var localVideo = document.createElement('video');
  6278. localVideo.id = 'localVideo_' +
  6279. APP.RTC.getStreamID(stream.getOriginalStream());
  6280. localVideo.autoplay = true;
  6281. localVideo.volume = 0; // is it required if audio is separated ?
  6282. localVideo.oncontextmenu = function () { return false; };
  6283. var localVideoContainer = document.getElementById('localVideoWrapper');
  6284. localVideoContainer.appendChild(localVideo);
  6285. // Set default display name.
  6286. setDisplayName('localVideoContainer');
  6287. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6288. VideoLayout.connectionIndicators["localVideoContainer"]
  6289. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6290. }
  6291. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6292. var localVideoSelector = $('#' + localVideo.id);
  6293. function localVideoClick(event) {
  6294. event.stopPropagation();
  6295. VideoLayout.handleVideoThumbClicked(
  6296. APP.RTC.getVideoSrc(localVideo),
  6297. false,
  6298. APP.xmpp.myResource());
  6299. }
  6300. // Add click handler to both video and video wrapper elements in case
  6301. // there's no video.
  6302. localVideoSelector.click(localVideoClick);
  6303. $('#localVideoContainer').click(localVideoClick);
  6304. // Add hover handler
  6305. $('#localVideoContainer').hover(
  6306. function() {
  6307. VideoLayout.showDisplayName('localVideoContainer', true);
  6308. },
  6309. function() {
  6310. if (!VideoLayout.isLargeVideoVisible()
  6311. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6312. VideoLayout.showDisplayName('localVideoContainer', false);
  6313. }
  6314. );
  6315. // Add stream ended handler
  6316. stream.getOriginalStream().onended = function () {
  6317. localVideoContainer.removeChild(localVideo);
  6318. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6319. };
  6320. // Flip video x axis if needed
  6321. flipXLocalVideo = flipX;
  6322. if (flipX) {
  6323. localVideoSelector.addClass("flipVideoX");
  6324. }
  6325. // Attach WebRTC stream
  6326. var videoStream = APP.simulcast.getLocalVideoStream();
  6327. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6328. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6329. var myResourceJid = APP.xmpp.myResource();
  6330. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6331. myResourceJid);
  6332. };
  6333. /**
  6334. * Adds or removes icons for not available camera and microphone.
  6335. * @param resourceJid the jid of user
  6336. * @param devices available devices
  6337. */
  6338. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  6339. if(!devices)
  6340. return;
  6341. var container = null
  6342. if(!resourceJid)
  6343. {
  6344. container = $("#localVideoContainer")[0];
  6345. }
  6346. else
  6347. {
  6348. container = $("#participant_" + resourceJid)[0];
  6349. }
  6350. if(!container)
  6351. return;
  6352. $("#" + container.id + " > .noMic").remove();
  6353. $("#" + container.id + " > .noVideo").remove();
  6354. if(!devices.audio)
  6355. {
  6356. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  6357. }
  6358. if(!devices.video)
  6359. {
  6360. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  6361. }
  6362. if(!devices.audio && !devices.video)
  6363. {
  6364. $("#" + container.id + " > .noMic").css("background-position", "75%");
  6365. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  6366. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  6367. }
  6368. }
  6369. /**
  6370. * Checks if removed video is currently displayed and tries to display
  6371. * another one instead.
  6372. * @param removedVideoSrc src stream identifier of the video.
  6373. */
  6374. my.updateRemovedVideo = function(removedVideoSrc) {
  6375. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6376. // this is currently displayed as large
  6377. // pick the last visible video in the row
  6378. // if nobody else is left, this picks the local video
  6379. var pick
  6380. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6381. .get(0);
  6382. if (!pick) {
  6383. console.info("Last visible video no longer exists");
  6384. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6385. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6386. // Try local video
  6387. console.info("Fallback to local video...");
  6388. pick = $('#remoteVideos>span>span>video').get(0);
  6389. }
  6390. }
  6391. // mute if localvideo
  6392. if (pick) {
  6393. var container = pick.parentNode;
  6394. var jid = null;
  6395. if(container)
  6396. {
  6397. if(container.id == "localVideoWrapper")
  6398. {
  6399. jid = APP.xmpp.myResource();
  6400. }
  6401. else
  6402. {
  6403. jid = VideoLayout.getPeerContainerResourceJid(container);
  6404. }
  6405. }
  6406. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6407. } else {
  6408. console.warn("Failed to elect large video");
  6409. }
  6410. }
  6411. };
  6412. my.onRemoteStreamAdded = function (stream) {
  6413. var container;
  6414. var remotes = document.getElementById('remoteVideos');
  6415. if (stream.peerjid) {
  6416. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6417. container = document.getElementById(
  6418. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6419. } else {
  6420. var id = stream.getOriginalStream().id;
  6421. if (id !== 'mixedmslabel'
  6422. // FIXME: default stream is added always with new focus
  6423. // (to be investigated)
  6424. && id !== 'default') {
  6425. console.error('can not associate stream',
  6426. id,
  6427. 'with a participant');
  6428. // We don't want to add it here since it will cause troubles
  6429. return;
  6430. }
  6431. // FIXME: for the mixed ms we dont need a video -- currently
  6432. container = document.createElement('span');
  6433. container.id = 'mixedstream';
  6434. container.className = 'videocontainer';
  6435. remotes.appendChild(container);
  6436. UIUtil.playSoundNotification('userJoined');
  6437. }
  6438. if (container) {
  6439. VideoLayout.addRemoteStreamElement( container,
  6440. stream.sid,
  6441. stream.getOriginalStream(),
  6442. stream.peerjid,
  6443. stream.ssrc);
  6444. }
  6445. }
  6446. my.getLargeVideoState = function () {
  6447. return largeVideoState;
  6448. };
  6449. /**
  6450. * Updates the large video with the given new video source.
  6451. */
  6452. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6453. console.log('hover in', newSrc);
  6454. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6455. $('#activeSpeaker').css('visibility', 'hidden');
  6456. // Due to the simulcast the localVideoSrc may have changed when the
  6457. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6458. // isVideoSrcDesktop methods will not function correctly.
  6459. //
  6460. // Also, again due to the simulcast, the updateLargeVideo method can
  6461. // be called multiple times almost simultaneously. Therefore, we
  6462. // store the state here and update only once.
  6463. largeVideoState.newSrc = newSrc;
  6464. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6465. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6466. APP.xmpp.findJidFromResource(resourceJid));
  6467. if(largeVideoState.userResourceJid) {
  6468. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6469. } else {
  6470. largeVideoState.oldResourceJid = null;
  6471. }
  6472. largeVideoState.userResourceJid = resourceJid;
  6473. // Screen stream is already rotated
  6474. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6475. var userChanged = false;
  6476. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6477. userChanged = true;
  6478. // we want the notification to trigger even if userJid is undefined,
  6479. // or null.
  6480. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6481. largeVideoState.userResourceJid);
  6482. }
  6483. if (!largeVideoState.updateInProgress) {
  6484. largeVideoState.updateInProgress = true;
  6485. var doUpdate = function () {
  6486. Avatar.updateActiveSpeakerAvatarSrc(
  6487. APP.xmpp.findJidFromResource(
  6488. largeVideoState.userResourceJid));
  6489. if (!userChanged && largeVideoState.preload &&
  6490. largeVideoState.preload !== null &&
  6491. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6492. {
  6493. console.info('Switching to preloaded video');
  6494. var attributes = $('#largeVideo').prop("attributes");
  6495. // loop through largeVideo attributes and apply them on
  6496. // preload.
  6497. $.each(attributes, function () {
  6498. if (this.name !== 'id' && this.name !== 'src') {
  6499. largeVideoState.preload.attr(this.name, this.value);
  6500. }
  6501. });
  6502. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6503. $('#largeVideo').attr('id', 'previousLargeVideo');
  6504. largeVideoState.preload.attr('id', 'largeVideo');
  6505. $('#previousLargeVideo').remove();
  6506. largeVideoState.preload.on('loadedmetadata', function (e) {
  6507. currentVideoWidth = this.videoWidth;
  6508. currentVideoHeight = this.videoHeight;
  6509. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6510. });
  6511. largeVideoState.preload = null;
  6512. largeVideoState.preload_ssrc = 0;
  6513. } else {
  6514. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6515. }
  6516. var videoTransform = document.getElementById('largeVideo')
  6517. .style.webkitTransform;
  6518. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6519. document.getElementById('largeVideo').style.webkitTransform
  6520. = "scaleX(-1)";
  6521. }
  6522. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6523. document.getElementById('largeVideo').style.webkitTransform
  6524. = "none";
  6525. }
  6526. // Change the way we'll be measuring and positioning large video
  6527. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6528. ? getDesktopVideoSize
  6529. : getCameraVideoSize;
  6530. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6531. ? getDesktopVideoPosition
  6532. : getCameraVideoPosition;
  6533. // Only if the large video is currently visible.
  6534. // Disable previous dominant speaker video.
  6535. if (largeVideoState.oldResourceJid) {
  6536. VideoLayout.enableDominantSpeaker(
  6537. largeVideoState.oldResourceJid,
  6538. false);
  6539. }
  6540. // Enable new dominant speaker in the remote videos section.
  6541. if (largeVideoState.userResourceJid) {
  6542. VideoLayout.enableDominantSpeaker(
  6543. largeVideoState.userResourceJid,
  6544. true);
  6545. }
  6546. if (userChanged && largeVideoState.isVisible) {
  6547. // using "this" should be ok because we're called
  6548. // from within the fadeOut event.
  6549. $(this).fadeIn(300);
  6550. }
  6551. if(userChanged) {
  6552. Avatar.showUserAvatar(
  6553. APP.xmpp.findJidFromResource(
  6554. largeVideoState.oldResourceJid));
  6555. }
  6556. largeVideoState.updateInProgress = false;
  6557. };
  6558. if (userChanged) {
  6559. $('#largeVideo').fadeOut(300, doUpdate);
  6560. } else {
  6561. doUpdate();
  6562. }
  6563. }
  6564. } else {
  6565. Avatar.showUserAvatar(
  6566. APP.xmpp.findJidFromResource(
  6567. largeVideoState.userResourceJid));
  6568. }
  6569. };
  6570. my.handleVideoThumbClicked = function(videoSrc,
  6571. noPinnedEndpointChangedEvent,
  6572. resourceJid) {
  6573. // Restore style for previously focused video
  6574. var oldContainer = null;
  6575. if(focusedVideoInfo) {
  6576. var focusResourceJid = focusedVideoInfo.resourceJid;
  6577. oldContainer = getParticipantContainer(focusResourceJid);
  6578. }
  6579. if (oldContainer) {
  6580. oldContainer.removeClass("videoContainerFocused");
  6581. }
  6582. // Unlock current focused.
  6583. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6584. {
  6585. focusedVideoInfo = null;
  6586. var dominantSpeakerVideo = null;
  6587. // Enable the currently set dominant speaker.
  6588. if (currentDominantSpeaker) {
  6589. dominantSpeakerVideo
  6590. = $('#participant_' + currentDominantSpeaker + '>video')
  6591. .get(0);
  6592. if (dominantSpeakerVideo) {
  6593. VideoLayout.updateLargeVideo(
  6594. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6595. 1,
  6596. currentDominantSpeaker);
  6597. }
  6598. }
  6599. if (!noPinnedEndpointChangedEvent) {
  6600. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6601. }
  6602. return;
  6603. }
  6604. // Lock new video
  6605. focusedVideoInfo = {
  6606. src: videoSrc,
  6607. resourceJid: resourceJid
  6608. };
  6609. // Update focused/pinned interface.
  6610. if (resourceJid)
  6611. {
  6612. var container = getParticipantContainer(resourceJid);
  6613. container.addClass("videoContainerFocused");
  6614. if (!noPinnedEndpointChangedEvent) {
  6615. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6616. }
  6617. }
  6618. if ($('#largeVideo').attr('src') === videoSrc &&
  6619. VideoLayout.isLargeVideoOnTop()) {
  6620. return;
  6621. }
  6622. // Triggers a "video.selected" event. The "false" parameter indicates
  6623. // this isn't a prezi.
  6624. $(document).trigger("video.selected", [false]);
  6625. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6626. $('audio').each(function (idx, el) {
  6627. if (el.id.indexOf('mixedmslabel') !== -1) {
  6628. el.volume = 0;
  6629. el.volume = 1;
  6630. }
  6631. });
  6632. };
  6633. /**
  6634. * Positions the large video.
  6635. *
  6636. * @param videoWidth the stream video width
  6637. * @param videoHeight the stream video height
  6638. */
  6639. my.positionLarge = function (videoWidth, videoHeight) {
  6640. var videoSpaceWidth = $('#videospace').width();
  6641. var videoSpaceHeight = window.innerHeight;
  6642. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6643. videoHeight,
  6644. videoSpaceWidth,
  6645. videoSpaceHeight);
  6646. var largeVideoWidth = videoSize[0];
  6647. var largeVideoHeight = videoSize[1];
  6648. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6649. largeVideoHeight,
  6650. videoSpaceWidth,
  6651. videoSpaceHeight);
  6652. var horizontalIndent = videoPosition[0];
  6653. var verticalIndent = videoPosition[1];
  6654. positionVideo($('#largeVideo'),
  6655. largeVideoWidth,
  6656. largeVideoHeight,
  6657. horizontalIndent, verticalIndent);
  6658. };
  6659. /**
  6660. * Shows/hides the large video.
  6661. */
  6662. my.setLargeVideoVisible = function(isVisible) {
  6663. var resourceJid = largeVideoState.userResourceJid;
  6664. if (isVisible) {
  6665. $('#largeVideo').css({visibility: 'visible'});
  6666. $('.watermark').css({visibility: 'visible'});
  6667. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6668. }
  6669. else {
  6670. $('#largeVideo').css({visibility: 'hidden'});
  6671. $('#activeSpeaker').css('visibility', 'hidden');
  6672. $('.watermark').css({visibility: 'hidden'});
  6673. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6674. if(focusedVideoInfo) {
  6675. var focusResourceJid = focusedVideoInfo.resourceJid;
  6676. var oldContainer = getParticipantContainer(focusResourceJid);
  6677. if (oldContainer && oldContainer.length > 0) {
  6678. oldContainer.removeClass("videoContainerFocused");
  6679. }
  6680. focusedVideoInfo = null;
  6681. if(focusResourceJid) {
  6682. Avatar.showUserAvatar(
  6683. APP.xmpp.findJidFromResource(focusResourceJid));
  6684. }
  6685. }
  6686. }
  6687. };
  6688. /**
  6689. * Indicates if the large video is currently visible.
  6690. *
  6691. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6692. */
  6693. my.isLargeVideoVisible = function() {
  6694. return $('#largeVideo').is(':visible');
  6695. };
  6696. my.isLargeVideoOnTop = function () {
  6697. var Etherpad = require("../etherpad/Etherpad");
  6698. var Prezi = require("../prezi/Prezi");
  6699. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6700. };
  6701. /**
  6702. * Checks if container for participant identified by given peerJid exists
  6703. * in the document and creates it eventually.
  6704. *
  6705. * @param peerJid peer Jid to check.
  6706. * @param userId user email or id for setting the avatar
  6707. *
  6708. * @return Returns <tt>true</tt> if the peer container exists,
  6709. * <tt>false</tt> - otherwise
  6710. */
  6711. my.ensurePeerContainerExists = function(peerJid, userId) {
  6712. ContactList.ensureAddContact(peerJid, userId);
  6713. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6714. var videoSpanId = 'participant_' + resourceJid;
  6715. if (!$('#' + videoSpanId).length) {
  6716. var container =
  6717. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6718. Avatar.setUserAvatar(peerJid, userId);
  6719. // Set default display name.
  6720. setDisplayName(videoSpanId);
  6721. VideoLayout.connectionIndicators[videoSpanId] =
  6722. new ConnectionIndicator(container, peerJid, VideoLayout);
  6723. var nickfield = document.createElement('span');
  6724. nickfield.className = "nick";
  6725. nickfield.appendChild(document.createTextNode(resourceJid));
  6726. container.appendChild(nickfield);
  6727. // In case this is not currently in the last n we don't show it.
  6728. if (localLastNCount
  6729. && localLastNCount > 0
  6730. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6731. showPeerContainer(resourceJid, 'hide');
  6732. }
  6733. else
  6734. VideoLayout.resizeThumbnails();
  6735. }
  6736. };
  6737. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6738. var container = document.createElement('span');
  6739. container.id = spanId;
  6740. container.className = 'videocontainer';
  6741. var remotes = document.getElementById('remoteVideos');
  6742. remotes.appendChild(container);
  6743. // If the peerJid is null then this video span couldn't be directly
  6744. // associated with a participant (this could happen in the case of prezi).
  6745. if (APP.xmpp.isModerator() && peerJid !== null)
  6746. addRemoteVideoMenu(peerJid, container);
  6747. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6748. return container;
  6749. };
  6750. /**
  6751. * Creates an audio or video stream element.
  6752. */
  6753. my.createStreamElement = function (sid, stream) {
  6754. var isVideo = stream.getVideoTracks().length > 0;
  6755. var element = isVideo
  6756. ? document.createElement('video')
  6757. : document.createElement('audio');
  6758. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6759. + sid + '_' + APP.RTC.getStreamID(stream);
  6760. element.id = id;
  6761. element.autoplay = true;
  6762. element.oncontextmenu = function () { return false; };
  6763. return element;
  6764. };
  6765. my.addRemoteStreamElement
  6766. = function (container, sid, stream, peerJid, thessrc) {
  6767. var newElementId = null;
  6768. var isVideo = stream.getVideoTracks().length > 0;
  6769. if (container) {
  6770. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6771. newElementId = streamElement.id;
  6772. container.appendChild(streamElement);
  6773. var sel = $('#' + newElementId);
  6774. sel.hide();
  6775. // If the container is currently visible we attach the stream.
  6776. if (!isVideo
  6777. || (container.offsetParent !== null && isVideo)) {
  6778. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6779. APP.RTC.attachMediaStream(sel, videoStream);
  6780. if (isVideo)
  6781. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6782. }
  6783. stream.onended = function () {
  6784. console.log('stream ended', this);
  6785. VideoLayout.removeRemoteStreamElement(
  6786. stream, isVideo, container);
  6787. // NOTE(gp) it seems that under certain circumstances, the
  6788. // onended event is not fired and thus the contact list is not
  6789. // updated.
  6790. //
  6791. // The onended event of a stream should be fired when the SSRCs
  6792. // corresponding to that stream are removed from the SDP; but
  6793. // this doesn't seem to always be the case, resulting in ghost
  6794. // contacts.
  6795. //
  6796. // In an attempt to fix the ghost contacts problem, I'm moving
  6797. // the removeContact() method call in app.js, inside the
  6798. // 'muc.left' event handler.
  6799. //if (peerJid)
  6800. // ContactList.removeContact(peerJid);
  6801. };
  6802. // Add click handler.
  6803. container.onclick = function (event) {
  6804. /*
  6805. * FIXME It turns out that videoThumb may not exist (if there is
  6806. * no actual video).
  6807. */
  6808. var videoThumb = $('#' + container.id + '>video').get(0);
  6809. if (videoThumb) {
  6810. VideoLayout.handleVideoThumbClicked(
  6811. APP.RTC.getVideoSrc(videoThumb),
  6812. false,
  6813. Strophe.getResourceFromJid(peerJid));
  6814. }
  6815. event.stopPropagation();
  6816. event.preventDefault();
  6817. return false;
  6818. };
  6819. // Add hover handler
  6820. $(container).hover(
  6821. function() {
  6822. VideoLayout.showDisplayName(container.id, true);
  6823. },
  6824. function() {
  6825. var videoSrc = null;
  6826. if ($('#' + container.id + '>video')
  6827. && $('#' + container.id + '>video').length > 0) {
  6828. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6829. }
  6830. // If the video has been "pinned" by the user we want to
  6831. // keep the display name on place.
  6832. if (!VideoLayout.isLargeVideoVisible()
  6833. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6834. VideoLayout.showDisplayName(container.id, false);
  6835. }
  6836. );
  6837. }
  6838. return newElementId;
  6839. };
  6840. /**
  6841. * Removes the remote stream element corresponding to the given stream and
  6842. * parent container.
  6843. *
  6844. * @param stream the stream
  6845. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6846. * @param container
  6847. */
  6848. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6849. if (!container)
  6850. return;
  6851. var select = null;
  6852. var removedVideoSrc = null;
  6853. if (isVideo) {
  6854. select = $('#' + container.id + '>video');
  6855. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6856. }
  6857. else
  6858. select = $('#' + container.id + '>audio');
  6859. // Mark video as removed to cancel waiting loop(if video is removed
  6860. // before has started)
  6861. select.removed = true;
  6862. select.remove();
  6863. var audioCount = $('#' + container.id + '>audio').length;
  6864. var videoCount = $('#' + container.id + '>video').length;
  6865. if (!audioCount && !videoCount) {
  6866. console.log("Remove whole user", container.id);
  6867. if(VideoLayout.connectionIndicators[container.id])
  6868. VideoLayout.connectionIndicators[container.id].remove();
  6869. // Remove whole container
  6870. container.remove();
  6871. UIUtil.playSoundNotification('userLeft');
  6872. VideoLayout.resizeThumbnails();
  6873. }
  6874. if (removedVideoSrc)
  6875. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6876. };
  6877. /**
  6878. * Show/hide peer container for the given resourceJid.
  6879. */
  6880. function showPeerContainer(resourceJid, state) {
  6881. var peerContainer = $('#participant_' + resourceJid);
  6882. if (!peerContainer)
  6883. return;
  6884. var isHide = state === 'hide';
  6885. var resizeThumbnails = false;
  6886. if (!isHide) {
  6887. if (!peerContainer.is(':visible')) {
  6888. resizeThumbnails = true;
  6889. peerContainer.show();
  6890. }
  6891. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6892. if (state == 'show')
  6893. {
  6894. // peerContainer.css('-webkit-filter', '');
  6895. Avatar.showUserAvatar(jid, false);
  6896. }
  6897. else // if (state == 'avatar')
  6898. {
  6899. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6900. Avatar.showUserAvatar(jid, true);
  6901. }
  6902. }
  6903. else if (peerContainer.is(':visible') && isHide)
  6904. {
  6905. resizeThumbnails = true;
  6906. peerContainer.hide();
  6907. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6908. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6909. }
  6910. if (resizeThumbnails) {
  6911. VideoLayout.resizeThumbnails();
  6912. }
  6913. // We want to be able to pin a participant from the contact list, even
  6914. // if he's not in the lastN set!
  6915. // ContactList.setClickable(resourceJid, !isHide);
  6916. };
  6917. my.inputDisplayNameHandler = function (name) {
  6918. NicknameHandler.setNickname(name);
  6919. if (!$('#localDisplayName').is(":visible")) {
  6920. if (NicknameHandler.getNickname())
  6921. {
  6922. var meHTML = APP.translation.generateTranslatonHTML("me");
  6923. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6924. }
  6925. else
  6926. {
  6927. var defaultHTML = APP.translation.generateTranslatonHTML(
  6928. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6929. $('#localDisplayName')
  6930. .html(defaultHTML);
  6931. }
  6932. $('#localDisplayName').show();
  6933. }
  6934. $('#editDisplayName').hide();
  6935. };
  6936. /**
  6937. * Shows/hides the display name on the remote video.
  6938. * @param videoSpanId the identifier of the video span element
  6939. * @param isShow indicates if the display name should be shown or hidden
  6940. */
  6941. my.showDisplayName = function(videoSpanId, isShow) {
  6942. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6943. if (isShow) {
  6944. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6945. nameSpan.setAttribute("style", "display:inline-block;");
  6946. }
  6947. else {
  6948. if (nameSpan)
  6949. nameSpan.setAttribute("style", "display:none;");
  6950. }
  6951. };
  6952. /**
  6953. * Shows the presence status message for the given video.
  6954. */
  6955. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6956. if (!$('#' + videoSpanId).length) {
  6957. // No container
  6958. return;
  6959. }
  6960. var statusSpan = $('#' + videoSpanId + '>span.status');
  6961. if (!statusSpan.length) {
  6962. //Add status span
  6963. statusSpan = document.createElement('span');
  6964. statusSpan.className = 'status';
  6965. statusSpan.id = videoSpanId + '_status';
  6966. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6967. statusSpan = $('#' + videoSpanId + '>span.status');
  6968. }
  6969. // Display status
  6970. if (statusMsg && statusMsg.length) {
  6971. $('#' + videoSpanId + '_status').text(statusMsg);
  6972. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6973. }
  6974. else {
  6975. // Hide
  6976. statusSpan.get(0).setAttribute("style", "display:none;");
  6977. }
  6978. };
  6979. /**
  6980. * Shows a visual indicator for the moderator of the conference.
  6981. */
  6982. my.showModeratorIndicator = function () {
  6983. var isModerator = APP.xmpp.isModerator();
  6984. if (isModerator) {
  6985. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6986. if (indicatorSpan.children().length === 0)
  6987. {
  6988. createModeratorIndicatorElement(indicatorSpan[0]);
  6989. //translates text in focus indicator
  6990. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6991. }
  6992. }
  6993. var members = APP.xmpp.getMembers();
  6994. Object.keys(members).forEach(function (jid) {
  6995. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6996. // Skip server side focus
  6997. return;
  6998. }
  6999. var resourceJid = Strophe.getResourceFromJid(jid);
  7000. var videoSpanId = 'participant_' + resourceJid;
  7001. var videoContainer = document.getElementById(videoSpanId);
  7002. if (!videoContainer) {
  7003. console.error("No video container for " + jid);
  7004. return;
  7005. }
  7006. var member = members[jid];
  7007. if (member.role === 'moderator') {
  7008. // Remove menu if peer is moderator
  7009. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7010. if (menuSpan.length) {
  7011. removeRemoteVideoMenu(videoSpanId);
  7012. }
  7013. // Show moderator indicator
  7014. var indicatorSpan
  7015. = $('#' + videoSpanId + ' .focusindicator');
  7016. if (!indicatorSpan || indicatorSpan.length === 0) {
  7017. indicatorSpan = document.createElement('span');
  7018. indicatorSpan.className = 'focusindicator';
  7019. videoContainer.appendChild(indicatorSpan);
  7020. createModeratorIndicatorElement(indicatorSpan);
  7021. //translates text in focus indicators
  7022. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7023. }
  7024. } else if (isModerator) {
  7025. // We are moderator, but user is not - add menu
  7026. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7027. addRemoteVideoMenu(
  7028. jid,
  7029. document.getElementById('participant_' + resourceJid));
  7030. }
  7031. }
  7032. });
  7033. };
  7034. /**
  7035. * Shows video muted indicator over small videos.
  7036. */
  7037. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7038. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7039. if (isMuted === 'false') {
  7040. if (videoMutedSpan.length > 0) {
  7041. videoMutedSpan.remove();
  7042. }
  7043. }
  7044. else {
  7045. if(videoMutedSpan.length == 0) {
  7046. videoMutedSpan = document.createElement('span');
  7047. videoMutedSpan.className = 'videoMuted';
  7048. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7049. var mutedIndicator = document.createElement('i');
  7050. mutedIndicator.className = 'icon-camera-disabled';
  7051. UIUtil.setTooltip(mutedIndicator,
  7052. "videothumbnail.videomute",
  7053. "top");
  7054. videoMutedSpan.appendChild(mutedIndicator);
  7055. //translate texts for muted indicator
  7056. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7057. }
  7058. VideoLayout.updateMutePosition(videoSpanId);
  7059. }
  7060. };
  7061. my.updateMutePosition = function (videoSpanId) {
  7062. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7063. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7064. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7065. if(connectionIndicator.length > 0
  7066. && connectionIndicator[0].style.display != "none") {
  7067. audioMutedSpan.css({right: "23px"});
  7068. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7069. }
  7070. else
  7071. {
  7072. audioMutedSpan.css({right: "0px"});
  7073. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7074. }
  7075. }
  7076. /**
  7077. * Shows audio muted indicator over small videos.
  7078. * @param {string} isMuted
  7079. */
  7080. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7081. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7082. if (isMuted === 'false') {
  7083. if (audioMutedSpan.length > 0) {
  7084. audioMutedSpan.popover('hide');
  7085. audioMutedSpan.remove();
  7086. }
  7087. }
  7088. else {
  7089. if(audioMutedSpan.length == 0 ) {
  7090. audioMutedSpan = document.createElement('span');
  7091. audioMutedSpan.className = 'audioMuted';
  7092. UIUtil.setTooltip(audioMutedSpan,
  7093. "videothumbnail.mute",
  7094. "top");
  7095. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7096. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7097. var mutedIndicator = document.createElement('i');
  7098. mutedIndicator.className = 'icon-mic-disabled';
  7099. audioMutedSpan.appendChild(mutedIndicator);
  7100. }
  7101. VideoLayout.updateMutePosition(videoSpanId);
  7102. }
  7103. };
  7104. /*
  7105. * Shows or hides the audio muted indicator over the local thumbnail video.
  7106. * @param {boolean} isMuted
  7107. */
  7108. my.showLocalAudioIndicator = function(isMuted) {
  7109. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7110. };
  7111. /**
  7112. * Resizes the large video container.
  7113. */
  7114. my.resizeLargeVideoContainer = function () {
  7115. Chat.resizeChat();
  7116. var availableHeight = window.innerHeight;
  7117. var availableWidth = UIUtil.getAvailableVideoWidth();
  7118. if (availableWidth < 0 || availableHeight < 0) return;
  7119. $('#videospace').width(availableWidth);
  7120. $('#videospace').height(availableHeight);
  7121. $('#largeVideoContainer').width(availableWidth);
  7122. $('#largeVideoContainer').height(availableHeight);
  7123. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7124. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7125. $('#activeSpeaker').css('top', top);
  7126. VideoLayout.resizeThumbnails();
  7127. };
  7128. /**
  7129. * Resizes thumbnails.
  7130. */
  7131. my.resizeThumbnails = function() {
  7132. var videoSpaceWidth = $('#remoteVideos').width();
  7133. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7134. var width = thumbnailSize[0];
  7135. var height = thumbnailSize[1];
  7136. // size videos so that while keeping AR and max height, we have a
  7137. // nice fit
  7138. $('#remoteVideos').height(height);
  7139. $('#remoteVideos>span').width(width);
  7140. $('#remoteVideos>span').height(height);
  7141. $('.userAvatar').css('left', (width - height) / 2);
  7142. $(document).trigger("remotevideo.resized", [width, height]);
  7143. };
  7144. /**
  7145. * Enables the dominant speaker UI.
  7146. *
  7147. * @param resourceJid the jid indicating the video element to
  7148. * activate/deactivate
  7149. * @param isEnable indicates if the dominant speaker should be enabled or
  7150. * disabled
  7151. */
  7152. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7153. var videoSpanId = null;
  7154. var videoContainerId = null;
  7155. if (resourceJid
  7156. === APP.xmpp.myResource()) {
  7157. videoSpanId = 'localVideoWrapper';
  7158. videoContainerId = 'localVideoContainer';
  7159. }
  7160. else {
  7161. videoSpanId = 'participant_' + resourceJid;
  7162. videoContainerId = videoSpanId;
  7163. }
  7164. var displayName = resourceJid;
  7165. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7166. if (nameSpan.length > 0)
  7167. displayName = nameSpan.html();
  7168. console.log("UI enable dominant speaker",
  7169. displayName,
  7170. resourceJid,
  7171. isEnable);
  7172. videoSpan = document.getElementById(videoContainerId);
  7173. if (!videoSpan) {
  7174. return;
  7175. }
  7176. var video = $('#' + videoSpanId + '>video');
  7177. if (video && video.length > 0) {
  7178. if (isEnable) {
  7179. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7180. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7181. if (!videoSpan.classList.contains("dominantspeaker"))
  7182. videoSpan.classList.add("dominantspeaker");
  7183. }
  7184. else {
  7185. VideoLayout.showDisplayName(videoContainerId, false);
  7186. if (videoSpan.classList.contains("dominantspeaker"))
  7187. videoSpan.classList.remove("dominantspeaker");
  7188. }
  7189. Avatar.showUserAvatar(
  7190. APP.xmpp.findJidFromResource(resourceJid));
  7191. }
  7192. };
  7193. /**
  7194. * Calculates the thumbnail size.
  7195. *
  7196. * @param videoSpaceWidth the width of the video space
  7197. */
  7198. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7199. // Calculate the available height, which is the inner window height minus
  7200. // 39px for the header minus 2px for the delimiter lines on the top and
  7201. // bottom of the large video, minus the 36px space inside the remoteVideos
  7202. // container used for highlighting shadow.
  7203. var availableHeight = 100;
  7204. var numvids = $('#remoteVideos>span:visible').length;
  7205. if (localLastNCount && localLastNCount > 0) {
  7206. numvids = Math.min(localLastNCount + 1, numvids);
  7207. }
  7208. // Remove the 3px borders arround videos and border around the remote
  7209. // videos area and the 4 pixels between the local video and the others
  7210. //TODO: Find out where the 4 pixels come from and remove them
  7211. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7212. var availableWidth = availableWinWidth / numvids;
  7213. var aspectRatio = 16.0 / 9.0;
  7214. var maxHeight = Math.min(160, availableHeight);
  7215. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7216. if (availableHeight < availableWidth / aspectRatio) {
  7217. availableWidth = Math.floor(availableHeight * aspectRatio);
  7218. }
  7219. return [availableWidth, availableHeight];
  7220. };
  7221. /**
  7222. * Updates the remote video menu.
  7223. *
  7224. * @param jid the jid indicating the video for which we're adding a menu.
  7225. * @param isMuted indicates the current mute state
  7226. */
  7227. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7228. var muteMenuItem
  7229. = $('#remote_popupmenu_'
  7230. + Strophe.getResourceFromJid(jid)
  7231. + '>li>a.mutelink');
  7232. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7233. if (muteMenuItem.length) {
  7234. var muteLink = muteMenuItem.get(0);
  7235. if (isMuted === 'true') {
  7236. muteLink.innerHTML = mutedIndicator + ' Muted';
  7237. muteLink.className = 'mutelink disabled';
  7238. }
  7239. else {
  7240. muteLink.innerHTML = mutedIndicator + ' Mute';
  7241. muteLink.className = 'mutelink';
  7242. }
  7243. }
  7244. };
  7245. /**
  7246. * Returns the current dominant speaker resource jid.
  7247. */
  7248. my.getDominantSpeakerResourceJid = function () {
  7249. return currentDominantSpeaker;
  7250. };
  7251. /**
  7252. * Returns the corresponding resource jid to the given peer container
  7253. * DOM element.
  7254. *
  7255. * @return the corresponding resource jid to the given peer container
  7256. * DOM element
  7257. */
  7258. my.getPeerContainerResourceJid = function (containerElement) {
  7259. var i = containerElement.id.indexOf('participant_');
  7260. if (i >= 0)
  7261. return containerElement.id.substring(i + 12);
  7262. };
  7263. /**
  7264. * On contact list item clicked.
  7265. */
  7266. $(ContactList).bind('contactclicked', function(event, jid) {
  7267. if (!jid) {
  7268. return;
  7269. }
  7270. var resource = Strophe.getResourceFromJid(jid);
  7271. var videoContainer = $("#participant_" + resource);
  7272. if (videoContainer.length > 0) {
  7273. var videoThumb = $('video', videoContainer).get(0);
  7274. // It is not always the case that a videoThumb exists (if there is
  7275. // no actual video).
  7276. if (videoThumb) {
  7277. if (videoThumb.src && videoThumb.src != '') {
  7278. // We have a video src, great! Let's update the large video
  7279. // now.
  7280. VideoLayout.handleVideoThumbClicked(
  7281. videoThumb.src,
  7282. false,
  7283. Strophe.getResourceFromJid(jid));
  7284. } else {
  7285. // If we don't have a video src for jid, there's absolutely
  7286. // no point in calling handleVideoThumbClicked; Quite
  7287. // simply, it won't work because it needs an src to attach
  7288. // to the large video.
  7289. //
  7290. // Instead, we trigger the pinned endpoint changed event to
  7291. // let the bridge adjust its lastN set for myjid and store
  7292. // the pinned user in the lastNPickupJid variable to be
  7293. // picked up later by the lastN changed event handler.
  7294. lastNPickupJid = jid;
  7295. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7296. Strophe.getResourceFromJid(jid));
  7297. }
  7298. } else if (jid == APP.xmpp.myJid()) {
  7299. $("#localVideoContainer").click();
  7300. }
  7301. }
  7302. });
  7303. /**
  7304. * On audio muted event.
  7305. */
  7306. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7307. /*
  7308. // FIXME: but focus can not mute in this case ? - check
  7309. if (jid === xmpp.myJid()) {
  7310. // The local mute indicator is controlled locally
  7311. return;
  7312. }*/
  7313. var videoSpanId = null;
  7314. if (jid === APP.xmpp.myJid()) {
  7315. videoSpanId = 'localVideoContainer';
  7316. } else {
  7317. VideoLayout.ensurePeerContainerExists(jid);
  7318. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7319. }
  7320. mutedAudios[jid] = isMuted;
  7321. if (APP.xmpp.isModerator()) {
  7322. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7323. }
  7324. if (videoSpanId)
  7325. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7326. });
  7327. /**
  7328. * On video muted event.
  7329. */
  7330. $(document).bind('videomuted.muc', function (event, jid, value) {
  7331. var isMuted = (value === "true");
  7332. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7333. return;
  7334. Avatar.showUserAvatar(jid, isMuted);
  7335. var videoSpanId = null;
  7336. if (jid === APP.xmpp.myJid()) {
  7337. videoSpanId = 'localVideoContainer';
  7338. } else {
  7339. VideoLayout.ensurePeerContainerExists(jid);
  7340. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7341. }
  7342. if (videoSpanId)
  7343. VideoLayout.showVideoIndicator(videoSpanId, value);
  7344. });
  7345. /**
  7346. * Display name changed.
  7347. */
  7348. my.onDisplayNameChanged =
  7349. function (jid, displayName, status) {
  7350. if (jid === 'localVideoContainer'
  7351. || jid === APP.xmpp.myJid()) {
  7352. setDisplayName('localVideoContainer',
  7353. displayName);
  7354. } else {
  7355. VideoLayout.ensurePeerContainerExists(jid);
  7356. setDisplayName(
  7357. 'participant_' + Strophe.getResourceFromJid(jid),
  7358. displayName,
  7359. status);
  7360. }
  7361. };
  7362. /**
  7363. * On dominant speaker changed event.
  7364. */
  7365. my.onDominantSpeakerChanged = function (resourceJid) {
  7366. // We ignore local user events.
  7367. if (resourceJid
  7368. === APP.xmpp.myResource())
  7369. return;
  7370. var members = APP.xmpp.getMembers();
  7371. // Update the current dominant speaker.
  7372. if (resourceJid !== currentDominantSpeaker) {
  7373. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7374. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7375. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7376. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7377. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7378. !members[currentJID].displayName)) {
  7379. setDisplayName(oldSpeakerVideoSpanId, null);
  7380. }
  7381. if(resourceJid && (!members || !members[newJID] ||
  7382. !members[newJID].displayName)) {
  7383. setDisplayName(newSpeakerVideoSpanId, null,
  7384. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7385. }
  7386. currentDominantSpeaker = resourceJid;
  7387. } else {
  7388. return;
  7389. }
  7390. // Obtain container for new dominant speaker.
  7391. var container = document.getElementById(
  7392. 'participant_' + resourceJid);
  7393. // Local video will not have container found, but that's ok
  7394. // since we don't want to switch to local video.
  7395. if (container && !focusedVideoInfo)
  7396. {
  7397. var video = container.getElementsByTagName("video");
  7398. // Update the large video if the video source is already available,
  7399. // otherwise wait for the "videoactive.jingle" event.
  7400. if (video.length && video[0].currentTime > 0)
  7401. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7402. }
  7403. };
  7404. /**
  7405. * On last N change event.
  7406. *
  7407. * @param lastNEndpoints the list of last N endpoints
  7408. * @param endpointsEnteringLastN the list currently entering last N
  7409. * endpoints
  7410. */
  7411. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7412. endpointsEnteringLastN,
  7413. stream) {
  7414. if (lastNCount !== lastNEndpoints.length)
  7415. lastNCount = lastNEndpoints.length;
  7416. lastNEndpointsCache = lastNEndpoints;
  7417. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7418. //
  7419. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7420. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7421. // so E sees them. C is only in E's local LastN set.
  7422. //
  7423. // If F starts talking and LastN = 3, then E should see thumbnails for
  7424. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7425. // enters E's local LastN ejecting C.
  7426. // Increase the local LastN set size, if necessary.
  7427. if (lastNCount > localLastNCount) {
  7428. localLastNCount = lastNCount;
  7429. }
  7430. // Update the local LastN set preserving the order in which the
  7431. // endpoints appeared in the LastN/local LastN set.
  7432. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7433. for (var i = 0; i < localLastNSet.length; i++) {
  7434. if (nextLocalLastNSet.length >= localLastNCount) {
  7435. break;
  7436. }
  7437. var resourceJid = localLastNSet[i];
  7438. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7439. nextLocalLastNSet.push(resourceJid);
  7440. }
  7441. }
  7442. localLastNSet = nextLocalLastNSet;
  7443. var updateLargeVideo = false;
  7444. // Handle LastN/local LastN changes.
  7445. $('#remoteVideos>span').each(function( index, element ) {
  7446. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7447. var isReceived = true;
  7448. if (resourceJid
  7449. && lastNEndpoints.indexOf(resourceJid) < 0
  7450. && localLastNSet.indexOf(resourceJid) < 0) {
  7451. console.log("Remove from last N", resourceJid);
  7452. showPeerContainer(resourceJid, 'hide');
  7453. isReceived = false;
  7454. } else if (resourceJid
  7455. && $('#participant_' + resourceJid).is(':visible')
  7456. && lastNEndpoints.indexOf(resourceJid) < 0
  7457. && localLastNSet.indexOf(resourceJid) >= 0) {
  7458. showPeerContainer(resourceJid, 'avatar');
  7459. isReceived = false;
  7460. }
  7461. if (!isReceived) {
  7462. // resourceJid has dropped out of the server side lastN set, so
  7463. // it is no longer being received. If resourceJid was being
  7464. // displayed in the large video we have to switch to another
  7465. // user.
  7466. var largeVideoResource = largeVideoState.userResourceJid;
  7467. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7468. updateLargeVideo = true;
  7469. }
  7470. }
  7471. });
  7472. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7473. endpointsEnteringLastN = lastNEndpoints;
  7474. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7475. endpointsEnteringLastN.forEach(function (resourceJid) {
  7476. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7477. showPeerContainer(resourceJid, 'show');
  7478. if (!isVisible) {
  7479. console.log("Add to last N", resourceJid);
  7480. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7481. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7482. var sel = $('#participant_' + resourceJid + '>video');
  7483. var videoStream = APP.simulcast.getReceivingVideoStream(
  7484. mediaStream.stream);
  7485. APP.RTC.attachMediaStream(sel, videoStream);
  7486. if (lastNPickupJid == mediaStream.peerjid) {
  7487. // Clean up the lastN pickup jid.
  7488. lastNPickupJid = null;
  7489. // Don't fire the events again, they've already
  7490. // been fired in the contact list click handler.
  7491. VideoLayout.handleVideoThumbClicked(
  7492. $(sel).attr('src'),
  7493. false,
  7494. Strophe.getResourceFromJid(mediaStream.peerjid));
  7495. updateLargeVideo = false;
  7496. }
  7497. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7498. }
  7499. })
  7500. }
  7501. // The endpoint that was being shown in the large video has dropped out
  7502. // of the lastN set and there was no lastN pickup jid. We need to update
  7503. // the large video now.
  7504. if (updateLargeVideo) {
  7505. var resource, container, src;
  7506. var myResource
  7507. = APP.xmpp.myResource();
  7508. // Find out which endpoint to show in the large video.
  7509. for (var i = 0; i < lastNEndpoints.length; i++) {
  7510. resource = lastNEndpoints[i];
  7511. if (!resource || resource === myResource)
  7512. continue;
  7513. container = $("#participant_" + resource);
  7514. if (container.length == 0)
  7515. continue;
  7516. src = $('video', container).attr('src');
  7517. if (!src)
  7518. continue;
  7519. // videoSrcToSsrc needs to be update for this call to succeed.
  7520. VideoLayout.updateLargeVideo(src);
  7521. break;
  7522. }
  7523. }
  7524. };
  7525. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7526. endpointSimulcastLayers.forEach(function (esl) {
  7527. var resource = esl.endpoint;
  7528. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7529. // then ignore the event (= do not preload anything).
  7530. //
  7531. // The bridge could probably stop sending this message if it's for
  7532. // an endpoint that's not in lastN.
  7533. if (lastNCount != -1
  7534. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7535. return;
  7536. }
  7537. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7538. // Get session and stream from primary ssrc.
  7539. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7540. var sid = res.sid;
  7541. var electedStream = res.stream;
  7542. if (sid && electedStream) {
  7543. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7544. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7545. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7546. if (preload) {
  7547. if (largeVideoState.preload)
  7548. {
  7549. $(largeVideoState.preload).remove();
  7550. }
  7551. console.info('Preloading remote video');
  7552. largeVideoState.preload = $('<video autoplay></video>');
  7553. // ssrcs are unique in an rtp session
  7554. largeVideoState.preload_ssrc = primarySSRC;
  7555. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7556. }
  7557. } else {
  7558. console.error('Could not find a stream or a session.', sid, electedStream);
  7559. }
  7560. });
  7561. };
  7562. /**
  7563. * On simulcast layers changed event.
  7564. */
  7565. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7566. endpointSimulcastLayers.forEach(function (esl) {
  7567. var resource = esl.endpoint;
  7568. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7569. // then ignore the event (= do not change large video/thumbnail
  7570. // SRCs).
  7571. //
  7572. // Note that even if we ignore the "changed" event in this event
  7573. // handler, the bridge must continue sending these events because
  7574. // the simulcast code in simulcast.js uses it to know what's going
  7575. // to be streamed by the bridge when/if the endpoint gets back into
  7576. // the lastN set.
  7577. if (lastNCount != -1
  7578. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7579. return;
  7580. }
  7581. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7582. // Get session and stream from primary ssrc.
  7583. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7584. var sid = res.sid;
  7585. var electedStream = res.stream;
  7586. if (sid && electedStream) {
  7587. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7588. console.info('Switching simulcast substream.');
  7589. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7590. var msidParts = msid.split(' ');
  7591. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7592. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7593. == largeVideoState.userResourceJid);
  7594. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7595. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7596. var electedStreamUrl;
  7597. if (largeVideoState.preload_ssrc == primarySSRC)
  7598. {
  7599. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7600. }
  7601. else
  7602. {
  7603. if (largeVideoState.preload
  7604. && largeVideoState.preload != null) {
  7605. $(largeVideoState.preload).remove();
  7606. }
  7607. largeVideoState.preload_ssrc = 0;
  7608. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7609. }
  7610. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7611. if (updateLargeVideo) {
  7612. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7613. Strophe.getResourceFromJid(jid));
  7614. }
  7615. if (updateFocusedVideoSrc) {
  7616. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7617. }
  7618. var videoId;
  7619. if(resource == APP.xmpp.myResource())
  7620. {
  7621. videoId = "localVideoContainer";
  7622. }
  7623. else
  7624. {
  7625. videoId = "participant_" + resource;
  7626. }
  7627. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7628. if(connectionIndicator)
  7629. connectionIndicator.updatePopoverData();
  7630. } else {
  7631. console.error('Could not find a stream or a sid.', sid, electedStream);
  7632. }
  7633. });
  7634. };
  7635. /**
  7636. * Updates local stats
  7637. * @param percent
  7638. * @param object
  7639. */
  7640. my.updateLocalConnectionStats = function (percent, object) {
  7641. var resolution = null;
  7642. if(object.resolution !== null)
  7643. {
  7644. resolution = object.resolution;
  7645. object.resolution = resolution[APP.xmpp.myJid()];
  7646. delete resolution[APP.xmpp.myJid()];
  7647. }
  7648. updateStatsIndicator("localVideoContainer", percent, object);
  7649. for(var jid in resolution)
  7650. {
  7651. if(resolution[jid] === null)
  7652. continue;
  7653. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7654. if(VideoLayout.connectionIndicators[id])
  7655. {
  7656. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7657. }
  7658. }
  7659. };
  7660. /**
  7661. * Updates remote stats.
  7662. * @param jid the jid associated with the stats
  7663. * @param percent the connection quality percent
  7664. * @param object the stats data
  7665. */
  7666. my.updateConnectionStats = function (jid, percent, object) {
  7667. var resourceJid = Strophe.getResourceFromJid(jid);
  7668. var videoSpanId = 'participant_' + resourceJid;
  7669. updateStatsIndicator(videoSpanId, percent, object);
  7670. };
  7671. /**
  7672. * Removes the connection
  7673. * @param jid
  7674. */
  7675. my.removeConnectionIndicator = function (jid) {
  7676. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7677. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7678. };
  7679. /**
  7680. * Hides the connection indicator
  7681. * @param jid
  7682. */
  7683. my.hideConnectionIndicator = function (jid) {
  7684. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7685. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7686. };
  7687. /**
  7688. * Hides all the indicators
  7689. */
  7690. my.onStatsStop = function () {
  7691. for(var indicator in VideoLayout.connectionIndicators)
  7692. {
  7693. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7694. }
  7695. };
  7696. my.participantLeft = function (jid) {
  7697. // Unlock large video
  7698. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7699. {
  7700. console.info("Focused video owner has left the conference");
  7701. focusedVideoInfo = null;
  7702. }
  7703. }
  7704. my.onVideoTypeChanged = function (jid) {
  7705. if(jid &&
  7706. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7707. {
  7708. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7709. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7710. ? getDesktopVideoSize
  7711. : getCameraVideoSize;
  7712. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7713. ? getDesktopVideoPosition
  7714. : getCameraVideoPosition;
  7715. VideoLayout.positionLarge(null, null);
  7716. }
  7717. }
  7718. return my;
  7719. }(VideoLayout || {}));
  7720. module.exports = VideoLayout;
  7721. },{"../../../service/RTC/MediaStreamTypes":88,"../../../service/UI/UIEvents":93,"../audio_levels/AudioLevels":9,"../avatar/Avatar":13,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/chat/Chat":18,"../side_pannels/contactlist/ContactList":22,"../util/NicknameHandler":29,"../util/UIUtil":30,"./ConnectionIndicator":31}],33:[function(require,module,exports){
  7722. //var nouns = [
  7723. //];
  7724. var pluralNouns = [
  7725. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7726. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7727. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7728. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7729. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7730. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7731. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7732. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7733. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7734. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7735. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7736. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7737. ];
  7738. //var places = [
  7739. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7740. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7741. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7742. // "Bridge"
  7743. //];
  7744. var verbs = [
  7745. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7746. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7747. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7748. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7749. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7750. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7751. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7752. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7753. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7754. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7755. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7756. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7757. ];
  7758. var adverbs = [
  7759. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7760. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7761. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7762. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7763. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7764. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7765. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7766. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7767. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7768. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7769. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7770. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7771. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7772. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7773. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7774. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7775. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7776. ];
  7777. var adjectives = [
  7778. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7779. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7780. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7781. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7782. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7783. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7784. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7785. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7786. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7787. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7788. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7789. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7790. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7791. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7792. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7793. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7794. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7795. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7796. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7797. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7798. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7799. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7800. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7801. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7802. "Zealous"
  7803. ];
  7804. //var pronouns = [
  7805. //];
  7806. //var conjunctions = [
  7807. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7808. //];
  7809. /*
  7810. * Maps a string (category name) to the array of words from that category.
  7811. */
  7812. var CATEGORIES =
  7813. {
  7814. //"_NOUN_": nouns,
  7815. "_PLURALNOUN_": pluralNouns,
  7816. //"_PLACE_": places,
  7817. "_VERB_": verbs,
  7818. "_ADVERB_": adverbs,
  7819. "_ADJECTIVE_": adjectives
  7820. //"_PRONOUN_": pronouns,
  7821. //"_CONJUNCTION_": conjunctions,
  7822. };
  7823. var PATTERNS = [
  7824. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7825. // BeautifulFungiOrSpaghetti
  7826. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7827. // AmazinglyScaryToy
  7828. //"_ADVERB__ADJECTIVE__NOUN_",
  7829. // NeitherTrashNorRifle
  7830. //"Neither_NOUN_Nor_NOUN_",
  7831. //"Either_NOUN_Or_NOUN_",
  7832. // EitherCopulateOrInvestigate
  7833. //"Either_VERB_Or_VERB_",
  7834. //"Neither_VERB_Nor_VERB_",
  7835. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7836. //"The_ADVERB__ADJECTIVE__NOUN_",
  7837. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7838. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7839. // WolvesComputeBadly
  7840. //"_PLURALNOUN__VERB__ADVERB_",
  7841. // UniteFacilitateAndMerge
  7842. //"_VERB__VERB_And_VERB_",
  7843. //NastyWitchesAtThePub
  7844. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7845. ];
  7846. /*
  7847. * Returns a random element from the array 'arr'
  7848. */
  7849. function randomElement(arr)
  7850. {
  7851. return arr[Math.floor(Math.random() * arr.length)];
  7852. }
  7853. /*
  7854. * Returns true if the string 's' contains one of the
  7855. * template strings.
  7856. */
  7857. function hasTemplate(s)
  7858. {
  7859. for (var template in CATEGORIES){
  7860. if (s.indexOf(template) >= 0){
  7861. return true;
  7862. }
  7863. }
  7864. }
  7865. /**
  7866. * Generates new room name.
  7867. */
  7868. var RoomNameGenerator = {
  7869. generateRoomWithoutSeparator: function()
  7870. {
  7871. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7872. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7873. var name = randomElement(PATTERNS);
  7874. var word;
  7875. while (hasTemplate(name)){
  7876. for (var template in CATEGORIES){
  7877. word = randomElement(CATEGORIES[template]);
  7878. name = name.replace(template, word);
  7879. }
  7880. }
  7881. return name;
  7882. }
  7883. }
  7884. module.exports = RoomNameGenerator;
  7885. },{}],34:[function(require,module,exports){
  7886. var animateTimeout, updateTimeout;
  7887. var RoomNameGenerator = require("./RoomnameGenerator");
  7888. function enter_room()
  7889. {
  7890. var val = $("#enter_room_field").val();
  7891. if(!val) {
  7892. val = $("#enter_room_field").attr("room_name");
  7893. }
  7894. if (val) {
  7895. window.location.pathname = "/" + val;
  7896. }
  7897. }
  7898. function animate(word) {
  7899. var currentVal = $("#enter_room_field").attr("placeholder");
  7900. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7901. animateTimeout = setTimeout(function() {
  7902. animate(word.substring(1, word.length))
  7903. }, 70);
  7904. }
  7905. function update_roomname()
  7906. {
  7907. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7908. $("#enter_room_field").attr("room_name", word);
  7909. $("#enter_room_field").attr("placeholder", "");
  7910. clearTimeout(animateTimeout);
  7911. animate(word);
  7912. updateTimeout = setTimeout(update_roomname, 10000);
  7913. }
  7914. function setupWelcomePage()
  7915. {
  7916. $("#videoconference_page").hide();
  7917. $("#domain_name").text(
  7918. window.location.protocol + "//" + window.location.host + "/");
  7919. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7920. var leftWatermarkDiv
  7921. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7922. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7923. {
  7924. leftWatermarkDiv.css({display: 'block'});
  7925. leftWatermarkDiv.parent().get(0).href
  7926. = interfaceConfig.JITSI_WATERMARK_LINK;
  7927. }
  7928. }
  7929. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7930. var rightWatermarkDiv
  7931. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7932. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7933. rightWatermarkDiv.css({display: 'block'});
  7934. rightWatermarkDiv.parent().get(0).href
  7935. = interfaceConfig.BRAND_WATERMARK_LINK;
  7936. rightWatermarkDiv.get(0).style.backgroundImage
  7937. = "url(images/rightwatermark.png)";
  7938. }
  7939. }
  7940. if (interfaceConfig.SHOW_POWERED_BY) {
  7941. $("#welcome_page_header>a[class='poweredby']")
  7942. .css({display: 'block'});
  7943. }
  7944. $("#enter_room_button").click(function()
  7945. {
  7946. enter_room();
  7947. });
  7948. $("#enter_room_field").keydown(function (event) {
  7949. if (event.keyCode === 13 /* enter */) {
  7950. enter_room();
  7951. }
  7952. });
  7953. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7954. var updateTimeout;
  7955. var animateTimeout;
  7956. $("#reload_roomname").click(function () {
  7957. clearTimeout(updateTimeout);
  7958. clearTimeout(animateTimeout);
  7959. update_roomname();
  7960. });
  7961. $("#reload_roomname").show();
  7962. update_roomname();
  7963. }
  7964. $("#disable_welcome").click(function () {
  7965. window.localStorage.welcomePageDisabled
  7966. = $("#disable_welcome").is(":checked");
  7967. });
  7968. }
  7969. module.exports = setupWelcomePage;
  7970. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7971. var EventEmitter = require("events");
  7972. var eventEmitter = new EventEmitter();
  7973. var CQEvents = require("../../service/connectionquality/CQEvents");
  7974. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7975. /**
  7976. * local stats
  7977. * @type {{}}
  7978. */
  7979. var stats = {};
  7980. /**
  7981. * remote stats
  7982. * @type {{}}
  7983. */
  7984. var remoteStats = {};
  7985. /**
  7986. * Interval for sending statistics to other participants
  7987. * @type {null}
  7988. */
  7989. var sendIntervalId = null;
  7990. /**
  7991. * Start statistics sending.
  7992. */
  7993. function startSendingStats() {
  7994. sendStats();
  7995. sendIntervalId = setInterval(sendStats, 10000);
  7996. }
  7997. /**
  7998. * Sends statistics to other participants
  7999. */
  8000. function sendStats() {
  8001. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8002. }
  8003. /**
  8004. * Converts statistics to format for sending through XMPP
  8005. * @param stats the statistics
  8006. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8007. */
  8008. function convertToMUCStats(stats) {
  8009. return {
  8010. "bitrate_download": stats.bitrate.download,
  8011. "bitrate_upload": stats.bitrate.upload,
  8012. "packetLoss_total": stats.packetLoss.total,
  8013. "packetLoss_download": stats.packetLoss.download,
  8014. "packetLoss_upload": stats.packetLoss.upload
  8015. };
  8016. }
  8017. /**
  8018. * Converts statitistics to format used by VideoLayout
  8019. * @param stats
  8020. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8021. */
  8022. function parseMUCStats(stats) {
  8023. return {
  8024. bitrate: {
  8025. download: stats.bitrate_download,
  8026. upload: stats.bitrate_upload
  8027. },
  8028. packetLoss: {
  8029. total: stats.packetLoss_total,
  8030. download: stats.packetLoss_download,
  8031. upload: stats.packetLoss_upload
  8032. }
  8033. };
  8034. }
  8035. var ConnectionQuality = {
  8036. init: function () {
  8037. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8038. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8039. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8040. },
  8041. /**
  8042. * Updates the local statistics
  8043. * @param data new statistics
  8044. */
  8045. updateLocalStats: function (data) {
  8046. stats = data;
  8047. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8048. if (sendIntervalId == null) {
  8049. startSendingStats();
  8050. }
  8051. },
  8052. /**
  8053. * Updates remote statistics
  8054. * @param jid the jid associated with the statistics
  8055. * @param data the statistics
  8056. */
  8057. updateRemoteStats: function (jid, data) {
  8058. if (data == null || data.packetLoss_total == null) {
  8059. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8060. return;
  8061. }
  8062. remoteStats[jid] = parseMUCStats(data);
  8063. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8064. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8065. },
  8066. /**
  8067. * Stops statistics sending.
  8068. */
  8069. stopSendingStats: function () {
  8070. clearInterval(sendIntervalId);
  8071. sendIntervalId = null;
  8072. //notify UI about stopping statistics gathering
  8073. eventEmitter.emit(CQEvents.STOP);
  8074. },
  8075. /**
  8076. * Returns the local statistics.
  8077. */
  8078. getStats: function () {
  8079. return stats;
  8080. },
  8081. addListener: function (type, listener) {
  8082. eventEmitter.on(type, listener);
  8083. }
  8084. };
  8085. module.exports = ConnectionQuality;
  8086. },{"../../service/connectionquality/CQEvents":95,"../../service/xmpp/XMPPEvents":98,"events":62}],36:[function(require,module,exports){
  8087. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8088. getUserMediaWithConstraints */
  8089. /**
  8090. * Indicates that desktop stream is currently in use(for toggle purpose).
  8091. * @type {boolean}
  8092. */
  8093. var isUsingScreenStream = false;
  8094. /**
  8095. * Indicates that switch stream operation is in progress and prevent from
  8096. * triggering new events.
  8097. * @type {boolean}
  8098. */
  8099. var switchInProgress = false;
  8100. /**
  8101. * Method used to get screen sharing stream.
  8102. *
  8103. * @type {function (stream_callback, failure_callback}
  8104. */
  8105. var obtainDesktopStream = null;
  8106. /**
  8107. * Indicates whether desktop sharing extension is installed.
  8108. * @type {boolean}
  8109. */
  8110. var extInstalled = false;
  8111. /**
  8112. * Indicates whether update of desktop sharing extension is required.
  8113. * @type {boolean}
  8114. */
  8115. var extUpdateRequired = false;
  8116. /**
  8117. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8118. * it can be <tt>null</tt>.
  8119. *
  8120. * @type {null|boolean}
  8121. */
  8122. var _desktopSharingEnabled = null;
  8123. var EventEmitter = require("events");
  8124. var eventEmitter = new EventEmitter();
  8125. var DesktopSharingEventTypes
  8126. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8127. /**
  8128. * Method obtains desktop stream from WebRTC 'screen' source.
  8129. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8130. */
  8131. function obtainWebRTCScreen(streamCallback, failCallback) {
  8132. APP.RTC.getUserMediaWithConstraints(
  8133. ['screen'],
  8134. streamCallback,
  8135. failCallback
  8136. );
  8137. }
  8138. /**
  8139. * Constructs inline install URL for Chrome desktop streaming extension.
  8140. * The 'chromeExtensionId' must be defined in config.js.
  8141. * @returns {string}
  8142. */
  8143. function getWebStoreInstallUrl()
  8144. {
  8145. return "https://chrome.google.com/webstore/detail/" +
  8146. config.chromeExtensionId;
  8147. }
  8148. /**
  8149. * Checks whether extension update is required.
  8150. * @param minVersion minimal required version
  8151. * @param extVersion current extension version
  8152. * @returns {boolean}
  8153. */
  8154. function isUpdateRequired(minVersion, extVersion)
  8155. {
  8156. try
  8157. {
  8158. var s1 = minVersion.split('.');
  8159. var s2 = extVersion.split('.');
  8160. var len = Math.max(s1.length, s2.length);
  8161. for (var i = 0; i < len; i++)
  8162. {
  8163. var n1 = 0,
  8164. n2 = 0;
  8165. if (i < s1.length)
  8166. n1 = parseInt(s1[i]);
  8167. if (i < s2.length)
  8168. n2 = parseInt(s2[i]);
  8169. if (isNaN(n1) || isNaN(n2))
  8170. {
  8171. return true;
  8172. }
  8173. else if (n1 !== n2)
  8174. {
  8175. return n1 > n2;
  8176. }
  8177. }
  8178. // will happen if boths version has identical numbers in
  8179. // their components (even if one of them is longer, has more components)
  8180. return false;
  8181. }
  8182. catch (e)
  8183. {
  8184. console.error("Failed to parse extension version", e);
  8185. APP.UI.messageHandler.showError("dialog.error",
  8186. "dialog.detectext");
  8187. return true;
  8188. }
  8189. }
  8190. function checkExtInstalled(callback) {
  8191. if (!chrome.runtime) {
  8192. // No API, so no extension for sure
  8193. callback(false, false);
  8194. return;
  8195. }
  8196. chrome.runtime.sendMessage(
  8197. config.chromeExtensionId,
  8198. { getVersion: true },
  8199. function (response) {
  8200. if (!response || !response.version) {
  8201. // Communication failure - assume that no endpoint exists
  8202. console.warn(
  8203. "Extension not installed?: ", chrome.runtime.lastError);
  8204. callback(false, false);
  8205. return;
  8206. }
  8207. // Check installed extension version
  8208. var extVersion = response.version;
  8209. console.log('Extension version is: ' + extVersion);
  8210. var updateRequired
  8211. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8212. callback(!updateRequired, updateRequired);
  8213. }
  8214. );
  8215. }
  8216. function doGetStreamFromExtension(streamCallback, failCallback) {
  8217. // Sends 'getStream' msg to the extension.
  8218. // Extension id must be defined in the config.
  8219. chrome.runtime.sendMessage(
  8220. config.chromeExtensionId,
  8221. { getStream: true, sources: config.desktopSharingSources },
  8222. function (response) {
  8223. if (!response) {
  8224. failCallback(chrome.runtime.lastError);
  8225. return;
  8226. }
  8227. console.log("Response from extension: " + response);
  8228. if (response.streamId) {
  8229. APP.RTC.getUserMediaWithConstraints(
  8230. ['desktop'],
  8231. function (stream) {
  8232. streamCallback(stream);
  8233. },
  8234. failCallback,
  8235. null, null, null,
  8236. response.streamId);
  8237. } else {
  8238. failCallback("Extension failed to get the stream");
  8239. }
  8240. }
  8241. );
  8242. }
  8243. /**
  8244. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8245. * stream for returned stream token.
  8246. */
  8247. function obtainScreenFromExtension(streamCallback, failCallback) {
  8248. if (extInstalled) {
  8249. doGetStreamFromExtension(streamCallback, failCallback);
  8250. } else {
  8251. if (extUpdateRequired) {
  8252. alert(
  8253. 'Jitsi Desktop Streamer requires update. ' +
  8254. 'Changes will take effect after next Chrome restart.');
  8255. }
  8256. chrome.webstore.install(
  8257. getWebStoreInstallUrl(),
  8258. function (arg) {
  8259. console.log("Extension installed successfully", arg);
  8260. // We need to reload the page in order to get the access to
  8261. // chrome.runtime
  8262. window.location.reload(false);
  8263. },
  8264. function (arg) {
  8265. console.log("Failed to install the extension", arg);
  8266. failCallback(arg);
  8267. APP.UI.messageHandler.showError("dialog.error",
  8268. "dialog.failtoinstall");
  8269. }
  8270. );
  8271. }
  8272. }
  8273. /**
  8274. * Call this method to toggle desktop sharing feature.
  8275. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8276. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8277. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8278. * enabled), pass any other string or nothing in order to disable this
  8279. * feature completely.
  8280. */
  8281. function setDesktopSharing(method) {
  8282. // Check if we are running chrome
  8283. if (!navigator.webkitGetUserMedia) {
  8284. obtainDesktopStream = null;
  8285. console.info("Desktop sharing disabled");
  8286. } else if (method == "ext") {
  8287. obtainDesktopStream = obtainScreenFromExtension;
  8288. console.info("Using Chrome extension for desktop sharing");
  8289. } else if (method == "webrtc") {
  8290. obtainDesktopStream = obtainWebRTCScreen;
  8291. console.info("Using Chrome WebRTC for desktop sharing");
  8292. }
  8293. // Reset enabled cache
  8294. _desktopSharingEnabled = null;
  8295. }
  8296. /**
  8297. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8298. * config.js to support inline installs. Host site must be selected as main
  8299. * website of published extension.
  8300. */
  8301. function initInlineInstalls()
  8302. {
  8303. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8304. }
  8305. function getVideoStreamFailed(error) {
  8306. console.error("Failed to obtain the stream to switch to", error);
  8307. switchInProgress = false;
  8308. isUsingScreenStream = false;
  8309. newStreamCreated(null);
  8310. }
  8311. function getDesktopStreamFailed(error) {
  8312. console.error("Failed to obtain the stream to switch to", error);
  8313. switchInProgress = false;
  8314. }
  8315. function streamSwitchDone() {
  8316. switchInProgress = false;
  8317. eventEmitter.emit(
  8318. DesktopSharingEventTypes.SWITCHING_DONE,
  8319. isUsingScreenStream);
  8320. }
  8321. function newStreamCreated(stream)
  8322. {
  8323. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8324. stream, isUsingScreenStream, streamSwitchDone);
  8325. }
  8326. module.exports = {
  8327. isUsingScreenStream: function () {
  8328. return isUsingScreenStream;
  8329. },
  8330. /**
  8331. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8332. * and enabled.
  8333. */
  8334. isDesktopSharingEnabled: function () {
  8335. if (_desktopSharingEnabled === null) {
  8336. if (obtainDesktopStream === obtainScreenFromExtension) {
  8337. // Parse chrome version
  8338. var userAgent = navigator.userAgent.toLowerCase();
  8339. // We can assume that user agent is chrome, because it's
  8340. // enforced when 'ext' streaming method is set
  8341. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8342. console.log("Chrome version" + userAgent, ver);
  8343. _desktopSharingEnabled = ver >= 34;
  8344. } else {
  8345. _desktopSharingEnabled =
  8346. obtainDesktopStream === obtainWebRTCScreen;
  8347. }
  8348. }
  8349. return _desktopSharingEnabled;
  8350. },
  8351. init: function () {
  8352. setDesktopSharing(config.desktopSharing);
  8353. // Initialize Chrome extension inline installs
  8354. if (config.chromeExtensionId) {
  8355. initInlineInstalls();
  8356. // Check if extension is installed
  8357. checkExtInstalled(function (installed, updateRequired) {
  8358. extInstalled = installed;
  8359. extUpdateRequired = updateRequired;
  8360. console.info(
  8361. "Chrome extension installed: " + extInstalled +
  8362. " updateRequired: " + extUpdateRequired);
  8363. });
  8364. }
  8365. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8366. },
  8367. addListener: function (listener, type)
  8368. {
  8369. eventEmitter.on(type, listener);
  8370. },
  8371. removeListener: function (listener, type) {
  8372. eventEmitter.removeListener(type, listener);
  8373. },
  8374. /*
  8375. * Toggles screen sharing.
  8376. */
  8377. toggleScreenSharing: function () {
  8378. if (switchInProgress || !obtainDesktopStream) {
  8379. console.warn("Switch in progress or no method defined");
  8380. return;
  8381. }
  8382. switchInProgress = true;
  8383. if (!isUsingScreenStream)
  8384. {
  8385. // Switch to desktop stream
  8386. obtainDesktopStream(
  8387. function (stream) {
  8388. // We now use screen stream
  8389. isUsingScreenStream = true;
  8390. // Hook 'ended' event to restore camera
  8391. // when screen stream stops
  8392. stream.addEventListener('ended',
  8393. function (e) {
  8394. if (!switchInProgress && isUsingScreenStream) {
  8395. APP.desktopsharing.toggleScreenSharing();
  8396. }
  8397. }
  8398. );
  8399. newStreamCreated(stream);
  8400. },
  8401. getDesktopStreamFailed);
  8402. } else {
  8403. // Disable screen stream
  8404. APP.RTC.getUserMediaWithConstraints(
  8405. ['video'],
  8406. function (stream) {
  8407. // We are now using camera stream
  8408. isUsingScreenStream = false;
  8409. newStreamCreated(stream);
  8410. },
  8411. getVideoStreamFailed, config.resolution || '360'
  8412. );
  8413. }
  8414. }
  8415. };
  8416. },{"../../service/desktopsharing/DesktopSharingEventTypes":96,"events":62}],37:[function(require,module,exports){
  8417. //maps keycode to character, id of popover for given function and function
  8418. var shortcuts = {
  8419. 67: {
  8420. character: "C",
  8421. id: "toggleChatPopover",
  8422. function: APP.UI.toggleChat
  8423. },
  8424. 70: {
  8425. character: "F",
  8426. id: "filmstripPopover",
  8427. function: APP.UI.toggleFilmStrip
  8428. },
  8429. 77: {
  8430. character: "M",
  8431. id: "mutePopover",
  8432. function: APP.UI.toggleAudio
  8433. },
  8434. 84: {
  8435. character: "T",
  8436. function: function() {
  8437. if(!APP.RTC.localAudio.isMuted()) {
  8438. APP.UI.toggleAudio();
  8439. }
  8440. }
  8441. },
  8442. 86: {
  8443. character: "V",
  8444. id: "toggleVideoPopover",
  8445. function: APP.UI.toggleVideo
  8446. }
  8447. };
  8448. var KeyboardShortcut = {
  8449. init: function () {
  8450. window.onkeyup = function(e) {
  8451. var keycode = e.which;
  8452. if(!($(":focus").is("input[type=text]") ||
  8453. $(":focus").is("input[type=password]") ||
  8454. $(":focus").is("textarea"))) {
  8455. if (typeof shortcuts[keycode] === "object") {
  8456. shortcuts[keycode].function();
  8457. }
  8458. else if (keycode >= "0".charCodeAt(0) &&
  8459. keycode <= "9".charCodeAt(0)) {
  8460. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8461. }
  8462. //esc while the smileys are visible hides them
  8463. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8464. APP.UI.toggleSmileys();
  8465. }
  8466. };
  8467. window.onkeydown = function(e) {
  8468. if(!($(":focus").is("input[type=text]") ||
  8469. $(":focus").is("input[type=password]") ||
  8470. $(":focus").is("textarea"))) {
  8471. if(e.which === "T".charCodeAt(0)) {
  8472. if(APP.RTC.localAudio.isMuted()) {
  8473. APP.UI.toggleAudio();
  8474. }
  8475. }
  8476. }
  8477. };
  8478. var self = this;
  8479. $('body').popover({ selector: '[data-toggle=popover]',
  8480. trigger: 'click hover',
  8481. content: function() {
  8482. return this.getAttribute("content") +
  8483. self.getShortcut(this.getAttribute("shortcut"));
  8484. }
  8485. });
  8486. },
  8487. /**
  8488. *
  8489. * @param id indicates the popover associated with the shortcut
  8490. * @returns {string} the keyboard shortcut used for the id given
  8491. */
  8492. getShortcut: function (id) {
  8493. for (var keycode in shortcuts) {
  8494. if (shortcuts.hasOwnProperty(keycode)) {
  8495. if (shortcuts[keycode].id === id) {
  8496. return " (" + shortcuts[keycode].character + ")";
  8497. }
  8498. }
  8499. }
  8500. return "";
  8501. }
  8502. };
  8503. module.exports = KeyboardShortcut;
  8504. },{}],38:[function(require,module,exports){
  8505. var email = '';
  8506. var displayName = '';
  8507. var userId;
  8508. var language = null;
  8509. function supportsLocalStorage() {
  8510. try {
  8511. return 'localStorage' in window && window.localStorage !== null;
  8512. } catch (e) {
  8513. console.log("localstorage is not supported");
  8514. return false;
  8515. }
  8516. }
  8517. function generateUniqueId() {
  8518. function _p8() {
  8519. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8520. }
  8521. return _p8() + _p8() + _p8() + _p8();
  8522. }
  8523. if (supportsLocalStorage()) {
  8524. if (!window.localStorage.jitsiMeetId) {
  8525. window.localStorage.jitsiMeetId = generateUniqueId();
  8526. console.log("generated id", window.localStorage.jitsiMeetId);
  8527. }
  8528. userId = window.localStorage.jitsiMeetId || '';
  8529. email = window.localStorage.email || '';
  8530. displayName = window.localStorage.displayname || '';
  8531. language = window.localStorage.language;
  8532. } else {
  8533. console.log("local storage is not supported");
  8534. userId = generateUniqueId();
  8535. }
  8536. var Settings =
  8537. {
  8538. setDisplayName: function (newDisplayName) {
  8539. displayName = newDisplayName;
  8540. window.localStorage.displayname = displayName;
  8541. return displayName;
  8542. },
  8543. setEmail: function (newEmail)
  8544. {
  8545. email = newEmail;
  8546. window.localStorage.email = newEmail;
  8547. return email;
  8548. },
  8549. getSettings: function () {
  8550. return {
  8551. email: email,
  8552. displayName: displayName,
  8553. uid: userId,
  8554. language: language
  8555. };
  8556. },
  8557. setLanguage: function (lang) {
  8558. language = lang;
  8559. window.localStorage.language = lang;
  8560. }
  8561. };
  8562. module.exports = Settings;
  8563. },{}],39:[function(require,module,exports){
  8564. /**
  8565. *
  8566. * @constructor
  8567. */
  8568. function SimulcastLogger(name, lvl) {
  8569. this.name = name;
  8570. this.lvl = lvl;
  8571. }
  8572. SimulcastLogger.prototype.log = function (text) {
  8573. if (this.lvl) {
  8574. console.log(text);
  8575. }
  8576. };
  8577. SimulcastLogger.prototype.info = function (text) {
  8578. if (this.lvl > 1) {
  8579. console.info(text);
  8580. }
  8581. };
  8582. SimulcastLogger.prototype.fine = function (text) {
  8583. if (this.lvl > 2) {
  8584. console.log(text);
  8585. }
  8586. };
  8587. SimulcastLogger.prototype.error = function (text) {
  8588. console.error(text);
  8589. };
  8590. module.exports = SimulcastLogger;
  8591. },{}],40:[function(require,module,exports){
  8592. var SimulcastLogger = require("./SimulcastLogger");
  8593. var SimulcastUtils = require("./SimulcastUtils");
  8594. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8595. function SimulcastReceiver() {
  8596. this.simulcastUtils = new SimulcastUtils();
  8597. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8598. }
  8599. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8600. SimulcastReceiver.prototype._remoteMaps = {
  8601. msid2Quality: {},
  8602. ssrc2Msid: {},
  8603. msid2ssrc: {},
  8604. receivingVideoStreams: {}
  8605. };
  8606. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8607. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8608. };
  8609. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8610. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8611. };
  8612. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8613. var sb;
  8614. this.logger.info('Ensuring x-google-conference flag...')
  8615. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8616. // TODO(gp) do that for the audio as well as suggested by fippo.
  8617. // Add the google conference flag
  8618. sb = this.simulcastUtils._getVideoSources(lines);
  8619. sb = ['a=x-google-flag:conference'].concat(sb);
  8620. this.simulcastUtils._replaceVideoSources(lines, sb);
  8621. }
  8622. };
  8623. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8624. this._restoreRemoteVideoSources(sb);
  8625. };
  8626. /**
  8627. * Restores the simulcast groups of the remote description. In
  8628. * transformRemoteDescription we remove those in order for the set remote
  8629. * description to succeed. The focus needs the signal the groups to new
  8630. * participants.
  8631. *
  8632. * @param desc
  8633. * @returns {*}
  8634. */
  8635. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8636. var sb;
  8637. if (!this.simulcastUtils.isValidDescription(desc)) {
  8638. return desc;
  8639. }
  8640. if (config.enableSimulcast) {
  8641. sb = desc.sdp.split('\r\n');
  8642. this._restoreSimulcastGroups(sb);
  8643. desc = new RTCSessionDescription({
  8644. type: desc.type,
  8645. sdp: sb.join('\r\n')
  8646. });
  8647. }
  8648. return desc;
  8649. };
  8650. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8651. var videoSources, sb;
  8652. videoSources = this.parseMedia(lines, ['video'])[0];
  8653. sb = this._compileVideoSources(videoSources);
  8654. this._replaceVideoSources(lines, sb);
  8655. };
  8656. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8657. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8658. videoSource, quality;
  8659. // (re) initialize the remote maps.
  8660. this._remoteMaps.msid2Quality = {};
  8661. this._remoteMaps.ssrc2Msid = {};
  8662. this._remoteMaps.msid2ssrc = {};
  8663. var self = this;
  8664. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8665. remoteVideoSources.groups.forEach(function (group) {
  8666. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8667. quality = 0;
  8668. group.ssrcs.forEach(function (ssrc) {
  8669. videoSource = remoteVideoSources.sources[ssrc];
  8670. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8671. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8672. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8673. });
  8674. }
  8675. });
  8676. }
  8677. };
  8678. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8679. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8680. };
  8681. /**
  8682. * Returns a stream with single video track, the one currently being
  8683. * received by this endpoint.
  8684. *
  8685. * @param stream the remote simulcast stream.
  8686. * @returns {webkitMediaStream}
  8687. */
  8688. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8689. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8690. var self = this;
  8691. if (config.enableSimulcast) {
  8692. stream.getVideoTracks().some(function (track) {
  8693. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8694. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8695. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8696. if (msid == [stream.id, track.id].join(' ')) {
  8697. electedTrack = track;
  8698. return true;
  8699. }
  8700. });
  8701. });
  8702. if (!electedTrack) {
  8703. // we don't have an elected track, choose by initial quality.
  8704. tracks = stream.getVideoTracks();
  8705. for (i = 0; i < tracks.length; i++) {
  8706. msid = [stream.id, tracks[i].id].join(' ');
  8707. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8708. electedTrack = tracks[i];
  8709. break;
  8710. }
  8711. }
  8712. // TODO(gp) if the initialQuality could not be satisfied, lower
  8713. // the requirement and try again.
  8714. }
  8715. }
  8716. return (electedTrack)
  8717. ? new webkitMediaStream([electedTrack])
  8718. : stream;
  8719. };
  8720. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8721. var resource = Strophe.getResourceFromJid(jid);
  8722. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8723. // If we haven't receiving a "changed" event yet, then we must be receiving
  8724. // low quality (that the sender always streams).
  8725. if(!ssrc)
  8726. {
  8727. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8728. var remoteStream = remoteStreamObject.getOriginalStream();
  8729. var tracks = remoteStream.getVideoTracks();
  8730. if (tracks) {
  8731. for (var k = 0; k < tracks.length; k++) {
  8732. var track = tracks[k];
  8733. var msid = [remoteStream.id, track.id].join(' ');
  8734. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8735. var quality = this._remoteMaps.msid2Quality[msid];
  8736. if (quality == 0) {
  8737. ssrc = _ssrc;
  8738. }
  8739. }
  8740. }
  8741. }
  8742. return ssrc;
  8743. };
  8744. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8745. {
  8746. var sid, electedStream;
  8747. var i, j, k;
  8748. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8749. if(jid && APP.RTC.remoteStreams[jid])
  8750. {
  8751. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8752. var remoteStream = remoteStreamObject.getOriginalStream();
  8753. var tracks = remoteStream.getVideoTracks();
  8754. if (tracks) {
  8755. for (k = 0; k < tracks.length; k++) {
  8756. var track = tracks[k];
  8757. var msid = [remoteStream.id, track.id].join(' ');
  8758. var tmp = this._remoteMaps.msid2ssrc[msid];
  8759. if (tmp == ssrc) {
  8760. electedStream = new webkitMediaStream([track]);
  8761. sid = remoteStreamObject.sid;
  8762. // stream found, stop.
  8763. break;
  8764. }
  8765. }
  8766. }
  8767. }
  8768. else
  8769. {
  8770. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8771. }
  8772. return {
  8773. sid: sid,
  8774. stream: electedStream
  8775. };
  8776. };
  8777. /**
  8778. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8779. * SSRC.
  8780. *
  8781. * @param ssrc
  8782. * @returns {*}
  8783. */
  8784. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8785. return this._remoteMaps.ssrc2Msid[ssrc];
  8786. };
  8787. /**
  8788. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8789. * either gets confused and thinks this is an FID group or, if an FID group
  8790. * is already present, it fails to set the remote description.
  8791. *
  8792. * @param desc
  8793. * @returns {*}
  8794. */
  8795. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8796. if (desc && desc.sdp) {
  8797. var sb = desc.sdp.split('\r\n');
  8798. this._updateRemoteMaps(sb);
  8799. this._cacheRemoteVideoSources(sb);
  8800. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8801. // need the simulcast group in the _updateRemoteMaps() method.
  8802. this.simulcastUtils._removeSimulcastGroup(sb);
  8803. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8804. // We don't need the goog conference flag if we're not doing
  8805. // simulcast.
  8806. this._ensureGoogConference(sb);
  8807. }
  8808. desc = new RTCSessionDescription({
  8809. type: desc.type,
  8810. sdp: sb.join('\r\n')
  8811. });
  8812. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8813. }
  8814. return desc;
  8815. };
  8816. module.exports = SimulcastReceiver;
  8817. },{"../../service/RTC/MediaStreamTypes":88,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8818. var SimulcastLogger = require("./SimulcastLogger");
  8819. var SimulcastUtils = require("./SimulcastUtils");
  8820. function SimulcastSender() {
  8821. this.simulcastUtils = new SimulcastUtils();
  8822. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8823. }
  8824. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8825. SimulcastSender.prototype._generateGuid = (function () {
  8826. function s4() {
  8827. return Math.floor((1 + Math.random()) * 0x10000)
  8828. .toString(16)
  8829. .substring(1);
  8830. }
  8831. return function () {
  8832. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8833. s4() + '-' + s4() + s4() + s4();
  8834. };
  8835. }());
  8836. // Returns a random integer between min (included) and max (excluded)
  8837. // Using Math.round() gives a non-uniform distribution!
  8838. SimulcastSender.prototype._generateRandomSSRC = function () {
  8839. var min = 0, max = 0xffffffff;
  8840. return Math.floor(Math.random() * (max - min)) + min;
  8841. };
  8842. SimulcastSender.prototype.getLocalVideoStream = function () {
  8843. return (this.displayedLocalVideoStream != null)
  8844. ? this.displayedLocalVideoStream
  8845. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8846. : APP.RTC.localVideo.getOriginalStream();
  8847. };
  8848. function NativeSimulcastSender() {
  8849. SimulcastSender.call(this); // call the super constructor.
  8850. }
  8851. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8852. NativeSimulcastSender.prototype._localExplosionMap = {};
  8853. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8854. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8855. NativeSimulcastSender.prototype.reset = function () {
  8856. this._localExplosionMap = {};
  8857. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8858. };
  8859. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8860. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8861. };
  8862. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8863. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8864. };
  8865. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8866. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8867. this.logger.info('Appending simulcast group...');
  8868. // Get the primary SSRC information.
  8869. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8870. // Start building the SIM SSRC group.
  8871. ssrcGroup = ['a=ssrc-group:SIM'];
  8872. // The video source buffer.
  8873. sb = [];
  8874. // Create the simulcast sub-streams.
  8875. for (i = 0; i < numOfSubs; i++) {
  8876. // TODO(gp) prevent SSRC collision.
  8877. simSSRC = this._generateRandomSSRC();
  8878. ssrcGroup.push(simSSRC);
  8879. if (videoSources.base) {
  8880. sb.splice.apply(sb, [sb.length, 0].concat(
  8881. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8882. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8883. ));
  8884. }
  8885. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8886. }
  8887. // Add the group sim layers.
  8888. sb.splice(0, 0, ssrcGroup.join(' '))
  8889. this.simulcastUtils._replaceVideoSources(lines, sb);
  8890. };
  8891. // Does the actual patching.
  8892. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8893. this.logger.info('Ensuring simulcast group...');
  8894. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8895. this._appendSimulcastGroup(lines);
  8896. this._cacheLocalVideoSources(lines);
  8897. } else {
  8898. // verify that the ssrcs participating in the SIM group are present
  8899. // in the SDP (needed for presence).
  8900. this._restoreLocalVideoSources(lines);
  8901. }
  8902. };
  8903. /**
  8904. * Produces a single stream with multiple tracks for local video sources.
  8905. *
  8906. * @param lines
  8907. * @private
  8908. */
  8909. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8910. var sb, msid, sid, tid, videoSources, self;
  8911. this.logger.info('Exploding local video sources...');
  8912. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8913. self = this;
  8914. if (videoSources.groups && videoSources.groups.length !== 0) {
  8915. videoSources.groups.forEach(function (group) {
  8916. if (group.semantics === 'SIM') {
  8917. group.ssrcs.forEach(function (ssrc) {
  8918. // Get the msid for this ssrc..
  8919. if (self._localExplosionMap[ssrc]) {
  8920. // .. either from the explosion map..
  8921. msid = self._localExplosionMap[ssrc];
  8922. } else {
  8923. // .. or generate a new one (msid).
  8924. sid = videoSources.sources[ssrc].msid
  8925. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8926. tid = self._generateGuid();
  8927. msid = [sid, tid].join(' ');
  8928. self._localExplosionMap[ssrc] = msid;
  8929. }
  8930. // Assign it to the source object.
  8931. videoSources.sources[ssrc].msid = msid;
  8932. // TODO(gp) Change the msid of associated sources.
  8933. });
  8934. }
  8935. });
  8936. }
  8937. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8938. this.simulcastUtils._replaceVideoSources(lines, sb);
  8939. };
  8940. /**
  8941. * GUM for simulcast.
  8942. *
  8943. * @param constraints
  8944. * @param success
  8945. * @param err
  8946. */
  8947. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8948. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8949. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8950. success(hqStream);
  8951. }, err);
  8952. };
  8953. /**
  8954. * Prepares the local description for public usage (i.e. to be signaled
  8955. * through Jingle to the focus).
  8956. *
  8957. * @param desc
  8958. * @returns {RTCSessionDescription}
  8959. */
  8960. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8961. var sb;
  8962. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8963. return desc;
  8964. }
  8965. sb = desc.sdp.split('\r\n');
  8966. this._explodeSimulcastSenderSources(sb);
  8967. desc = new RTCSessionDescription({
  8968. type: desc.type,
  8969. sdp: sb.join('\r\n')
  8970. });
  8971. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8972. return desc;
  8973. };
  8974. /**
  8975. * Ensures that the simulcast group is present in the answer, _if_ native
  8976. * simulcast is enabled,
  8977. *
  8978. * @param desc
  8979. * @returns {*}
  8980. */
  8981. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8982. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8983. return desc;
  8984. }
  8985. var sb = desc.sdp.split('\r\n');
  8986. // Even if we have enabled native simulcasting previously
  8987. // (with a call to SLD with an appropriate SDP, for example),
  8988. // createAnswer seems to consistently generate incomplete SDP
  8989. // with missing SSRCS.
  8990. //
  8991. // So, subsequent calls to SLD will have missing SSRCS and presence
  8992. // won't have the complete list of SRCs.
  8993. this._ensureSimulcastGroup(sb);
  8994. desc = new RTCSessionDescription({
  8995. type: desc.type,
  8996. sdp: sb.join('\r\n')
  8997. });
  8998. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8999. return desc;
  9000. };
  9001. /**
  9002. *
  9003. *
  9004. * @param desc
  9005. * @returns {*}
  9006. */
  9007. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9008. return desc;
  9009. };
  9010. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9011. // Nothing to do here, native simulcast does that auto-magically.
  9012. };
  9013. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  9014. function SimpleSimulcastSender() {
  9015. SimulcastSender.call(this);
  9016. }
  9017. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9018. SimpleSimulcastSender.prototype.localStream = null;
  9019. SimpleSimulcastSender.prototype._localMaps = {
  9020. msids: [],
  9021. msid2ssrc: {}
  9022. };
  9023. /**
  9024. * Groups local video sources together in the ssrc-group:SIM group.
  9025. *
  9026. * @param lines
  9027. * @private
  9028. */
  9029. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  9030. var sb, videoSources, ssrcs = [], ssrc;
  9031. this.logger.info('Grouping local video sources...');
  9032. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9033. for (ssrc in videoSources.sources) {
  9034. // jitsi-meet destroys/creates streams at various places causing
  9035. // the original local stream ids to change. The only thing that
  9036. // remains unchanged is the trackid.
  9037. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  9038. }
  9039. var self = this;
  9040. // TODO(gp) add only "free" sources.
  9041. this._localMaps.msids.forEach(function (msid) {
  9042. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  9043. });
  9044. if (!videoSources.groups) {
  9045. videoSources.groups = [];
  9046. }
  9047. videoSources.groups.push({
  9048. 'semantics': 'SIM',
  9049. 'ssrcs': ssrcs
  9050. });
  9051. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9052. this.simulcastUtils._replaceVideoSources(lines, sb);
  9053. };
  9054. /**
  9055. * GUM for simulcast.
  9056. *
  9057. * @param constraints
  9058. * @param success
  9059. * @param err
  9060. */
  9061. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9062. // TODO(gp) what if we request a resolution not supported by the hardware?
  9063. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  9064. var lqConstraints = {
  9065. audio: false,
  9066. video: {
  9067. mandatory: {
  9068. maxWidth: 320,
  9069. maxHeight: 180,
  9070. maxFrameRate: 15
  9071. }
  9072. }
  9073. };
  9074. this.logger.info('HQ constraints: ', constraints);
  9075. this.logger.info('LQ constraints: ', lqConstraints);
  9076. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  9077. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  9078. // reason appears to be that Chrome only acquires the cam once and
  9079. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  9080. var self = this;
  9081. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9082. self.localStream = hqStream;
  9083. // reset local maps.
  9084. self._localMaps.msids = [];
  9085. self._localMaps.msid2ssrc = {};
  9086. // add hq trackid to local map
  9087. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  9088. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  9089. self.displayedLocalVideoStream = lqStream;
  9090. // NOTE(gp) The specification says Array.forEach() will visit
  9091. // the array elements in numeric order, and that it doesn't
  9092. // visit elements that don't exist.
  9093. // add lq trackid to local map
  9094. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  9095. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  9096. success(self.localStream);
  9097. }, err);
  9098. }, err);
  9099. };
  9100. /**
  9101. * Prepares the local description for public usage (i.e. to be signaled
  9102. * through Jingle to the focus).
  9103. *
  9104. * @param desc
  9105. * @returns {RTCSessionDescription}
  9106. */
  9107. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9108. var sb;
  9109. if (!this.simulcastUtils.isValidDescription(desc)) {
  9110. return desc;
  9111. }
  9112. sb = desc.sdp.split('\r\n');
  9113. this._groupLocalVideoSources(sb);
  9114. desc = new RTCSessionDescription({
  9115. type: desc.type,
  9116. sdp: sb.join('\r\n')
  9117. });
  9118. this.logger.fine('Grouped local video sources');
  9119. this.logger.fine(desc.sdp);
  9120. return desc;
  9121. };
  9122. /**
  9123. * Ensures that the simulcast group is present in the answer, _if_ native
  9124. * simulcast is enabled,
  9125. *
  9126. * @param desc
  9127. * @returns {*}
  9128. */
  9129. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  9130. return desc;
  9131. };
  9132. /**
  9133. *
  9134. *
  9135. * @param desc
  9136. * @returns {*}
  9137. */
  9138. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9139. var sb = desc.sdp.split('\r\n');
  9140. this.simulcastUtils._removeSimulcastGroup(sb);
  9141. desc = new RTCSessionDescription({
  9142. type: desc.type,
  9143. sdp: sb.join('\r\n')
  9144. });
  9145. this.logger.fine('Transformed local description');
  9146. this.logger.fine(desc.sdp);
  9147. return desc;
  9148. };
  9149. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9150. var trackid;
  9151. var self = this;
  9152. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  9153. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  9154. // Search for the track id that corresponds to the ssrc
  9155. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  9156. trackid = tid;
  9157. return true;
  9158. }
  9159. }) && self.localStream.getVideoTracks().some(function (track) {
  9160. // Start/stop the track that corresponds to the track id
  9161. if (track.id === trackid) {
  9162. track.enabled = enabled;
  9163. return true;
  9164. }
  9165. })) {
  9166. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9167. $(document).trigger(enabled
  9168. ? 'simulcastlayerstarted'
  9169. : 'simulcastlayerstopped');
  9170. } else {
  9171. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9172. }
  9173. };
  9174. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9175. function NoSimulcastSender() {
  9176. SimulcastSender.call(this);
  9177. }
  9178. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9179. /**
  9180. * GUM for simulcast.
  9181. *
  9182. * @param constraints
  9183. * @param success
  9184. * @param err
  9185. */
  9186. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9187. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9188. success(hqStream);
  9189. }, err);
  9190. };
  9191. /**
  9192. * Prepares the local description for public usage (i.e. to be signaled
  9193. * through Jingle to the focus).
  9194. *
  9195. * @param desc
  9196. * @returns {RTCSessionDescription}
  9197. */
  9198. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9199. return desc;
  9200. };
  9201. /**
  9202. * Ensures that the simulcast group is present in the answer, _if_ native
  9203. * simulcast is enabled,
  9204. *
  9205. * @param desc
  9206. * @returns {*}
  9207. */
  9208. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9209. return desc;
  9210. };
  9211. /**
  9212. *
  9213. *
  9214. * @param desc
  9215. * @returns {*}
  9216. */
  9217. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9218. return desc;
  9219. };
  9220. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9221. };
  9222. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9223. module.exports = {
  9224. "native": NativeSimulcastSender,
  9225. "no": NoSimulcastSender
  9226. }
  9227. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  9228. var SimulcastLogger = require("./SimulcastLogger");
  9229. /**
  9230. *
  9231. * @constructor
  9232. */
  9233. function SimulcastUtils() {
  9234. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9235. }
  9236. /**
  9237. *
  9238. * @type {{}}
  9239. * @private
  9240. */
  9241. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9242. /**
  9243. *
  9244. * @param lines
  9245. * @param videoSources
  9246. * @private
  9247. */
  9248. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9249. var i, inVideo = false, index = -1, howMany = 0;
  9250. this.logger.info('Replacing video sources...');
  9251. for (i = 0; i < lines.length; i++) {
  9252. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9253. // Out of video.
  9254. break;
  9255. }
  9256. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9257. // In video.
  9258. inVideo = true;
  9259. }
  9260. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9261. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9262. if (index === -1) {
  9263. index = i;
  9264. }
  9265. howMany++;
  9266. }
  9267. }
  9268. // efficiency baby ;)
  9269. lines.splice.apply(lines,
  9270. [index, howMany].concat(videoSources));
  9271. };
  9272. SimulcastUtils.prototype.isValidDescription = function (desc)
  9273. {
  9274. return desc && desc != null
  9275. && desc.type && desc.type != ''
  9276. && desc.sdp && desc.sdp != '';
  9277. };
  9278. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9279. var i, inVideo = false, sb = [];
  9280. this.logger.info('Getting video sources...');
  9281. for (i = 0; i < lines.length; i++) {
  9282. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9283. // Out of video.
  9284. break;
  9285. }
  9286. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9287. // In video.
  9288. inVideo = true;
  9289. }
  9290. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9291. // In SSRC.
  9292. sb.push(lines[i]);
  9293. }
  9294. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9295. sb.push(lines[i]);
  9296. }
  9297. }
  9298. return sb;
  9299. };
  9300. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9301. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9302. ssrc_attribute, group, semantics, skip = true;
  9303. this.logger.info('Parsing media sources...');
  9304. for (i = 0; i < lines.length; i++) {
  9305. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9306. type = lines[i]
  9307. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9308. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9309. if (!skip) {
  9310. cur_media = {
  9311. 'type': type,
  9312. 'sources': {},
  9313. 'groups': []
  9314. };
  9315. res.push(cur_media);
  9316. }
  9317. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9318. idx = lines[i].indexOf(' ');
  9319. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9320. if (cur_media.sources[ssrc] === undefined) {
  9321. cur_ssrc = {'ssrc': ssrc};
  9322. cur_media.sources[ssrc] = cur_ssrc;
  9323. }
  9324. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9325. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9326. if (cur_media.base === undefined) {
  9327. cur_media.base = cur_ssrc;
  9328. }
  9329. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9330. idx = lines[i].indexOf(' ');
  9331. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9332. ssrcs = lines[i].substr(idx).trim().split(' ');
  9333. group = {
  9334. 'semantics': semantics,
  9335. 'ssrcs': ssrcs
  9336. };
  9337. cur_media.groups.push(group);
  9338. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9339. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9340. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9341. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9342. cur_media.direction = lines[i].substring('a='.length);
  9343. }
  9344. }
  9345. return res;
  9346. };
  9347. /**
  9348. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9349. * given element can be found in the array, or _emptyCompoundIndex if it is
  9350. * not present.
  9351. *
  9352. * Example:
  9353. *
  9354. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9355. *
  9356. * returns {row: 2, column: 14}
  9357. *
  9358. * @param needle
  9359. * @param haystack
  9360. * @param start
  9361. * @returns {}
  9362. * @private
  9363. */
  9364. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9365. var length = haystack.length, idx, i;
  9366. if (!start) {
  9367. start = 0;
  9368. }
  9369. for (i = start; i < length; i++) {
  9370. idx = haystack[i].indexOf(needle);
  9371. if (idx !== -1) {
  9372. return {row: i, column: idx};
  9373. }
  9374. }
  9375. return this._emptyCompoundIndex;
  9376. };
  9377. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9378. var i;
  9379. for (i = lines.length - 1; i >= 0; i--) {
  9380. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9381. lines.splice(i, 1);
  9382. }
  9383. }
  9384. };
  9385. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9386. var sb = [], ssrc, addedSSRCs = [];
  9387. this.logger.info('Compiling video sources...');
  9388. // Add the groups
  9389. if (videoSources.groups && videoSources.groups.length !== 0) {
  9390. videoSources.groups.forEach(function (group) {
  9391. if (group.ssrcs && group.ssrcs.length !== 0) {
  9392. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9393. // if (group.semantics !== 'SIM') {
  9394. group.ssrcs.forEach(function (ssrc) {
  9395. addedSSRCs.push(ssrc);
  9396. sb.splice.apply(sb, [sb.length, 0].concat([
  9397. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9398. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9399. });
  9400. //}
  9401. }
  9402. });
  9403. }
  9404. // Then add any free sources.
  9405. if (videoSources.sources) {
  9406. for (ssrc in videoSources.sources) {
  9407. if (addedSSRCs.indexOf(ssrc) === -1) {
  9408. sb.splice.apply(sb, [sb.length, 0].concat([
  9409. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9410. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9411. }
  9412. }
  9413. }
  9414. return sb;
  9415. };
  9416. module.exports = SimulcastUtils;
  9417. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9418. /*jslint plusplus: true */
  9419. /*jslint nomen: true*/
  9420. var SimulcastSender = require("./SimulcastSender");
  9421. var NoSimulcastSender = SimulcastSender["no"];
  9422. var NativeSimulcastSender = SimulcastSender["native"];
  9423. var SimulcastReceiver = require("./SimulcastReceiver");
  9424. var SimulcastUtils = require("./SimulcastUtils");
  9425. var RTCEvents = require("../../service/RTC/RTCEvents");
  9426. /**
  9427. *
  9428. * @constructor
  9429. */
  9430. function SimulcastManager() {
  9431. // Create the simulcast utilities.
  9432. this.simulcastUtils = new SimulcastUtils();
  9433. // Create remote simulcast.
  9434. this.simulcastReceiver = new SimulcastReceiver();
  9435. // Initialize local simulcast.
  9436. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9437. // account constraints.
  9438. if (!config.enableSimulcast) {
  9439. this.simulcastSender = new NoSimulcastSender();
  9440. } else {
  9441. var isChromium = window.chrome,
  9442. vendorName = window.navigator.vendor;
  9443. if(isChromium !== null && isChromium !== undefined
  9444. /* skip opera */
  9445. && vendorName === "Google Inc."
  9446. /* skip Chromium as suggested by fippo */
  9447. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9448. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9449. if (ver > 37) {
  9450. this.simulcastSender = new NativeSimulcastSender();
  9451. } else {
  9452. this.simulcastSender = new NoSimulcastSender();
  9453. }
  9454. } else {
  9455. this.simulcastSender = new NoSimulcastSender();
  9456. }
  9457. }
  9458. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9459. function (endpointSimulcastLayers) {
  9460. endpointSimulcastLayers.forEach(function (esl) {
  9461. var ssrc = esl.simulcastLayer.primarySSRC;
  9462. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9463. });
  9464. });
  9465. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9466. var ssrc = simulcastLayer.primarySSRC;
  9467. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9468. });
  9469. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9470. var ssrc = simulcastLayer.primarySSRC;
  9471. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9472. });
  9473. }
  9474. /**
  9475. * Restores the simulcast groups of the remote description. In
  9476. * transformRemoteDescription we remove those in order for the set remote
  9477. * description to succeed. The focus needs the signal the groups to new
  9478. * participants.
  9479. *
  9480. * @param desc
  9481. * @returns {*}
  9482. */
  9483. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9484. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9485. };
  9486. /**
  9487. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9488. * either gets confused and thinks this is an FID group or, if an FID group
  9489. * is already present, it fails to set the remote description.
  9490. *
  9491. * @param desc
  9492. * @returns {*}
  9493. */
  9494. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9495. return this.simulcastReceiver.transformRemoteDescription(desc);
  9496. };
  9497. /**
  9498. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9499. * SSRC.
  9500. *
  9501. * @param ssrc
  9502. * @returns {*}
  9503. */
  9504. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9505. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9506. };
  9507. /**
  9508. * Returns a stream with single video track, the one currently being
  9509. * received by this endpoint.
  9510. *
  9511. * @param stream the remote simulcast stream.
  9512. * @returns {webkitMediaStream}
  9513. */
  9514. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9515. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9516. };
  9517. /**
  9518. *
  9519. *
  9520. * @param desc
  9521. * @returns {*}
  9522. */
  9523. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9524. return this.simulcastSender.transformLocalDescription(desc);
  9525. };
  9526. /**
  9527. *
  9528. * @returns {*}
  9529. */
  9530. SimulcastManager.prototype.getLocalVideoStream = function() {
  9531. return this.simulcastSender.getLocalVideoStream();
  9532. };
  9533. /**
  9534. * GUM for simulcast.
  9535. *
  9536. * @param constraints
  9537. * @param success
  9538. * @param err
  9539. */
  9540. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9541. this.simulcastSender.getUserMedia(constraints, success, err);
  9542. };
  9543. /**
  9544. * Prepares the local description for public usage (i.e. to be signaled
  9545. * through Jingle to the focus).
  9546. *
  9547. * @param desc
  9548. * @returns {RTCSessionDescription}
  9549. */
  9550. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9551. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9552. };
  9553. /**
  9554. * Ensures that the simulcast group is present in the answer, _if_ native
  9555. * simulcast is enabled,
  9556. *
  9557. * @param desc
  9558. * @returns {*}
  9559. */
  9560. SimulcastManager.prototype.transformAnswer = function (desc) {
  9561. return this.simulcastSender.transformAnswer(desc);
  9562. };
  9563. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9564. return this.simulcastReceiver.getReceivingSSRC(jid);
  9565. };
  9566. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9567. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9568. };
  9569. /**
  9570. *
  9571. * @param lines
  9572. * @param mediatypes
  9573. * @returns {*}
  9574. */
  9575. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9576. var sb = lines.sdp.split('\r\n');
  9577. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9578. };
  9579. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9580. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9581. };
  9582. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9583. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9584. };
  9585. SimulcastManager.prototype.resetSender = function() {
  9586. if (typeof this.simulcastSender.reset === 'function'){
  9587. this.simulcastSender.reset();
  9588. }
  9589. };
  9590. var simulcast = new SimulcastManager();
  9591. module.exports = simulcast;
  9592. },{"../../service/RTC/RTCEvents":90,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9593. /**
  9594. * Provides statistics for the local stream.
  9595. */
  9596. /**
  9597. * Size of the webaudio analizer buffer.
  9598. * @type {number}
  9599. */
  9600. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9601. /**
  9602. * Value of the webaudio analizer smoothing time parameter.
  9603. * @type {number}
  9604. */
  9605. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9606. /**
  9607. * Converts time domain data array to audio level.
  9608. * @param array the time domain data array.
  9609. * @returns {number} the audio level
  9610. */
  9611. function timeDomainDataToAudioLevel(samples) {
  9612. var maxVolume = 0;
  9613. var length = samples.length;
  9614. for (var i = 0; i < length; i++) {
  9615. if (maxVolume < samples[i])
  9616. maxVolume = samples[i];
  9617. }
  9618. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9619. };
  9620. /**
  9621. * Animates audio level change
  9622. * @param newLevel the new audio level
  9623. * @param lastLevel the last audio level
  9624. * @returns {Number} the audio level to be set
  9625. */
  9626. function animateLevel(newLevel, lastLevel)
  9627. {
  9628. var value = 0;
  9629. var diff = lastLevel - newLevel;
  9630. if(diff > 0.2)
  9631. {
  9632. value = lastLevel - 0.2;
  9633. }
  9634. else if(diff < -0.4)
  9635. {
  9636. value = lastLevel + 0.4;
  9637. }
  9638. else
  9639. {
  9640. value = newLevel;
  9641. }
  9642. return parseFloat(value.toFixed(3));
  9643. }
  9644. /**
  9645. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9646. *
  9647. * @param stream the local stream
  9648. * @param interval stats refresh interval given in ms.
  9649. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9650. * update.
  9651. * @constructor
  9652. */
  9653. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9654. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9655. this.stream = stream;
  9656. this.intervalId = null;
  9657. this.intervalMilis = interval;
  9658. this.eventEmitter = eventEmitter;
  9659. this.audioLevel = 0;
  9660. this.statisticsService = statisticsService;
  9661. }
  9662. /**
  9663. * Starts the collecting the statistics.
  9664. */
  9665. LocalStatsCollector.prototype.start = function () {
  9666. if (config.disableAudioLevels || !window.AudioContext)
  9667. return;
  9668. var context = new AudioContext();
  9669. var analyser = context.createAnalyser();
  9670. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9671. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9672. var source = context.createMediaStreamSource(this.stream);
  9673. source.connect(analyser);
  9674. var self = this;
  9675. this.intervalId = setInterval(
  9676. function () {
  9677. var array = new Uint8Array(analyser.frequencyBinCount);
  9678. analyser.getByteTimeDomainData(array);
  9679. var audioLevel = timeDomainDataToAudioLevel(array);
  9680. if(audioLevel != self.audioLevel) {
  9681. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9682. self.eventEmitter.emit(
  9683. "statistics.audioLevel",
  9684. self.statisticsService.LOCAL_JID,
  9685. self.audioLevel);
  9686. }
  9687. },
  9688. this.intervalMilis
  9689. );
  9690. };
  9691. /**
  9692. * Stops collecting the statistics.
  9693. */
  9694. LocalStatsCollector.prototype.stop = function () {
  9695. if (this.intervalId) {
  9696. clearInterval(this.intervalId);
  9697. this.intervalId = null;
  9698. }
  9699. };
  9700. module.exports = LocalStatsCollector;
  9701. },{}],45:[function(require,module,exports){
  9702. /* global ssrc2jid */
  9703. /* jshint -W117 */
  9704. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9705. /**
  9706. * Calculates packet lost percent using the number of lost packets and the
  9707. * number of all packet.
  9708. * @param lostPackets the number of lost packets
  9709. * @param totalPackets the number of all packets.
  9710. * @returns {number} packet loss percent
  9711. */
  9712. function calculatePacketLoss(lostPackets, totalPackets) {
  9713. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9714. return 0;
  9715. return Math.round((lostPackets/totalPackets)*100);
  9716. }
  9717. function getStatValue(item, name) {
  9718. if(!keyMap[APP.RTC.getBrowserType()][name])
  9719. throw "The property isn't supported!";
  9720. var key = keyMap[APP.RTC.getBrowserType()][name];
  9721. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9722. }
  9723. /**
  9724. * Peer statistics data holder.
  9725. * @constructor
  9726. */
  9727. function PeerStats()
  9728. {
  9729. this.ssrc2Loss = {};
  9730. this.ssrc2AudioLevel = {};
  9731. this.ssrc2bitrate = {};
  9732. this.ssrc2resolution = {};
  9733. }
  9734. /**
  9735. * The bandwidth
  9736. * @type {{}}
  9737. */
  9738. PeerStats.bandwidth = {};
  9739. /**
  9740. * The bit rate
  9741. * @type {{}}
  9742. */
  9743. PeerStats.bitrate = {};
  9744. /**
  9745. * The packet loss rate
  9746. * @type {{}}
  9747. */
  9748. PeerStats.packetLoss = null;
  9749. /**
  9750. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9751. * represented by this instance.
  9752. * @param ssrc audio or video RTP stream SSRC.
  9753. * @param lossRate new packet loss rate value to be set.
  9754. */
  9755. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9756. {
  9757. this.ssrc2Loss[ssrc] = lossRate;
  9758. };
  9759. /**
  9760. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9761. * represented by this instance.
  9762. * @param ssrc audio or video RTP stream SSRC.
  9763. * @param resolution new resolution value to be set.
  9764. */
  9765. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9766. {
  9767. if(resolution === null && this.ssrc2resolution[ssrc])
  9768. {
  9769. delete this.ssrc2resolution[ssrc];
  9770. }
  9771. else if(resolution !== null)
  9772. this.ssrc2resolution[ssrc] = resolution;
  9773. };
  9774. /**
  9775. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9776. * represented by this instance.
  9777. * @param ssrc audio or video RTP stream SSRC.
  9778. * @param bitrate new bitrate value to be set.
  9779. */
  9780. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9781. {
  9782. if(this.ssrc2bitrate[ssrc])
  9783. {
  9784. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9785. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9786. }
  9787. else {
  9788. this.ssrc2bitrate[ssrc] = bitrate;
  9789. }
  9790. };
  9791. /**
  9792. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9793. * the stream which belongs to the peer represented by this instance.
  9794. * @param ssrc RTP stream SSRC for which current audio level value will be
  9795. * updated.
  9796. * @param audioLevel the new audio level value to be set. Value is truncated to
  9797. * fit the range from 0 to 1.
  9798. */
  9799. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9800. {
  9801. // Range limit 0 - 1
  9802. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9803. };
  9804. function formatAudioLevel(audioLevel) {
  9805. return Math.min(Math.max(audioLevel, 0), 1);
  9806. }
  9807. /**
  9808. * Array with the transport information.
  9809. * @type {Array}
  9810. */
  9811. PeerStats.transport = [];
  9812. /**
  9813. * <tt>StatsCollector</tt> registers for stats updates of given
  9814. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9815. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9816. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9817. * instance as an event source.
  9818. *
  9819. * @param peerconnection webRTC peer connection object.
  9820. * @param interval stats refresh interval given in ms.
  9821. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9822. * called on stats update.
  9823. * @constructor
  9824. */
  9825. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9826. {
  9827. this.peerconnection = peerconnection;
  9828. this.baselineAudioLevelsReport = null;
  9829. this.currentAudioLevelsReport = null;
  9830. this.currentStatsReport = null;
  9831. this.baselineStatsReport = null;
  9832. this.audioLevelsIntervalId = null;
  9833. this.eventEmitter = eventEmitter;
  9834. /**
  9835. * Gather PeerConnection stats once every this many milliseconds.
  9836. */
  9837. this.GATHER_INTERVAL = 15000;
  9838. /**
  9839. * Log stats via the focus once every this many milliseconds.
  9840. */
  9841. this.LOG_INTERVAL = 60000;
  9842. /**
  9843. * Gather stats and store them in this.statsToBeLogged.
  9844. */
  9845. this.gatherStatsIntervalId = null;
  9846. /**
  9847. * Send the stats already saved in this.statsToBeLogged to be logged via
  9848. * the focus.
  9849. */
  9850. this.logStatsIntervalId = null;
  9851. /**
  9852. * Stores the statistics which will be send to the focus to be logged.
  9853. */
  9854. this.statsToBeLogged =
  9855. {
  9856. timestamps: [],
  9857. stats: {}
  9858. };
  9859. // Updates stats interval
  9860. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9861. this.statsIntervalId = null;
  9862. this.statsIntervalMilis = statsInterval;
  9863. // Map of jids to PeerStats
  9864. this.jid2stats = {};
  9865. }
  9866. module.exports = StatsCollector;
  9867. /**
  9868. * Stops stats updates.
  9869. */
  9870. StatsCollector.prototype.stop = function () {
  9871. if (this.audioLevelsIntervalId) {
  9872. clearInterval(this.audioLevelsIntervalId);
  9873. this.audioLevelsIntervalId = null;
  9874. }
  9875. if (this.statsIntervalId)
  9876. {
  9877. clearInterval(this.statsIntervalId);
  9878. this.statsIntervalId = null;
  9879. }
  9880. if(this.logStatsIntervalId)
  9881. {
  9882. clearInterval(this.logStatsIntervalId);
  9883. this.logStatsIntervalId = null;
  9884. }
  9885. if(this.gatherStatsIntervalId)
  9886. {
  9887. clearInterval(this.gatherStatsIntervalId);
  9888. this.gatherStatsIntervalId = null;
  9889. }
  9890. };
  9891. /**
  9892. * Callback passed to <tt>getStats</tt> method.
  9893. * @param error an error that occurred on <tt>getStats</tt> call.
  9894. */
  9895. StatsCollector.prototype.errorCallback = function (error)
  9896. {
  9897. console.error("Get stats error", error);
  9898. this.stop();
  9899. };
  9900. /**
  9901. * Starts stats updates.
  9902. */
  9903. StatsCollector.prototype.start = function ()
  9904. {
  9905. var self = this;
  9906. if(!config.disableAudioLevels) {
  9907. this.audioLevelsIntervalId = setInterval(
  9908. function () {
  9909. // Interval updates
  9910. self.peerconnection.getStats(
  9911. function (report) {
  9912. var results = null;
  9913. if (!report || !report.result ||
  9914. typeof report.result != 'function') {
  9915. results = report;
  9916. }
  9917. else {
  9918. results = report.result();
  9919. }
  9920. //console.error("Got interval report", results);
  9921. self.currentAudioLevelsReport = results;
  9922. self.processAudioLevelReport();
  9923. self.baselineAudioLevelsReport =
  9924. self.currentAudioLevelsReport;
  9925. },
  9926. self.errorCallback
  9927. );
  9928. },
  9929. self.audioLevelsIntervalMilis
  9930. );
  9931. }
  9932. if(!config.disableStats) {
  9933. this.statsIntervalId = setInterval(
  9934. function () {
  9935. // Interval updates
  9936. self.peerconnection.getStats(
  9937. function (report) {
  9938. var results = null;
  9939. if (!report || !report.result ||
  9940. typeof report.result != 'function') {
  9941. //firefox
  9942. results = report;
  9943. }
  9944. else {
  9945. //chrome
  9946. results = report.result();
  9947. }
  9948. //console.error("Got interval report", results);
  9949. self.currentStatsReport = results;
  9950. try {
  9951. self.processStatsReport();
  9952. }
  9953. catch (e) {
  9954. console.error("Unsupported key:" + e, e);
  9955. }
  9956. self.baselineStatsReport = self.currentStatsReport;
  9957. },
  9958. self.errorCallback
  9959. );
  9960. },
  9961. self.statsIntervalMilis
  9962. );
  9963. }
  9964. if (config.logStats) {
  9965. this.gatherStatsIntervalId = setInterval(
  9966. function () {
  9967. self.peerconnection.getStats(
  9968. function (report) {
  9969. self.addStatsToBeLogged(report.result());
  9970. },
  9971. function () {
  9972. }
  9973. );
  9974. },
  9975. this.GATHER_INTERVAL
  9976. );
  9977. this.logStatsIntervalId = setInterval(
  9978. function() { self.logStats(); },
  9979. this.LOG_INTERVAL);
  9980. }
  9981. };
  9982. /**
  9983. * Checks whether a certain record should be included in the logged statistics.
  9984. */
  9985. function acceptStat(reportId, reportType, statName) {
  9986. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9987. return false;
  9988. if (reportType == "ssrc") {
  9989. if (statName == "googTrackId" ||
  9990. statName == "transportId" ||
  9991. statName == "ssrc")
  9992. return false;
  9993. }
  9994. return true;
  9995. }
  9996. /**
  9997. * Checks whether a certain record should be included in the logged statistics.
  9998. */
  9999. function acceptReport(id, type) {
  10000. if (id.substring(0, 15) == "googCertificate" ||
  10001. id.substring(0, 9) == "googTrack" ||
  10002. id.substring(0, 20) == "googLibjingleSession")
  10003. return false;
  10004. if (type == "googComponent")
  10005. return false;
  10006. return true;
  10007. }
  10008. /**
  10009. * Converts the stats to the format used for logging, and saves the data in
  10010. * this.statsToBeLogged.
  10011. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10012. */
  10013. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10014. var self = this;
  10015. var num_records = this.statsToBeLogged.timestamps.length;
  10016. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10017. reports.map(function (report) {
  10018. if (!acceptReport(report.id, report.type))
  10019. return;
  10020. var stat = self.statsToBeLogged.stats[report.id];
  10021. if (!stat) {
  10022. stat = self.statsToBeLogged.stats[report.id] = {};
  10023. }
  10024. stat.type = report.type;
  10025. report.names().map(function (name) {
  10026. if (!acceptStat(report.id, report.type, name))
  10027. return;
  10028. var values = stat[name];
  10029. if (!values) {
  10030. values = stat[name] = [];
  10031. }
  10032. while (values.length < num_records) {
  10033. values.push(null);
  10034. }
  10035. values.push(report.stat(name));
  10036. });
  10037. });
  10038. };
  10039. StatsCollector.prototype.logStats = function () {
  10040. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10041. return;
  10042. // Reset the stats
  10043. this.statsToBeLogged.stats = {};
  10044. this.statsToBeLogged.timestamps = [];
  10045. };
  10046. var keyMap = {};
  10047. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10048. "ssrc": "ssrc",
  10049. "packetsReceived": "packetsReceived",
  10050. "packetsLost": "packetsLost",
  10051. "packetsSent": "packetsSent",
  10052. "bytesReceived": "bytesReceived",
  10053. "bytesSent": "bytesSent"
  10054. };
  10055. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10056. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10057. "sendBandwidth": "googAvailableSendBandwidth",
  10058. "remoteAddress": "googRemoteAddress",
  10059. "transportType": "googTransportType",
  10060. "localAddress": "googLocalAddress",
  10061. "activeConnection": "googActiveConnection",
  10062. "ssrc": "ssrc",
  10063. "packetsReceived": "packetsReceived",
  10064. "packetsSent": "packetsSent",
  10065. "packetsLost": "packetsLost",
  10066. "bytesReceived": "bytesReceived",
  10067. "bytesSent": "bytesSent",
  10068. "googFrameHeightReceived": "googFrameHeightReceived",
  10069. "googFrameWidthReceived": "googFrameWidthReceived",
  10070. "googFrameHeightSent": "googFrameHeightSent",
  10071. "googFrameWidthSent": "googFrameWidthSent",
  10072. "audioInputLevel": "audioInputLevel",
  10073. "audioOutputLevel": "audioOutputLevel"
  10074. };
  10075. /**
  10076. * Stats processing logic.
  10077. */
  10078. StatsCollector.prototype.processStatsReport = function () {
  10079. if (!this.baselineStatsReport) {
  10080. return;
  10081. }
  10082. for (var idx in this.currentStatsReport) {
  10083. var now = this.currentStatsReport[idx];
  10084. try {
  10085. if (getStatValue(now, 'receiveBandwidth') ||
  10086. getStatValue(now, 'sendBandwidth')) {
  10087. PeerStats.bandwidth = {
  10088. "download": Math.round(
  10089. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10090. "upload": Math.round(
  10091. (getStatValue(now, 'sendBandwidth')) / 1000)
  10092. };
  10093. }
  10094. }
  10095. catch(e){/*not supported*/}
  10096. if(now.type == 'googCandidatePair')
  10097. {
  10098. var ip, type, localIP, active;
  10099. try {
  10100. ip = getStatValue(now, 'remoteAddress');
  10101. type = getStatValue(now, "transportType");
  10102. localIP = getStatValue(now, "localAddress");
  10103. active = getStatValue(now, "activeConnection");
  10104. }
  10105. catch(e){/*not supported*/}
  10106. if(!ip || !type || !localIP || active != "true")
  10107. continue;
  10108. var addressSaved = false;
  10109. for(var i = 0; i < PeerStats.transport.length; i++)
  10110. {
  10111. if(PeerStats.transport[i].ip == ip &&
  10112. PeerStats.transport[i].type == type &&
  10113. PeerStats.transport[i].localip == localIP)
  10114. {
  10115. addressSaved = true;
  10116. }
  10117. }
  10118. if(addressSaved)
  10119. continue;
  10120. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10121. continue;
  10122. }
  10123. if(now.type == "candidatepair")
  10124. {
  10125. if(now.state == "succeeded")
  10126. continue;
  10127. var local = this.currentStatsReport[now.localCandidateId];
  10128. var remote = this.currentStatsReport[now.remoteCandidateId];
  10129. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10130. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10131. }
  10132. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10133. now.type != "inboundrtp") {
  10134. continue;
  10135. }
  10136. var before = this.baselineStatsReport[idx];
  10137. if (!before) {
  10138. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10139. continue;
  10140. }
  10141. var ssrc = getStatValue(now, 'ssrc');
  10142. if(!ssrc)
  10143. continue;
  10144. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10145. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10146. console.warn("No jid for ssrc: " + ssrc);
  10147. continue;
  10148. }
  10149. var jidStats = this.jid2stats[jid];
  10150. if (!jidStats) {
  10151. jidStats = new PeerStats();
  10152. this.jid2stats[jid] = jidStats;
  10153. }
  10154. var isDownloadStream = true;
  10155. var key = 'packetsReceived';
  10156. if (!getStatValue(now, key))
  10157. {
  10158. isDownloadStream = false;
  10159. key = 'packetsSent';
  10160. if (!getStatValue(now, key))
  10161. {
  10162. console.warn("No packetsReceived nor packetSent stat found");
  10163. continue;
  10164. }
  10165. }
  10166. var packetsNow = getStatValue(now, key);
  10167. if(!packetsNow || packetsNow < 0)
  10168. packetsNow = 0;
  10169. var packetsBefore = getStatValue(before, key);
  10170. if(!packetsBefore || packetsBefore < 0)
  10171. packetsBefore = 0;
  10172. var packetRate = packetsNow - packetsBefore;
  10173. if(!packetRate || packetRate < 0)
  10174. packetRate = 0;
  10175. var currentLoss = getStatValue(now, 'packetsLost');
  10176. if(!currentLoss || currentLoss < 0)
  10177. currentLoss = 0;
  10178. var previousLoss = getStatValue(before, 'packetsLost');
  10179. if(!previousLoss || previousLoss < 0)
  10180. previousLoss = 0;
  10181. var lossRate = currentLoss - previousLoss;
  10182. if(!lossRate || lossRate < 0)
  10183. lossRate = 0;
  10184. var packetsTotal = (packetRate + lossRate);
  10185. jidStats.setSsrcLoss(ssrc,
  10186. {"packetsTotal": packetsTotal,
  10187. "packetsLost": lossRate,
  10188. "isDownloadStream": isDownloadStream});
  10189. var bytesReceived = 0, bytesSent = 0;
  10190. if(getStatValue(now, "bytesReceived"))
  10191. {
  10192. bytesReceived = getStatValue(now, "bytesReceived") -
  10193. getStatValue(before, "bytesReceived");
  10194. }
  10195. if(getStatValue(now, "bytesSent"))
  10196. {
  10197. bytesSent = getStatValue(now, "bytesSent") -
  10198. getStatValue(before, "bytesSent");
  10199. }
  10200. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10201. if(bytesReceived <= 0 || time <= 0)
  10202. {
  10203. bytesReceived = 0;
  10204. }
  10205. else
  10206. {
  10207. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10208. }
  10209. if(bytesSent <= 0 || time <= 0)
  10210. {
  10211. bytesSent = 0;
  10212. }
  10213. else
  10214. {
  10215. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10216. }
  10217. jidStats.setSsrcBitrate(ssrc, {
  10218. "download": bytesReceived,
  10219. "upload": bytesSent});
  10220. var resolution = {height: null, width: null};
  10221. try {
  10222. if (getStatValue(now, "googFrameHeightReceived") &&
  10223. getStatValue(now, "googFrameWidthReceived")) {
  10224. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10225. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10226. }
  10227. else if (getStatValue(now, "googFrameHeightSent") &&
  10228. getStatValue(now, "googFrameWidthSent")) {
  10229. resolution.height = getStatValue(now, "googFrameHeightSent");
  10230. resolution.width = getStatValue(now, "googFrameWidthSent");
  10231. }
  10232. }
  10233. catch(e){/*not supported*/}
  10234. if(resolution.height && resolution.width)
  10235. {
  10236. jidStats.setSsrcResolution(ssrc, resolution);
  10237. }
  10238. else
  10239. {
  10240. jidStats.setSsrcResolution(ssrc, null);
  10241. }
  10242. }
  10243. var self = this;
  10244. // Jid stats
  10245. var totalPackets = {download: 0, upload: 0};
  10246. var lostPackets = {download: 0, upload: 0};
  10247. var bitrateDownload = 0;
  10248. var bitrateUpload = 0;
  10249. var resolutions = {};
  10250. Object.keys(this.jid2stats).forEach(
  10251. function (jid)
  10252. {
  10253. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10254. function (ssrc)
  10255. {
  10256. var type = "upload";
  10257. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10258. type = "download";
  10259. totalPackets[type] +=
  10260. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10261. lostPackets[type] +=
  10262. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10263. }
  10264. );
  10265. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10266. function (ssrc) {
  10267. bitrateDownload +=
  10268. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10269. bitrateUpload +=
  10270. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10271. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10272. }
  10273. );
  10274. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10275. }
  10276. );
  10277. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10278. PeerStats.packetLoss = {
  10279. total:
  10280. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10281. totalPackets.download + totalPackets.upload),
  10282. download:
  10283. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10284. upload:
  10285. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10286. };
  10287. this.eventEmitter.emit("statistics.connectionstats",
  10288. {
  10289. "bitrate": PeerStats.bitrate,
  10290. "packetLoss": PeerStats.packetLoss,
  10291. "bandwidth": PeerStats.bandwidth,
  10292. "resolution": resolutions,
  10293. "transport": PeerStats.transport
  10294. });
  10295. PeerStats.transport = [];
  10296. };
  10297. /**
  10298. * Stats processing logic.
  10299. */
  10300. StatsCollector.prototype.processAudioLevelReport = function ()
  10301. {
  10302. if (!this.baselineAudioLevelsReport)
  10303. {
  10304. return;
  10305. }
  10306. for (var idx in this.currentAudioLevelsReport)
  10307. {
  10308. var now = this.currentAudioLevelsReport[idx];
  10309. if (now.type != 'ssrc')
  10310. {
  10311. continue;
  10312. }
  10313. var before = this.baselineAudioLevelsReport[idx];
  10314. if (!before)
  10315. {
  10316. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10317. continue;
  10318. }
  10319. var ssrc = getStatValue(now, 'ssrc');
  10320. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10321. if (!jid && (Date.now() - now.timestamp) < 3000)
  10322. {
  10323. console.warn("No jid for ssrc: " + ssrc);
  10324. continue;
  10325. }
  10326. var jidStats = this.jid2stats[jid];
  10327. if (!jidStats)
  10328. {
  10329. jidStats = new PeerStats();
  10330. this.jid2stats[jid] = jidStats;
  10331. }
  10332. // Audio level
  10333. var audioLevel = null;
  10334. try {
  10335. audioLevel = getStatValue(now, 'audioInputLevel');
  10336. if (!audioLevel)
  10337. audioLevel = getStatValue(now, 'audioOutputLevel');
  10338. }
  10339. catch(e) {/*not supported*/
  10340. console.warn("Audio Levels are not available in the statistics.");
  10341. clearInterval(this.audioLevelsIntervalId);
  10342. return;
  10343. }
  10344. if (audioLevel)
  10345. {
  10346. // TODO: can't find specs about what this value really is,
  10347. // but it seems to vary between 0 and around 32k.
  10348. audioLevel = audioLevel / 32767;
  10349. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10350. if(jid != APP.xmpp.myJid())
  10351. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10352. }
  10353. }
  10354. };
  10355. },{"../../service/RTC/RTCBrowserType":89}],46:[function(require,module,exports){
  10356. /**
  10357. * Created by hristo on 8/4/14.
  10358. */
  10359. var LocalStats = require("./LocalStatsCollector.js");
  10360. var RTPStats = require("./RTPStatsCollector.js");
  10361. var EventEmitter = require("events");
  10362. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10363. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10364. var eventEmitter = new EventEmitter();
  10365. var localStats = null;
  10366. var rtpStats = null;
  10367. function stopLocal()
  10368. {
  10369. if(localStats)
  10370. {
  10371. localStats.stop();
  10372. localStats = null;
  10373. }
  10374. }
  10375. function stopRemote()
  10376. {
  10377. if(rtpStats)
  10378. {
  10379. rtpStats.stop();
  10380. eventEmitter.emit("statistics.stop");
  10381. rtpStats = null;
  10382. }
  10383. }
  10384. function startRemoteStats (peerconnection) {
  10385. if(rtpStats)
  10386. {
  10387. rtpStats.stop();
  10388. rtpStats = null;
  10389. }
  10390. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10391. rtpStats.start();
  10392. }
  10393. function onStreamCreated(stream)
  10394. {
  10395. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10396. return;
  10397. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10398. eventEmitter);
  10399. localStats.start();
  10400. }
  10401. function onDisposeConference(onUnload) {
  10402. stopRemote();
  10403. if(onUnload) {
  10404. stopLocal();
  10405. eventEmitter.removeAllListeners();
  10406. }
  10407. }
  10408. var statistics =
  10409. {
  10410. /**
  10411. * Indicates that this audio level is for local jid.
  10412. * @type {string}
  10413. */
  10414. LOCAL_JID: 'local',
  10415. addAudioLevelListener: function(listener)
  10416. {
  10417. eventEmitter.on("statistics.audioLevel", listener);
  10418. },
  10419. removeAudioLevelListener: function(listener)
  10420. {
  10421. eventEmitter.removeListener("statistics.audioLevel", listener);
  10422. },
  10423. addConnectionStatsListener: function(listener)
  10424. {
  10425. eventEmitter.on("statistics.connectionstats", listener);
  10426. },
  10427. removeConnectionStatsListener: function(listener)
  10428. {
  10429. eventEmitter.removeListener("statistics.connectionstats", listener);
  10430. },
  10431. addRemoteStatsStopListener: function(listener)
  10432. {
  10433. eventEmitter.on("statistics.stop", listener);
  10434. },
  10435. removeRemoteStatsStopListener: function(listener)
  10436. {
  10437. eventEmitter.removeListener("statistics.stop", listener);
  10438. },
  10439. stop: function () {
  10440. stopLocal();
  10441. stopRemote();
  10442. if(eventEmitter)
  10443. {
  10444. eventEmitter.removeAllListeners();
  10445. }
  10446. },
  10447. stopRemoteStatistics: function()
  10448. {
  10449. stopRemote();
  10450. },
  10451. start: function () {
  10452. APP.RTC.addStreamListener(onStreamCreated,
  10453. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10454. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10455. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10456. startRemoteStats(event.peerconnection);
  10457. });
  10458. }
  10459. };
  10460. module.exports = statistics;
  10461. },{"../../service/RTC/StreamEventTypes.js":92,"../../service/xmpp/XMPPEvents":98,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":62}],47:[function(require,module,exports){
  10462. var i18n = require("i18next-client");
  10463. var languages = require("../../service/translation/languages");
  10464. var Settings = require("../settings/Settings");
  10465. var DEFAULT_LANG = languages.EN;
  10466. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10467. return value.replace("__app__", interfaceConfig.APP_NAME);
  10468. });
  10469. var defaultOptions = {
  10470. detectLngQS: "lang",
  10471. useCookie: false,
  10472. fallbackLng: DEFAULT_LANG,
  10473. load: "unspecific",
  10474. resGetPath: 'lang/__ns__-__lng__.json',
  10475. ns: {
  10476. namespaces: ['main', 'languages'],
  10477. defaultNs: 'main'
  10478. },
  10479. lngWhitelist : languages.getLanguages(),
  10480. fallbackOnNull: true,
  10481. fallbackOnEmpty: true,
  10482. useDataAttrOptions: true,
  10483. defaultValueFromContent: false,
  10484. app: interfaceConfig.APP_NAME,
  10485. getAsync: false,
  10486. defaultValueFromContent: false,
  10487. customLoad: function(lng, ns, options, done) {
  10488. var resPath = "lang/__ns__-__lng__.json";
  10489. if(lng === languages.EN)
  10490. resPath = "lang/__ns__.json";
  10491. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10492. i18n.functions.ajax({
  10493. url: url,
  10494. success: function(data, status, xhr) {
  10495. i18n.functions.log('loaded: ' + url);
  10496. done(null, data);
  10497. },
  10498. error : function(xhr, status, error) {
  10499. if ((status && status == 200) ||
  10500. (xhr && xhr.status && xhr.status == 200)) {
  10501. // file loaded but invalid json, stop waste time !
  10502. i18n.functions.error('There is a typo in: ' + url);
  10503. } else if ((status && status == 404) ||
  10504. (xhr && xhr.status && xhr.status == 404)) {
  10505. i18n.functions.log('Does not exist: ' + url);
  10506. } else {
  10507. var theStatus = status ? status :
  10508. ((xhr && xhr.status) ? xhr.status : null);
  10509. i18n.functions.log(theStatus + ' when loading ' + url);
  10510. }
  10511. done(error, {});
  10512. },
  10513. dataType: "json",
  10514. async : options.getAsync
  10515. });
  10516. }
  10517. // options for caching
  10518. // useLocalStorage: true,
  10519. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10520. };
  10521. function initCompleted(t)
  10522. {
  10523. $("[data-i18n]").i18n();
  10524. }
  10525. function checkForParameter() {
  10526. var query = window.location.search.substring(1);
  10527. var vars = query.split("&");
  10528. for (var i=0;i<vars.length;i++) {
  10529. var pair = vars[i].split("=");
  10530. if(pair[0] == "lang")
  10531. {
  10532. return pair[1];
  10533. }
  10534. }
  10535. return null;
  10536. }
  10537. module.exports = {
  10538. init: function (lang) {
  10539. var options = defaultOptions;
  10540. if(!lang)
  10541. {
  10542. lang = checkForParameter();
  10543. if(!lang)
  10544. {
  10545. var settings = Settings.getSettings();
  10546. if(settings)
  10547. lang = settings.language;
  10548. }
  10549. }
  10550. if(lang) {
  10551. options.lng = lang;
  10552. }
  10553. i18n.init(options, initCompleted);
  10554. },
  10555. translateString: function (key, options) {
  10556. return i18n.t(key, options);
  10557. },
  10558. setLanguage: function (lang) {
  10559. if(!lang)
  10560. lang = DEFAULT_LANG;
  10561. i18n.setLng(lang, defaultOptions, initCompleted);
  10562. },
  10563. getCurrentLanguage: function () {
  10564. return i18n.lng();
  10565. },
  10566. translateElement: function (selector) {
  10567. selector.i18n();
  10568. },
  10569. generateTranslatonHTML: function (key, options) {
  10570. var str = "<span data-i18n=\"" + key + "\"";
  10571. if(options)
  10572. {
  10573. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10574. }
  10575. str += ">";
  10576. str += this.translateString(key, options);
  10577. str += "</span>";
  10578. return str;
  10579. }
  10580. };
  10581. },{"../../service/translation/languages":97,"../settings/Settings":38,"i18next-client":63}],48:[function(require,module,exports){
  10582. /* jshint -W117 */
  10583. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10584. var SDPDiffer = require("./SDPDiffer");
  10585. var SDPUtil = require("./SDPUtil");
  10586. var SDP = require("./SDP");
  10587. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10588. // Jingle stuff
  10589. function JingleSession(me, sid, connection, service) {
  10590. this.me = me;
  10591. this.sid = sid;
  10592. this.connection = connection;
  10593. this.initiator = null;
  10594. this.responder = null;
  10595. this.isInitiator = null;
  10596. this.peerjid = null;
  10597. this.state = null;
  10598. this.localSDP = null;
  10599. this.remoteSDP = null;
  10600. this.relayedStreams = [];
  10601. this.startTime = null;
  10602. this.stopTime = null;
  10603. this.media_constraints = null;
  10604. this.pc_constraints = null;
  10605. this.ice_config = {};
  10606. this.drip_container = [];
  10607. this.service = service;
  10608. this.usetrickle = true;
  10609. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10610. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10611. this.hadstuncandidate = false;
  10612. this.hadturncandidate = false;
  10613. this.lasticecandidate = false;
  10614. this.statsinterval = null;
  10615. this.reason = null;
  10616. this.addssrc = [];
  10617. this.removessrc = [];
  10618. this.pendingop = null;
  10619. this.switchstreams = false;
  10620. this.wait = true;
  10621. this.localStreamsSSRC = null;
  10622. /**
  10623. * The indicator which determines whether the (local) video has been muted
  10624. * in response to a user command in contrast to an automatic decision made
  10625. * by the application logic.
  10626. */
  10627. this.videoMuteByUser = false;
  10628. }
  10629. //TODO: this array must be removed when firefox implement multistream support
  10630. JingleSession.notReceivedSSRCs = [];
  10631. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10632. var self = this;
  10633. if (this.state !== null) {
  10634. console.error('attempt to initiate on session ' + this.sid +
  10635. 'in state ' + this.state);
  10636. return;
  10637. }
  10638. this.isInitiator = isInitiator;
  10639. this.state = 'pending';
  10640. this.initiator = isInitiator ? this.me : peerjid;
  10641. this.responder = !isInitiator ? this.me : peerjid;
  10642. this.peerjid = peerjid;
  10643. this.hadstuncandidate = false;
  10644. this.hadturncandidate = false;
  10645. this.lasticecandidate = false;
  10646. this.peerconnection
  10647. = new TraceablePeerConnection(
  10648. this.connection.jingle.ice_config,
  10649. this.connection.jingle.pc_constraints );
  10650. this.peerconnection.onicecandidate = function (event) {
  10651. self.sendIceCandidate(event.candidate);
  10652. };
  10653. this.peerconnection.onaddstream = function (event) {
  10654. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10655. self.remoteStreamAdded(event);
  10656. };
  10657. this.peerconnection.onremovestream = function (event) {
  10658. // Remove the stream from remoteStreams
  10659. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10660. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10661. };
  10662. this.peerconnection.onsignalingstatechange = function (event) {
  10663. if (!(self && self.peerconnection)) return;
  10664. };
  10665. this.peerconnection.oniceconnectionstatechange = function (event) {
  10666. if (!(self && self.peerconnection)) return;
  10667. switch (self.peerconnection.iceConnectionState) {
  10668. case 'connected':
  10669. this.startTime = new Date();
  10670. break;
  10671. case 'disconnected':
  10672. this.stopTime = new Date();
  10673. break;
  10674. }
  10675. onIceConnectionStateChange(self.sid, self);
  10676. };
  10677. // add any local and relayed stream
  10678. APP.RTC.localStreams.forEach(function(stream) {
  10679. self.peerconnection.addStream(stream.getOriginalStream());
  10680. });
  10681. this.relayedStreams.forEach(function(stream) {
  10682. self.peerconnection.addStream(stream);
  10683. });
  10684. };
  10685. function onIceConnectionStateChange(sid, session) {
  10686. switch (session.peerconnection.iceConnectionState) {
  10687. case 'checking':
  10688. session.timeChecking = (new Date()).getTime();
  10689. session.firstconnect = true;
  10690. break;
  10691. case 'completed': // on caller side
  10692. case 'connected':
  10693. if (session.firstconnect) {
  10694. session.firstconnect = false;
  10695. var metadata = {};
  10696. metadata.setupTime
  10697. = (new Date()).getTime() - session.timeChecking;
  10698. session.peerconnection.getStats(function (res) {
  10699. if(res && res.result) {
  10700. res.result().forEach(function (report) {
  10701. if (report.type == 'googCandidatePair' &&
  10702. report.stat('googActiveConnection') == 'true') {
  10703. metadata.localCandidateType
  10704. = report.stat('googLocalCandidateType');
  10705. metadata.remoteCandidateType
  10706. = report.stat('googRemoteCandidateType');
  10707. // log pair as well so we can get nice pie
  10708. // charts
  10709. metadata.candidatePair
  10710. = report.stat('googLocalCandidateType') +
  10711. ';' +
  10712. report.stat('googRemoteCandidateType');
  10713. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10714. {
  10715. metadata.ipv6 = true;
  10716. }
  10717. }
  10718. });
  10719. }
  10720. });
  10721. }
  10722. break;
  10723. }
  10724. }
  10725. JingleSession.prototype.accept = function () {
  10726. var self = this;
  10727. this.state = 'active';
  10728. var pranswer = this.peerconnection.localDescription;
  10729. if (!pranswer || pranswer.type != 'pranswer') {
  10730. return;
  10731. }
  10732. console.log('going from pranswer to answer');
  10733. if (this.usetrickle) {
  10734. // remove candidates already sent from session-accept
  10735. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10736. for (var i = 0; i < lines.length; i++) {
  10737. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10738. }
  10739. }
  10740. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10741. // FIXME: change any inactive to sendrecv or whatever they were originally
  10742. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10743. }
  10744. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10745. var prsdp = new SDP(pranswer.sdp);
  10746. var accept = $iq({to: this.peerjid,
  10747. type: 'set'})
  10748. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10749. action: 'session-accept',
  10750. initiator: this.initiator,
  10751. responder: this.responder,
  10752. sid: this.sid });
  10753. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10754. var sdp = this.peerconnection.localDescription.sdp;
  10755. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10756. // FIXME: change any inactive to sendrecv or whatever they were originally
  10757. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10758. }
  10759. var self = this;
  10760. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10761. function () {
  10762. //console.log('setLocalDescription success');
  10763. self.setLocalDescription();
  10764. self.connection.sendIQ(accept,
  10765. function () {
  10766. var ack = {};
  10767. ack.source = 'answer';
  10768. $(document).trigger('ack.jingle', [self.sid, ack]);
  10769. },
  10770. function (stanza) {
  10771. var error = ($(stanza).find('error').length) ? {
  10772. code: $(stanza).find('error').attr('code'),
  10773. reason: $(stanza).find('error :first')[0].tagName
  10774. }:{};
  10775. error.source = 'answer';
  10776. JingleSession.onJingleError(self.sid, error);
  10777. },
  10778. 10000);
  10779. },
  10780. function (e) {
  10781. console.error('setLocalDescription failed', e);
  10782. }
  10783. );
  10784. };
  10785. JingleSession.prototype.terminate = function (reason) {
  10786. this.state = 'ended';
  10787. this.reason = reason;
  10788. this.peerconnection.close();
  10789. if (this.statsinterval !== null) {
  10790. window.clearInterval(this.statsinterval);
  10791. this.statsinterval = null;
  10792. }
  10793. };
  10794. JingleSession.prototype.active = function () {
  10795. return this.state == 'active';
  10796. };
  10797. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10798. var self = this;
  10799. if (candidate && !this.lasticecandidate) {
  10800. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10801. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10802. if (!(ice && jcand)) {
  10803. console.error('failed to get ice && jcand');
  10804. return;
  10805. }
  10806. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10807. if (jcand.type === 'srflx') {
  10808. this.hadstuncandidate = true;
  10809. } else if (jcand.type === 'relay') {
  10810. this.hadturncandidate = true;
  10811. }
  10812. if (this.usetrickle) {
  10813. if (this.usedrip) {
  10814. if (this.drip_container.length === 0) {
  10815. // start 20ms callout
  10816. window.setTimeout(function () {
  10817. if (self.drip_container.length === 0) return;
  10818. self.sendIceCandidates(self.drip_container);
  10819. self.drip_container = [];
  10820. }, 20);
  10821. }
  10822. this.drip_container.push(candidate);
  10823. return;
  10824. } else {
  10825. self.sendIceCandidate([candidate]);
  10826. }
  10827. }
  10828. } else {
  10829. //console.log('sendIceCandidate: last candidate.');
  10830. if (!this.usetrickle) {
  10831. //console.log('should send full offer now...');
  10832. var init = $iq({to: this.peerjid,
  10833. type: 'set'})
  10834. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10835. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10836. initiator: this.initiator,
  10837. sid: this.sid});
  10838. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10839. var self = this;
  10840. var sendJingle = function (ssrc) {
  10841. if(!ssrc)
  10842. ssrc = {};
  10843. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10844. self.connection.sendIQ(init,
  10845. function () {
  10846. //console.log('session initiate ack');
  10847. var ack = {};
  10848. ack.source = 'offer';
  10849. $(document).trigger('ack.jingle', [self.sid, ack]);
  10850. },
  10851. function (stanza) {
  10852. self.state = 'error';
  10853. self.peerconnection.close();
  10854. var error = ($(stanza).find('error').length) ? {
  10855. code: $(stanza).find('error').attr('code'),
  10856. reason: $(stanza).find('error :first')[0].tagName,
  10857. }:{};
  10858. error.source = 'offer';
  10859. JingleSession.onJingleError(self.sid, error);
  10860. },
  10861. 10000);
  10862. }
  10863. sendJingle();
  10864. }
  10865. this.lasticecandidate = true;
  10866. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10867. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10868. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10869. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10870. }
  10871. }
  10872. };
  10873. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10874. console.log('sendIceCandidates', candidates);
  10875. var cand = $iq({to: this.peerjid, type: 'set'})
  10876. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10877. action: 'transport-info',
  10878. initiator: this.initiator,
  10879. sid: this.sid});
  10880. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10881. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10882. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10883. if (cands.length > 0) {
  10884. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10885. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10886. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10887. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10888. }).c('transport', ice);
  10889. for (var i = 0; i < cands.length; i++) {
  10890. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10891. }
  10892. // add fingerprint
  10893. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10894. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10895. tmp.required = true;
  10896. cand.c(
  10897. 'fingerprint',
  10898. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10899. .t(tmp.fingerprint);
  10900. delete tmp.fingerprint;
  10901. cand.attrs(tmp);
  10902. cand.up();
  10903. }
  10904. cand.up(); // transport
  10905. cand.up(); // content
  10906. }
  10907. }
  10908. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10909. //console.log('was this the last candidate', this.lasticecandidate);
  10910. this.connection.sendIQ(cand,
  10911. function () {
  10912. var ack = {};
  10913. ack.source = 'transportinfo';
  10914. $(document).trigger('ack.jingle', [this.sid, ack]);
  10915. },
  10916. function (stanza) {
  10917. var error = ($(stanza).find('error').length) ? {
  10918. code: $(stanza).find('error').attr('code'),
  10919. reason: $(stanza).find('error :first')[0].tagName,
  10920. }:{};
  10921. error.source = 'transportinfo';
  10922. JingleSession.onJingleError(this.sid, error);
  10923. },
  10924. 10000);
  10925. };
  10926. JingleSession.prototype.sendOffer = function () {
  10927. //console.log('sendOffer...');
  10928. var self = this;
  10929. this.peerconnection.createOffer(function (sdp) {
  10930. self.createdOffer(sdp);
  10931. },
  10932. function (e) {
  10933. console.error('createOffer failed', e);
  10934. },
  10935. this.media_constraints
  10936. );
  10937. };
  10938. JingleSession.prototype.createdOffer = function (sdp) {
  10939. //console.log('createdOffer', sdp);
  10940. var self = this;
  10941. this.localSDP = new SDP(sdp.sdp);
  10942. //this.localSDP.mangle();
  10943. var sendJingle = function () {
  10944. var init = $iq({to: this.peerjid,
  10945. type: 'set'})
  10946. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10947. action: 'session-initiate',
  10948. initiator: this.initiator,
  10949. sid: this.sid});
  10950. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10951. self.connection.sendIQ(init,
  10952. function () {
  10953. var ack = {};
  10954. ack.source = 'offer';
  10955. $(document).trigger('ack.jingle', [self.sid, ack]);
  10956. },
  10957. function (stanza) {
  10958. self.state = 'error';
  10959. self.peerconnection.close();
  10960. var error = ($(stanza).find('error').length) ? {
  10961. code: $(stanza).find('error').attr('code'),
  10962. reason: $(stanza).find('error :first')[0].tagName,
  10963. }:{};
  10964. error.source = 'offer';
  10965. JingleSession.onJingleError(self.sid, error);
  10966. },
  10967. 10000);
  10968. }
  10969. sdp.sdp = this.localSDP.raw;
  10970. this.peerconnection.setLocalDescription(sdp,
  10971. function () {
  10972. if(self.usetrickle)
  10973. {
  10974. sendJingle();
  10975. }
  10976. self.setLocalDescription();
  10977. //console.log('setLocalDescription success');
  10978. },
  10979. function (e) {
  10980. console.error('setLocalDescription failed', e);
  10981. }
  10982. );
  10983. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10984. for (var i = 0; i < cands.length; i++) {
  10985. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10986. if (cand.type == 'srflx') {
  10987. this.hadstuncandidate = true;
  10988. } else if (cand.type == 'relay') {
  10989. this.hadturncandidate = true;
  10990. }
  10991. }
  10992. };
  10993. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10994. //console.log('setting remote description... ', desctype);
  10995. this.remoteSDP = new SDP('');
  10996. this.remoteSDP.fromJingle(elem);
  10997. if (this.peerconnection.remoteDescription !== null) {
  10998. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10999. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11000. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11001. for (var i = 0; i < pranswer.media.length; i++) {
  11002. // make sure we have ice ufrag and pwd
  11003. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11004. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11005. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11006. } else {
  11007. console.warn('no ice ufrag?');
  11008. }
  11009. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11010. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11011. } else {
  11012. console.warn('no ice pwd?');
  11013. }
  11014. }
  11015. // copy over candidates
  11016. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11017. for (var j = 0; j < lines.length; j++) {
  11018. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11019. }
  11020. }
  11021. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11022. }
  11023. }
  11024. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11025. this.peerconnection.setRemoteDescription(remotedesc,
  11026. function () {
  11027. //console.log('setRemoteDescription success');
  11028. },
  11029. function (e) {
  11030. console.error('setRemoteDescription error', e);
  11031. JingleSession.onJingleFatalError(self, e);
  11032. }
  11033. );
  11034. };
  11035. JingleSession.prototype.addIceCandidate = function (elem) {
  11036. var self = this;
  11037. if (this.peerconnection.signalingState == 'closed') {
  11038. return;
  11039. }
  11040. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11041. console.log('trickle ice candidate arriving before session accept...');
  11042. // create a PRANSWER for setRemoteDescription
  11043. if (!this.remoteSDP) {
  11044. var cobbled = 'v=0\r\n' +
  11045. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11046. 's=-\r\n' +
  11047. 't=0 0\r\n';
  11048. // first, take some things from the local description
  11049. for (var i = 0; i < this.localSDP.media.length; i++) {
  11050. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11051. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11052. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11053. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11054. }
  11055. cobbled += 'a=inactive\r\n';
  11056. }
  11057. this.remoteSDP = new SDP(cobbled);
  11058. }
  11059. // then add things like ice and dtls from remote candidate
  11060. elem.each(function () {
  11061. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11062. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11063. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11064. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11065. var tmp = $(this).find('transport');
  11066. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11067. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11068. tmp = $(this).find('transport>fingerprint');
  11069. if (tmp.length) {
  11070. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11071. } else {
  11072. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11073. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11074. }
  11075. break;
  11076. }
  11077. }
  11078. }
  11079. });
  11080. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11081. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11082. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11083. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11084. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11085. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11086. }).length == this.remoteSDP.media.length;
  11087. if (iscomplete) {
  11088. console.log('setting pranswer');
  11089. try {
  11090. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11091. function() {
  11092. },
  11093. function(e) {
  11094. console.log('setRemoteDescription pranswer failed', e.toString());
  11095. });
  11096. } catch (e) {
  11097. console.error('setting pranswer failed', e);
  11098. }
  11099. } else {
  11100. //console.log('not yet setting pranswer');
  11101. }
  11102. }
  11103. // operate on each content element
  11104. elem.each(function () {
  11105. // would love to deactivate this, but firefox still requires it
  11106. var idx = -1;
  11107. var i;
  11108. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11109. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11110. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11111. idx = i;
  11112. break;
  11113. }
  11114. }
  11115. if (idx == -1) { // fall back to localdescription
  11116. for (i = 0; i < self.localSDP.media.length; i++) {
  11117. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11118. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11119. idx = i;
  11120. break;
  11121. }
  11122. }
  11123. }
  11124. var name = $(this).attr('name');
  11125. // TODO: check ice-pwd and ice-ufrag?
  11126. $(this).find('transport>candidate').each(function () {
  11127. var line, candidate;
  11128. line = SDPUtil.candidateFromJingle(this);
  11129. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11130. sdpMid: name,
  11131. candidate: line});
  11132. try {
  11133. self.peerconnection.addIceCandidate(candidate);
  11134. } catch (e) {
  11135. console.error('addIceCandidate failed', e.toString(), line);
  11136. }
  11137. });
  11138. });
  11139. };
  11140. JingleSession.prototype.sendAnswer = function (provisional) {
  11141. //console.log('createAnswer', provisional);
  11142. var self = this;
  11143. this.peerconnection.createAnswer(
  11144. function (sdp) {
  11145. self.createdAnswer(sdp, provisional);
  11146. },
  11147. function (e) {
  11148. console.error('createAnswer failed', e);
  11149. },
  11150. this.media_constraints
  11151. );
  11152. };
  11153. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11154. //console.log('createAnswer callback');
  11155. var self = this;
  11156. this.localSDP = new SDP(sdp.sdp);
  11157. //this.localSDP.mangle();
  11158. this.usepranswer = provisional === true;
  11159. if (this.usetrickle) {
  11160. if (this.usepranswer) {
  11161. sdp.type = 'pranswer';
  11162. for (var i = 0; i < this.localSDP.media.length; i++) {
  11163. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11164. }
  11165. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11166. }
  11167. }
  11168. var self = this;
  11169. var sendJingle = function (ssrcs) {
  11170. var accept = $iq({to: self.peerjid,
  11171. type: 'set'})
  11172. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11173. action: 'session-accept',
  11174. initiator: self.initiator,
  11175. responder: self.responder,
  11176. sid: self.sid });
  11177. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11178. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11179. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11180. self.connection.sendIQ(accept,
  11181. function () {
  11182. var ack = {};
  11183. ack.source = 'answer';
  11184. $(document).trigger('ack.jingle', [self.sid, ack]);
  11185. },
  11186. function (stanza) {
  11187. var error = ($(stanza).find('error').length) ? {
  11188. code: $(stanza).find('error').attr('code'),
  11189. reason: $(stanza).find('error :first')[0].tagName,
  11190. }:{};
  11191. error.source = 'answer';
  11192. JingleSession.onJingleError(self.sid, error);
  11193. },
  11194. 10000);
  11195. }
  11196. sdp.sdp = this.localSDP.raw;
  11197. this.peerconnection.setLocalDescription(sdp,
  11198. function () {
  11199. //console.log('setLocalDescription success');
  11200. if (self.usetrickle && !self.usepranswer) {
  11201. sendJingle();
  11202. }
  11203. self.setLocalDescription();
  11204. },
  11205. function (e) {
  11206. console.error('setLocalDescription failed', e);
  11207. }
  11208. );
  11209. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11210. for (var j = 0; j < cands.length; j++) {
  11211. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11212. if (cand.type == 'srflx') {
  11213. this.hadstuncandidate = true;
  11214. } else if (cand.type == 'relay') {
  11215. this.hadturncandidate = true;
  11216. }
  11217. }
  11218. };
  11219. JingleSession.prototype.sendTerminate = function (reason, text) {
  11220. var self = this,
  11221. term = $iq({to: this.peerjid,
  11222. type: 'set'})
  11223. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11224. action: 'session-terminate',
  11225. initiator: this.initiator,
  11226. sid: this.sid})
  11227. .c('reason')
  11228. .c(reason || 'success');
  11229. if (text) {
  11230. term.up().c('text').t(text);
  11231. }
  11232. this.connection.sendIQ(term,
  11233. function () {
  11234. self.peerconnection.close();
  11235. self.peerconnection = null;
  11236. self.terminate();
  11237. var ack = {};
  11238. ack.source = 'terminate';
  11239. $(document).trigger('ack.jingle', [self.sid, ack]);
  11240. },
  11241. function (stanza) {
  11242. var error = ($(stanza).find('error').length) ? {
  11243. code: $(stanza).find('error').attr('code'),
  11244. reason: $(stanza).find('error :first')[0].tagName,
  11245. }:{};
  11246. $(document).trigger('ack.jingle', [self.sid, error]);
  11247. },
  11248. 10000);
  11249. if (this.statsinterval !== null) {
  11250. window.clearInterval(this.statsinterval);
  11251. this.statsinterval = null;
  11252. }
  11253. };
  11254. JingleSession.prototype.addSource = function (elem, fromJid) {
  11255. var self = this;
  11256. // FIXME: dirty waiting
  11257. if (!this.peerconnection.localDescription)
  11258. {
  11259. console.warn("addSource - localDescription not ready yet")
  11260. setTimeout(function()
  11261. {
  11262. self.addSource(elem, fromJid);
  11263. },
  11264. 200
  11265. );
  11266. return;
  11267. }
  11268. console.log('addssrc', new Date().getTime());
  11269. console.log('ice', this.peerconnection.iceConnectionState);
  11270. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11271. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11272. $(elem).each(function (idx, content) {
  11273. var name = $(content).attr('name');
  11274. var lines = '';
  11275. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11276. var semantics = this.getAttribute('semantics');
  11277. var ssrcs = $(this).find('>source').map(function () {
  11278. return this.getAttribute('ssrc');
  11279. }).get();
  11280. if (ssrcs.length != 0) {
  11281. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11282. }
  11283. });
  11284. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11285. tmp.each(function () {
  11286. var ssrc = $(this).attr('ssrc');
  11287. if(mySdp.containsSSRC(ssrc)){
  11288. /**
  11289. * This happens when multiple participants change their streams at the same time and
  11290. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11291. * addssrc are scheduled for update IQ. See
  11292. */
  11293. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11294. return;
  11295. }
  11296. $(this).find('>parameter').each(function () {
  11297. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11298. if ($(this).attr('value') && $(this).attr('value').length)
  11299. lines += ':' + $(this).attr('value');
  11300. lines += '\r\n';
  11301. });
  11302. });
  11303. sdp.media.forEach(function(media, idx) {
  11304. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11305. return;
  11306. sdp.media[idx] += lines;
  11307. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11308. self.addssrc[idx] += lines;
  11309. });
  11310. sdp.raw = sdp.session + sdp.media.join('');
  11311. });
  11312. this.modifySources();
  11313. };
  11314. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11315. var self = this;
  11316. // FIXME: dirty waiting
  11317. if (!this.peerconnection.localDescription)
  11318. {
  11319. console.warn("removeSource - localDescription not ready yet")
  11320. setTimeout(function()
  11321. {
  11322. self.removeSource(elem, fromJid);
  11323. },
  11324. 200
  11325. );
  11326. return;
  11327. }
  11328. console.log('removessrc', new Date().getTime());
  11329. console.log('ice', this.peerconnection.iceConnectionState);
  11330. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11331. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11332. $(elem).each(function (idx, content) {
  11333. var name = $(content).attr('name');
  11334. var lines = '';
  11335. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11336. var semantics = this.getAttribute('semantics');
  11337. var ssrcs = $(this).find('>source').map(function () {
  11338. return this.getAttribute('ssrc');
  11339. }).get();
  11340. if (ssrcs.length != 0) {
  11341. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11342. }
  11343. });
  11344. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11345. tmp.each(function () {
  11346. var ssrc = $(this).attr('ssrc');
  11347. // This should never happen, but can be useful for bug detection
  11348. if(mySdp.containsSSRC(ssrc)){
  11349. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11350. return;
  11351. }
  11352. $(this).find('>parameter').each(function () {
  11353. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11354. if ($(this).attr('value') && $(this).attr('value').length)
  11355. lines += ':' + $(this).attr('value');
  11356. lines += '\r\n';
  11357. });
  11358. });
  11359. sdp.media.forEach(function(media, idx) {
  11360. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11361. return;
  11362. sdp.media[idx] += lines;
  11363. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11364. self.removessrc[idx] += lines;
  11365. });
  11366. sdp.raw = sdp.session + sdp.media.join('');
  11367. });
  11368. this.modifySources();
  11369. };
  11370. JingleSession.prototype.modifySources = function (successCallback) {
  11371. var self = this;
  11372. if (this.peerconnection.signalingState == 'closed') return;
  11373. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11374. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11375. this.setLocalDescription();
  11376. if(successCallback){
  11377. successCallback();
  11378. }
  11379. return;
  11380. }
  11381. // FIXME: this is a big hack
  11382. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11383. // ^ has been fixed.
  11384. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11385. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11386. this.wait = true;
  11387. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11388. return;
  11389. }
  11390. if (this.wait) {
  11391. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11392. this.wait = false;
  11393. return;
  11394. }
  11395. // Reset switch streams flag
  11396. this.switchstreams = false;
  11397. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11398. // add sources
  11399. this.addssrc.forEach(function(lines, idx) {
  11400. sdp.media[idx] += lines;
  11401. });
  11402. this.addssrc = [];
  11403. // remove sources
  11404. this.removessrc.forEach(function(lines, idx) {
  11405. lines = lines.split('\r\n');
  11406. lines.pop(); // remove empty last element;
  11407. lines.forEach(function(line) {
  11408. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11409. });
  11410. });
  11411. this.removessrc = [];
  11412. // FIXME:
  11413. // this was a hack for the situation when only one peer exists
  11414. // in the conference.
  11415. // check if still required and remove
  11416. if (sdp.media[0])
  11417. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11418. if (sdp.media[1])
  11419. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11420. sdp.raw = sdp.session + sdp.media.join('');
  11421. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11422. function() {
  11423. if(self.signalingState == 'closed') {
  11424. console.error("createAnswer attempt on closed state");
  11425. return;
  11426. }
  11427. self.peerconnection.createAnswer(
  11428. function(modifiedAnswer) {
  11429. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11430. if (self.pendingop !== null) {
  11431. var sdp = new SDP(modifiedAnswer.sdp);
  11432. if (sdp.media.length > 1) {
  11433. switch(self.pendingop) {
  11434. case 'mute':
  11435. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11436. break;
  11437. case 'unmute':
  11438. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11439. break;
  11440. }
  11441. sdp.raw = sdp.session + sdp.media.join('');
  11442. modifiedAnswer.sdp = sdp.raw;
  11443. }
  11444. self.pendingop = null;
  11445. }
  11446. // FIXME: pushing down an answer while ice connection state
  11447. // is still checking is bad...
  11448. //console.log(self.peerconnection.iceConnectionState);
  11449. // trying to work around another chrome bug
  11450. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11451. self.peerconnection.setLocalDescription(modifiedAnswer,
  11452. function() {
  11453. //console.log('modified setLocalDescription ok');
  11454. self.setLocalDescription();
  11455. if(successCallback){
  11456. successCallback();
  11457. }
  11458. },
  11459. function(error) {
  11460. console.error('modified setLocalDescription failed', error);
  11461. }
  11462. );
  11463. },
  11464. function(error) {
  11465. console.error('modified answer failed', error);
  11466. }
  11467. );
  11468. },
  11469. function(error) {
  11470. console.error('modify failed', error);
  11471. }
  11472. );
  11473. };
  11474. /**
  11475. * Switches video streams.
  11476. * @param new_stream new stream that will be used as video of this session.
  11477. * @param oldStream old video stream of this session.
  11478. * @param success_callback callback executed after successful stream switch.
  11479. */
  11480. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11481. var self = this;
  11482. // Remember SDP to figure out added/removed SSRCs
  11483. var oldSdp = null;
  11484. if(self.peerconnection) {
  11485. if(self.peerconnection.localDescription) {
  11486. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11487. }
  11488. self.peerconnection.removeStream(oldStream, true);
  11489. if(new_stream)
  11490. self.peerconnection.addStream(new_stream);
  11491. }
  11492. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11493. // Conference is not active
  11494. if(!oldSdp || !self.peerconnection) {
  11495. success_callback();
  11496. return;
  11497. }
  11498. self.switchstreams = true;
  11499. self.modifySources(function() {
  11500. console.log('modify sources done');
  11501. success_callback();
  11502. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11503. console.log("SDPs", oldSdp, newSdp);
  11504. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11505. });
  11506. };
  11507. /**
  11508. * Figures out added/removed ssrcs and send update IQs.
  11509. * @param old_sdp SDP object for old description.
  11510. * @param new_sdp SDP object for new description.
  11511. */
  11512. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11513. if (!(this.peerconnection.signalingState == 'stable' &&
  11514. this.peerconnection.iceConnectionState == 'connected')){
  11515. console.log("Too early to send updates");
  11516. return;
  11517. }
  11518. // send source-remove IQ.
  11519. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11520. var remove = $iq({to: this.peerjid, type: 'set'})
  11521. .c('jingle', {
  11522. xmlns: 'urn:xmpp:jingle:1',
  11523. action: 'source-remove',
  11524. initiator: this.initiator,
  11525. sid: this.sid
  11526. }
  11527. );
  11528. var removed = sdpDiffer.toJingle(remove);
  11529. if (removed) {
  11530. this.connection.sendIQ(remove,
  11531. function (res) {
  11532. console.info('got remove result', res);
  11533. },
  11534. function (err) {
  11535. console.error('got remove error', err);
  11536. }
  11537. );
  11538. } else {
  11539. console.log('removal not necessary');
  11540. }
  11541. // send source-add IQ.
  11542. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11543. var add = $iq({to: this.peerjid, type: 'set'})
  11544. .c('jingle', {
  11545. xmlns: 'urn:xmpp:jingle:1',
  11546. action: 'source-add',
  11547. initiator: this.initiator,
  11548. sid: this.sid
  11549. }
  11550. );
  11551. var added = sdpDiffer.toJingle(add);
  11552. if (added) {
  11553. this.connection.sendIQ(add,
  11554. function (res) {
  11555. console.info('got add result', res);
  11556. },
  11557. function (err) {
  11558. console.error('got add error', err);
  11559. }
  11560. );
  11561. } else {
  11562. console.log('addition not necessary');
  11563. }
  11564. };
  11565. /**
  11566. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11567. *
  11568. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11569. * tracks; otherwise, <tt>false</tt>
  11570. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11571. * tracks have been enabled/disabled. The function may, optionally, return
  11572. * another function which is to be invoked after the whole mute/unmute operation
  11573. * has completed successfully.
  11574. * @param options an object which specifies optional arguments such as the
  11575. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11576. * specifies whether the method was initiated in response to a user command (in
  11577. * contrast to an automatic decision made by the application logic)
  11578. */
  11579. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11580. var byUser;
  11581. if (options) {
  11582. byUser = options.byUser;
  11583. if (typeof byUser === 'undefined') {
  11584. byUser = true;
  11585. }
  11586. } else {
  11587. byUser = true;
  11588. }
  11589. // The user's command to mute the (local) video takes precedence over any
  11590. // automatic decision made by the application logic.
  11591. if (byUser) {
  11592. this.videoMuteByUser = mute;
  11593. } else if (this.videoMuteByUser) {
  11594. return;
  11595. }
  11596. this.hardMuteVideo(mute);
  11597. this.modifySources(callback(mute));
  11598. };
  11599. JingleSession.prototype.hardMuteVideo = function (muted) {
  11600. this.pendingop = muted ? 'mute' : 'unmute';
  11601. };
  11602. JingleSession.prototype.sendMute = function (muted, content) {
  11603. var info = $iq({to: this.peerjid,
  11604. type: 'set'})
  11605. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11606. action: 'session-info',
  11607. initiator: this.initiator,
  11608. sid: this.sid });
  11609. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11610. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11611. if (content) {
  11612. info.attrs({'name': content});
  11613. }
  11614. this.connection.send(info);
  11615. };
  11616. JingleSession.prototype.sendRinging = function () {
  11617. var info = $iq({to: this.peerjid,
  11618. type: 'set'})
  11619. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11620. action: 'session-info',
  11621. initiator: this.initiator,
  11622. sid: this.sid });
  11623. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11624. this.connection.send(info);
  11625. };
  11626. JingleSession.prototype.getStats = function (interval) {
  11627. var self = this;
  11628. var recv = {audio: 0, video: 0};
  11629. var lost = {audio: 0, video: 0};
  11630. var lastrecv = {audio: 0, video: 0};
  11631. var lastlost = {audio: 0, video: 0};
  11632. var loss = {audio: 0, video: 0};
  11633. var delta = {audio: 0, video: 0};
  11634. this.statsinterval = window.setInterval(function () {
  11635. if (self && self.peerconnection && self.peerconnection.getStats) {
  11636. self.peerconnection.getStats(function (stats) {
  11637. var results = stats.result();
  11638. // TODO: there are so much statistics you can get from this..
  11639. for (var i = 0; i < results.length; ++i) {
  11640. if (results[i].type == 'ssrc') {
  11641. var packetsrecv = results[i].stat('packetsReceived');
  11642. var packetslost = results[i].stat('packetsLost');
  11643. if (packetsrecv && packetslost) {
  11644. packetsrecv = parseInt(packetsrecv, 10);
  11645. packetslost = parseInt(packetslost, 10);
  11646. if (results[i].stat('googFrameRateReceived')) {
  11647. lastlost.video = lost.video;
  11648. lastrecv.video = recv.video;
  11649. recv.video = packetsrecv;
  11650. lost.video = packetslost;
  11651. } else {
  11652. lastlost.audio = lost.audio;
  11653. lastrecv.audio = recv.audio;
  11654. recv.audio = packetsrecv;
  11655. lost.audio = packetslost;
  11656. }
  11657. }
  11658. }
  11659. }
  11660. delta.audio = recv.audio - lastrecv.audio;
  11661. delta.video = recv.video - lastrecv.video;
  11662. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11663. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11664. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11665. });
  11666. }
  11667. }, interval || 3000);
  11668. return this.statsinterval;
  11669. };
  11670. JingleSession.onJingleError = function (session, error)
  11671. {
  11672. console.error("Jingle error", error);
  11673. }
  11674. JingleSession.onJingleFatalError = function (session, error)
  11675. {
  11676. this.service.sessionTerminated = true;
  11677. this.connection.emuc.doLeave();
  11678. APP.UI.messageHandler.showError("dialog.sorry",
  11679. "dialog.internalError");
  11680. }
  11681. JingleSession.prototype.setLocalDescription = function () {
  11682. // put our ssrcs into presence so other clients can identify our stream
  11683. var newssrcs = [];
  11684. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11685. media.forEach(function (media) {
  11686. if(Object.keys(media.sources).length > 0) {
  11687. // TODO(gp) maybe exclude FID streams?
  11688. Object.keys(media.sources).forEach(function (ssrc) {
  11689. newssrcs.push({
  11690. 'ssrc': ssrc,
  11691. 'type': media.type,
  11692. 'direction': media.direction
  11693. });
  11694. });
  11695. }
  11696. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11697. {
  11698. newssrcs.push({
  11699. 'ssrc': this.localStreamsSSRC[media.type],
  11700. 'type': media.type,
  11701. 'direction': media.direction
  11702. });
  11703. }
  11704. });
  11705. console.log('new ssrcs', newssrcs);
  11706. // Have to clear presence map to get rid of removed streams
  11707. this.connection.emuc.clearPresenceMedia();
  11708. if (newssrcs.length > 0) {
  11709. for (var i = 1; i <= newssrcs.length; i ++) {
  11710. // Change video type to screen
  11711. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11712. newssrcs[i-1].type = 'screen';
  11713. }
  11714. this.connection.emuc.addMediaToPresence(i,
  11715. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11716. }
  11717. this.connection.emuc.sendPresence();
  11718. }
  11719. }
  11720. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11721. function sendKeyframe(pc) {
  11722. console.log('sendkeyframe', pc.iceConnectionState);
  11723. if (pc.iceConnectionState !== 'connected') return; // safe...
  11724. pc.setRemoteDescription(
  11725. pc.remoteDescription,
  11726. function () {
  11727. pc.createAnswer(
  11728. function (modifiedAnswer) {
  11729. pc.setLocalDescription(
  11730. modifiedAnswer,
  11731. function () {
  11732. // noop
  11733. },
  11734. function (error) {
  11735. console.log('triggerKeyframe setLocalDescription failed', error);
  11736. APP.UI.messageHandler.showError();
  11737. }
  11738. );
  11739. },
  11740. function (error) {
  11741. console.log('triggerKeyframe createAnswer failed', error);
  11742. APP.UI.messageHandler.showError();
  11743. }
  11744. );
  11745. },
  11746. function (error) {
  11747. console.log('triggerKeyframe setRemoteDescription failed', error);
  11748. APP.UI.messageHandler.showError();
  11749. }
  11750. );
  11751. }
  11752. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11753. var self = this;
  11754. var thessrc;
  11755. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11756. // look up an associated JID for a stream id
  11757. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11758. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11759. var ssrclines
  11760. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11761. ssrclines = ssrclines.filter(function (line) {
  11762. // NOTE(gp) previously we filtered on the mslabel, but that property
  11763. // is not always present.
  11764. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11765. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11766. });
  11767. if (ssrclines.length) {
  11768. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11769. // We signal our streams (through Jingle to the focus) before we set
  11770. // our presence (through which peers associate remote streams to
  11771. // jids). So, it might arrive that a remote stream is added but
  11772. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11773. // successfully set. Here we wait for up to a second for the
  11774. // presence to arrive.
  11775. if (!ssrc2jid[thessrc]) {
  11776. if (typeof times === 'undefined')
  11777. {
  11778. times = 0;
  11779. }
  11780. if (times > 10)
  11781. {
  11782. console.warning('Waiting for jid timed out', thessrc);
  11783. }
  11784. else
  11785. {
  11786. setTimeout(function(d) {
  11787. return function() {
  11788. self.remoteStreamAdded(d, times++);
  11789. }
  11790. }(data), 250);
  11791. }
  11792. return;
  11793. }
  11794. // ok to overwrite the one from focus? might save work in colibri.js
  11795. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11796. if (ssrc2jid[thessrc]) {
  11797. data.peerjid = ssrc2jid[thessrc];
  11798. }
  11799. }
  11800. }
  11801. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11802. var isVideo = data.stream.getVideoTracks().length > 0;
  11803. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11804. if (isVideo &&
  11805. data.peerjid && this.peerjid === data.peerjid &&
  11806. data.stream.getVideoTracks().length === 0 &&
  11807. APP.RTC.localVideo.getTracks().length > 0) {
  11808. window.setTimeout(function () {
  11809. sendKeyframe(self.peerconnection);
  11810. }, 3000);
  11811. }
  11812. }
  11813. module.exports = JingleSession;
  11814. },{"../../service/RTC/RTCBrowserType":89,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11815. /* jshint -W117 */
  11816. var SDPUtil = require("./SDPUtil");
  11817. // SDP STUFF
  11818. function SDP(sdp) {
  11819. this.media = sdp.split('\r\nm=');
  11820. for (var i = 1; i < this.media.length; i++) {
  11821. this.media[i] = 'm=' + this.media[i];
  11822. if (i != this.media.length - 1) {
  11823. this.media[i] += '\r\n';
  11824. }
  11825. }
  11826. this.session = this.media.shift() + '\r\n';
  11827. this.raw = this.session + this.media.join('');
  11828. }
  11829. /**
  11830. * Returns map of MediaChannel mapped per channel idx.
  11831. */
  11832. SDP.prototype.getMediaSsrcMap = function() {
  11833. var self = this;
  11834. var media_ssrcs = {};
  11835. var tmp;
  11836. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11837. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11838. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11839. var media = {
  11840. mediaindex: mediaindex,
  11841. mid: mid,
  11842. ssrcs: {},
  11843. ssrcGroups: []
  11844. };
  11845. media_ssrcs[mediaindex] = media;
  11846. tmp.forEach(function (line) {
  11847. var linessrc = line.substring(7).split(' ')[0];
  11848. // allocate new ChannelSsrc
  11849. if(!media.ssrcs[linessrc]) {
  11850. media.ssrcs[linessrc] = {
  11851. ssrc: linessrc,
  11852. lines: []
  11853. };
  11854. }
  11855. media.ssrcs[linessrc].lines.push(line);
  11856. });
  11857. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11858. tmp.forEach(function(line){
  11859. var semantics = line.substr(0, idx).substr(13);
  11860. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11861. if (ssrcs.length != 0) {
  11862. media.ssrcGroups.push({
  11863. semantics: semantics,
  11864. ssrcs: ssrcs
  11865. });
  11866. }
  11867. });
  11868. }
  11869. return media_ssrcs;
  11870. };
  11871. /**
  11872. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11873. * @param ssrc the ssrc to check.
  11874. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11875. */
  11876. SDP.prototype.containsSSRC = function(ssrc) {
  11877. var medias = this.getMediaSsrcMap();
  11878. var contains = false;
  11879. Object.keys(medias).forEach(function(mediaindex){
  11880. var media = medias[mediaindex];
  11881. //console.log("Check", channel, ssrc);
  11882. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11883. contains = true;
  11884. }
  11885. });
  11886. return contains;
  11887. };
  11888. // remove iSAC and CN from SDP
  11889. SDP.prototype.mangle = function () {
  11890. var i, j, mline, lines, rtpmap, newdesc;
  11891. for (i = 0; i < this.media.length; i++) {
  11892. lines = this.media[i].split('\r\n');
  11893. lines.pop(); // remove empty last element
  11894. mline = SDPUtil.parse_mline(lines.shift());
  11895. if (mline.media != 'audio')
  11896. continue;
  11897. newdesc = '';
  11898. mline.fmt.length = 0;
  11899. for (j = 0; j < lines.length; j++) {
  11900. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11901. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11902. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11903. continue;
  11904. mline.fmt.push(rtpmap.id);
  11905. newdesc += lines[j] + '\r\n';
  11906. } else {
  11907. newdesc += lines[j] + '\r\n';
  11908. }
  11909. }
  11910. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11911. this.media[i] += newdesc;
  11912. }
  11913. this.raw = this.session + this.media.join('');
  11914. };
  11915. // remove lines matching prefix from session section
  11916. SDP.prototype.removeSessionLines = function(prefix) {
  11917. var self = this;
  11918. var lines = SDPUtil.find_lines(this.session, prefix);
  11919. lines.forEach(function(line) {
  11920. self.session = self.session.replace(line + '\r\n', '');
  11921. });
  11922. this.raw = this.session + this.media.join('');
  11923. return lines;
  11924. }
  11925. // remove lines matching prefix from a media section specified by mediaindex
  11926. // TODO: non-numeric mediaindex could match mid
  11927. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11928. var self = this;
  11929. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11930. lines.forEach(function(line) {
  11931. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11932. });
  11933. this.raw = this.session + this.media.join('');
  11934. return lines;
  11935. }
  11936. // add content's to a jingle element
  11937. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11938. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11939. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11940. var self = this;
  11941. // new bundle plan
  11942. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11943. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11944. for (i = 0; i < lines.length; i++) {
  11945. tmp = lines[i].split(' ');
  11946. var semantics = tmp.shift().substr(8);
  11947. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11948. for (j = 0; j < tmp.length; j++) {
  11949. elem.c('content', {name: tmp[j]}).up();
  11950. }
  11951. elem.up();
  11952. }
  11953. }
  11954. for (i = 0; i < this.media.length; i++) {
  11955. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11956. if (!(mline.media === 'audio' ||
  11957. mline.media === 'video' ||
  11958. mline.media === 'application'))
  11959. {
  11960. continue;
  11961. }
  11962. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11963. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11964. } else {
  11965. if(ssrcs && ssrcs[mline.media])
  11966. {
  11967. ssrc = ssrcs[mline.media];
  11968. }
  11969. else
  11970. ssrc = false;
  11971. }
  11972. elem.c('content', {creator: thecreator, name: mline.media});
  11973. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11974. // prefer identifier from a=mid if present
  11975. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11976. elem.attrs({ name: mid });
  11977. }
  11978. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11979. {
  11980. elem.c('description',
  11981. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11982. media: mline.media });
  11983. if (ssrc) {
  11984. elem.attrs({ssrc: ssrc});
  11985. }
  11986. for (j = 0; j < mline.fmt.length; j++) {
  11987. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11988. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11989. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11990. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11991. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11992. for (k = 0; k < tmp.length; k++) {
  11993. elem.c('parameter', tmp[k]).up();
  11994. }
  11995. }
  11996. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11997. elem.up();
  11998. }
  11999. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12000. elem.c('encryption', {required: 1});
  12001. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12002. crypto.forEach(function(line) {
  12003. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12004. });
  12005. elem.up(); // end of encryption
  12006. }
  12007. if (ssrc) {
  12008. // new style mapping
  12009. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12010. // FIXME: group by ssrc and support multiple different ssrcs
  12011. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12012. if(ssrclines.length > 0) {
  12013. ssrclines.forEach(function (line) {
  12014. idx = line.indexOf(' ');
  12015. var linessrc = line.substr(0, idx).substr(7);
  12016. if (linessrc != ssrc) {
  12017. elem.up();
  12018. ssrc = linessrc;
  12019. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12020. }
  12021. var kv = line.substr(idx + 1);
  12022. elem.c('parameter');
  12023. if (kv.indexOf(':') == -1) {
  12024. elem.attrs({ name: kv });
  12025. } else {
  12026. elem.attrs({ name: kv.split(':', 2)[0] });
  12027. elem.attrs({ value: kv.split(':', 2)[1] });
  12028. }
  12029. elem.up();
  12030. });
  12031. elem.up();
  12032. }
  12033. else
  12034. {
  12035. elem.up();
  12036. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12037. elem.c('parameter');
  12038. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12039. elem.up();
  12040. var msid = null;
  12041. if(mline.media == "audio")
  12042. {
  12043. msid = APP.RTC.localAudio.getId();
  12044. }
  12045. else
  12046. {
  12047. msid = APP.RTC.localVideo.getId();
  12048. }
  12049. if(msid != null)
  12050. {
  12051. msid = msid.replace(/[\{,\}]/g,"");
  12052. elem.c('parameter');
  12053. elem.attrs({name: "msid", value:msid});
  12054. elem.up();
  12055. elem.c('parameter');
  12056. elem.attrs({name: "mslabel", value:msid});
  12057. elem.up();
  12058. elem.c('parameter');
  12059. elem.attrs({name: "label", value:msid});
  12060. elem.up();
  12061. elem.up();
  12062. }
  12063. }
  12064. // XEP-0339 handle ssrc-group attributes
  12065. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12066. ssrc_group_lines.forEach(function(line) {
  12067. idx = line.indexOf(' ');
  12068. var semantics = line.substr(0, idx).substr(13);
  12069. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12070. if (ssrcs.length != 0) {
  12071. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12072. ssrcs.forEach(function(ssrc) {
  12073. elem.c('source', { ssrc: ssrc })
  12074. .up();
  12075. });
  12076. elem.up();
  12077. }
  12078. });
  12079. }
  12080. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12081. elem.c('rtcp-mux').up();
  12082. }
  12083. // XEP-0293 -- map a=rtcp-fb:*
  12084. this.RtcpFbToJingle(i, elem, '*');
  12085. // XEP-0294
  12086. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12087. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12088. for (j = 0; j < lines.length; j++) {
  12089. tmp = SDPUtil.parse_extmap(lines[j]);
  12090. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12091. uri: tmp.uri,
  12092. id: tmp.value });
  12093. if (tmp.hasOwnProperty('direction')) {
  12094. switch (tmp.direction) {
  12095. case 'sendonly':
  12096. elem.attrs({senders: 'responder'});
  12097. break;
  12098. case 'recvonly':
  12099. elem.attrs({senders: 'initiator'});
  12100. break;
  12101. case 'sendrecv':
  12102. elem.attrs({senders: 'both'});
  12103. break;
  12104. case 'inactive':
  12105. elem.attrs({senders: 'none'});
  12106. break;
  12107. }
  12108. }
  12109. // TODO: handle params
  12110. elem.up();
  12111. }
  12112. }
  12113. elem.up(); // end of description
  12114. }
  12115. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12116. this.TransportToJingle(i, elem);
  12117. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12118. elem.attrs({senders: 'both'});
  12119. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12120. elem.attrs({senders: 'initiator'});
  12121. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12122. elem.attrs({senders: 'responder'});
  12123. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12124. elem.attrs({senders: 'none'});
  12125. }
  12126. if (mline.port == '0') {
  12127. // estos hack to reject an m-line
  12128. elem.attrs({senders: 'rejected'});
  12129. }
  12130. elem.up(); // end of content
  12131. }
  12132. elem.up();
  12133. return elem;
  12134. };
  12135. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12136. var i = mediaindex;
  12137. var tmp;
  12138. var self = this;
  12139. elem.c('transport');
  12140. // XEP-0343 DTLS/SCTP
  12141. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12142. {
  12143. var sctpmap = SDPUtil.find_line(
  12144. this.media[i], 'a=sctpmap:', self.session);
  12145. if (sctpmap)
  12146. {
  12147. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12148. elem.c('sctpmap',
  12149. {
  12150. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12151. number: sctpAttrs[0], /* SCTP port */
  12152. protocol: sctpAttrs[1], /* protocol */
  12153. });
  12154. // Optional stream count attribute
  12155. if (sctpAttrs.length > 2)
  12156. elem.attrs({ streams: sctpAttrs[2]});
  12157. elem.up();
  12158. }
  12159. }
  12160. // XEP-0320
  12161. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12162. fingerprints.forEach(function(line) {
  12163. tmp = SDPUtil.parse_fingerprint(line);
  12164. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12165. elem.c('fingerprint').t(tmp.fingerprint);
  12166. delete tmp.fingerprint;
  12167. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12168. if (line) {
  12169. tmp.setup = line.substr(8);
  12170. }
  12171. elem.attrs(tmp);
  12172. elem.up(); // end of fingerprint
  12173. });
  12174. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12175. if (tmp) {
  12176. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12177. elem.attrs(tmp);
  12178. // XEP-0176
  12179. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12180. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12181. lines.forEach(function (line) {
  12182. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12183. });
  12184. }
  12185. }
  12186. elem.up(); // end of transport
  12187. }
  12188. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12189. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12190. lines.forEach(function (line) {
  12191. var tmp = SDPUtil.parse_rtcpfb(line);
  12192. if (tmp.type == 'trr-int') {
  12193. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12194. elem.up();
  12195. } else {
  12196. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12197. if (tmp.params.length > 0) {
  12198. elem.attrs({'subtype': tmp.params[0]});
  12199. }
  12200. elem.up();
  12201. }
  12202. });
  12203. };
  12204. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12205. var media = '';
  12206. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12207. if (tmp.length) {
  12208. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12209. if (tmp.attr('value')) {
  12210. media += tmp.attr('value');
  12211. } else {
  12212. media += '0';
  12213. }
  12214. media += '\r\n';
  12215. }
  12216. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12217. tmp.each(function () {
  12218. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12219. if ($(this).attr('subtype')) {
  12220. media += ' ' + $(this).attr('subtype');
  12221. }
  12222. media += '\r\n';
  12223. });
  12224. return media;
  12225. };
  12226. // construct an SDP from a jingle stanza
  12227. SDP.prototype.fromJingle = function (jingle) {
  12228. var self = this;
  12229. this.raw = 'v=0\r\n' +
  12230. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12231. 's=-\r\n' +
  12232. 't=0 0\r\n';
  12233. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12234. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12235. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12236. var contents = $(group).find('>content').map(function (idx, content) {
  12237. return content.getAttribute('name');
  12238. }).get();
  12239. if (contents.length > 0) {
  12240. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12241. }
  12242. });
  12243. }
  12244. this.session = this.raw;
  12245. jingle.find('>content').each(function () {
  12246. var m = self.jingle2media($(this));
  12247. self.media.push(m);
  12248. });
  12249. // reconstruct msid-semantic -- apparently not necessary
  12250. /*
  12251. var msid = SDPUtil.parse_ssrc(this.raw);
  12252. if (msid.hasOwnProperty('mslabel')) {
  12253. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12254. }
  12255. */
  12256. this.raw = this.session + this.media.join('');
  12257. };
  12258. // translate a jingle content element into an an SDP media part
  12259. SDP.prototype.jingle2media = function (content) {
  12260. var media = '',
  12261. desc = content.find('description'),
  12262. ssrc = desc.attr('ssrc'),
  12263. self = this,
  12264. tmp;
  12265. var sctp = content.find(
  12266. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12267. tmp = { media: desc.attr('media') };
  12268. tmp.port = '1';
  12269. if (content.attr('senders') == 'rejected') {
  12270. // estos hack to reject an m-line.
  12271. tmp.port = '0';
  12272. }
  12273. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12274. if (sctp.length)
  12275. tmp.proto = 'DTLS/SCTP';
  12276. else
  12277. tmp.proto = 'RTP/SAVPF';
  12278. } else {
  12279. tmp.proto = 'RTP/AVPF';
  12280. }
  12281. if (!sctp.length)
  12282. {
  12283. tmp.fmt = desc.find('payload-type').map(
  12284. function () { return this.getAttribute('id'); }).get();
  12285. media += SDPUtil.build_mline(tmp) + '\r\n';
  12286. }
  12287. else
  12288. {
  12289. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12290. media += 'a=sctpmap:' + sctp.attr('number') +
  12291. ' ' + sctp.attr('protocol');
  12292. var streamCount = sctp.attr('streams');
  12293. if (streamCount)
  12294. media += ' ' + streamCount + '\r\n';
  12295. else
  12296. media += '\r\n';
  12297. }
  12298. media += 'c=IN IP4 0.0.0.0\r\n';
  12299. if (!sctp.length)
  12300. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12301. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12302. if (tmp.length) {
  12303. if (tmp.attr('ufrag')) {
  12304. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12305. }
  12306. if (tmp.attr('pwd')) {
  12307. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12308. }
  12309. tmp.find('>fingerprint').each(function () {
  12310. // FIXME: check namespace at some point
  12311. media += 'a=fingerprint:' + this.getAttribute('hash');
  12312. media += ' ' + $(this).text();
  12313. media += '\r\n';
  12314. if (this.getAttribute('setup')) {
  12315. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12316. }
  12317. });
  12318. }
  12319. switch (content.attr('senders')) {
  12320. case 'initiator':
  12321. media += 'a=sendonly\r\n';
  12322. break;
  12323. case 'responder':
  12324. media += 'a=recvonly\r\n';
  12325. break;
  12326. case 'none':
  12327. media += 'a=inactive\r\n';
  12328. break;
  12329. case 'both':
  12330. media += 'a=sendrecv\r\n';
  12331. break;
  12332. }
  12333. media += 'a=mid:' + content.attr('name') + '\r\n';
  12334. // <description><rtcp-mux/></description>
  12335. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12336. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12337. if (desc.find('rtcp-mux').length) {
  12338. media += 'a=rtcp-mux\r\n';
  12339. }
  12340. if (desc.find('encryption').length) {
  12341. desc.find('encryption>crypto').each(function () {
  12342. media += 'a=crypto:' + this.getAttribute('tag');
  12343. media += ' ' + this.getAttribute('crypto-suite');
  12344. media += ' ' + this.getAttribute('key-params');
  12345. if (this.getAttribute('session-params')) {
  12346. media += ' ' + this.getAttribute('session-params');
  12347. }
  12348. media += '\r\n';
  12349. });
  12350. }
  12351. desc.find('payload-type').each(function () {
  12352. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12353. if ($(this).find('>parameter').length) {
  12354. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12355. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12356. media += '\r\n';
  12357. }
  12358. // xep-0293
  12359. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12360. });
  12361. // xep-0293
  12362. media += self.RtcpFbFromJingle(desc, '*');
  12363. // xep-0294
  12364. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12365. tmp.each(function () {
  12366. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12367. });
  12368. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12369. media += SDPUtil.candidateFromJingle(this);
  12370. });
  12371. // XEP-0339 handle ssrc-group attributes
  12372. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12373. var semantics = this.getAttribute('semantics');
  12374. var ssrcs = $(this).find('>source').map(function() {
  12375. return this.getAttribute('ssrc');
  12376. }).get();
  12377. if (ssrcs.length != 0) {
  12378. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12379. }
  12380. });
  12381. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12382. tmp.each(function () {
  12383. var ssrc = this.getAttribute('ssrc');
  12384. $(this).find('>parameter').each(function () {
  12385. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12386. if (this.getAttribute('value') && this.getAttribute('value').length)
  12387. media += ':' + this.getAttribute('value');
  12388. media += '\r\n';
  12389. });
  12390. });
  12391. return media;
  12392. };
  12393. module.exports = SDP;
  12394. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12395. function SDPDiffer(mySDP, otherSDP) {
  12396. this.mySDP = mySDP;
  12397. this.otherSDP = otherSDP;
  12398. }
  12399. /**
  12400. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12401. * @param otherSdp the other SDP to check ssrc with.
  12402. */
  12403. SDPDiffer.prototype.getNewMedia = function() {
  12404. // this could be useful in Array.prototype.
  12405. function arrayEquals(array) {
  12406. // if the other array is a falsy value, return
  12407. if (!array)
  12408. return false;
  12409. // compare lengths - can save a lot of time
  12410. if (this.length != array.length)
  12411. return false;
  12412. for (var i = 0, l=this.length; i < l; i++) {
  12413. // Check if we have nested arrays
  12414. if (this[i] instanceof Array && array[i] instanceof Array) {
  12415. // recurse into the nested arrays
  12416. if (!this[i].equals(array[i]))
  12417. return false;
  12418. }
  12419. else if (this[i] != array[i]) {
  12420. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12421. return false;
  12422. }
  12423. }
  12424. return true;
  12425. }
  12426. var myMedias = this.mySDP.getMediaSsrcMap();
  12427. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12428. var newMedia = {};
  12429. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12430. var myMedia = myMedias[othersMediaIdx];
  12431. var othersMedia = othersMedias[othersMediaIdx];
  12432. if(!myMedia && othersMedia) {
  12433. // Add whole channel
  12434. newMedia[othersMediaIdx] = othersMedia;
  12435. return;
  12436. }
  12437. // Look for new ssrcs accross the channel
  12438. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12439. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12440. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12441. if(!newMedia[othersMediaIdx]){
  12442. newMedia[othersMediaIdx] = {
  12443. mediaindex: othersMedia.mediaindex,
  12444. mid: othersMedia.mid,
  12445. ssrcs: {},
  12446. ssrcGroups: []
  12447. };
  12448. }
  12449. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12450. }
  12451. });
  12452. // Look for new ssrc groups across the channels
  12453. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12454. // try to match the other ssrc-group with an ssrc-group of ours
  12455. var matched = false;
  12456. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12457. var mySsrcGroup = myMedia.ssrcGroups[i];
  12458. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12459. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12460. matched = true;
  12461. break;
  12462. }
  12463. }
  12464. if (!matched) {
  12465. // Allocate channel if we've found an ssrc-group that doesn't
  12466. // exist in our channel
  12467. if(!newMedia[othersMediaIdx]){
  12468. newMedia[othersMediaIdx] = {
  12469. mediaindex: othersMedia.mediaindex,
  12470. mid: othersMedia.mid,
  12471. ssrcs: {},
  12472. ssrcGroups: []
  12473. };
  12474. }
  12475. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12476. }
  12477. });
  12478. });
  12479. return newMedia;
  12480. };
  12481. /**
  12482. * Sends SSRC update IQ.
  12483. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12484. * @param sid session identifier that will be put into the IQ.
  12485. * @param initiator initiator identifier.
  12486. * @param toJid destination Jid
  12487. * @param isAdd indicates if this is remove or add operation.
  12488. */
  12489. SDPDiffer.prototype.toJingle = function(modify) {
  12490. var sdpMediaSsrcs = this.getNewMedia();
  12491. var self = this;
  12492. // FIXME: only announce video ssrcs since we mix audio and dont need
  12493. // the audio ssrcs therefore
  12494. var modified = false;
  12495. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12496. modified = true;
  12497. var media = sdpMediaSsrcs[mediaindex];
  12498. modify.c('content', {name: media.mid});
  12499. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12500. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12501. // generate sources from lines
  12502. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12503. var mediaSsrc = media.ssrcs[ssrcNum];
  12504. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12505. modify.attrs({ssrc: mediaSsrc.ssrc});
  12506. // iterate over ssrc lines
  12507. mediaSsrc.lines.forEach(function (line) {
  12508. var idx = line.indexOf(' ');
  12509. var kv = line.substr(idx + 1);
  12510. modify.c('parameter');
  12511. if (kv.indexOf(':') == -1) {
  12512. modify.attrs({ name: kv });
  12513. } else {
  12514. modify.attrs({ name: kv.split(':', 2)[0] });
  12515. modify.attrs({ value: kv.split(':', 2)[1] });
  12516. }
  12517. modify.up(); // end of parameter
  12518. });
  12519. modify.up(); // end of source
  12520. });
  12521. // generate source groups from lines
  12522. media.ssrcGroups.forEach(function(ssrcGroup) {
  12523. if (ssrcGroup.ssrcs.length != 0) {
  12524. modify.c('ssrc-group', {
  12525. semantics: ssrcGroup.semantics,
  12526. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12527. });
  12528. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12529. modify.c('source', { ssrc: ssrc })
  12530. .up(); // end of source
  12531. });
  12532. modify.up(); // end of ssrc-group
  12533. }
  12534. });
  12535. modify.up(); // end of description
  12536. modify.up(); // end of content
  12537. });
  12538. return modified;
  12539. };
  12540. module.exports = SDPDiffer;
  12541. },{}],51:[function(require,module,exports){
  12542. SDPUtil = {
  12543. iceparams: function (mediadesc, sessiondesc) {
  12544. var data = null;
  12545. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12546. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12547. data = {
  12548. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12549. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12550. };
  12551. }
  12552. return data;
  12553. },
  12554. parse_iceufrag: function (line) {
  12555. return line.substring(12);
  12556. },
  12557. build_iceufrag: function (frag) {
  12558. return 'a=ice-ufrag:' + frag;
  12559. },
  12560. parse_icepwd: function (line) {
  12561. return line.substring(10);
  12562. },
  12563. build_icepwd: function (pwd) {
  12564. return 'a=ice-pwd:' + pwd;
  12565. },
  12566. parse_mid: function (line) {
  12567. return line.substring(6);
  12568. },
  12569. parse_mline: function (line) {
  12570. var parts = line.substring(2).split(' '),
  12571. data = {};
  12572. data.media = parts.shift();
  12573. data.port = parts.shift();
  12574. data.proto = parts.shift();
  12575. if (parts[parts.length - 1] === '') { // trailing whitespace
  12576. parts.pop();
  12577. }
  12578. data.fmt = parts;
  12579. return data;
  12580. },
  12581. build_mline: function (mline) {
  12582. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12583. },
  12584. parse_rtpmap: function (line) {
  12585. var parts = line.substring(9).split(' '),
  12586. data = {};
  12587. data.id = parts.shift();
  12588. parts = parts[0].split('/');
  12589. data.name = parts.shift();
  12590. data.clockrate = parts.shift();
  12591. data.channels = parts.length ? parts.shift() : '1';
  12592. return data;
  12593. },
  12594. /**
  12595. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12596. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12597. * @returns [SCTP port number, protocol, streams]
  12598. */
  12599. parse_sctpmap: function (line)
  12600. {
  12601. var parts = line.substring(10).split(' ');
  12602. var sctpPort = parts[0];
  12603. var protocol = parts[1];
  12604. // Stream count is optional
  12605. var streamCount = parts.length > 2 ? parts[2] : null;
  12606. return [sctpPort, protocol, streamCount];// SCTP port
  12607. },
  12608. build_rtpmap: function (el) {
  12609. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12610. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12611. line += '/' + el.getAttribute('channels');
  12612. }
  12613. return line;
  12614. },
  12615. parse_crypto: function (line) {
  12616. var parts = line.substring(9).split(' '),
  12617. data = {};
  12618. data.tag = parts.shift();
  12619. data['crypto-suite'] = parts.shift();
  12620. data['key-params'] = parts.shift();
  12621. if (parts.length) {
  12622. data['session-params'] = parts.join(' ');
  12623. }
  12624. return data;
  12625. },
  12626. parse_fingerprint: function (line) { // RFC 4572
  12627. var parts = line.substring(14).split(' '),
  12628. data = {};
  12629. data.hash = parts.shift();
  12630. data.fingerprint = parts.shift();
  12631. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12632. return data;
  12633. },
  12634. parse_fmtp: function (line) {
  12635. var parts = line.split(' '),
  12636. i, key, value,
  12637. data = [];
  12638. parts.shift();
  12639. parts = parts.join(' ').split(';');
  12640. for (i = 0; i < parts.length; i++) {
  12641. key = parts[i].split('=')[0];
  12642. while (key.length && key[0] == ' ') {
  12643. key = key.substring(1);
  12644. }
  12645. value = parts[i].split('=')[1];
  12646. if (key && value) {
  12647. data.push({name: key, value: value});
  12648. } else if (key) {
  12649. // rfc 4733 (DTMF) style stuff
  12650. data.push({name: '', value: key});
  12651. }
  12652. }
  12653. return data;
  12654. },
  12655. parse_icecandidate: function (line) {
  12656. var candidate = {},
  12657. elems = line.split(' ');
  12658. candidate.foundation = elems[0].substring(12);
  12659. candidate.component = elems[1];
  12660. candidate.protocol = elems[2].toLowerCase();
  12661. candidate.priority = elems[3];
  12662. candidate.ip = elems[4];
  12663. candidate.port = elems[5];
  12664. // elems[6] => "typ"
  12665. candidate.type = elems[7];
  12666. candidate.generation = 0; // default value, may be overwritten below
  12667. for (var i = 8; i < elems.length; i += 2) {
  12668. switch (elems[i]) {
  12669. case 'raddr':
  12670. candidate['rel-addr'] = elems[i + 1];
  12671. break;
  12672. case 'rport':
  12673. candidate['rel-port'] = elems[i + 1];
  12674. break;
  12675. case 'generation':
  12676. candidate.generation = elems[i + 1];
  12677. break;
  12678. case 'tcptype':
  12679. candidate.tcptype = elems[i + 1];
  12680. break;
  12681. default: // TODO
  12682. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12683. }
  12684. }
  12685. candidate.network = '1';
  12686. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12687. return candidate;
  12688. },
  12689. build_icecandidate: function (cand) {
  12690. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12691. line += ' ';
  12692. switch (cand.type) {
  12693. case 'srflx':
  12694. case 'prflx':
  12695. case 'relay':
  12696. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12697. line += 'raddr';
  12698. line += ' ';
  12699. line += cand['rel-addr'];
  12700. line += ' ';
  12701. line += 'rport';
  12702. line += ' ';
  12703. line += cand['rel-port'];
  12704. line += ' ';
  12705. }
  12706. break;
  12707. }
  12708. if (cand.hasOwnAttribute('tcptype')) {
  12709. line += 'tcptype';
  12710. line += ' ';
  12711. line += cand.tcptype;
  12712. line += ' ';
  12713. }
  12714. line += 'generation';
  12715. line += ' ';
  12716. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12717. return line;
  12718. },
  12719. parse_ssrc: function (desc) {
  12720. // proprietary mapping of a=ssrc lines
  12721. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12722. // and parse according to that
  12723. var lines = desc.split('\r\n'),
  12724. data = {};
  12725. for (var i = 0; i < lines.length; i++) {
  12726. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12727. var idx = lines[i].indexOf(' ');
  12728. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12729. }
  12730. }
  12731. return data;
  12732. },
  12733. parse_rtcpfb: function (line) {
  12734. var parts = line.substr(10).split(' ');
  12735. var data = {};
  12736. data.pt = parts.shift();
  12737. data.type = parts.shift();
  12738. data.params = parts;
  12739. return data;
  12740. },
  12741. parse_extmap: function (line) {
  12742. var parts = line.substr(9).split(' ');
  12743. var data = {};
  12744. data.value = parts.shift();
  12745. if (data.value.indexOf('/') != -1) {
  12746. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12747. data.value = data.value.substr(0, data.value.indexOf('/'));
  12748. } else {
  12749. data.direction = 'both';
  12750. }
  12751. data.uri = parts.shift();
  12752. data.params = parts;
  12753. return data;
  12754. },
  12755. find_line: function (haystack, needle, sessionpart) {
  12756. var lines = haystack.split('\r\n');
  12757. for (var i = 0; i < lines.length; i++) {
  12758. if (lines[i].substring(0, needle.length) == needle) {
  12759. return lines[i];
  12760. }
  12761. }
  12762. if (!sessionpart) {
  12763. return false;
  12764. }
  12765. // search session part
  12766. lines = sessionpart.split('\r\n');
  12767. for (var j = 0; j < lines.length; j++) {
  12768. if (lines[j].substring(0, needle.length) == needle) {
  12769. return lines[j];
  12770. }
  12771. }
  12772. return false;
  12773. },
  12774. find_lines: function (haystack, needle, sessionpart) {
  12775. var lines = haystack.split('\r\n'),
  12776. needles = [];
  12777. for (var i = 0; i < lines.length; i++) {
  12778. if (lines[i].substring(0, needle.length) == needle)
  12779. needles.push(lines[i]);
  12780. }
  12781. if (needles.length || !sessionpart) {
  12782. return needles;
  12783. }
  12784. // search session part
  12785. lines = sessionpart.split('\r\n');
  12786. for (var j = 0; j < lines.length; j++) {
  12787. if (lines[j].substring(0, needle.length) == needle) {
  12788. needles.push(lines[j]);
  12789. }
  12790. }
  12791. return needles;
  12792. },
  12793. candidateToJingle: function (line) {
  12794. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12795. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12796. if (line.indexOf('candidate:') === 0) {
  12797. line = 'a=' + line;
  12798. } else if (line.substring(0, 12) != 'a=candidate:') {
  12799. console.log('parseCandidate called with a line that is not a candidate line');
  12800. console.log(line);
  12801. return null;
  12802. }
  12803. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12804. line = line.substring(0, line.length - 2);
  12805. var candidate = {},
  12806. elems = line.split(' '),
  12807. i;
  12808. if (elems[6] != 'typ') {
  12809. console.log('did not find typ in the right place');
  12810. console.log(line);
  12811. return null;
  12812. }
  12813. candidate.foundation = elems[0].substring(12);
  12814. candidate.component = elems[1];
  12815. candidate.protocol = elems[2].toLowerCase();
  12816. candidate.priority = elems[3];
  12817. candidate.ip = elems[4];
  12818. candidate.port = elems[5];
  12819. // elems[6] => "typ"
  12820. candidate.type = elems[7];
  12821. candidate.generation = '0'; // default, may be overwritten below
  12822. for (i = 8; i < elems.length; i += 2) {
  12823. switch (elems[i]) {
  12824. case 'raddr':
  12825. candidate['rel-addr'] = elems[i + 1];
  12826. break;
  12827. case 'rport':
  12828. candidate['rel-port'] = elems[i + 1];
  12829. break;
  12830. case 'generation':
  12831. candidate.generation = elems[i + 1];
  12832. break;
  12833. case 'tcptype':
  12834. candidate.tcptype = elems[i + 1];
  12835. break;
  12836. default: // TODO
  12837. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12838. }
  12839. }
  12840. candidate.network = '1';
  12841. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12842. return candidate;
  12843. },
  12844. candidateFromJingle: function (cand) {
  12845. var line = 'a=candidate:';
  12846. line += cand.getAttribute('foundation');
  12847. line += ' ';
  12848. line += cand.getAttribute('component');
  12849. line += ' ';
  12850. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12851. line += ' ';
  12852. line += cand.getAttribute('priority');
  12853. line += ' ';
  12854. line += cand.getAttribute('ip');
  12855. line += ' ';
  12856. line += cand.getAttribute('port');
  12857. line += ' ';
  12858. line += 'typ';
  12859. line += ' ' + cand.getAttribute('type');
  12860. line += ' ';
  12861. switch (cand.getAttribute('type')) {
  12862. case 'srflx':
  12863. case 'prflx':
  12864. case 'relay':
  12865. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12866. line += 'raddr';
  12867. line += ' ';
  12868. line += cand.getAttribute('rel-addr');
  12869. line += ' ';
  12870. line += 'rport';
  12871. line += ' ';
  12872. line += cand.getAttribute('rel-port');
  12873. line += ' ';
  12874. }
  12875. break;
  12876. }
  12877. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12878. line += 'tcptype';
  12879. line += ' ';
  12880. line += cand.getAttribute('tcptype');
  12881. line += ' ';
  12882. }
  12883. line += 'generation';
  12884. line += ' ';
  12885. line += cand.getAttribute('generation') || '0';
  12886. return line + '\r\n';
  12887. }
  12888. };
  12889. module.exports = SDPUtil;
  12890. },{}],52:[function(require,module,exports){
  12891. function TraceablePeerConnection(ice_config, constraints) {
  12892. var self = this;
  12893. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12894. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12895. this.updateLog = [];
  12896. this.stats = {};
  12897. this.statsinterval = null;
  12898. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12899. var Interop = require('sdp-interop').Interop;
  12900. this.interop = new Interop();
  12901. // override as desired
  12902. this.trace = function (what, info) {
  12903. //console.warn('WTRACE', what, info);
  12904. self.updateLog.push({
  12905. time: new Date(),
  12906. type: what,
  12907. value: info || ""
  12908. });
  12909. };
  12910. this.onicecandidate = null;
  12911. this.peerconnection.onicecandidate = function (event) {
  12912. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12913. if (self.onicecandidate !== null) {
  12914. self.onicecandidate(event);
  12915. }
  12916. };
  12917. this.onaddstream = null;
  12918. this.peerconnection.onaddstream = function (event) {
  12919. self.trace('onaddstream', event.stream.id);
  12920. if (self.onaddstream !== null) {
  12921. self.onaddstream(event);
  12922. }
  12923. };
  12924. this.onremovestream = null;
  12925. this.peerconnection.onremovestream = function (event) {
  12926. self.trace('onremovestream', event.stream.id);
  12927. if (self.onremovestream !== null) {
  12928. self.onremovestream(event);
  12929. }
  12930. };
  12931. this.onsignalingstatechange = null;
  12932. this.peerconnection.onsignalingstatechange = function (event) {
  12933. self.trace('onsignalingstatechange', self.signalingState);
  12934. if (self.onsignalingstatechange !== null) {
  12935. self.onsignalingstatechange(event);
  12936. }
  12937. };
  12938. this.oniceconnectionstatechange = null;
  12939. this.peerconnection.oniceconnectionstatechange = function (event) {
  12940. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12941. if (self.oniceconnectionstatechange !== null) {
  12942. self.oniceconnectionstatechange(event);
  12943. }
  12944. };
  12945. this.onnegotiationneeded = null;
  12946. this.peerconnection.onnegotiationneeded = function (event) {
  12947. self.trace('onnegotiationneeded');
  12948. if (self.onnegotiationneeded !== null) {
  12949. self.onnegotiationneeded(event);
  12950. }
  12951. };
  12952. self.ondatachannel = null;
  12953. this.peerconnection.ondatachannel = function (event) {
  12954. self.trace('ondatachannel', event);
  12955. if (self.ondatachannel !== null) {
  12956. self.ondatachannel(event);
  12957. }
  12958. };
  12959. if (!navigator.mozGetUserMedia && this.maxstats) {
  12960. this.statsinterval = window.setInterval(function() {
  12961. self.peerconnection.getStats(function(stats) {
  12962. var results = stats.result();
  12963. for (var i = 0; i < results.length; ++i) {
  12964. //console.log(results[i].type, results[i].id, results[i].names())
  12965. var now = new Date();
  12966. results[i].names().forEach(function (name) {
  12967. var id = results[i].id + '-' + name;
  12968. if (!self.stats[id]) {
  12969. self.stats[id] = {
  12970. startTime: now,
  12971. endTime: now,
  12972. values: [],
  12973. times: []
  12974. };
  12975. }
  12976. self.stats[id].values.push(results[i].stat(name));
  12977. self.stats[id].times.push(now.getTime());
  12978. if (self.stats[id].values.length > self.maxstats) {
  12979. self.stats[id].values.shift();
  12980. self.stats[id].times.shift();
  12981. }
  12982. self.stats[id].endTime = now;
  12983. });
  12984. }
  12985. });
  12986. }, 1000);
  12987. }
  12988. };
  12989. dumpSDP = function(description) {
  12990. if (typeof description === 'undefined' || description == null) {
  12991. return '';
  12992. }
  12993. return 'type: ' + description.type + '\r\n' + description.sdp;
  12994. };
  12995. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12996. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12997. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12998. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12999. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  13000. // if we're running on FF, transform to Plan B first.
  13001. var desc = this.peerconnection.localDescription;
  13002. if (navigator.mozGetUserMedia) {
  13003. desc = this.interop.toPlanB(desc);
  13004. } else {
  13005. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  13006. }
  13007. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13008. return desc;
  13009. });
  13010. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13011. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  13012. // if we're running on FF, transform to Plan B first.
  13013. var desc = this.peerconnection.remoteDescription;
  13014. if (navigator.mozGetUserMedia) {
  13015. desc = this.interop.toPlanB(desc);
  13016. } else {
  13017. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  13018. }
  13019. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13020. return desc;
  13021. });
  13022. }
  13023. TraceablePeerConnection.prototype.addStream = function (stream) {
  13024. this.trace('addStream', stream.id);
  13025. APP.simulcast.resetSender();
  13026. try
  13027. {
  13028. this.peerconnection.addStream(stream);
  13029. }
  13030. catch (e)
  13031. {
  13032. console.error(e);
  13033. return;
  13034. }
  13035. };
  13036. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13037. this.trace('removeStream', stream.id);
  13038. APP.simulcast.resetSender();
  13039. if(stopStreams) {
  13040. stream.getAudioTracks().forEach(function (track) {
  13041. track.stop();
  13042. });
  13043. stream.getVideoTracks().forEach(function (track) {
  13044. track.stop();
  13045. });
  13046. }
  13047. try {
  13048. // FF doesn't support this yet.
  13049. this.peerconnection.removeStream(stream);
  13050. } catch (e) {
  13051. console.error(e);
  13052. }
  13053. };
  13054. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13055. this.trace('createDataChannel', label, opts);
  13056. return this.peerconnection.createDataChannel(label, opts);
  13057. };
  13058. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13059. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  13060. // if we're running on FF, transform to Plan A first.
  13061. if (navigator.mozGetUserMedia) {
  13062. description = this.interop.toPlanA(description);
  13063. } else {
  13064. description = APP.simulcast.transformLocalDescription(description);
  13065. }
  13066. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13067. var self = this;
  13068. this.peerconnection.setLocalDescription(description,
  13069. function () {
  13070. self.trace('setLocalDescriptionOnSuccess');
  13071. successCallback();
  13072. },
  13073. function (err) {
  13074. self.trace('setLocalDescriptionOnFailure', err);
  13075. failureCallback(err);
  13076. }
  13077. );
  13078. /*
  13079. if (this.statsinterval === null && this.maxstats > 0) {
  13080. // start gathering stats
  13081. }
  13082. */
  13083. };
  13084. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13085. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  13086. // if we're running on FF, transform to Plan A first.
  13087. if (navigator.mozGetUserMedia) {
  13088. description = this.interop.toPlanA(description);
  13089. }
  13090. else {
  13091. description = APP.simulcast.transformRemoteDescription(description);
  13092. }
  13093. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13094. var self = this;
  13095. this.peerconnection.setRemoteDescription(description,
  13096. function () {
  13097. self.trace('setRemoteDescriptionOnSuccess');
  13098. successCallback();
  13099. },
  13100. function (err) {
  13101. self.trace('setRemoteDescriptionOnFailure', err);
  13102. failureCallback(err);
  13103. }
  13104. );
  13105. /*
  13106. if (this.statsinterval === null && this.maxstats > 0) {
  13107. // start gathering stats
  13108. }
  13109. */
  13110. };
  13111. TraceablePeerConnection.prototype.close = function () {
  13112. this.trace('stop');
  13113. if (this.statsinterval !== null) {
  13114. window.clearInterval(this.statsinterval);
  13115. this.statsinterval = null;
  13116. }
  13117. this.peerconnection.close();
  13118. };
  13119. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13120. var self = this;
  13121. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13122. this.peerconnection.createOffer(
  13123. function (offer) {
  13124. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  13125. // if we're running on FF, transform to Plan B first.
  13126. if (navigator.mozGetUserMedia) {
  13127. offer = self.interop.toPlanB(offer);
  13128. }
  13129. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13130. successCallback(offer);
  13131. },
  13132. function(err) {
  13133. self.trace('createOfferOnFailure', err);
  13134. failureCallback(err);
  13135. },
  13136. constraints
  13137. );
  13138. };
  13139. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13140. var self = this;
  13141. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13142. this.peerconnection.createAnswer(
  13143. function (answer) {
  13144. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13145. // if we're running on FF, transform to Plan A first.
  13146. if (navigator.mozGetUserMedia) {
  13147. answer = self.interop.toPlanB(answer);
  13148. } else {
  13149. answer = APP.simulcast.transformAnswer(answer);
  13150. }
  13151. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13152. successCallback(answer);
  13153. },
  13154. function(err) {
  13155. self.trace('createAnswerOnFailure', err);
  13156. failureCallback(err);
  13157. },
  13158. constraints
  13159. );
  13160. };
  13161. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13162. var self = this;
  13163. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13164. this.peerconnection.addIceCandidate(candidate);
  13165. /* maybe later
  13166. this.peerconnection.addIceCandidate(candidate,
  13167. function () {
  13168. self.trace('addIceCandidateOnSuccess');
  13169. successCallback();
  13170. },
  13171. function (err) {
  13172. self.trace('addIceCandidateOnFailure', err);
  13173. failureCallback(err);
  13174. }
  13175. );
  13176. */
  13177. };
  13178. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13179. if (navigator.mozGetUserMedia) {
  13180. // ignore for now...
  13181. if(!errback)
  13182. errback = function () {
  13183. }
  13184. this.peerconnection.getStats(null,callback,errback);
  13185. } else {
  13186. this.peerconnection.getStats(callback);
  13187. }
  13188. };
  13189. module.exports = TraceablePeerConnection;
  13190. },{"sdp-interop":81}],53:[function(require,module,exports){
  13191. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13192. roomName, sessionTerminated, Strophe, Util */
  13193. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13194. var Settings = require("../settings/Settings");
  13195. var AuthenticationEvents
  13196. = require("../../service/authentication/AuthenticationEvents");
  13197. /**
  13198. * Contains logic responsible for enabling/disabling functionality available
  13199. * only to moderator users.
  13200. */
  13201. var connection = null;
  13202. var focusUserJid;
  13203. function createExpBackoffTimer(step) {
  13204. var count = 1;
  13205. return function (reset) {
  13206. // Reset call
  13207. if (reset) {
  13208. count = 1;
  13209. return;
  13210. }
  13211. // Calculate next timeout
  13212. var timeout = Math.pow(2, count - 1);
  13213. count += 1;
  13214. return timeout * step;
  13215. };
  13216. }
  13217. var getNextTimeout = createExpBackoffTimer(1000);
  13218. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13219. // External authentication stuff
  13220. var externalAuthEnabled = false;
  13221. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13222. // it will be enabled automatically if focus detects the component through
  13223. // service discovery.
  13224. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13225. var eventEmitter = null;
  13226. var Moderator = {
  13227. isModerator: function () {
  13228. return connection && connection.emuc.isModerator();
  13229. },
  13230. isPeerModerator: function (peerJid) {
  13231. return connection &&
  13232. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13233. },
  13234. isExternalAuthEnabled: function () {
  13235. return externalAuthEnabled;
  13236. },
  13237. isSipGatewayEnabled: function () {
  13238. return sipGatewayEnabled;
  13239. },
  13240. setConnection: function (con) {
  13241. connection = con;
  13242. },
  13243. init: function (xmpp, emitter) {
  13244. this.xmppService = xmpp;
  13245. eventEmitter = emitter;
  13246. // Message listener that talks to POPUP window
  13247. function listener(event) {
  13248. if (event.data && event.data.sessionId) {
  13249. if (event.origin !== window.location.origin) {
  13250. console.warn(
  13251. "Ignoring sessionId from different origin: " + event.origin);
  13252. return;
  13253. }
  13254. localStorage.setItem('sessionId', event.data.sessionId);
  13255. // After popup is closed we will authenticate
  13256. }
  13257. }
  13258. // Register
  13259. if (window.addEventListener) {
  13260. window.addEventListener("message", listener, false);
  13261. } else {
  13262. window.attachEvent("onmessage", listener);
  13263. }
  13264. },
  13265. onMucLeft: function (jid) {
  13266. console.info("Someone left is it focus ? " + jid);
  13267. var resource = Strophe.getResourceFromJid(jid);
  13268. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13269. console.info(
  13270. "Focus has left the room - leaving conference");
  13271. //hangUp();
  13272. // We'd rather reload to have everything re-initialized
  13273. // FIXME: show some message before reload
  13274. location.reload();
  13275. }
  13276. },
  13277. setFocusUserJid: function (focusJid) {
  13278. if (!focusUserJid) {
  13279. focusUserJid = focusJid;
  13280. console.info("Focus jid set to: " + focusUserJid);
  13281. }
  13282. },
  13283. getFocusUserJid: function () {
  13284. return focusUserJid;
  13285. },
  13286. getFocusComponent: function () {
  13287. // Get focus component address
  13288. var focusComponent = config.hosts.focus;
  13289. // If not specified use default: 'focus.domain'
  13290. if (!focusComponent) {
  13291. focusComponent = 'focus.' + config.hosts.domain;
  13292. }
  13293. return focusComponent;
  13294. },
  13295. createConferenceIq: function (roomName) {
  13296. // Generate create conference IQ
  13297. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13298. // Session Id used for authentication
  13299. var sessionId = localStorage.getItem('sessionId');
  13300. var machineUID = Settings.getSettings().uid;
  13301. console.info(
  13302. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13303. elem.c('conference', {
  13304. xmlns: 'http://jitsi.org/protocol/focus',
  13305. room: roomName,
  13306. 'machine-uid': machineUID
  13307. });
  13308. if (sessionId) {
  13309. elem.attrs({ 'session-id': sessionId});
  13310. }
  13311. if (config.hosts.bridge !== undefined) {
  13312. elem.c(
  13313. 'property',
  13314. { name: 'bridge', value: config.hosts.bridge})
  13315. .up();
  13316. }
  13317. // Tell the focus we have Jigasi configured
  13318. if (config.hosts.call_control !== undefined) {
  13319. elem.c(
  13320. 'property',
  13321. { name: 'call_control', value: config.hosts.call_control})
  13322. .up();
  13323. }
  13324. if (config.channelLastN !== undefined) {
  13325. elem.c(
  13326. 'property',
  13327. { name: 'channelLastN', value: config.channelLastN})
  13328. .up();
  13329. }
  13330. if (config.adaptiveLastN !== undefined) {
  13331. elem.c(
  13332. 'property',
  13333. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13334. .up();
  13335. }
  13336. if (config.adaptiveSimulcast !== undefined) {
  13337. elem.c(
  13338. 'property',
  13339. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13340. .up();
  13341. }
  13342. if (config.openSctp !== undefined) {
  13343. elem.c(
  13344. 'property',
  13345. { name: 'openSctp', value: config.openSctp})
  13346. .up();
  13347. }
  13348. elem.up();
  13349. return elem;
  13350. },
  13351. parseSessionId: function (resultIq) {
  13352. var sessionId = $(resultIq).find('conference').attr('session-id');
  13353. if (sessionId) {
  13354. console.info('Received sessionId: ' + sessionId);
  13355. localStorage.setItem('sessionId', sessionId);
  13356. }
  13357. },
  13358. parseConfigOptions: function (resultIq) {
  13359. Moderator.setFocusUserJid(
  13360. $(resultIq).find('conference').attr('focusjid'));
  13361. var authenticationEnabled
  13362. = $(resultIq).find(
  13363. '>conference>property' +
  13364. '[name=\'authentication\'][value=\'true\']').length > 0;
  13365. console.info("Authentication enabled: " + authenticationEnabled);
  13366. externalAuthEnabled
  13367. = $(resultIq).find(
  13368. '>conference>property' +
  13369. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13370. console.info('External authentication enabled: ' + externalAuthEnabled);
  13371. if (!externalAuthEnabled) {
  13372. // We expect to receive sessionId in 'internal' authentication mode
  13373. Moderator.parseSessionId(resultIq);
  13374. }
  13375. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13376. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13377. authenticationEnabled, authIdentity);
  13378. // Check if focus has auto-detected Jigasi component(this will be also
  13379. // included if we have passed our host from the config)
  13380. if ($(resultIq).find(
  13381. '>conference>property' +
  13382. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13383. sipGatewayEnabled = true;
  13384. }
  13385. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13386. },
  13387. // FIXME: we need to show the fact that we're waiting for the focus
  13388. // to the user(or that focus is not available)
  13389. allocateConferenceFocus: function (roomName, callback) {
  13390. // Try to use focus user JID from the config
  13391. Moderator.setFocusUserJid(config.focusUserJid);
  13392. // Send create conference IQ
  13393. var iq = Moderator.createConferenceIq(roomName);
  13394. var self = this;
  13395. connection.sendIQ(
  13396. iq,
  13397. function (result) {
  13398. // Setup config options
  13399. Moderator.parseConfigOptions(result);
  13400. if ('true' === $(result).find('conference').attr('ready')) {
  13401. // Reset both timers
  13402. getNextTimeout(true);
  13403. getNextErrorTimeout(true);
  13404. // Exec callback
  13405. callback();
  13406. } else {
  13407. var waitMs = getNextTimeout();
  13408. console.info("Waiting for the focus... " + waitMs);
  13409. // Reset error timeout
  13410. getNextErrorTimeout(true);
  13411. window.setTimeout(
  13412. function () {
  13413. Moderator.allocateConferenceFocus(
  13414. roomName, callback);
  13415. }, waitMs);
  13416. }
  13417. },
  13418. function (error) {
  13419. // Invalid session ? remove and try again
  13420. // without session ID to get a new one
  13421. var invalidSession
  13422. = $(error).find('>error>session-invalid').length;
  13423. if (invalidSession) {
  13424. console.info("Session expired! - removing");
  13425. localStorage.removeItem("sessionId");
  13426. }
  13427. if ($(error).find('>error>graceful-shutdown').length) {
  13428. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13429. return;
  13430. }
  13431. // Check for error returned by the reservation system
  13432. var reservationErr = $(error).find('>error>reservation-error');
  13433. if (reservationErr.length) {
  13434. // Trigger error event
  13435. var errorCode = reservationErr.attr('error-code');
  13436. var errorMsg;
  13437. if ($(error).find('>error>text')) {
  13438. errorMsg = $(error).find('>error>text').text();
  13439. }
  13440. eventEmitter.emit(
  13441. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13442. return;
  13443. }
  13444. // Not authorized to create new room
  13445. if ($(error).find('>error>not-authorized').length) {
  13446. console.warn("Unauthorized to start the conference", error);
  13447. var toDomain
  13448. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13449. if (toDomain !== config.hosts.anonymousdomain) {
  13450. // FIXME: "is external" should come either from
  13451. // the focus or config.js
  13452. externalAuthEnabled = true;
  13453. }
  13454. eventEmitter.emit(
  13455. XMPPEvents.AUTHENTICATION_REQUIRED,
  13456. function () {
  13457. Moderator.allocateConferenceFocus(
  13458. roomName, callback);
  13459. });
  13460. return;
  13461. }
  13462. var waitMs = getNextErrorTimeout();
  13463. console.error("Focus error, retry after " + waitMs, error);
  13464. // Show message
  13465. var focusComponent = Moderator.getFocusComponent();
  13466. var retrySec = waitMs / 1000;
  13467. // FIXME: message is duplicated ?
  13468. // Do not show in case of session invalid
  13469. // which means just a retry
  13470. if (!invalidSession) {
  13471. APP.UI.messageHandler.notify(
  13472. null, "notify.focus",
  13473. 'disconnected', "notify.focusFail",
  13474. {component: focusComponent, ms: retrySec});
  13475. }
  13476. // Reset response timeout
  13477. getNextTimeout(true);
  13478. window.setTimeout(
  13479. function () {
  13480. Moderator.allocateConferenceFocus(roomName, callback);
  13481. }, waitMs);
  13482. }
  13483. );
  13484. },
  13485. getLoginUrl: function (roomName, urlCallback) {
  13486. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13487. iq.c('login-url', {
  13488. xmlns: 'http://jitsi.org/protocol/focus',
  13489. room: roomName,
  13490. 'machine-uid': Settings.getSettings().uid
  13491. });
  13492. connection.sendIQ(
  13493. iq,
  13494. function (result) {
  13495. var url = $(result).find('login-url').attr('url');
  13496. url = url = decodeURIComponent(url);
  13497. if (url) {
  13498. console.info("Got auth url: " + url);
  13499. urlCallback(url);
  13500. } else {
  13501. console.error(
  13502. "Failed to get auth url from the focus", result);
  13503. }
  13504. },
  13505. function (error) {
  13506. console.error("Get auth url error", error);
  13507. }
  13508. );
  13509. },
  13510. getPopupLoginUrl: function (roomName, urlCallback) {
  13511. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13512. iq.c('login-url', {
  13513. xmlns: 'http://jitsi.org/protocol/focus',
  13514. room: roomName,
  13515. 'machine-uid': Settings.getSettings().uid,
  13516. popup: true
  13517. });
  13518. connection.sendIQ(
  13519. iq,
  13520. function (result) {
  13521. var url = $(result).find('login-url').attr('url');
  13522. url = url = decodeURIComponent(url);
  13523. if (url) {
  13524. console.info("Got POPUP auth url: " + url);
  13525. urlCallback(url);
  13526. } else {
  13527. console.error(
  13528. "Failed to get POPUP auth url from the focus", result);
  13529. }
  13530. },
  13531. function (error) {
  13532. console.error('Get POPUP auth url error', error);
  13533. }
  13534. );
  13535. },
  13536. logout: function (callback) {
  13537. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13538. var sessionId = localStorage.getItem('sessionId');
  13539. if (!sessionId) {
  13540. callback();
  13541. return;
  13542. }
  13543. iq.c('logout', {
  13544. xmlns: 'http://jitsi.org/protocol/focus',
  13545. 'session-id': sessionId
  13546. });
  13547. connection.sendIQ(
  13548. iq,
  13549. function (result) {
  13550. var logoutUrl = $(result).find('logout').attr('logout-url');
  13551. if (logoutUrl) {
  13552. logoutUrl = decodeURIComponent(logoutUrl);
  13553. }
  13554. console.info("Log out OK, url: " + logoutUrl, result);
  13555. localStorage.removeItem('sessionId');
  13556. callback(logoutUrl);
  13557. },
  13558. function (error) {
  13559. console.error("Logout error", error);
  13560. }
  13561. );
  13562. }
  13563. };
  13564. module.exports = Moderator;
  13565. },{"../../service/authentication/AuthenticationEvents":94,"../../service/xmpp/XMPPEvents":98,"../settings/Settings":38}],54:[function(require,module,exports){
  13566. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13567. Toolbar, Util */
  13568. var Moderator = require("./moderator");
  13569. var recordingToken = null;
  13570. var recordingEnabled;
  13571. /**
  13572. * Whether to use a jirecon component for recording, or use the videobridge
  13573. * through COLIBRI.
  13574. */
  13575. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13576. /**
  13577. * The ID of the jirecon recording session. Jirecon generates it when we
  13578. * initially start recording, and it needs to be used in subsequent requests
  13579. * to jirecon.
  13580. */
  13581. var jireconRid = null;
  13582. function setRecordingToken(token) {
  13583. recordingToken = token;
  13584. }
  13585. function setRecording(state, token, callback, connection) {
  13586. if (useJirecon){
  13587. setRecordingJirecon(state, token, callback, connection);
  13588. } else {
  13589. setRecordingColibri(state, token, callback, connection);
  13590. }
  13591. }
  13592. function setRecordingJirecon(state, token, callback, connection) {
  13593. if (state == recordingEnabled){
  13594. return;
  13595. }
  13596. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13597. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13598. action: state ? 'start' : 'stop',
  13599. mucjid: connection.emuc.roomjid});
  13600. if (!state){
  13601. iq.attrs({rid: jireconRid});
  13602. }
  13603. console.log('Start recording');
  13604. connection.sendIQ(
  13605. iq,
  13606. function (result) {
  13607. // TODO wait for an IQ with the real status, since this is
  13608. // provisional?
  13609. jireconRid = $(result).find('recording').attr('rid');
  13610. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13611. '(jirecon)' + result);
  13612. recordingEnabled = state;
  13613. if (!state){
  13614. jireconRid = null;
  13615. }
  13616. callback(state);
  13617. },
  13618. function (error) {
  13619. console.log('Failed to start recording, error: ', error);
  13620. callback(recordingEnabled);
  13621. });
  13622. }
  13623. // Sends a COLIBRI message which enables or disables (according to 'state')
  13624. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13625. // with the new recording state, according to the IQ.
  13626. function setRecordingColibri(state, token, callback, connection) {
  13627. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13628. elem.c('conference', {
  13629. xmlns: 'http://jitsi.org/protocol/colibri'
  13630. });
  13631. elem.c('recording', {state: state, token: token});
  13632. connection.sendIQ(elem,
  13633. function (result) {
  13634. console.log('Set recording "', state, '". Result:', result);
  13635. var recordingElem = $(result).find('>conference>recording');
  13636. var newState = ('true' === recordingElem.attr('state'));
  13637. recordingEnabled = newState;
  13638. callback(newState);
  13639. },
  13640. function (error) {
  13641. console.warn(error);
  13642. callback(recordingEnabled);
  13643. }
  13644. );
  13645. }
  13646. var Recording = {
  13647. toggleRecording: function (tokenEmptyCallback,
  13648. startingCallback, startedCallback, connection) {
  13649. if (!Moderator.isModerator()) {
  13650. console.log(
  13651. 'non-focus, or conference not yet organized:' +
  13652. ' not enabling recording');
  13653. return;
  13654. }
  13655. var self = this;
  13656. // Jirecon does not (currently) support a token.
  13657. if (!recordingToken && !useJirecon) {
  13658. tokenEmptyCallback(function (value) {
  13659. setRecordingToken(value);
  13660. self.toggleRecording(tokenEmptyCallback,
  13661. startingCallback, startedCallback, connection);
  13662. });
  13663. return;
  13664. }
  13665. var oldState = recordingEnabled;
  13666. startingCallback(!oldState);
  13667. setRecording(!oldState,
  13668. recordingToken,
  13669. function (state) {
  13670. console.log("New recording state: ", state);
  13671. if (state === oldState) {
  13672. // FIXME: new focus:
  13673. // this will not work when moderator changes
  13674. // during active session. Then it will assume that
  13675. // recording status has changed to true, but it might have
  13676. // been already true(and we only received actual status from
  13677. // the focus).
  13678. //
  13679. // SO we start with status null, so that it is initialized
  13680. // here and will fail only after second click, so if invalid
  13681. // token was used we have to press the button twice before
  13682. // current status will be fetched and token will be reset.
  13683. //
  13684. // Reliable way would be to return authentication error.
  13685. // Or status update when moderator connects.
  13686. // Or we have to stop recording session when current
  13687. // moderator leaves the room.
  13688. // Failed to change, reset the token because it might
  13689. // have been wrong
  13690. setRecordingToken(null);
  13691. }
  13692. startedCallback(state);
  13693. },
  13694. connection
  13695. );
  13696. }
  13697. }
  13698. module.exports = Recording;
  13699. },{"./moderator":53}],55:[function(require,module,exports){
  13700. /* jshint -W117 */
  13701. /* a simple MUC connection plugin
  13702. * can only handle a single MUC room
  13703. */
  13704. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13705. var Moderator = require("./moderator");
  13706. var JingleSession = require("./JingleSession");
  13707. var bridgeIsDown = false;
  13708. module.exports = function(XMPP, eventEmitter) {
  13709. Strophe.addConnectionPlugin('emuc', {
  13710. connection: null,
  13711. roomjid: null,
  13712. myroomjid: null,
  13713. members: {},
  13714. list_members: [], // so we can elect a new focus
  13715. presMap: {},
  13716. preziMap: {},
  13717. joined: false,
  13718. isOwner: false,
  13719. role: null,
  13720. focusMucJid: null,
  13721. ssrc2jid: {},
  13722. init: function (conn) {
  13723. this.connection = conn;
  13724. },
  13725. initPresenceMap: function (myroomjid) {
  13726. this.presMap['to'] = myroomjid;
  13727. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13728. },
  13729. doJoin: function (jid, password) {
  13730. this.myroomjid = jid;
  13731. console.info("Joined MUC as " + this.myroomjid);
  13732. this.initPresenceMap(this.myroomjid);
  13733. if (!this.roomjid) {
  13734. this.roomjid = Strophe.getBareJidFromJid(jid);
  13735. // add handlers (just once)
  13736. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13737. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13738. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13739. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13740. }
  13741. if (password !== undefined) {
  13742. this.presMap['password'] = password;
  13743. }
  13744. this.sendPresence();
  13745. },
  13746. doLeave: function () {
  13747. console.log("do leave", this.myroomjid);
  13748. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13749. this.presMap.length = 0;
  13750. this.connection.send(pres);
  13751. },
  13752. createNonAnonymousRoom: function () {
  13753. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13754. var getForm = $iq({type: 'get', to: this.roomjid})
  13755. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13756. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13757. var self = this;
  13758. this.connection.sendIQ(getForm, function (form) {
  13759. if (!$(form).find(
  13760. '>query>x[xmlns="jabber:x:data"]' +
  13761. '>field[var="muc#roomconfig_whois"]').length) {
  13762. console.error('non-anonymous rooms not supported');
  13763. return;
  13764. }
  13765. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13766. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13767. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13768. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13769. .c('value')
  13770. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13771. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13772. .c('value').t('anyone').up().up();
  13773. self.connection.sendIQ(formSubmit);
  13774. }, function (error) {
  13775. console.error("Error getting room configuration form");
  13776. });
  13777. },
  13778. onPresence: function (pres) {
  13779. var from = pres.getAttribute('from');
  13780. // What is this for? A workaround for something?
  13781. if (pres.getAttribute('type')) {
  13782. return true;
  13783. }
  13784. // Parse etherpad tag.
  13785. var etherpad = $(pres).find('>etherpad');
  13786. if (etherpad.length) {
  13787. if (config.etherpad_base && !Moderator.isModerator()) {
  13788. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13789. }
  13790. }
  13791. // Parse prezi tag.
  13792. var presentation = $(pres).find('>prezi');
  13793. if (presentation.length) {
  13794. var url = presentation.attr('url');
  13795. var current = presentation.find('>current').text();
  13796. console.log('presentation info received from', from, url);
  13797. if (this.preziMap[from] == null) {
  13798. this.preziMap[from] = url;
  13799. $(document).trigger('presentationadded.muc', [from, url, current]);
  13800. }
  13801. else {
  13802. $(document).trigger('gotoslide.muc', [from, url, current]);
  13803. }
  13804. }
  13805. else if (this.preziMap[from] != null) {
  13806. var url = this.preziMap[from];
  13807. delete this.preziMap[from];
  13808. $(document).trigger('presentationremoved.muc', [from, url]);
  13809. }
  13810. // Parse audio info tag.
  13811. var audioMuted = $(pres).find('>audiomuted');
  13812. if (audioMuted.length) {
  13813. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13814. }
  13815. // Parse video info tag.
  13816. var videoMuted = $(pres).find('>videomuted');
  13817. if (videoMuted.length) {
  13818. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13819. }
  13820. var devices = $(pres).find('>devices');
  13821. if(devices.length)
  13822. {
  13823. var audio = devices.find('>audio');
  13824. var video = devices.find('>video');
  13825. var devicesValues = {audio: false, video: false};
  13826. if(audio.length && audio.text() === "true")
  13827. {
  13828. devicesValues.audio = true;
  13829. }
  13830. if(video.length && video.text() === "true")
  13831. {
  13832. devicesValues.video = true;
  13833. }
  13834. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  13835. Strophe.getResourceFromJid(from), devicesValues);
  13836. }
  13837. var stats = $(pres).find('>stats');
  13838. if (stats.length) {
  13839. var statsObj = {};
  13840. Strophe.forEachChild(stats[0], "stat", function (el) {
  13841. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13842. });
  13843. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13844. }
  13845. // Parse status.
  13846. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13847. this.isOwner = true;
  13848. this.createNonAnonymousRoom();
  13849. }
  13850. // Parse roles.
  13851. var member = {};
  13852. member.show = $(pres).find('>show').text();
  13853. member.status = $(pres).find('>status').text();
  13854. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13855. member.affiliation = tmp.attr('affiliation');
  13856. member.role = tmp.attr('role');
  13857. // Focus recognition
  13858. member.jid = tmp.attr('jid');
  13859. member.isFocus = false;
  13860. if (member.jid
  13861. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13862. member.isFocus = true;
  13863. }
  13864. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13865. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13866. if (from == this.myroomjid) {
  13867. if (member.affiliation == 'owner') this.isOwner = true;
  13868. if (this.role !== member.role) {
  13869. this.role = member.role;
  13870. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13871. from, member, pres, Moderator.isModerator());
  13872. }
  13873. if (!this.joined) {
  13874. this.joined = true;
  13875. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13876. this.list_members.push(from);
  13877. }
  13878. } else if (this.members[from] === undefined) {
  13879. // new participant
  13880. this.members[from] = member;
  13881. this.list_members.push(from);
  13882. console.log('entered', from, member);
  13883. if (member.isFocus) {
  13884. this.focusMucJid = from;
  13885. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13886. }
  13887. else {
  13888. var id = $(pres).find('>userID').text();
  13889. var email = $(pres).find('>email');
  13890. if (email.length > 0) {
  13891. id = email.text();
  13892. }
  13893. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13894. }
  13895. } else {
  13896. // Presence update for existing participant
  13897. // Watch role change:
  13898. if (this.members[from].role != member.role) {
  13899. this.members[from].role = member.role;
  13900. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13901. member.role, member.displayName);
  13902. }
  13903. }
  13904. // Always trigger presence to update bindings
  13905. this.parsePresence(from, member, pres);
  13906. // Trigger status message update
  13907. if (member.status) {
  13908. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13909. }
  13910. return true;
  13911. },
  13912. onPresenceUnavailable: function (pres) {
  13913. var from = pres.getAttribute('from');
  13914. // room destroyed ?
  13915. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13916. '>destroy').length) {
  13917. var reason;
  13918. var reasonSelect = $(pres).find(
  13919. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13920. '>destroy>reason');
  13921. if (reasonSelect.length) {
  13922. reason = reasonSelect.text();
  13923. }
  13924. XMPP.disposeConference(false);
  13925. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13926. return true;
  13927. }
  13928. // Status code 110 indicates that this notification is "self-presence".
  13929. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13930. delete this.members[from];
  13931. this.list_members.splice(this.list_members.indexOf(from), 1);
  13932. this.onParticipantLeft(from);
  13933. }
  13934. // If the status code is 110 this means we're leaving and we would like
  13935. // to remove everyone else from our view, so we trigger the event.
  13936. else if (this.list_members.length > 1) {
  13937. for (var i = 0; i < this.list_members.length; i++) {
  13938. var member = this.list_members[i];
  13939. delete this.members[i];
  13940. this.list_members.splice(i, 1);
  13941. this.onParticipantLeft(member);
  13942. }
  13943. }
  13944. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13945. $(document).trigger('kicked.muc', [from]);
  13946. if (this.myroomjid === from) {
  13947. XMPP.disposeConference(false);
  13948. eventEmitter.emit(XMPPEvents.KICKED);
  13949. }
  13950. }
  13951. return true;
  13952. },
  13953. onPresenceError: function (pres) {
  13954. var from = pres.getAttribute('from');
  13955. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13956. console.log('on password required', from);
  13957. var self = this;
  13958. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13959. self.doJoin(from, value);
  13960. });
  13961. } else if ($(pres).find(
  13962. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13963. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13964. if (toDomain === config.hosts.anonymousdomain) {
  13965. // enter the room by replying with 'not-authorized'. This would
  13966. // result in reconnection from authorized domain.
  13967. // We're either missing Jicofo/Prosody config for anonymous
  13968. // domains or something is wrong.
  13969. // XMPP.promptLogin();
  13970. APP.UI.messageHandler.openReportDialog(null,
  13971. "dialog.joinError", pres);
  13972. } else {
  13973. console.warn('onPresError ', pres);
  13974. APP.UI.messageHandler.openReportDialog(null,
  13975. "dialog.connectError",
  13976. pres);
  13977. }
  13978. } else {
  13979. console.warn('onPresError ', pres);
  13980. APP.UI.messageHandler.openReportDialog(null,
  13981. "dialog.connectError",
  13982. pres);
  13983. }
  13984. return true;
  13985. },
  13986. sendMessage: function (body, nickname) {
  13987. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13988. msg.c('body', body).up();
  13989. if (nickname) {
  13990. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13991. }
  13992. this.connection.send(msg);
  13993. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13994. },
  13995. setSubject: function (subject) {
  13996. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13997. msg.c('subject', subject);
  13998. this.connection.send(msg);
  13999. console.log("topic changed to " + subject);
  14000. },
  14001. onMessage: function (msg) {
  14002. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14003. var from = msg.getAttribute('from');
  14004. var nick =
  14005. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14006. .text() ||
  14007. Strophe.getResourceFromJid(from);
  14008. var txt = $(msg).find('>body').text();
  14009. var type = msg.getAttribute("type");
  14010. if (type == "error") {
  14011. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14012. $(msg).find('>text').text(), txt);
  14013. return true;
  14014. }
  14015. var subject = $(msg).find('>subject');
  14016. if (subject.length) {
  14017. var subjectText = subject.text();
  14018. if (subjectText || subjectText == "") {
  14019. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14020. console.log("Subject is changed to " + subjectText);
  14021. }
  14022. }
  14023. if (txt) {
  14024. console.log('chat', nick, txt);
  14025. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14026. from, nick, txt, this.myroomjid);
  14027. }
  14028. return true;
  14029. },
  14030. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14031. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14032. var ob = this;
  14033. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14034. function (res) {
  14035. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14036. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14037. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14038. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14039. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14040. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14041. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14042. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14043. ob.connection.sendIQ(formsubmit,
  14044. onSuccess,
  14045. onError);
  14046. } else {
  14047. onNotSupported();
  14048. }
  14049. }, onError);
  14050. },
  14051. kick: function (jid) {
  14052. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14053. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14054. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14055. .c('reason').t('You have been kicked.').up().up().up();
  14056. this.connection.sendIQ(
  14057. kickIQ,
  14058. function (result) {
  14059. console.log('Kick participant with jid: ', jid, result);
  14060. },
  14061. function (error) {
  14062. console.log('Kick participant error: ', error);
  14063. });
  14064. },
  14065. sendPresence: function () {
  14066. var pres = $pres({to: this.presMap['to'] });
  14067. pres.c('x', {xmlns: this.presMap['xns']});
  14068. if (this.presMap['password']) {
  14069. pres.c('password').t(this.presMap['password']).up();
  14070. }
  14071. pres.up();
  14072. // Send XEP-0115 'c' stanza that contains our capabilities info
  14073. if (this.connection.caps) {
  14074. this.connection.caps.node = config.clientNode;
  14075. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14076. }
  14077. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14078. .t(navigator.userAgent).up();
  14079. if (this.presMap['bridgeIsDown']) {
  14080. pres.c('bridgeIsDown').up();
  14081. }
  14082. if (this.presMap['email']) {
  14083. pres.c('email').t(this.presMap['email']).up();
  14084. }
  14085. if (this.presMap['userId']) {
  14086. pres.c('userId').t(this.presMap['userId']).up();
  14087. }
  14088. if (this.presMap['displayName']) {
  14089. // XEP-0172
  14090. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14091. .t(this.presMap['displayName']).up();
  14092. }
  14093. if(this.presMap["devices"])
  14094. {
  14095. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14096. .c('video').t(this.presMap['devices'].video).up().up();
  14097. }
  14098. if (this.presMap['audions']) {
  14099. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14100. .t(this.presMap['audiomuted']).up();
  14101. }
  14102. if (this.presMap['videons']) {
  14103. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14104. .t(this.presMap['videomuted']).up();
  14105. }
  14106. if (this.presMap['statsns']) {
  14107. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14108. for (var stat in this.presMap["stats"])
  14109. if (this.presMap["stats"][stat] != null)
  14110. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14111. pres.up();
  14112. }
  14113. if (this.presMap['prezins']) {
  14114. pres.c('prezi',
  14115. {xmlns: this.presMap['prezins'],
  14116. 'url': this.presMap['preziurl']})
  14117. .c('current').t(this.presMap['prezicurrent']).up().up();
  14118. }
  14119. if (this.presMap['etherpadns']) {
  14120. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  14121. .t(this.presMap['etherpadname']).up();
  14122. }
  14123. if (this.presMap['medians']) {
  14124. pres.c('media', {xmlns: this.presMap['medians']});
  14125. var sourceNumber = 0;
  14126. Object.keys(this.presMap).forEach(function (key) {
  14127. if (key.indexOf('source') >= 0) {
  14128. sourceNumber++;
  14129. }
  14130. });
  14131. if (sourceNumber > 0)
  14132. for (var i = 1; i <= sourceNumber / 3; i++) {
  14133. pres.c('source',
  14134. {type: this.presMap['source' + i + '_type'],
  14135. ssrc: this.presMap['source' + i + '_ssrc'],
  14136. direction: this.presMap['source' + i + '_direction']
  14137. || 'sendrecv' }
  14138. ).up();
  14139. }
  14140. }
  14141. pres.up();
  14142. this.connection.send(pres);
  14143. },
  14144. addDisplayNameToPresence: function (displayName) {
  14145. this.presMap['displayName'] = displayName;
  14146. },
  14147. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14148. if (!this.presMap['medians'])
  14149. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14150. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14151. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14152. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14153. },
  14154. addDevicesToPresence: function (devices) {
  14155. this.presMap['devices'] = devices;
  14156. },
  14157. clearPresenceMedia: function () {
  14158. var self = this;
  14159. Object.keys(this.presMap).forEach(function (key) {
  14160. if (key.indexOf('source') != -1) {
  14161. delete self.presMap[key];
  14162. }
  14163. });
  14164. },
  14165. addPreziToPresence: function (url, currentSlide) {
  14166. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14167. this.presMap['preziurl'] = url;
  14168. this.presMap['prezicurrent'] = currentSlide;
  14169. },
  14170. removePreziFromPresence: function () {
  14171. delete this.presMap['prezins'];
  14172. delete this.presMap['preziurl'];
  14173. delete this.presMap['prezicurrent'];
  14174. },
  14175. addCurrentSlideToPresence: function (currentSlide) {
  14176. this.presMap['prezicurrent'] = currentSlide;
  14177. },
  14178. getPrezi: function (roomjid) {
  14179. return this.preziMap[roomjid];
  14180. },
  14181. addEtherpadToPresence: function (etherpadName) {
  14182. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14183. this.presMap['etherpadname'] = etherpadName;
  14184. },
  14185. addAudioInfoToPresence: function (isMuted) {
  14186. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14187. this.presMap['audiomuted'] = isMuted.toString();
  14188. },
  14189. addVideoInfoToPresence: function (isMuted) {
  14190. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14191. this.presMap['videomuted'] = isMuted.toString();
  14192. },
  14193. addConnectionInfoToPresence: function (stats) {
  14194. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14195. this.presMap['stats'] = stats;
  14196. },
  14197. findJidFromResource: function (resourceJid) {
  14198. if (resourceJid &&
  14199. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14200. return this.myroomjid;
  14201. }
  14202. var peerJid = null;
  14203. Object.keys(this.members).some(function (jid) {
  14204. peerJid = jid;
  14205. return Strophe.getResourceFromJid(jid) === resourceJid;
  14206. });
  14207. return peerJid;
  14208. },
  14209. addBridgeIsDownToPresence: function () {
  14210. this.presMap['bridgeIsDown'] = true;
  14211. },
  14212. addEmailToPresence: function (email) {
  14213. this.presMap['email'] = email;
  14214. },
  14215. addUserIdToPresence: function (userId) {
  14216. this.presMap['userId'] = userId;
  14217. },
  14218. isModerator: function () {
  14219. return this.role === 'moderator';
  14220. },
  14221. getMemberRole: function (peerJid) {
  14222. if (this.members[peerJid]) {
  14223. return this.members[peerJid].role;
  14224. }
  14225. return null;
  14226. },
  14227. onParticipantLeft: function (jid) {
  14228. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  14229. this.connection.jingle.terminateByJid(jid);
  14230. if (this.getPrezi(jid)) {
  14231. $(document).trigger('presentationremoved.muc',
  14232. [jid, this.getPrezi(jid)]);
  14233. }
  14234. Moderator.onMucLeft(jid);
  14235. },
  14236. parsePresence: function (from, memeber, pres) {
  14237. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14238. bridgeIsDown = true;
  14239. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14240. }
  14241. if(memeber.isFocus)
  14242. return;
  14243. var self = this;
  14244. // Remove old ssrcs coming from the jid
  14245. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14246. if (self.ssrc2jid[ssrc] == from) {
  14247. delete self.ssrc2jid[ssrc];
  14248. }
  14249. });
  14250. var changedStreams = [];
  14251. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14252. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14253. var ssrcV = ssrc.getAttribute('ssrc');
  14254. self.ssrc2jid[ssrcV] = from;
  14255. JingleSession.notReceivedSSRCs.push(ssrcV);
  14256. var type = ssrc.getAttribute('type');
  14257. var direction = ssrc.getAttribute('direction');
  14258. changedStreams.push({type: type, direction: direction});
  14259. });
  14260. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  14261. var displayName = !config.displayJids
  14262. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14263. if (displayName && displayName.length > 0)
  14264. {
  14265. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14266. }
  14267. var id = $(pres).find('>userID').text();
  14268. var email = $(pres).find('>email');
  14269. if(email.length > 0) {
  14270. id = email.text();
  14271. }
  14272. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14273. }
  14274. });
  14275. };
  14276. },{"../../service/xmpp/XMPPEvents":98,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  14277. /* jshint -W117 */
  14278. var JingleSession = require("./JingleSession");
  14279. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14280. module.exports = function(XMPP, eventEmitter)
  14281. {
  14282. function CallIncomingJingle(sid, connection) {
  14283. var sess = connection.jingle.sessions[sid];
  14284. // TODO: do we check activecall == null?
  14285. connection.jingle.activecall = sess;
  14286. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14287. // TODO: check affiliation and/or role
  14288. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14289. sess.usedrip = true; // not-so-naive trickle ice
  14290. sess.sendAnswer();
  14291. sess.accept();
  14292. };
  14293. Strophe.addConnectionPlugin('jingle', {
  14294. connection: null,
  14295. sessions: {},
  14296. jid2session: {},
  14297. ice_config: {iceServers: []},
  14298. pc_constraints: {},
  14299. activecall: null,
  14300. media_constraints: {
  14301. mandatory: {
  14302. 'OfferToReceiveAudio': true,
  14303. 'OfferToReceiveVideo': true
  14304. }
  14305. // MozDontOfferDataChannel: true when this is firefox
  14306. },
  14307. init: function (conn) {
  14308. this.connection = conn;
  14309. if (this.connection.disco) {
  14310. // http://xmpp.org/extensions/xep-0167.html#support
  14311. // http://xmpp.org/extensions/xep-0176.html#support
  14312. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14313. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14314. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14315. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14316. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14317. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14318. // this is dealt with by SDP O/A so we don't need to annouce this
  14319. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14320. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14321. if (config.useRtcpMux) {
  14322. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14323. }
  14324. if (config.useBundle) {
  14325. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14326. }
  14327. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14328. }
  14329. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14330. },
  14331. onJingle: function (iq) {
  14332. var sid = $(iq).find('jingle').attr('sid');
  14333. var action = $(iq).find('jingle').attr('action');
  14334. var fromJid = iq.getAttribute('from');
  14335. // send ack first
  14336. var ack = $iq({type: 'result',
  14337. to: fromJid,
  14338. id: iq.getAttribute('id')
  14339. });
  14340. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14341. var sess = this.sessions[sid];
  14342. if ('session-initiate' != action) {
  14343. if (sess === null) {
  14344. ack.type = 'error';
  14345. ack.c('error', {type: 'cancel'})
  14346. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14347. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14348. this.connection.send(ack);
  14349. return true;
  14350. }
  14351. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14352. // local jid is not checked
  14353. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14354. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14355. ack.type = 'error';
  14356. ack.c('error', {type: 'cancel'})
  14357. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14358. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14359. this.connection.send(ack);
  14360. return true;
  14361. }
  14362. } else if (sess !== undefined) {
  14363. // existing session with same session id
  14364. // this might be out-of-order if the sess.peerjid is the same as from
  14365. ack.type = 'error';
  14366. ack.c('error', {type: 'cancel'})
  14367. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14368. console.warn('duplicate session id', sid);
  14369. this.connection.send(ack);
  14370. return true;
  14371. }
  14372. // FIXME: check for a defined action
  14373. this.connection.send(ack);
  14374. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14375. switch (action) {
  14376. case 'session-initiate':
  14377. sess = new JingleSession(
  14378. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14379. this.connection, XMPP);
  14380. // configure session
  14381. sess.media_constraints = this.media_constraints;
  14382. sess.pc_constraints = this.pc_constraints;
  14383. sess.ice_config = this.ice_config;
  14384. sess.initiate(fromJid, false);
  14385. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14386. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14387. this.sessions[sess.sid] = sess;
  14388. this.jid2session[sess.peerjid] = sess;
  14389. // the callback should either
  14390. // .sendAnswer and .accept
  14391. // or .sendTerminate -- not necessarily synchronus
  14392. CallIncomingJingle(sess.sid, this.connection);
  14393. break;
  14394. case 'session-accept':
  14395. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14396. sess.accept();
  14397. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14398. break;
  14399. case 'session-terminate':
  14400. // If this is not the focus sending the terminate, we have
  14401. // nothing more to do here.
  14402. if (Object.keys(this.sessions).length < 1
  14403. || !(this.sessions[Object.keys(this.sessions)[0]]
  14404. instanceof JingleSession))
  14405. {
  14406. break;
  14407. }
  14408. console.log('terminating...', sess.sid);
  14409. sess.terminate();
  14410. this.terminate(sess.sid);
  14411. if ($(iq).find('>jingle>reason').length) {
  14412. $(document).trigger('callterminated.jingle', [
  14413. sess.sid,
  14414. sess.peerjid,
  14415. $(iq).find('>jingle>reason>:first')[0].tagName,
  14416. $(iq).find('>jingle>reason>text').text()
  14417. ]);
  14418. } else {
  14419. $(document).trigger('callterminated.jingle',
  14420. [sess.sid, sess.peerjid]);
  14421. }
  14422. break;
  14423. case 'transport-info':
  14424. sess.addIceCandidate($(iq).find('>jingle>content'));
  14425. break;
  14426. case 'session-info':
  14427. var affected;
  14428. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14429. $(document).trigger('ringing.jingle', [sess.sid]);
  14430. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14431. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14432. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14433. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14434. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14435. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14436. }
  14437. break;
  14438. case 'addsource': // FIXME: proprietary, un-jingleish
  14439. case 'source-add': // FIXME: proprietary
  14440. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14441. break;
  14442. case 'removesource': // FIXME: proprietary, un-jingleish
  14443. case 'source-remove': // FIXME: proprietary
  14444. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14445. break;
  14446. default:
  14447. console.warn('jingle action not implemented', action);
  14448. break;
  14449. }
  14450. return true;
  14451. },
  14452. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14453. var sess = new JingleSession(myjid || this.connection.jid,
  14454. Math.random().toString(36).substr(2, 12), // random string
  14455. this.connection, XMPP);
  14456. // configure session
  14457. sess.media_constraints = this.media_constraints;
  14458. sess.pc_constraints = this.pc_constraints;
  14459. sess.ice_config = this.ice_config;
  14460. sess.initiate(peerjid, true);
  14461. this.sessions[sess.sid] = sess;
  14462. this.jid2session[sess.peerjid] = sess;
  14463. sess.sendOffer();
  14464. return sess;
  14465. },
  14466. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14467. if (sid === null || sid === undefined) {
  14468. for (sid in this.sessions) {
  14469. if (this.sessions[sid].state != 'ended') {
  14470. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14471. this.sessions[sid].terminate();
  14472. }
  14473. delete this.jid2session[this.sessions[sid].peerjid];
  14474. delete this.sessions[sid];
  14475. }
  14476. } else if (this.sessions.hasOwnProperty(sid)) {
  14477. if (this.sessions[sid].state != 'ended') {
  14478. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14479. this.sessions[sid].terminate();
  14480. }
  14481. delete this.jid2session[this.sessions[sid].peerjid];
  14482. delete this.sessions[sid];
  14483. }
  14484. },
  14485. // Used to terminate a session when an unavailable presence is received.
  14486. terminateByJid: function (jid) {
  14487. if (this.jid2session.hasOwnProperty(jid)) {
  14488. var sess = this.jid2session[jid];
  14489. if (sess) {
  14490. sess.terminate();
  14491. console.log('peer went away silently', jid);
  14492. delete this.sessions[sess.sid];
  14493. delete this.jid2session[jid];
  14494. $(document).trigger('callterminated.jingle',
  14495. [sess.sid, jid], 'gone');
  14496. }
  14497. }
  14498. },
  14499. terminateRemoteByJid: function (jid, reason) {
  14500. if (this.jid2session.hasOwnProperty(jid)) {
  14501. var sess = this.jid2session[jid];
  14502. if (sess) {
  14503. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14504. sess.terminate();
  14505. console.log('terminate peer with jid', sess.sid, jid);
  14506. delete this.sessions[sess.sid];
  14507. delete this.jid2session[jid];
  14508. $(document).trigger('callterminated.jingle',
  14509. [sess.sid, jid, 'kicked']);
  14510. }
  14511. }
  14512. },
  14513. getStunAndTurnCredentials: function () {
  14514. // get stun and turn configuration from server via xep-0215
  14515. // uses time-limited credentials as described in
  14516. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14517. //
  14518. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14519. // for a prosody module which implements this
  14520. //
  14521. // currently, this doesn't work with updateIce and therefore credentials with a long
  14522. // validity have to be fetched before creating the peerconnection
  14523. // TODO: implement refresh via updateIce as described in
  14524. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14525. var self = this;
  14526. this.connection.sendIQ(
  14527. $iq({type: 'get', to: this.connection.domain})
  14528. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14529. function (res) {
  14530. var iceservers = [];
  14531. $(res).find('>services>service').each(function (idx, el) {
  14532. el = $(el);
  14533. var dict = {};
  14534. var type = el.attr('type');
  14535. switch (type) {
  14536. case 'stun':
  14537. dict.url = 'stun:' + el.attr('host');
  14538. if (el.attr('port')) {
  14539. dict.url += ':' + el.attr('port');
  14540. }
  14541. iceservers.push(dict);
  14542. break;
  14543. case 'turn':
  14544. case 'turns':
  14545. dict.url = type + ':';
  14546. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14547. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14548. dict.url += el.attr('username') + '@';
  14549. } else {
  14550. dict.username = el.attr('username'); // only works in M28
  14551. }
  14552. }
  14553. dict.url += el.attr('host');
  14554. if (el.attr('port') && el.attr('port') != '3478') {
  14555. dict.url += ':' + el.attr('port');
  14556. }
  14557. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14558. dict.url += '?transport=' + el.attr('transport');
  14559. }
  14560. if (el.attr('password')) {
  14561. dict.credential = el.attr('password');
  14562. }
  14563. iceservers.push(dict);
  14564. break;
  14565. }
  14566. });
  14567. self.ice_config.iceServers = iceservers;
  14568. },
  14569. function (err) {
  14570. console.warn('getting turn credentials failed', err);
  14571. console.warn('is mod_turncredentials or similar installed?');
  14572. }
  14573. );
  14574. // implement push?
  14575. },
  14576. /**
  14577. * Populates the log data
  14578. */
  14579. populateData: function () {
  14580. var data = {};
  14581. Object.keys(this.sessions).forEach(function (sid) {
  14582. var session = this.sessions[sid];
  14583. if (session.peerconnection && session.peerconnection.updateLog) {
  14584. // FIXME: should probably be a .dump call
  14585. data["jingle_" + session.sid] = {
  14586. updateLog: session.peerconnection.updateLog,
  14587. stats: session.peerconnection.stats,
  14588. url: window.location.href
  14589. };
  14590. }
  14591. });
  14592. return data;
  14593. }
  14594. });
  14595. };
  14596. },{"../../service/xmpp/XMPPEvents":98,"./JingleSession":48}],57:[function(require,module,exports){
  14597. /* global Strophe */
  14598. module.exports = function () {
  14599. Strophe.addConnectionPlugin('logger', {
  14600. // logs raw stanzas and makes them available for download as JSON
  14601. connection: null,
  14602. log: [],
  14603. init: function (conn) {
  14604. this.connection = conn;
  14605. this.connection.rawInput = this.log_incoming.bind(this);
  14606. this.connection.rawOutput = this.log_outgoing.bind(this);
  14607. },
  14608. log_incoming: function (stanza) {
  14609. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14610. },
  14611. log_outgoing: function (stanza) {
  14612. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14613. }
  14614. });
  14615. };
  14616. },{}],58:[function(require,module,exports){
  14617. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14618. setAudioMuted, Strophe */
  14619. /**
  14620. * Moderate connection plugin.
  14621. */
  14622. module.exports = function (XMPP) {
  14623. Strophe.addConnectionPlugin('moderate', {
  14624. connection: null,
  14625. init: function (conn) {
  14626. this.connection = conn;
  14627. this.connection.addHandler(this.onMute.bind(this),
  14628. 'http://jitsi.org/jitmeet/audio',
  14629. 'iq',
  14630. 'set',
  14631. null,
  14632. null);
  14633. },
  14634. setMute: function (jid, mute) {
  14635. console.info("set mute", mute);
  14636. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14637. .c('mute', {
  14638. xmlns: 'http://jitsi.org/jitmeet/audio',
  14639. jid: jid
  14640. })
  14641. .t(mute.toString())
  14642. .up();
  14643. this.connection.sendIQ(
  14644. iqToFocus,
  14645. function (result) {
  14646. console.log('set mute', result);
  14647. },
  14648. function (error) {
  14649. console.log('set mute error', error);
  14650. });
  14651. },
  14652. onMute: function (iq) {
  14653. var from = iq.getAttribute('from');
  14654. if (from !== this.connection.emuc.focusMucJid) {
  14655. console.warn("Ignored mute from non focus peer");
  14656. return false;
  14657. }
  14658. var mute = $(iq).find('mute');
  14659. if (mute.length) {
  14660. var doMuteAudio = mute.text() === "true";
  14661. APP.UI.setAudioMuted(doMuteAudio);
  14662. XMPP.forceMuted = doMuteAudio;
  14663. }
  14664. return true;
  14665. },
  14666. eject: function (jid) {
  14667. // We're not the focus, so can't terminate
  14668. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14669. this.connection.emuc.kick(jid);
  14670. }
  14671. });
  14672. }
  14673. },{}],59:[function(require,module,exports){
  14674. /* jshint -W117 */
  14675. module.exports = function() {
  14676. Strophe.addConnectionPlugin('rayo',
  14677. {
  14678. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14679. connection: null,
  14680. init: function (conn) {
  14681. this.connection = conn;
  14682. if (this.connection.disco) {
  14683. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14684. }
  14685. this.connection.addHandler(
  14686. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14687. },
  14688. onRayo: function (iq) {
  14689. console.info("Rayo IQ", iq);
  14690. },
  14691. dial: function (to, from, roomName, roomPass) {
  14692. var self = this;
  14693. var req = $iq(
  14694. {
  14695. type: 'set',
  14696. to: this.connection.emuc.focusMucJid
  14697. }
  14698. );
  14699. req.c('dial',
  14700. {
  14701. xmlns: this.RAYO_XMLNS,
  14702. to: to,
  14703. from: from
  14704. });
  14705. req.c('header',
  14706. {
  14707. name: 'JvbRoomName',
  14708. value: roomName
  14709. }).up();
  14710. if (roomPass !== null && roomPass.length) {
  14711. req.c('header',
  14712. {
  14713. name: 'JvbRoomPassword',
  14714. value: roomPass
  14715. }).up();
  14716. }
  14717. this.connection.sendIQ(
  14718. req,
  14719. function (result) {
  14720. console.info('Dial result ', result);
  14721. var resource = $(result).find('ref').attr('uri');
  14722. this.call_resource = resource.substr('xmpp:'.length);
  14723. console.info(
  14724. "Received call resource: " + this.call_resource);
  14725. },
  14726. function (error) {
  14727. console.info('Dial error ', error);
  14728. }
  14729. );
  14730. },
  14731. hang_up: function () {
  14732. if (!this.call_resource) {
  14733. console.warn("No call in progress");
  14734. return;
  14735. }
  14736. var self = this;
  14737. var req = $iq(
  14738. {
  14739. type: 'set',
  14740. to: this.call_resource
  14741. }
  14742. );
  14743. req.c('hangup',
  14744. {
  14745. xmlns: this.RAYO_XMLNS
  14746. });
  14747. this.connection.sendIQ(
  14748. req,
  14749. function (result) {
  14750. console.info('Hangup result ', result);
  14751. self.call_resource = null;
  14752. },
  14753. function (error) {
  14754. console.info('Hangup error ', error);
  14755. self.call_resource = null;
  14756. }
  14757. );
  14758. }
  14759. }
  14760. );
  14761. };
  14762. },{}],60:[function(require,module,exports){
  14763. /**
  14764. * Strophe logger implementation. Logs from level WARN and above.
  14765. */
  14766. module.exports = function () {
  14767. Strophe.log = function (level, msg) {
  14768. switch (level) {
  14769. case Strophe.LogLevel.WARN:
  14770. console.warn("Strophe: " + msg);
  14771. break;
  14772. case Strophe.LogLevel.ERROR:
  14773. case Strophe.LogLevel.FATAL:
  14774. console.error("Strophe: " + msg);
  14775. break;
  14776. }
  14777. };
  14778. Strophe.getStatusString = function (status) {
  14779. switch (status) {
  14780. case Strophe.Status.ERROR:
  14781. return "ERROR";
  14782. case Strophe.Status.CONNECTING:
  14783. return "CONNECTING";
  14784. case Strophe.Status.CONNFAIL:
  14785. return "CONNFAIL";
  14786. case Strophe.Status.AUTHENTICATING:
  14787. return "AUTHENTICATING";
  14788. case Strophe.Status.AUTHFAIL:
  14789. return "AUTHFAIL";
  14790. case Strophe.Status.CONNECTED:
  14791. return "CONNECTED";
  14792. case Strophe.Status.DISCONNECTED:
  14793. return "DISCONNECTED";
  14794. case Strophe.Status.DISCONNECTING:
  14795. return "DISCONNECTING";
  14796. case Strophe.Status.ATTACHED:
  14797. return "ATTACHED";
  14798. default:
  14799. return "unknown";
  14800. }
  14801. };
  14802. };
  14803. },{}],61:[function(require,module,exports){
  14804. /* global $, APP, config, Strophe*/
  14805. var Moderator = require("./moderator");
  14806. var EventEmitter = require("events");
  14807. var Recording = require("./recording");
  14808. var SDP = require("./SDP");
  14809. var Settings = require("../settings/Settings");
  14810. var Pako = require("pako");
  14811. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14812. var RTCEvents = require("../../service/RTC/RTCEvents");
  14813. var UIEvents = require("../../service/UI/UIEvents");
  14814. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14815. var eventEmitter = new EventEmitter();
  14816. var connection = null;
  14817. var authenticatedUser = false;
  14818. function connect(jid, password) {
  14819. connection = XMPP.createConnection();
  14820. Moderator.setConnection(connection);
  14821. if (connection.disco) {
  14822. // for chrome, add multistream cap
  14823. }
  14824. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14825. if (config.useIPv6) {
  14826. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14827. if (!connection.jingle.pc_constraints.optional)
  14828. connection.jingle.pc_constraints.optional = [];
  14829. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14830. }
  14831. // Include user info in MUC presence
  14832. var settings = Settings.getSettings();
  14833. if (settings.email) {
  14834. connection.emuc.addEmailToPresence(settings.email);
  14835. }
  14836. if (settings.uid) {
  14837. connection.emuc.addUserIdToPresence(settings.uid);
  14838. }
  14839. if (settings.displayName) {
  14840. connection.emuc.addDisplayNameToPresence(settings.displayName);
  14841. }
  14842. var anonymousConnectionFailed = false;
  14843. connection.connect(jid, password, function (status, msg) {
  14844. console.log('Strophe status changed to',
  14845. Strophe.getStatusString(status));
  14846. if (status === Strophe.Status.CONNECTED) {
  14847. if (config.useStunTurn) {
  14848. connection.jingle.getStunAndTurnCredentials();
  14849. }
  14850. console.info("My Jabber ID: " + connection.jid);
  14851. if(password)
  14852. authenticatedUser = true;
  14853. maybeDoJoin();
  14854. } else if (status === Strophe.Status.CONNFAIL) {
  14855. if(msg === 'x-strophe-bad-non-anon-jid') {
  14856. anonymousConnectionFailed = true;
  14857. }
  14858. } else if (status === Strophe.Status.DISCONNECTED) {
  14859. if(anonymousConnectionFailed) {
  14860. // prompt user for username and password
  14861. XMPP.promptLogin();
  14862. }
  14863. } else if (status === Strophe.Status.AUTHFAIL) {
  14864. // wrong password or username, prompt user
  14865. XMPP.promptLogin();
  14866. }
  14867. });
  14868. }
  14869. function maybeDoJoin() {
  14870. if (connection && connection.connected &&
  14871. Strophe.getResourceFromJid(connection.jid)
  14872. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14873. // .connected is true while connecting?
  14874. doJoin();
  14875. }
  14876. }
  14877. function doJoin() {
  14878. var roomName = APP.UI.generateRoomName();
  14879. Moderator.allocateConferenceFocus(
  14880. roomName, APP.UI.checkForNicknameAndJoin);
  14881. }
  14882. function initStrophePlugins()
  14883. {
  14884. require("./strophe.emuc")(XMPP, eventEmitter);
  14885. require("./strophe.jingle")(XMPP, eventEmitter);
  14886. require("./strophe.moderate")(XMPP);
  14887. require("./strophe.util")();
  14888. require("./strophe.rayo")();
  14889. require("./strophe.logger")();
  14890. }
  14891. function registerListeners() {
  14892. APP.RTC.addStreamListener(maybeDoJoin,
  14893. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14894. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  14895. XMPP.addToPresence("devices", devices);
  14896. })
  14897. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14898. XMPP.addToPresence("displayName", nickname);
  14899. });
  14900. }
  14901. function setupEvents() {
  14902. $(window).bind('beforeunload', function () {
  14903. if (connection && connection.connected) {
  14904. // ensure signout
  14905. $.ajax({
  14906. type: 'POST',
  14907. url: config.bosh,
  14908. async: false,
  14909. cache: false,
  14910. contentType: 'application/xml',
  14911. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14912. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14913. + (connection.sid || connection._proto.sid)
  14914. + "' type='terminate'>" +
  14915. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14916. "</body>",
  14917. success: function (data) {
  14918. console.log('signed out');
  14919. console.log(data);
  14920. },
  14921. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14922. console.log('signout error',
  14923. textStatus + ' (' + errorThrown + ')');
  14924. }
  14925. });
  14926. }
  14927. XMPP.disposeConference(true);
  14928. });
  14929. }
  14930. var XMPP = {
  14931. sessionTerminated: false,
  14932. /**
  14933. * XMPP connection status
  14934. */
  14935. Status: Strophe.Status,
  14936. /**
  14937. * Remembers if we were muted by the focus.
  14938. * @type {boolean}
  14939. */
  14940. forceMuted: false,
  14941. start: function () {
  14942. setupEvents();
  14943. initStrophePlugins();
  14944. registerListeners();
  14945. Moderator.init(this, eventEmitter);
  14946. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14947. // Force authenticated domain if room is appended with '?login=true'
  14948. if (config.hosts.anonymousdomain &&
  14949. window.location.search.indexOf("login=true") !== -1) {
  14950. configDomain = config.hosts.domain;
  14951. }
  14952. var jid = configDomain || window.location.hostname;
  14953. connect(jid, null);
  14954. },
  14955. createConnection: function () {
  14956. var bosh = config.bosh || '/http-bind';
  14957. return new Strophe.Connection(bosh);
  14958. },
  14959. getStatusString: function (status) {
  14960. return Strophe.getStatusString(status);
  14961. },
  14962. promptLogin: function () {
  14963. // FIXME: re-use LoginDialog which supports retries
  14964. APP.UI.showLoginPopup(connect);
  14965. },
  14966. joinRoom: function(roomName, useNicks, nick)
  14967. {
  14968. var roomjid;
  14969. roomjid = roomName;
  14970. if (useNicks) {
  14971. if (nick) {
  14972. roomjid += '/' + nick;
  14973. } else {
  14974. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14975. }
  14976. } else {
  14977. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14978. if(!authenticatedUser)
  14979. tmpJid = tmpJid.substr(0, 8);
  14980. roomjid += '/' + tmpJid;
  14981. }
  14982. connection.emuc.doJoin(roomjid);
  14983. },
  14984. myJid: function () {
  14985. if(!connection)
  14986. return null;
  14987. return connection.emuc.myroomjid;
  14988. },
  14989. myResource: function () {
  14990. if(!connection || ! connection.emuc.myroomjid)
  14991. return null;
  14992. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14993. },
  14994. disposeConference: function (onUnload) {
  14995. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14996. var handler = connection.jingle.activecall;
  14997. if (handler && handler.peerconnection) {
  14998. // FIXME: probably removing streams is not required and close() should
  14999. // be enough
  15000. if (APP.RTC.localAudio) {
  15001. handler.peerconnection.removeStream(
  15002. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15003. }
  15004. if (APP.RTC.localVideo) {
  15005. handler.peerconnection.removeStream(
  15006. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15007. }
  15008. handler.peerconnection.close();
  15009. }
  15010. connection.jingle.activecall = null;
  15011. if(!onUnload)
  15012. {
  15013. this.sessionTerminated = true;
  15014. connection.emuc.doLeave();
  15015. }
  15016. },
  15017. addListener: function(type, listener)
  15018. {
  15019. eventEmitter.on(type, listener);
  15020. },
  15021. removeListener: function (type, listener) {
  15022. eventEmitter.removeListener(type, listener);
  15023. },
  15024. allocateConferenceFocus: function(roomName, callback) {
  15025. Moderator.allocateConferenceFocus(roomName, callback);
  15026. },
  15027. getLoginUrl: function (roomName, callback) {
  15028. Moderator.getLoginUrl(roomName, callback);
  15029. },
  15030. getPopupLoginUrl: function (roomName, callback) {
  15031. Moderator.getPopupLoginUrl(roomName, callback);
  15032. },
  15033. isModerator: function () {
  15034. return Moderator.isModerator();
  15035. },
  15036. isSipGatewayEnabled: function () {
  15037. return Moderator.isSipGatewayEnabled();
  15038. },
  15039. isExternalAuthEnabled: function () {
  15040. return Moderator.isExternalAuthEnabled();
  15041. },
  15042. switchStreams: function (stream, oldStream, callback) {
  15043. if (connection && connection.jingle.activecall) {
  15044. // FIXME: will block switchInProgress on true value in case of exception
  15045. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  15046. } else {
  15047. // We are done immediately
  15048. console.warn("No conference handler or conference not started yet");
  15049. callback();
  15050. }
  15051. },
  15052. sendVideoInfoPresence: function (mute) {
  15053. connection.emuc.addVideoInfoToPresence(mute);
  15054. connection.emuc.sendPresence();
  15055. },
  15056. setVideoMute: function (mute, callback, options) {
  15057. if(!connection)
  15058. return;
  15059. var self = this;
  15060. var localCallback = function (mute) {
  15061. self.sendVideoInfoPresence(mute);
  15062. return callback(mute);
  15063. };
  15064. if(connection.jingle.activecall)
  15065. {
  15066. connection.jingle.activecall.setVideoMute(
  15067. mute, localCallback, options);
  15068. }
  15069. else {
  15070. localCallback(mute);
  15071. }
  15072. },
  15073. setAudioMute: function (mute, callback) {
  15074. if (!(connection && APP.RTC.localAudio)) {
  15075. return false;
  15076. }
  15077. if (this.forceMuted && !mute) {
  15078. console.info("Asking focus for unmute");
  15079. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  15080. // FIXME: wait for result before resetting muted status
  15081. this.forceMuted = false;
  15082. }
  15083. if (mute == APP.RTC.localAudio.isMuted()) {
  15084. // Nothing to do
  15085. return true;
  15086. }
  15087. // It is not clear what is the right way to handle multiple tracks.
  15088. // So at least make sure that they are all muted or all unmuted and
  15089. // that we send presence just once.
  15090. APP.RTC.localAudio.mute();
  15091. // isMuted is the opposite of audioEnabled
  15092. connection.emuc.addAudioInfoToPresence(mute);
  15093. connection.emuc.sendPresence();
  15094. callback();
  15095. return true;
  15096. },
  15097. // Really mute video, i.e. dont even send black frames
  15098. muteVideo: function (pc, unmute) {
  15099. // FIXME: this probably needs another of those lovely state safeguards...
  15100. // which checks for iceconn == connected and sigstate == stable
  15101. pc.setRemoteDescription(pc.remoteDescription,
  15102. function () {
  15103. pc.createAnswer(
  15104. function (answer) {
  15105. var sdp = new SDP(answer.sdp);
  15106. if (sdp.media.length > 1) {
  15107. if (unmute)
  15108. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  15109. else
  15110. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15111. sdp.raw = sdp.session + sdp.media.join('');
  15112. answer.sdp = sdp.raw;
  15113. }
  15114. pc.setLocalDescription(answer,
  15115. function () {
  15116. console.log('mute SLD ok');
  15117. },
  15118. function (error) {
  15119. console.log('mute SLD error');
  15120. APP.UI.messageHandler.showError("dialog.error",
  15121. "dialog.SLDFailure");
  15122. }
  15123. );
  15124. },
  15125. function (error) {
  15126. console.log(error);
  15127. APP.UI.messageHandler.showError();
  15128. }
  15129. );
  15130. },
  15131. function (error) {
  15132. console.log('muteVideo SRD error');
  15133. APP.UI.messageHandler.showError("dialog.error",
  15134. "dialog.SRDFailure");
  15135. }
  15136. );
  15137. },
  15138. toggleRecording: function (tokenEmptyCallback,
  15139. startingCallback, startedCallback) {
  15140. Recording.toggleRecording(tokenEmptyCallback,
  15141. startingCallback, startedCallback, connection);
  15142. },
  15143. addToPresence: function (name, value, dontSend) {
  15144. switch (name)
  15145. {
  15146. case "displayName":
  15147. connection.emuc.addDisplayNameToPresence(value);
  15148. break;
  15149. case "etherpad":
  15150. connection.emuc.addEtherpadToPresence(value);
  15151. break;
  15152. case "prezi":
  15153. connection.emuc.addPreziToPresence(value, 0);
  15154. break;
  15155. case "preziSlide":
  15156. connection.emuc.addCurrentSlideToPresence(value);
  15157. break;
  15158. case "connectionQuality":
  15159. connection.emuc.addConnectionInfoToPresence(value);
  15160. break;
  15161. case "email":
  15162. connection.emuc.addEmailToPresence(value);
  15163. break;
  15164. case "devices":
  15165. connection.emuc.addDevicesToPresence(value);
  15166. break;
  15167. default :
  15168. console.log("Unknown tag for presence: " + name);
  15169. return;
  15170. }
  15171. if (!dontSend)
  15172. connection.emuc.sendPresence();
  15173. },
  15174. /**
  15175. * Sends 'data' as a log message to the focus. Returns true iff a message
  15176. * was sent.
  15177. * @param data
  15178. * @returns {boolean} true iff a message was sent.
  15179. */
  15180. sendLogs: function (data) {
  15181. if(!connection.emuc.focusMucJid)
  15182. return false;
  15183. var deflate = true;
  15184. var content = JSON.stringify(data);
  15185. if (deflate) {
  15186. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15187. }
  15188. content = Base64.encode(content);
  15189. // XEP-0337-ish
  15190. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15191. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15192. id: 'PeerConnectionStats'});
  15193. message.c('message').t(content).up();
  15194. if (deflate) {
  15195. message.c('tag', {name: "deflated", value: "true"}).up();
  15196. }
  15197. message.up();
  15198. connection.send(message);
  15199. return true;
  15200. },
  15201. populateData: function () {
  15202. var data = {};
  15203. if (connection.jingle) {
  15204. data = connection.jingle.populateData();
  15205. }
  15206. return data;
  15207. },
  15208. getLogger: function () {
  15209. if(connection.logger)
  15210. return connection.logger.log;
  15211. return null;
  15212. },
  15213. getPrezi: function () {
  15214. return connection.emuc.getPrezi(this.myJid());
  15215. },
  15216. removePreziFromPresence: function () {
  15217. connection.emuc.removePreziFromPresence();
  15218. connection.emuc.sendPresence();
  15219. },
  15220. sendChatMessage: function (message, nickname) {
  15221. connection.emuc.sendMessage(message, nickname);
  15222. },
  15223. setSubject: function (topic) {
  15224. connection.emuc.setSubject(topic);
  15225. },
  15226. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15227. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15228. },
  15229. dial: function (to, from, roomName,roomPass) {
  15230. connection.rayo.dial(to, from, roomName,roomPass);
  15231. },
  15232. setMute: function (jid, mute) {
  15233. connection.moderate.setMute(jid, mute);
  15234. },
  15235. eject: function (jid) {
  15236. connection.moderate.eject(jid);
  15237. },
  15238. logout: function (callback) {
  15239. Moderator.logout(callback);
  15240. },
  15241. findJidFromResource: function (resource) {
  15242. return connection.emuc.findJidFromResource(resource);
  15243. },
  15244. getMembers: function () {
  15245. return connection.emuc.members;
  15246. },
  15247. getJidFromSSRC: function (ssrc) {
  15248. if(!connection)
  15249. return null;
  15250. return connection.emuc.ssrc2jid[ssrc];
  15251. },
  15252. getMUCJoined: function () {
  15253. return connection.emuc.joined;
  15254. },
  15255. getSessions: function () {
  15256. return connection.jingle.sessions;
  15257. },
  15258. removeStream: function (stream) {
  15259. if(!connection || !connection.jingle.activecall ||
  15260. !connection.jingle.activecall.peerconnection)
  15261. return;
  15262. connection.jingle.activecall.peerconnection.removeStream(stream);
  15263. }
  15264. };
  15265. module.exports = XMPP;
  15266. },{"../../service/RTC/RTCEvents":90,"../../service/RTC/StreamEventTypes":92,"../../service/UI/UIEvents":93,"../../service/xmpp/XMPPEvents":98,"../settings/Settings":38,"./SDP":49,"./moderator":53,"./recording":54,"./strophe.emuc":55,"./strophe.jingle":56,"./strophe.logger":57,"./strophe.moderate":58,"./strophe.rayo":59,"./strophe.util":60,"events":62,"pako":64}],62:[function(require,module,exports){
  15267. // Copyright Joyent, Inc. and other Node contributors.
  15268. //
  15269. // Permission is hereby granted, free of charge, to any person obtaining a
  15270. // copy of this software and associated documentation files (the
  15271. // "Software"), to deal in the Software without restriction, including
  15272. // without limitation the rights to use, copy, modify, merge, publish,
  15273. // distribute, sublicense, and/or sell copies of the Software, and to permit
  15274. // persons to whom the Software is furnished to do so, subject to the
  15275. // following conditions:
  15276. //
  15277. // The above copyright notice and this permission notice shall be included
  15278. // in all copies or substantial portions of the Software.
  15279. //
  15280. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15281. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15282. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  15283. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  15284. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15285. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  15286. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  15287. function EventEmitter() {
  15288. this._events = this._events || {};
  15289. this._maxListeners = this._maxListeners || undefined;
  15290. }
  15291. module.exports = EventEmitter;
  15292. // Backwards-compat with node 0.10.x
  15293. EventEmitter.EventEmitter = EventEmitter;
  15294. EventEmitter.prototype._events = undefined;
  15295. EventEmitter.prototype._maxListeners = undefined;
  15296. // By default EventEmitters will print a warning if more than 10 listeners are
  15297. // added to it. This is a useful default which helps finding memory leaks.
  15298. EventEmitter.defaultMaxListeners = 10;
  15299. // Obviously not all Emitters should be limited to 10. This function allows
  15300. // that to be increased. Set to zero for unlimited.
  15301. EventEmitter.prototype.setMaxListeners = function(n) {
  15302. if (!isNumber(n) || n < 0 || isNaN(n))
  15303. throw TypeError('n must be a positive number');
  15304. this._maxListeners = n;
  15305. return this;
  15306. };
  15307. EventEmitter.prototype.emit = function(type) {
  15308. var er, handler, len, args, i, listeners;
  15309. if (!this._events)
  15310. this._events = {};
  15311. // If there is no 'error' event listener then throw.
  15312. if (type === 'error') {
  15313. if (!this._events.error ||
  15314. (isObject(this._events.error) && !this._events.error.length)) {
  15315. er = arguments[1];
  15316. if (er instanceof Error) {
  15317. throw er; // Unhandled 'error' event
  15318. }
  15319. throw TypeError('Uncaught, unspecified "error" event.');
  15320. }
  15321. }
  15322. handler = this._events[type];
  15323. if (isUndefined(handler))
  15324. return false;
  15325. if (isFunction(handler)) {
  15326. switch (arguments.length) {
  15327. // fast cases
  15328. case 1:
  15329. handler.call(this);
  15330. break;
  15331. case 2:
  15332. handler.call(this, arguments[1]);
  15333. break;
  15334. case 3:
  15335. handler.call(this, arguments[1], arguments[2]);
  15336. break;
  15337. // slower
  15338. default:
  15339. len = arguments.length;
  15340. args = new Array(len - 1);
  15341. for (i = 1; i < len; i++)
  15342. args[i - 1] = arguments[i];
  15343. handler.apply(this, args);
  15344. }
  15345. } else if (isObject(handler)) {
  15346. len = arguments.length;
  15347. args = new Array(len - 1);
  15348. for (i = 1; i < len; i++)
  15349. args[i - 1] = arguments[i];
  15350. listeners = handler.slice();
  15351. len = listeners.length;
  15352. for (i = 0; i < len; i++)
  15353. listeners[i].apply(this, args);
  15354. }
  15355. return true;
  15356. };
  15357. EventEmitter.prototype.addListener = function(type, listener) {
  15358. var m;
  15359. if (!isFunction(listener))
  15360. throw TypeError('listener must be a function');
  15361. if (!this._events)
  15362. this._events = {};
  15363. // To avoid recursion in the case that type === "newListener"! Before
  15364. // adding it to the listeners, first emit "newListener".
  15365. if (this._events.newListener)
  15366. this.emit('newListener', type,
  15367. isFunction(listener.listener) ?
  15368. listener.listener : listener);
  15369. if (!this._events[type])
  15370. // Optimize the case of one listener. Don't need the extra array object.
  15371. this._events[type] = listener;
  15372. else if (isObject(this._events[type]))
  15373. // If we've already got an array, just append.
  15374. this._events[type].push(listener);
  15375. else
  15376. // Adding the second element, need to change to array.
  15377. this._events[type] = [this._events[type], listener];
  15378. // Check for listener leak
  15379. if (isObject(this._events[type]) && !this._events[type].warned) {
  15380. var m;
  15381. if (!isUndefined(this._maxListeners)) {
  15382. m = this._maxListeners;
  15383. } else {
  15384. m = EventEmitter.defaultMaxListeners;
  15385. }
  15386. if (m && m > 0 && this._events[type].length > m) {
  15387. this._events[type].warned = true;
  15388. console.error('(node) warning: possible EventEmitter memory ' +
  15389. 'leak detected. %d listeners added. ' +
  15390. 'Use emitter.setMaxListeners() to increase limit.',
  15391. this._events[type].length);
  15392. if (typeof console.trace === 'function') {
  15393. // not supported in IE 10
  15394. console.trace();
  15395. }
  15396. }
  15397. }
  15398. return this;
  15399. };
  15400. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  15401. EventEmitter.prototype.once = function(type, listener) {
  15402. if (!isFunction(listener))
  15403. throw TypeError('listener must be a function');
  15404. var fired = false;
  15405. function g() {
  15406. this.removeListener(type, g);
  15407. if (!fired) {
  15408. fired = true;
  15409. listener.apply(this, arguments);
  15410. }
  15411. }
  15412. g.listener = listener;
  15413. this.on(type, g);
  15414. return this;
  15415. };
  15416. // emits a 'removeListener' event iff the listener was removed
  15417. EventEmitter.prototype.removeListener = function(type, listener) {
  15418. var list, position, length, i;
  15419. if (!isFunction(listener))
  15420. throw TypeError('listener must be a function');
  15421. if (!this._events || !this._events[type])
  15422. return this;
  15423. list = this._events[type];
  15424. length = list.length;
  15425. position = -1;
  15426. if (list === listener ||
  15427. (isFunction(list.listener) && list.listener === listener)) {
  15428. delete this._events[type];
  15429. if (this._events.removeListener)
  15430. this.emit('removeListener', type, listener);
  15431. } else if (isObject(list)) {
  15432. for (i = length; i-- > 0;) {
  15433. if (list[i] === listener ||
  15434. (list[i].listener && list[i].listener === listener)) {
  15435. position = i;
  15436. break;
  15437. }
  15438. }
  15439. if (position < 0)
  15440. return this;
  15441. if (list.length === 1) {
  15442. list.length = 0;
  15443. delete this._events[type];
  15444. } else {
  15445. list.splice(position, 1);
  15446. }
  15447. if (this._events.removeListener)
  15448. this.emit('removeListener', type, listener);
  15449. }
  15450. return this;
  15451. };
  15452. EventEmitter.prototype.removeAllListeners = function(type) {
  15453. var key, listeners;
  15454. if (!this._events)
  15455. return this;
  15456. // not listening for removeListener, no need to emit
  15457. if (!this._events.removeListener) {
  15458. if (arguments.length === 0)
  15459. this._events = {};
  15460. else if (this._events[type])
  15461. delete this._events[type];
  15462. return this;
  15463. }
  15464. // emit removeListener for all listeners on all events
  15465. if (arguments.length === 0) {
  15466. for (key in this._events) {
  15467. if (key === 'removeListener') continue;
  15468. this.removeAllListeners(key);
  15469. }
  15470. this.removeAllListeners('removeListener');
  15471. this._events = {};
  15472. return this;
  15473. }
  15474. listeners = this._events[type];
  15475. if (isFunction(listeners)) {
  15476. this.removeListener(type, listeners);
  15477. } else {
  15478. // LIFO order
  15479. while (listeners.length)
  15480. this.removeListener(type, listeners[listeners.length - 1]);
  15481. }
  15482. delete this._events[type];
  15483. return this;
  15484. };
  15485. EventEmitter.prototype.listeners = function(type) {
  15486. var ret;
  15487. if (!this._events || !this._events[type])
  15488. ret = [];
  15489. else if (isFunction(this._events[type]))
  15490. ret = [this._events[type]];
  15491. else
  15492. ret = this._events[type].slice();
  15493. return ret;
  15494. };
  15495. EventEmitter.listenerCount = function(emitter, type) {
  15496. var ret;
  15497. if (!emitter._events || !emitter._events[type])
  15498. ret = 0;
  15499. else if (isFunction(emitter._events[type]))
  15500. ret = 1;
  15501. else
  15502. ret = emitter._events[type].length;
  15503. return ret;
  15504. };
  15505. function isFunction(arg) {
  15506. return typeof arg === 'function';
  15507. }
  15508. function isNumber(arg) {
  15509. return typeof arg === 'number';
  15510. }
  15511. function isObject(arg) {
  15512. return typeof arg === 'object' && arg !== null;
  15513. }
  15514. function isUndefined(arg) {
  15515. return arg === void 0;
  15516. }
  15517. },{}],63:[function(require,module,exports){
  15518. // i18next, v1.7.7
  15519. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  15520. // Distributed under MIT license
  15521. // http://i18next.com
  15522. (function() {
  15523. // add indexOf to non ECMA-262 standard compliant browsers
  15524. if (!Array.prototype.indexOf) {
  15525. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  15526. "use strict";
  15527. if (this == null) {
  15528. throw new TypeError();
  15529. }
  15530. var t = Object(this);
  15531. var len = t.length >>> 0;
  15532. if (len === 0) {
  15533. return -1;
  15534. }
  15535. var n = 0;
  15536. if (arguments.length > 0) {
  15537. n = Number(arguments[1]);
  15538. if (n != n) { // shortcut for verifying if it's NaN
  15539. n = 0;
  15540. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15541. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15542. }
  15543. }
  15544. if (n >= len) {
  15545. return -1;
  15546. }
  15547. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15548. for (; k < len; k++) {
  15549. if (k in t && t[k] === searchElement) {
  15550. return k;
  15551. }
  15552. }
  15553. return -1;
  15554. }
  15555. }
  15556. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15557. if (!Array.prototype.lastIndexOf) {
  15558. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15559. "use strict";
  15560. if (this == null) {
  15561. throw new TypeError();
  15562. }
  15563. var t = Object(this);
  15564. var len = t.length >>> 0;
  15565. if (len === 0) {
  15566. return -1;
  15567. }
  15568. var n = len;
  15569. if (arguments.length > 1) {
  15570. n = Number(arguments[1]);
  15571. if (n != n) {
  15572. n = 0;
  15573. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15574. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15575. }
  15576. }
  15577. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15578. for (; k >= 0; k--) {
  15579. if (k in t && t[k] === searchElement) {
  15580. return k;
  15581. }
  15582. }
  15583. return -1;
  15584. };
  15585. }
  15586. // Add string trim for IE8.
  15587. if (typeof String.prototype.trim !== 'function') {
  15588. String.prototype.trim = function() {
  15589. return this.replace(/^\s+|\s+$/g, '');
  15590. }
  15591. }
  15592. var root = this
  15593. , $ = root.jQuery || root.Zepto
  15594. , i18n = {}
  15595. , resStore = {}
  15596. , currentLng
  15597. , replacementCounter = 0
  15598. , languages = []
  15599. , initialized = false
  15600. , sync = {};
  15601. // Export the i18next object for **CommonJS**.
  15602. // If we're not in CommonJS, add `i18n` to the
  15603. // global object or to jquery.
  15604. if (typeof module !== 'undefined' && module.exports) {
  15605. if (!$) {
  15606. try {
  15607. $ = require('jquery');
  15608. } catch(e) {
  15609. // just ignore
  15610. }
  15611. }
  15612. if ($) {
  15613. $.i18n = $.i18n || i18n;
  15614. }
  15615. module.exports = i18n;
  15616. } else {
  15617. if ($) {
  15618. $.i18n = $.i18n || i18n;
  15619. }
  15620. root.i18n = root.i18n || i18n;
  15621. }
  15622. sync = {
  15623. load: function(lngs, options, cb) {
  15624. if (options.useLocalStorage) {
  15625. sync._loadLocal(lngs, options, function(err, store) {
  15626. var missingLngs = [];
  15627. for (var i = 0, len = lngs.length; i < len; i++) {
  15628. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15629. }
  15630. if (missingLngs.length > 0) {
  15631. sync._fetch(missingLngs, options, function(err, fetched) {
  15632. f.extend(store, fetched);
  15633. sync._storeLocal(fetched);
  15634. cb(null, store);
  15635. });
  15636. } else {
  15637. cb(null, store);
  15638. }
  15639. });
  15640. } else {
  15641. sync._fetch(lngs, options, function(err, store){
  15642. cb(null, store);
  15643. });
  15644. }
  15645. },
  15646. _loadLocal: function(lngs, options, cb) {
  15647. var store = {}
  15648. , nowMS = new Date().getTime();
  15649. if(window.localStorage) {
  15650. var todo = lngs.length;
  15651. f.each(lngs, function(key, lng) {
  15652. var local = window.localStorage.getItem('res_' + lng);
  15653. if (local) {
  15654. local = JSON.parse(local);
  15655. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15656. store[lng] = local;
  15657. }
  15658. }
  15659. todo--; // wait for all done befor callback
  15660. if (todo === 0) cb(null, store);
  15661. });
  15662. }
  15663. },
  15664. _storeLocal: function(store) {
  15665. if(window.localStorage) {
  15666. for (var m in store) {
  15667. store[m].i18nStamp = new Date().getTime();
  15668. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15669. }
  15670. }
  15671. return;
  15672. },
  15673. _fetch: function(lngs, options, cb) {
  15674. var ns = options.ns
  15675. , store = {};
  15676. if (!options.dynamicLoad) {
  15677. var todo = ns.namespaces.length * lngs.length
  15678. , errors;
  15679. // load each file individual
  15680. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15681. f.each(lngs, function(lngIndex, lngValue) {
  15682. // Call this once our translation has returned.
  15683. var loadComplete = function(err, data) {
  15684. if (err) {
  15685. errors = errors || [];
  15686. errors.push(err);
  15687. }
  15688. store[lngValue] = store[lngValue] || {};
  15689. store[lngValue][nsValue] = data;
  15690. todo--; // wait for all done befor callback
  15691. if (todo === 0) cb(errors, store);
  15692. };
  15693. if(typeof options.customLoad == 'function'){
  15694. // Use the specified custom callback.
  15695. options.customLoad(lngValue, nsValue, options, loadComplete);
  15696. } else {
  15697. //~ // Use our inbuilt sync.
  15698. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15699. }
  15700. });
  15701. });
  15702. } else {
  15703. // Call this once our translation has returned.
  15704. var loadComplete = function(err, data) {
  15705. cb(null, data);
  15706. };
  15707. if(typeof options.customLoad == 'function'){
  15708. // Use the specified custom callback.
  15709. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15710. } else {
  15711. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15712. // load all needed stuff once
  15713. f.ajax({
  15714. url: url,
  15715. success: function(data, status, xhr) {
  15716. f.log('loaded: ' + url);
  15717. loadComplete(null, data);
  15718. },
  15719. error : function(xhr, status, error) {
  15720. f.log('failed loading: ' + url);
  15721. loadComplete('failed loading resource.json error: ' + error);
  15722. },
  15723. dataType: "json",
  15724. async : options.getAsync
  15725. });
  15726. }
  15727. }
  15728. },
  15729. _fetchOne: function(lng, ns, options, done) {
  15730. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15731. f.ajax({
  15732. url: url,
  15733. success: function(data, status, xhr) {
  15734. f.log('loaded: ' + url);
  15735. done(null, data);
  15736. },
  15737. error : function(xhr, status, error) {
  15738. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15739. // file loaded but invalid json, stop waste time !
  15740. f.error('There is a typo in: ' + url);
  15741. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15742. f.log('Does not exist: ' + url);
  15743. } else {
  15744. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15745. f.log(theStatus + ' when loading ' + url);
  15746. }
  15747. done(error, {});
  15748. },
  15749. dataType: "json",
  15750. async : options.getAsync
  15751. });
  15752. },
  15753. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15754. var payload = {};
  15755. payload[key] = defaultValue;
  15756. var urls = [];
  15757. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15758. for (var i = 0; i < o.fallbackLng.length; i++) {
  15759. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15760. }
  15761. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15762. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15763. } else if (o.sendMissingTo === 'all') {
  15764. for (var i = 0, l = lngs.length; i < l; i++) {
  15765. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15766. }
  15767. }
  15768. for (var y = 0, len = urls.length; y < len; y++) {
  15769. var item = urls[y];
  15770. f.ajax({
  15771. url: item.url,
  15772. type: o.sendType,
  15773. data: payload,
  15774. success: function(data, status, xhr) {
  15775. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15776. // add key to resStore
  15777. var keys = key.split('.');
  15778. var x = 0;
  15779. var value = resStore[item.lng][ns];
  15780. while (keys[x]) {
  15781. if (x === keys.length - 1) {
  15782. value = value[keys[x]] = defaultValue;
  15783. } else {
  15784. value = value[keys[x]] = value[keys[x]] || {};
  15785. }
  15786. x++;
  15787. }
  15788. },
  15789. error : function(xhr, status, error) {
  15790. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15791. },
  15792. dataType: "json",
  15793. async : o.postAsync
  15794. });
  15795. }
  15796. },
  15797. reload: reload
  15798. };
  15799. // defaults
  15800. var o = {
  15801. lng: undefined,
  15802. load: 'all',
  15803. preload: [],
  15804. lowerCaseLng: false,
  15805. returnObjectTrees: false,
  15806. fallbackLng: ['dev'],
  15807. fallbackNS: [],
  15808. detectLngQS: 'setLng',
  15809. detectLngFromLocalStorage: false,
  15810. ns: 'translation',
  15811. fallbackOnNull: true,
  15812. fallbackOnEmpty: false,
  15813. fallbackToDefaultNS: false,
  15814. nsseparator: ':',
  15815. keyseparator: '.',
  15816. selectorAttr: 'data-i18n',
  15817. debug: false,
  15818. resGetPath: 'locales/__lng__/__ns__.json',
  15819. resPostPath: 'locales/add/__lng__/__ns__',
  15820. getAsync: true,
  15821. postAsync: true,
  15822. resStore: undefined,
  15823. useLocalStorage: false,
  15824. localStorageExpirationTime: 7*24*60*60*1000,
  15825. dynamicLoad: false,
  15826. sendMissing: false,
  15827. sendMissingTo: 'fallback', // current | all
  15828. sendType: 'POST',
  15829. interpolationPrefix: '__',
  15830. interpolationSuffix: '__',
  15831. defaultVariables: false,
  15832. reusePrefix: '$t(',
  15833. reuseSuffix: ')',
  15834. pluralSuffix: '_plural',
  15835. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15836. contextNotFound: ['context_not_found', Math.random()].join(''),
  15837. escapeInterpolation: false,
  15838. indefiniteSuffix: '_indefinite',
  15839. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15840. setJqueryExt: true,
  15841. defaultValueFromContent: true,
  15842. useDataAttrOptions: false,
  15843. cookieExpirationTime: undefined,
  15844. useCookie: true,
  15845. cookieName: 'i18next',
  15846. cookieDomain: undefined,
  15847. objectTreeKeyHandler: undefined,
  15848. postProcess: undefined,
  15849. parseMissingKey: undefined,
  15850. missingKeyHandler: sync.postMissing,
  15851. shortcutFunction: 'sprintf' // or: defaultValue
  15852. };
  15853. function _extend(target, source) {
  15854. if (!source || typeof source === 'function') {
  15855. return target;
  15856. }
  15857. for (var attr in source) { target[attr] = source[attr]; }
  15858. return target;
  15859. }
  15860. function _deepExtend(target, source) {
  15861. for (var prop in source)
  15862. if (prop in target)
  15863. _deepExtend(target[prop], source[prop]);
  15864. else
  15865. target[prop] = source[prop];
  15866. return target;
  15867. }
  15868. function _each(object, callback, args) {
  15869. var name, i = 0,
  15870. length = object.length,
  15871. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15872. if (args) {
  15873. if (isObj) {
  15874. for (name in object) {
  15875. if (callback.apply(object[name], args) === false) {
  15876. break;
  15877. }
  15878. }
  15879. } else {
  15880. for ( ; i < length; ) {
  15881. if (callback.apply(object[i++], args) === false) {
  15882. break;
  15883. }
  15884. }
  15885. }
  15886. // A special, fast, case for the most common use of each
  15887. } else {
  15888. if (isObj) {
  15889. for (name in object) {
  15890. if (callback.call(object[name], name, object[name]) === false) {
  15891. break;
  15892. }
  15893. }
  15894. } else {
  15895. for ( ; i < length; ) {
  15896. if (callback.call(object[i], i, object[i++]) === false) {
  15897. break;
  15898. }
  15899. }
  15900. }
  15901. }
  15902. return object;
  15903. }
  15904. var _entityMap = {
  15905. "&": "&amp;",
  15906. "<": "&lt;",
  15907. ">": "&gt;",
  15908. '"': '&quot;',
  15909. "'": '&#39;',
  15910. "/": '&#x2F;'
  15911. };
  15912. function _escape(data) {
  15913. if (typeof data === 'string') {
  15914. return data.replace(/[&<>"'\/]/g, function (s) {
  15915. return _entityMap[s];
  15916. });
  15917. }else{
  15918. return data;
  15919. }
  15920. }
  15921. function _ajax(options) {
  15922. // v0.5.0 of https://github.com/goloroden/http.js
  15923. var getXhr = function (callback) {
  15924. // Use the native XHR object if the browser supports it.
  15925. if (window.XMLHttpRequest) {
  15926. return callback(null, new XMLHttpRequest());
  15927. } else if (window.ActiveXObject) {
  15928. // In Internet Explorer check for ActiveX versions of the XHR object.
  15929. try {
  15930. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15931. } catch (e) {
  15932. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15933. }
  15934. }
  15935. // If no XHR support was found, throw an error.
  15936. return callback(new Error());
  15937. };
  15938. var encodeUsingUrlEncoding = function (data) {
  15939. if(typeof data === 'string') {
  15940. return data;
  15941. }
  15942. var result = [];
  15943. for(var dataItem in data) {
  15944. if(data.hasOwnProperty(dataItem)) {
  15945. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15946. }
  15947. }
  15948. return result.join('&');
  15949. };
  15950. var utf8 = function (text) {
  15951. text = text.replace(/\r\n/g, '\n');
  15952. var result = '';
  15953. for(var i = 0; i < text.length; i++) {
  15954. var c = text.charCodeAt(i);
  15955. if(c < 128) {
  15956. result += String.fromCharCode(c);
  15957. } else if((c > 127) && (c < 2048)) {
  15958. result += String.fromCharCode((c >> 6) | 192);
  15959. result += String.fromCharCode((c & 63) | 128);
  15960. } else {
  15961. result += String.fromCharCode((c >> 12) | 224);
  15962. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15963. result += String.fromCharCode((c & 63) | 128);
  15964. }
  15965. }
  15966. return result;
  15967. };
  15968. var base64 = function (text) {
  15969. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15970. text = utf8(text);
  15971. var result = '',
  15972. chr1, chr2, chr3,
  15973. enc1, enc2, enc3, enc4,
  15974. i = 0;
  15975. do {
  15976. chr1 = text.charCodeAt(i++);
  15977. chr2 = text.charCodeAt(i++);
  15978. chr3 = text.charCodeAt(i++);
  15979. enc1 = chr1 >> 2;
  15980. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15981. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15982. enc4 = chr3 & 63;
  15983. if(isNaN(chr2)) {
  15984. enc3 = enc4 = 64;
  15985. } else if(isNaN(chr3)) {
  15986. enc4 = 64;
  15987. }
  15988. result +=
  15989. keyStr.charAt(enc1) +
  15990. keyStr.charAt(enc2) +
  15991. keyStr.charAt(enc3) +
  15992. keyStr.charAt(enc4);
  15993. chr1 = chr2 = chr3 = '';
  15994. enc1 = enc2 = enc3 = enc4 = '';
  15995. } while(i < text.length);
  15996. return result;
  15997. };
  15998. var mergeHeaders = function () {
  15999. // Use the first header object as base.
  16000. var result = arguments[0];
  16001. // Iterate through the remaining header objects and add them.
  16002. for(var i = 1; i < arguments.length; i++) {
  16003. var currentHeaders = arguments[i];
  16004. for(var header in currentHeaders) {
  16005. if(currentHeaders.hasOwnProperty(header)) {
  16006. result[header] = currentHeaders[header];
  16007. }
  16008. }
  16009. }
  16010. // Return the merged headers.
  16011. return result;
  16012. };
  16013. var ajax = function (method, url, options, callback) {
  16014. // Adjust parameters.
  16015. if(typeof options === 'function') {
  16016. callback = options;
  16017. options = {};
  16018. }
  16019. // Set default parameter values.
  16020. options.cache = options.cache || false;
  16021. options.data = options.data || {};
  16022. options.headers = options.headers || {};
  16023. options.jsonp = options.jsonp || false;
  16024. options.async = options.async === undefined ? true : options.async;
  16025. // Merge the various header objects.
  16026. var headers = mergeHeaders({
  16027. 'accept': '*/*',
  16028. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  16029. }, ajax.headers, options.headers);
  16030. // Encode the data according to the content-type.
  16031. var payload;
  16032. if (headers['content-type'] === 'application/json') {
  16033. payload = JSON.stringify(options.data);
  16034. } else {
  16035. payload = encodeUsingUrlEncoding(options.data);
  16036. }
  16037. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  16038. // if neccessary.
  16039. if(method === 'GET') {
  16040. // Setup the query string.
  16041. var queryString = [];
  16042. if(payload) {
  16043. queryString.push(payload);
  16044. payload = null;
  16045. }
  16046. // Handle caching.
  16047. if(!options.cache) {
  16048. queryString.push('_=' + (new Date()).getTime());
  16049. }
  16050. // If neccessary prepare the query string for a JSONP call.
  16051. if(options.jsonp) {
  16052. queryString.push('callback=' + options.jsonp);
  16053. queryString.push('jsonp=' + options.jsonp);
  16054. }
  16055. // Merge the query string and attach it to the url.
  16056. queryString = queryString.join('&');
  16057. if (queryString.length > 1) {
  16058. if (url.indexOf('?') > -1) {
  16059. url += '&' + queryString;
  16060. } else {
  16061. url += '?' + queryString;
  16062. }
  16063. }
  16064. // Make a JSONP call if neccessary.
  16065. if(options.jsonp) {
  16066. var head = document.getElementsByTagName('head')[0];
  16067. var script = document.createElement('script');
  16068. script.type = 'text/javascript';
  16069. script.src = url;
  16070. head.appendChild(script);
  16071. return;
  16072. }
  16073. }
  16074. // Since we got here, it is no JSONP request, so make a normal XHR request.
  16075. getXhr(function (err, xhr) {
  16076. if(err) return callback(err);
  16077. // Open the request.
  16078. xhr.open(method, url, options.async);
  16079. // Set the request headers.
  16080. for(var header in headers) {
  16081. if(headers.hasOwnProperty(header)) {
  16082. xhr.setRequestHeader(header, headers[header]);
  16083. }
  16084. }
  16085. // Handle the request events.
  16086. xhr.onreadystatechange = function () {
  16087. if(xhr.readyState === 4) {
  16088. var data = xhr.responseText || '';
  16089. // If no callback is given, return.
  16090. if(!callback) {
  16091. return;
  16092. }
  16093. // Return an object that provides access to the data as text and JSON.
  16094. callback(xhr.status, {
  16095. text: function () {
  16096. return data;
  16097. },
  16098. json: function () {
  16099. try {
  16100. return JSON.parse(data)
  16101. } catch (e) {
  16102. f.error('Can not parse JSON. URL: ' + url);
  16103. return {};
  16104. }
  16105. }
  16106. });
  16107. }
  16108. };
  16109. // Actually send the XHR request.
  16110. xhr.send(payload);
  16111. });
  16112. };
  16113. // Define the external interface.
  16114. var http = {
  16115. authBasic: function (username, password) {
  16116. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  16117. },
  16118. connect: function (url, options, callback) {
  16119. return ajax('CONNECT', url, options, callback);
  16120. },
  16121. del: function (url, options, callback) {
  16122. return ajax('DELETE', url, options, callback);
  16123. },
  16124. get: function (url, options, callback) {
  16125. return ajax('GET', url, options, callback);
  16126. },
  16127. head: function (url, options, callback) {
  16128. return ajax('HEAD', url, options, callback);
  16129. },
  16130. headers: function (headers) {
  16131. ajax.headers = headers || {};
  16132. },
  16133. isAllowed: function (url, verb, callback) {
  16134. this.options(url, function (status, data) {
  16135. callback(data.text().indexOf(verb) !== -1);
  16136. });
  16137. },
  16138. options: function (url, options, callback) {
  16139. return ajax('OPTIONS', url, options, callback);
  16140. },
  16141. patch: function (url, options, callback) {
  16142. return ajax('PATCH', url, options, callback);
  16143. },
  16144. post: function (url, options, callback) {
  16145. return ajax('POST', url, options, callback);
  16146. },
  16147. put: function (url, options, callback) {
  16148. return ajax('PUT', url, options, callback);
  16149. },
  16150. trace: function (url, options, callback) {
  16151. return ajax('TRACE', url, options, callback);
  16152. }
  16153. };
  16154. var methode = options.type ? options.type.toLowerCase() : 'get';
  16155. http[methode](options.url, options, function (status, data) {
  16156. // file: protocol always gives status code 0, so check for data
  16157. if (status === 200 || (status === 0 && data.text())) {
  16158. options.success(data.json(), status, null);
  16159. } else {
  16160. options.error(data.text(), status, null);
  16161. }
  16162. });
  16163. }
  16164. var _cookie = {
  16165. create: function(name,value,minutes,domain) {
  16166. var expires;
  16167. if (minutes) {
  16168. var date = new Date();
  16169. date.setTime(date.getTime()+(minutes*60*1000));
  16170. expires = "; expires="+date.toGMTString();
  16171. }
  16172. else expires = "";
  16173. domain = (domain)? "domain="+domain+";" : "";
  16174. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  16175. },
  16176. read: function(name) {
  16177. var nameEQ = name + "=";
  16178. var ca = document.cookie.split(';');
  16179. for(var i=0;i < ca.length;i++) {
  16180. var c = ca[i];
  16181. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  16182. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  16183. }
  16184. return null;
  16185. },
  16186. remove: function(name) {
  16187. this.create(name,"",-1);
  16188. }
  16189. };
  16190. var cookie_noop = {
  16191. create: function(name,value,minutes,domain) {},
  16192. read: function(name) { return null; },
  16193. remove: function(name) {}
  16194. };
  16195. // move dependent functions to a container so that
  16196. // they can be overriden easier in no jquery environment (node.js)
  16197. var f = {
  16198. extend: $ ? $.extend : _extend,
  16199. deepExtend: _deepExtend,
  16200. each: $ ? $.each : _each,
  16201. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  16202. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  16203. detectLanguage: detectLanguage,
  16204. escape: _escape,
  16205. log: function(str) {
  16206. if (o.debug && typeof console !== "undefined") console.log(str);
  16207. },
  16208. error: function(str) {
  16209. if (typeof console !== "undefined") console.error(str);
  16210. },
  16211. getCountyIndexOfLng: function(lng) {
  16212. var lng_index = 0;
  16213. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  16214. return lng_index;
  16215. },
  16216. toLanguages: function(lng) {
  16217. var log = this.log;
  16218. function applyCase(l) {
  16219. var ret = l;
  16220. if (typeof l === 'string' && l.indexOf('-') > -1) {
  16221. var parts = l.split('-');
  16222. ret = o.lowerCaseLng ?
  16223. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16224. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16225. } else {
  16226. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  16227. }
  16228. return ret;
  16229. }
  16230. var languages = [];
  16231. var whitelist = o.lngWhitelist || false;
  16232. var addLanguage = function(language){
  16233. //reject langs not whitelisted
  16234. if(!whitelist || whitelist.indexOf(language) > -1){
  16235. languages.push(language);
  16236. }else{
  16237. log('rejecting non-whitelisted language: ' + language);
  16238. }
  16239. };
  16240. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  16241. var parts = lng.split('-');
  16242. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  16243. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  16244. } else {
  16245. addLanguage(applyCase(lng));
  16246. }
  16247. for (var i = 0; i < o.fallbackLng.length; i++) {
  16248. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  16249. }
  16250. return languages;
  16251. },
  16252. regexEscape: function(str) {
  16253. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  16254. },
  16255. regexReplacementEscape: function(strOrFn) {
  16256. if (typeof strOrFn === 'string') {
  16257. return strOrFn.replace(/\$/g, "$$$$");
  16258. } else {
  16259. return strOrFn;
  16260. }
  16261. },
  16262. localStorage: {
  16263. setItem: function(key, value) {
  16264. if (window.localStorage) {
  16265. try {
  16266. window.localStorage.setItem(key, value);
  16267. } catch (e) {
  16268. f.log('failed to set value for key "' + key + '" to localStorage.');
  16269. }
  16270. }
  16271. }
  16272. }
  16273. };
  16274. function init(options, cb) {
  16275. if (typeof options === 'function') {
  16276. cb = options;
  16277. options = {};
  16278. }
  16279. options = options || {};
  16280. // override defaults with passed in options
  16281. f.extend(o, options);
  16282. delete o.fixLng; /* passed in each time */
  16283. // override functions: .log(), .detectLanguage(), etc
  16284. if (o.functions) {
  16285. delete o.functions;
  16286. f.extend(f, options.functions);
  16287. }
  16288. // create namespace object if namespace is passed in as string
  16289. if (typeof o.ns == 'string') {
  16290. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  16291. }
  16292. // fallback namespaces
  16293. if (typeof o.fallbackNS == 'string') {
  16294. o.fallbackNS = [o.fallbackNS];
  16295. }
  16296. // fallback languages
  16297. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  16298. o.fallbackLng = [o.fallbackLng];
  16299. }
  16300. // escape prefix/suffix
  16301. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  16302. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  16303. if (!o.lng) o.lng = f.detectLanguage();
  16304. languages = f.toLanguages(o.lng);
  16305. currentLng = languages[0];
  16306. f.log('currentLng set to: ' + currentLng);
  16307. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  16308. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  16309. }
  16310. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  16311. f.localStorage.setItem('i18next_lng', currentLng);
  16312. }
  16313. var lngTranslate = translate;
  16314. if (options.fixLng) {
  16315. lngTranslate = function(key, options) {
  16316. options = options || {};
  16317. options.lng = options.lng || lngTranslate.lng;
  16318. return translate(key, options);
  16319. };
  16320. lngTranslate.lng = currentLng;
  16321. }
  16322. pluralExtensions.setCurrentLng(currentLng);
  16323. // add JQuery extensions
  16324. if ($ && o.setJqueryExt) addJqueryFunct();
  16325. // jQuery deferred
  16326. var deferred;
  16327. if ($ && $.Deferred) {
  16328. deferred = $.Deferred();
  16329. }
  16330. // return immidiatly if res are passed in
  16331. if (o.resStore) {
  16332. resStore = o.resStore;
  16333. initialized = true;
  16334. if (cb) cb(lngTranslate);
  16335. if (deferred) deferred.resolve(lngTranslate);
  16336. if (deferred) return deferred.promise();
  16337. return;
  16338. }
  16339. // languages to load
  16340. var lngsToLoad = f.toLanguages(o.lng);
  16341. if (typeof o.preload === 'string') o.preload = [o.preload];
  16342. for (var i = 0, l = o.preload.length; i < l; i++) {
  16343. var pres = f.toLanguages(o.preload[i]);
  16344. for (var y = 0, len = pres.length; y < len; y++) {
  16345. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16346. lngsToLoad.push(pres[y]);
  16347. }
  16348. }
  16349. }
  16350. // else load them
  16351. i18n.sync.load(lngsToLoad, o, function(err, store) {
  16352. resStore = store;
  16353. initialized = true;
  16354. if (cb) cb(lngTranslate);
  16355. if (deferred) deferred.resolve(lngTranslate);
  16356. });
  16357. if (deferred) return deferred.promise();
  16358. }
  16359. function preload(lngs, cb) {
  16360. if (typeof lngs === 'string') lngs = [lngs];
  16361. for (var i = 0, l = lngs.length; i < l; i++) {
  16362. if (o.preload.indexOf(lngs[i]) < 0) {
  16363. o.preload.push(lngs[i]);
  16364. }
  16365. }
  16366. return init(cb);
  16367. }
  16368. function addResourceBundle(lng, ns, resources, deep) {
  16369. if (typeof ns !== 'string') {
  16370. resources = ns;
  16371. ns = o.ns.defaultNs;
  16372. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16373. o.ns.namespaces.push(ns);
  16374. }
  16375. resStore[lng] = resStore[lng] || {};
  16376. resStore[lng][ns] = resStore[lng][ns] || {};
  16377. if (deep) {
  16378. f.deepExtend(resStore[lng][ns], resources);
  16379. } else {
  16380. f.extend(resStore[lng][ns], resources);
  16381. }
  16382. }
  16383. function hasResourceBundle(lng, ns) {
  16384. if (typeof ns !== 'string') {
  16385. ns = o.ns.defaultNs;
  16386. }
  16387. resStore[lng] = resStore[lng] || {};
  16388. var res = resStore[lng][ns] || {};
  16389. var hasValues = false;
  16390. for(var prop in res) {
  16391. if (res.hasOwnProperty(prop)) {
  16392. hasValues = true;
  16393. }
  16394. }
  16395. return hasValues;
  16396. }
  16397. function removeResourceBundle(lng, ns) {
  16398. if (typeof ns !== 'string') {
  16399. ns = o.ns.defaultNs;
  16400. }
  16401. resStore[lng] = resStore[lng] || {};
  16402. resStore[lng][ns] = {};
  16403. }
  16404. function addResource(lng, ns, key, value) {
  16405. if (typeof ns !== 'string') {
  16406. resource = ns;
  16407. ns = o.ns.defaultNs;
  16408. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16409. o.ns.namespaces.push(ns);
  16410. }
  16411. resStore[lng] = resStore[lng] || {};
  16412. resStore[lng][ns] = resStore[lng][ns] || {};
  16413. var keys = key.split(o.keyseparator);
  16414. var x = 0;
  16415. var node = resStore[lng][ns];
  16416. var origRef = node;
  16417. while (keys[x]) {
  16418. if (x == keys.length - 1)
  16419. node[keys[x]] = value;
  16420. else {
  16421. if (node[keys[x]] == null)
  16422. node[keys[x]] = {};
  16423. node = node[keys[x]];
  16424. }
  16425. x++;
  16426. }
  16427. }
  16428. function addResources(lng, ns, resources) {
  16429. if (typeof ns !== 'string') {
  16430. resource = ns;
  16431. ns = o.ns.defaultNs;
  16432. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16433. o.ns.namespaces.push(ns);
  16434. }
  16435. for (var m in resources) {
  16436. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  16437. }
  16438. }
  16439. function setDefaultNamespace(ns) {
  16440. o.ns.defaultNs = ns;
  16441. }
  16442. function loadNamespace(namespace, cb) {
  16443. loadNamespaces([namespace], cb);
  16444. }
  16445. function loadNamespaces(namespaces, cb) {
  16446. var opts = {
  16447. dynamicLoad: o.dynamicLoad,
  16448. resGetPath: o.resGetPath,
  16449. getAsync: o.getAsync,
  16450. customLoad: o.customLoad,
  16451. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  16452. };
  16453. // languages to load
  16454. var lngsToLoad = f.toLanguages(o.lng);
  16455. if (typeof o.preload === 'string') o.preload = [o.preload];
  16456. for (var i = 0, l = o.preload.length; i < l; i++) {
  16457. var pres = f.toLanguages(o.preload[i]);
  16458. for (var y = 0, len = pres.length; y < len; y++) {
  16459. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16460. lngsToLoad.push(pres[y]);
  16461. }
  16462. }
  16463. }
  16464. // check if we have to load
  16465. var lngNeedLoad = [];
  16466. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  16467. var needLoad = false;
  16468. var resSet = resStore[lngsToLoad[a]];
  16469. if (resSet) {
  16470. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16471. if (!resSet[namespaces[b]]) needLoad = true;
  16472. }
  16473. } else {
  16474. needLoad = true;
  16475. }
  16476. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16477. }
  16478. if (lngNeedLoad.length) {
  16479. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16480. var todo = namespaces.length * lngNeedLoad.length;
  16481. // load each file individual
  16482. f.each(namespaces, function(nsIndex, nsValue) {
  16483. // append namespace to namespace array
  16484. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16485. o.ns.namespaces.push(nsValue);
  16486. }
  16487. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16488. resStore[lngValue] = resStore[lngValue] || {};
  16489. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16490. todo--; // wait for all done befor callback
  16491. if (todo === 0 && cb) {
  16492. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16493. cb();
  16494. }
  16495. });
  16496. });
  16497. });
  16498. } else {
  16499. if (cb) cb();
  16500. }
  16501. }
  16502. function setLng(lng, options, cb) {
  16503. if (typeof options === 'function') {
  16504. cb = options;
  16505. options = {};
  16506. } else if (!options) {
  16507. options = {};
  16508. }
  16509. options.lng = lng;
  16510. return init(options, cb);
  16511. }
  16512. function lng() {
  16513. return currentLng;
  16514. }
  16515. function reload(cb) {
  16516. resStore = {};
  16517. setLng(currentLng, cb);
  16518. }
  16519. function addJqueryFunct() {
  16520. // $.t shortcut
  16521. $.t = $.t || translate;
  16522. function parse(ele, key, options) {
  16523. if (key.length === 0) return;
  16524. var attr = 'text';
  16525. if (key.indexOf('[') === 0) {
  16526. var parts = key.split(']');
  16527. key = parts[1];
  16528. attr = parts[0].substr(1, parts[0].length-1);
  16529. }
  16530. if (key.indexOf(';') === key.length-1) {
  16531. key = key.substr(0, key.length-2);
  16532. }
  16533. var optionsToUse;
  16534. if (attr === 'html') {
  16535. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16536. ele.html($.t(key, optionsToUse));
  16537. } else if (attr === 'text') {
  16538. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16539. ele.text($.t(key, optionsToUse));
  16540. } else if (attr === 'prepend') {
  16541. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16542. ele.prepend($.t(key, optionsToUse));
  16543. } else if (attr === 'append') {
  16544. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16545. ele.append($.t(key, optionsToUse));
  16546. } else if (attr.indexOf("data-") === 0) {
  16547. var dataAttr = attr.substr(("data-").length);
  16548. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16549. var translated = $.t(key, optionsToUse);
  16550. //we change into the data cache
  16551. ele.data(dataAttr, translated);
  16552. //we change into the dom
  16553. ele.attr(attr, translated);
  16554. } else {
  16555. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16556. ele.attr(attr, $.t(key, optionsToUse));
  16557. }
  16558. }
  16559. function localize(ele, options) {
  16560. var key = ele.attr(o.selectorAttr);
  16561. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16562. if (!key) return;
  16563. var target = ele
  16564. , targetSelector = ele.data("i18n-target");
  16565. if (targetSelector) {
  16566. target = ele.find(targetSelector) || ele;
  16567. }
  16568. if (!options && o.useDataAttrOptions === true) {
  16569. options = ele.data("i18n-options");
  16570. }
  16571. options = options || {};
  16572. if (key.indexOf(';') >= 0) {
  16573. var keys = key.split(';');
  16574. $.each(keys, function(m, k) {
  16575. if (k !== '') parse(target, k, options);
  16576. });
  16577. } else {
  16578. parse(target, key, options);
  16579. }
  16580. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16581. }
  16582. // fn
  16583. $.fn.i18n = function (options) {
  16584. return this.each(function() {
  16585. // localize element itself
  16586. localize($(this), options);
  16587. // localize childs
  16588. var elements = $(this).find('[' + o.selectorAttr + ']');
  16589. elements.each(function() {
  16590. localize($(this), options);
  16591. });
  16592. });
  16593. };
  16594. }
  16595. function applyReplacement(str, replacementHash, nestedKey, options) {
  16596. if (!str) return str;
  16597. options = options || replacementHash; // first call uses replacement hash combined with options
  16598. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16599. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16600. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16601. , unEscapingSuffix = 'HTML'+suffix;
  16602. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16603. f.each(hash, function(key, value) {
  16604. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16605. if (typeof value === 'object' && value !== null) {
  16606. str = applyReplacement(str, value, nextKey, options);
  16607. } else {
  16608. if (options.escapeInterpolation || o.escapeInterpolation) {
  16609. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16610. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16611. } else {
  16612. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16613. }
  16614. // str = options.escapeInterpolation;
  16615. }
  16616. });
  16617. return str;
  16618. }
  16619. // append it to functions
  16620. f.applyReplacement = applyReplacement;
  16621. function applyReuse(translated, options) {
  16622. var comma = ',';
  16623. var options_open = '{';
  16624. var options_close = '}';
  16625. var opts = f.extend({}, options);
  16626. delete opts.postProcess;
  16627. while (translated.indexOf(o.reusePrefix) != -1) {
  16628. replacementCounter++;
  16629. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16630. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16631. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16632. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16633. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16634. if (index_of_end_of_closing <= index_of_opening) {
  16635. f.error('there is an missing closing in following translation value', translated);
  16636. return '';
  16637. }
  16638. if (token_without_symbols.indexOf(comma) != -1) {
  16639. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16640. if (token_without_symbols.indexOf(options_open, index_of_token_end_of_closing) != -1 && token_without_symbols.indexOf(options_close, index_of_token_end_of_closing) != -1) {
  16641. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16642. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16643. try {
  16644. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16645. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16646. } catch (e) {
  16647. }
  16648. }
  16649. }
  16650. var translated_token = _translate(token_without_symbols, opts);
  16651. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16652. }
  16653. return translated;
  16654. }
  16655. function hasContext(options) {
  16656. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16657. }
  16658. function needsPlural(options, lng) {
  16659. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16660. }
  16661. function needsIndefiniteArticle(options) {
  16662. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16663. }
  16664. function exists(key, options) {
  16665. options = options || {};
  16666. var notFound = _getDefaultValue(key, options)
  16667. , found = _find(key, options);
  16668. return found !== undefined || found === notFound;
  16669. }
  16670. function translate(key, options) {
  16671. options = options || {};
  16672. if (!initialized) {
  16673. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16674. return options.defaultValue || '';
  16675. };
  16676. replacementCounter = 0;
  16677. return _translate.apply(null, arguments);
  16678. }
  16679. function _getDefaultValue(key, options) {
  16680. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16681. }
  16682. function _injectSprintfProcessor() {
  16683. var values = [];
  16684. // mh: build array from second argument onwards
  16685. for (var i = 1; i < arguments.length; i++) {
  16686. values.push(arguments[i]);
  16687. }
  16688. return {
  16689. postProcess: 'sprintf',
  16690. sprintf: values
  16691. };
  16692. }
  16693. function _translate(potentialKeys, options) {
  16694. if (options && typeof options !== 'object') {
  16695. if (o.shortcutFunction === 'sprintf') {
  16696. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16697. options = _injectSprintfProcessor.apply(null, arguments);
  16698. } else if (o.shortcutFunction === 'defaultValue') {
  16699. options = {
  16700. defaultValue: options
  16701. }
  16702. }
  16703. } else {
  16704. options = options || {};
  16705. }
  16706. if (typeof o.defaultVariables === 'object') {
  16707. options = f.extend({}, o.defaultVariables, options);
  16708. }
  16709. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16710. if (typeof potentialKeys === 'string') {
  16711. potentialKeys = [potentialKeys];
  16712. }
  16713. var key = potentialKeys[0];
  16714. if (potentialKeys.length > 1) {
  16715. for (var i = 0; i < potentialKeys.length; i++) {
  16716. key = potentialKeys[i];
  16717. if (exists(key, options)) {
  16718. break;
  16719. }
  16720. }
  16721. }
  16722. var notFound = _getDefaultValue(key, options)
  16723. , found = _find(key, options)
  16724. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16725. , ns = options.ns || o.ns.defaultNs
  16726. , parts;
  16727. // split ns and key
  16728. if (key.indexOf(o.nsseparator) > -1) {
  16729. parts = key.split(o.nsseparator);
  16730. ns = parts[0];
  16731. key = parts[1];
  16732. }
  16733. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16734. if (options.lng) {
  16735. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16736. } else {
  16737. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16738. }
  16739. }
  16740. var postProcessor = options.postProcess || o.postProcess;
  16741. if (found !== undefined && postProcessor) {
  16742. if (postProcessors[postProcessor]) {
  16743. found = postProcessors[postProcessor](found, key, options);
  16744. }
  16745. }
  16746. // process notFound if function exists
  16747. var splitNotFound = notFound;
  16748. if (notFound.indexOf(o.nsseparator) > -1) {
  16749. parts = notFound.split(o.nsseparator);
  16750. splitNotFound = parts[1];
  16751. }
  16752. if (splitNotFound === key && o.parseMissingKey) {
  16753. notFound = o.parseMissingKey(notFound);
  16754. }
  16755. if (found === undefined) {
  16756. notFound = applyReplacement(notFound, options);
  16757. notFound = applyReuse(notFound, options);
  16758. if (postProcessor && postProcessors[postProcessor]) {
  16759. var val = _getDefaultValue(key, options);
  16760. found = postProcessors[postProcessor](val, key, options);
  16761. }
  16762. }
  16763. return (found !== undefined) ? found : notFound;
  16764. }
  16765. function _find(key, options) {
  16766. options = options || {};
  16767. var optionWithoutCount, translated
  16768. , notFound = _getDefaultValue(key, options)
  16769. , lngs = languages;
  16770. if (!resStore) { return notFound; } // no resStore to translate from
  16771. // CI mode
  16772. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16773. // passed in lng
  16774. if (options.lngs) lngs = options.lngs;
  16775. if (options.lng) {
  16776. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16777. if (!resStore[lngs[0]]) {
  16778. var oldAsync = o.getAsync;
  16779. o.getAsync = false;
  16780. i18n.sync.load(lngs, o, function(err, store) {
  16781. f.extend(resStore, store);
  16782. o.getAsync = oldAsync;
  16783. });
  16784. }
  16785. }
  16786. var ns = options.ns || o.ns.defaultNs;
  16787. if (key.indexOf(o.nsseparator) > -1) {
  16788. var parts = key.split(o.nsseparator);
  16789. ns = parts[0];
  16790. key = parts[1];
  16791. }
  16792. if (hasContext(options)) {
  16793. optionWithoutCount = f.extend({}, options);
  16794. delete optionWithoutCount.context;
  16795. optionWithoutCount.defaultValue = o.contextNotFound;
  16796. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16797. translated = translate(contextKey, optionWithoutCount);
  16798. if (translated != o.contextNotFound) {
  16799. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16800. } // else continue translation with original/nonContext key
  16801. }
  16802. if (needsPlural(options, lngs[0])) {
  16803. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16804. delete optionWithoutCount.count;
  16805. delete optionWithoutCount.lng;
  16806. optionWithoutCount.defaultValue = o.pluralNotFound;
  16807. var pluralKey;
  16808. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16809. pluralKey = ns + o.nsseparator + key;
  16810. } else {
  16811. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16812. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16813. if (pluralExtension >= 0) {
  16814. pluralKey = pluralKey + '_' + pluralExtension;
  16815. } else if (pluralExtension === 1) {
  16816. pluralKey = ns + o.nsseparator + key; // singular
  16817. }
  16818. }
  16819. translated = translate(pluralKey, optionWithoutCount);
  16820. if (translated != o.pluralNotFound) {
  16821. return applyReplacement(translated, {
  16822. count: options.count,
  16823. interpolationPrefix: options.interpolationPrefix,
  16824. interpolationSuffix: options.interpolationSuffix
  16825. }); // apply replacement for count only
  16826. } else if (lngs.length > 1) {
  16827. // remove failed lng
  16828. var clone = lngs.slice();
  16829. clone.shift();
  16830. options = f.extend(options, { lngs: clone });
  16831. delete options.lng;
  16832. // retry with fallbacks
  16833. translated = translate(ns + o.nsseparator + key, options);
  16834. if (translated != o.pluralNotFound) return translated;
  16835. } else {
  16836. return translated;
  16837. }
  16838. }
  16839. if (needsIndefiniteArticle(options)) {
  16840. var optionsWithoutIndef = f.extend({}, options);
  16841. delete optionsWithoutIndef.indefinite_article;
  16842. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16843. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16844. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16845. translated = translate(indefiniteKey, optionsWithoutIndef);
  16846. if (translated != o.indefiniteNotFound) {
  16847. return translated;
  16848. }
  16849. }
  16850. var found;
  16851. var keys = key.split(o.keyseparator);
  16852. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16853. if (found !== undefined) break;
  16854. var l = lngs[i];
  16855. var x = 0;
  16856. var value = resStore[l] && resStore[l][ns];
  16857. while (keys[x]) {
  16858. value = value && value[keys[x]];
  16859. x++;
  16860. }
  16861. if (value !== undefined) {
  16862. var valueType = Object.prototype.toString.apply(value);
  16863. if (typeof value === 'string') {
  16864. value = applyReplacement(value, options);
  16865. value = applyReuse(value, options);
  16866. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16867. value = value.join('\n');
  16868. value = applyReplacement(value, options);
  16869. value = applyReuse(value, options);
  16870. } else if (value === null && o.fallbackOnNull === true) {
  16871. value = undefined;
  16872. } else if (value !== null) {
  16873. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16874. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16875. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16876. } else {
  16877. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16878. 'returned an object instead of string.';
  16879. f.log(value);
  16880. }
  16881. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16882. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16883. f.each(value, function(m) {
  16884. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16885. });
  16886. value = copy;
  16887. }
  16888. }
  16889. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16890. value = undefined;
  16891. found = value;
  16892. }
  16893. }
  16894. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16895. // set flag for fallback lookup - avoid recursion
  16896. options.isFallbackLookup = true;
  16897. if (o.fallbackNS.length) {
  16898. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16899. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16900. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16901. /* compare value without namespace */
  16902. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16903. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16904. if (foundValue !== notFoundValue) break;
  16905. }
  16906. }
  16907. } else {
  16908. found = _find(key, options); // fallback to default NS
  16909. }
  16910. options.isFallbackLookup = false;
  16911. }
  16912. return found;
  16913. }
  16914. function detectLanguage() {
  16915. var detectedLng;
  16916. var whitelist = o.lngWhitelist || [];
  16917. var userLngChoices = [];
  16918. // get from qs
  16919. var qsParm = [];
  16920. if (typeof window !== 'undefined') {
  16921. (function() {
  16922. var query = window.location.search.substring(1);
  16923. var params = query.split('&');
  16924. for (var i=0; i<params.length; i++) {
  16925. var pos = params[i].indexOf('=');
  16926. if (pos > 0) {
  16927. var key = params[i].substring(0,pos);
  16928. if (key == o.detectLngQS) {
  16929. userLngChoices.push(params[i].substring(pos+1));
  16930. }
  16931. }
  16932. }
  16933. })();
  16934. }
  16935. // get from cookie
  16936. if (o.useCookie && typeof document !== 'undefined') {
  16937. var c = f.cookie.read(o.cookieName);
  16938. if (c) userLngChoices.push(c);
  16939. }
  16940. // get from localStorage
  16941. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16942. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16943. }
  16944. // get from navigator
  16945. if (typeof navigator !== 'undefined') {
  16946. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16947. for (var i=0;i<navigator.languages.length;i++) {
  16948. userLngChoices.push(navigator.languages[i]);
  16949. }
  16950. }
  16951. if (navigator.userLanguage) {
  16952. userLngChoices.push(navigator.userLanguage);
  16953. }
  16954. if (navigator.language) {
  16955. userLngChoices.push(navigator.language);
  16956. }
  16957. }
  16958. (function() {
  16959. for (var i=0;i<userLngChoices.length;i++) {
  16960. var lng = userLngChoices[i];
  16961. if (lng.indexOf('-') > -1) {
  16962. var parts = lng.split('-');
  16963. lng = o.lowerCaseLng ?
  16964. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16965. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16966. }
  16967. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16968. detectedLng = lng;
  16969. break;
  16970. }
  16971. }
  16972. })();
  16973. //fallback
  16974. if (!detectedLng){
  16975. detectedLng = o.fallbackLng[0];
  16976. }
  16977. return detectedLng;
  16978. }
  16979. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16980. /* [code, name, numbers, pluralsType] */
  16981. var _rules = [
  16982. ["ach", "Acholi", [1,2], 1],
  16983. ["af", "Afrikaans",[1,2], 2],
  16984. ["ak", "Akan", [1,2], 1],
  16985. ["am", "Amharic", [1,2], 1],
  16986. ["an", "Aragonese",[1,2], 2],
  16987. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16988. ["arn", "Mapudungun",[1,2], 1],
  16989. ["ast", "Asturian", [1,2], 2],
  16990. ["ay", "Aymará", [1], 3],
  16991. ["az", "Azerbaijani",[1,2],2],
  16992. ["be", "Belarusian",[1,2,5],4],
  16993. ["bg", "Bulgarian",[1,2], 2],
  16994. ["bn", "Bengali", [1,2], 2],
  16995. ["bo", "Tibetan", [1], 3],
  16996. ["br", "Breton", [1,2], 1],
  16997. ["bs", "Bosnian", [1,2,5],4],
  16998. ["ca", "Catalan", [1,2], 2],
  16999. ["cgg", "Chiga", [1], 3],
  17000. ["cs", "Czech", [1,2,5],6],
  17001. ["csb", "Kashubian",[1,2,5],7],
  17002. ["cy", "Welsh", [1,2,3,8],8],
  17003. ["da", "Danish", [1,2], 2],
  17004. ["de", "German", [1,2], 2],
  17005. ["dev", "Development Fallback", [1,2], 2],
  17006. ["dz", "Dzongkha", [1], 3],
  17007. ["el", "Greek", [1,2], 2],
  17008. ["en", "English", [1,2], 2],
  17009. ["eo", "Esperanto",[1,2], 2],
  17010. ["es", "Spanish", [1,2], 2],
  17011. ["es_ar","Argentinean Spanish", [1,2], 2],
  17012. ["et", "Estonian", [1,2], 2],
  17013. ["eu", "Basque", [1,2], 2],
  17014. ["fa", "Persian", [1], 3],
  17015. ["fi", "Finnish", [1,2], 2],
  17016. ["fil", "Filipino", [1,2], 1],
  17017. ["fo", "Faroese", [1,2], 2],
  17018. ["fr", "French", [1,2], 9],
  17019. ["fur", "Friulian", [1,2], 2],
  17020. ["fy", "Frisian", [1,2], 2],
  17021. ["ga", "Irish", [1,2,3,7,11],10],
  17022. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  17023. ["gl", "Galician", [1,2], 2],
  17024. ["gu", "Gujarati", [1,2], 2],
  17025. ["gun", "Gun", [1,2], 1],
  17026. ["ha", "Hausa", [1,2], 2],
  17027. ["he", "Hebrew", [1,2], 2],
  17028. ["hi", "Hindi", [1,2], 2],
  17029. ["hr", "Croatian", [1,2,5],4],
  17030. ["hu", "Hungarian",[1,2], 2],
  17031. ["hy", "Armenian", [1,2], 2],
  17032. ["ia", "Interlingua",[1,2],2],
  17033. ["id", "Indonesian",[1], 3],
  17034. ["is", "Icelandic",[1,2], 12],
  17035. ["it", "Italian", [1,2], 2],
  17036. ["ja", "Japanese", [1], 3],
  17037. ["jbo", "Lojban", [1], 3],
  17038. ["jv", "Javanese", [0,1], 13],
  17039. ["ka", "Georgian", [1], 3],
  17040. ["kk", "Kazakh", [1], 3],
  17041. ["km", "Khmer", [1], 3],
  17042. ["kn", "Kannada", [1,2], 2],
  17043. ["ko", "Korean", [1], 3],
  17044. ["ku", "Kurdish", [1,2], 2],
  17045. ["kw", "Cornish", [1,2,3,4],14],
  17046. ["ky", "Kyrgyz", [1], 3],
  17047. ["lb", "Letzeburgesch",[1,2],2],
  17048. ["ln", "Lingala", [1,2], 1],
  17049. ["lo", "Lao", [1], 3],
  17050. ["lt", "Lithuanian",[1,2,10],15],
  17051. ["lv", "Latvian", [1,2,0],16],
  17052. ["mai", "Maithili", [1,2], 2],
  17053. ["mfe", "Mauritian Creole",[1,2],1],
  17054. ["mg", "Malagasy", [1,2], 1],
  17055. ["mi", "Maori", [1,2], 1],
  17056. ["mk", "Macedonian",[1,2],17],
  17057. ["ml", "Malayalam",[1,2], 2],
  17058. ["mn", "Mongolian",[1,2], 2],
  17059. ["mnk", "Mandinka", [0,1,2],18],
  17060. ["mr", "Marathi", [1,2], 2],
  17061. ["ms", "Malay", [1], 3],
  17062. ["mt", "Maltese", [1,2,11,20],19],
  17063. ["nah", "Nahuatl", [1,2], 2],
  17064. ["nap", "Neapolitan",[1,2], 2],
  17065. ["nb", "Norwegian Bokmal",[1,2],2],
  17066. ["ne", "Nepali", [1,2], 2],
  17067. ["nl", "Dutch", [1,2], 2],
  17068. ["nn", "Norwegian Nynorsk",[1,2],2],
  17069. ["no", "Norwegian",[1,2], 2],
  17070. ["nso", "Northern Sotho",[1,2],2],
  17071. ["oc", "Occitan", [1,2], 1],
  17072. ["or", "Oriya", [2,1], 2],
  17073. ["pa", "Punjabi", [1,2], 2],
  17074. ["pap", "Papiamento",[1,2], 2],
  17075. ["pl", "Polish", [1,2,5],7],
  17076. ["pms", "Piemontese",[1,2], 2],
  17077. ["ps", "Pashto", [1,2], 2],
  17078. ["pt", "Portuguese",[1,2], 2],
  17079. ["pt_br","Brazilian Portuguese",[1,2], 2],
  17080. ["rm", "Romansh", [1,2], 2],
  17081. ["ro", "Romanian", [1,2,20],20],
  17082. ["ru", "Russian", [1,2,5],4],
  17083. ["sah", "Yakut", [1], 3],
  17084. ["sco", "Scots", [1,2], 2],
  17085. ["se", "Northern Sami",[1,2], 2],
  17086. ["si", "Sinhala", [1,2], 2],
  17087. ["sk", "Slovak", [1,2,5],6],
  17088. ["sl", "Slovenian",[5,1,2,3],21],
  17089. ["so", "Somali", [1,2], 2],
  17090. ["son", "Songhay", [1,2], 2],
  17091. ["sq", "Albanian", [1,2], 2],
  17092. ["sr", "Serbian", [1,2,5],4],
  17093. ["su", "Sundanese",[1], 3],
  17094. ["sv", "Swedish", [1,2], 2],
  17095. ["sw", "Swahili", [1,2], 2],
  17096. ["ta", "Tamil", [1,2], 2],
  17097. ["te", "Telugu", [1,2], 2],
  17098. ["tg", "Tajik", [1,2], 1],
  17099. ["th", "Thai", [1], 3],
  17100. ["ti", "Tigrinya", [1,2], 1],
  17101. ["tk", "Turkmen", [1,2], 2],
  17102. ["tr", "Turkish", [1,2], 1],
  17103. ["tt", "Tatar", [1], 3],
  17104. ["ug", "Uyghur", [1], 3],
  17105. ["uk", "Ukrainian",[1,2,5],4],
  17106. ["ur", "Urdu", [1,2], 2],
  17107. ["uz", "Uzbek", [1,2], 1],
  17108. ["vi", "Vietnamese",[1], 3],
  17109. ["wa", "Walloon", [1,2], 1],
  17110. ["wo", "Wolof", [1], 3],
  17111. ["yo", "Yoruba", [1,2], 2],
  17112. ["zh", "Chinese", [1], 3]
  17113. ];
  17114. var _rulesPluralsTypes = {
  17115. 1: function(n) {return Number(n > 1);},
  17116. 2: function(n) {return Number(n != 1);},
  17117. 3: function(n) {return 0;},
  17118. 4: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  17119. 5: function(n) {return Number(n===0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);},
  17120. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  17121. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  17122. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  17123. 9: function(n) {return Number(n >= 2);},
  17124. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  17125. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  17126. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  17127. 13: function(n) {return Number(n !== 0);},
  17128. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  17129. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  17130. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  17131. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  17132. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  17133. 19: function(n) {return Number(n==1 ? 0 : n===0 || ( n%100>1 && n%100<11) ? 1 : (n%100>10 && n%100<20 ) ? 2 : 3);},
  17134. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  17135. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  17136. };
  17137. var pluralExtensions = {
  17138. rules: (function () {
  17139. var l, rules = {};
  17140. for (l=_rules.length; l-- ;) {
  17141. rules[_rules[l][0]] = {
  17142. name: _rules[l][1],
  17143. numbers: _rules[l][2],
  17144. plurals: _rulesPluralsTypes[_rules[l][3]]
  17145. }
  17146. }
  17147. return rules;
  17148. }()),
  17149. // you can add your own pluralExtensions
  17150. addRule: function(lng, obj) {
  17151. pluralExtensions.rules[lng] = obj;
  17152. },
  17153. setCurrentLng: function(lng) {
  17154. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  17155. var parts = lng.split('-');
  17156. pluralExtensions.currentRule = {
  17157. lng: lng,
  17158. rule: pluralExtensions.rules[parts[0]]
  17159. };
  17160. }
  17161. },
  17162. needsPlural: function(lng, count) {
  17163. var parts = lng.split('-');
  17164. var ext;
  17165. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  17166. ext = pluralExtensions.currentRule.rule;
  17167. } else {
  17168. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  17169. }
  17170. if (ext && ext.numbers.length <= 1) {
  17171. return false;
  17172. } else {
  17173. return this.get(lng, count) !== 1;
  17174. }
  17175. },
  17176. get: function(lng, count) {
  17177. var parts = lng.split('-');
  17178. function getResult(l, c) {
  17179. var ext;
  17180. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  17181. ext = pluralExtensions.currentRule.rule;
  17182. } else {
  17183. ext = pluralExtensions.rules[l];
  17184. }
  17185. if (ext) {
  17186. var i;
  17187. if (ext.noAbs) {
  17188. i = ext.plurals(c);
  17189. } else {
  17190. i = ext.plurals(Math.abs(c));
  17191. }
  17192. var number = ext.numbers[i];
  17193. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  17194. if (number === 2) {
  17195. number = -1; // regular plural
  17196. } else if (number === 1) {
  17197. number = 1; // singular
  17198. }
  17199. }//console.log(count + '-' + number);
  17200. return number;
  17201. } else {
  17202. return c === 1 ? '1' : '-1';
  17203. }
  17204. }
  17205. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  17206. }
  17207. };
  17208. var postProcessors = {};
  17209. var addPostProcessor = function(name, fc) {
  17210. postProcessors[name] = fc;
  17211. };
  17212. // sprintf support
  17213. var sprintf = (function() {
  17214. function get_type(variable) {
  17215. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  17216. }
  17217. function str_repeat(input, multiplier) {
  17218. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  17219. return output.join('');
  17220. }
  17221. var str_format = function() {
  17222. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  17223. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  17224. }
  17225. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  17226. };
  17227. str_format.format = function(parse_tree, argv) {
  17228. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  17229. for (i = 0; i < tree_length; i++) {
  17230. node_type = get_type(parse_tree[i]);
  17231. if (node_type === 'string') {
  17232. output.push(parse_tree[i]);
  17233. }
  17234. else if (node_type === 'array') {
  17235. match = parse_tree[i]; // convenience purposes only
  17236. if (match[2]) { // keyword argument
  17237. arg = argv[cursor];
  17238. for (k = 0; k < match[2].length; k++) {
  17239. if (!arg.hasOwnProperty(match[2][k])) {
  17240. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  17241. }
  17242. arg = arg[match[2][k]];
  17243. }
  17244. }
  17245. else if (match[1]) { // positional argument (explicit)
  17246. arg = argv[match[1]];
  17247. }
  17248. else { // positional argument (implicit)
  17249. arg = argv[cursor++];
  17250. }
  17251. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  17252. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  17253. }
  17254. switch (match[8]) {
  17255. case 'b': arg = arg.toString(2); break;
  17256. case 'c': arg = String.fromCharCode(arg); break;
  17257. case 'd': arg = parseInt(arg, 10); break;
  17258. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  17259. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  17260. case 'o': arg = arg.toString(8); break;
  17261. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  17262. case 'u': arg = Math.abs(arg); break;
  17263. case 'x': arg = arg.toString(16); break;
  17264. case 'X': arg = arg.toString(16).toUpperCase(); break;
  17265. }
  17266. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  17267. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  17268. pad_length = match[6] - String(arg).length;
  17269. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  17270. output.push(match[5] ? arg + pad : pad + arg);
  17271. }
  17272. }
  17273. return output.join('');
  17274. };
  17275. str_format.cache = {};
  17276. str_format.parse = function(fmt) {
  17277. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  17278. while (_fmt) {
  17279. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  17280. parse_tree.push(match[0]);
  17281. }
  17282. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  17283. parse_tree.push('%');
  17284. }
  17285. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  17286. if (match[2]) {
  17287. arg_names |= 1;
  17288. var field_list = [], replacement_field = match[2], field_match = [];
  17289. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17290. field_list.push(field_match[1]);
  17291. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  17292. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17293. field_list.push(field_match[1]);
  17294. }
  17295. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  17296. field_list.push(field_match[1]);
  17297. }
  17298. else {
  17299. throw('[sprintf] huh?');
  17300. }
  17301. }
  17302. }
  17303. else {
  17304. throw('[sprintf] huh?');
  17305. }
  17306. match[2] = field_list;
  17307. }
  17308. else {
  17309. arg_names |= 2;
  17310. }
  17311. if (arg_names === 3) {
  17312. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  17313. }
  17314. parse_tree.push(match);
  17315. }
  17316. else {
  17317. throw('[sprintf] huh?');
  17318. }
  17319. _fmt = _fmt.substring(match[0].length);
  17320. }
  17321. return parse_tree;
  17322. };
  17323. return str_format;
  17324. })();
  17325. var vsprintf = function(fmt, argv) {
  17326. argv.unshift(fmt);
  17327. return sprintf.apply(null, argv);
  17328. };
  17329. addPostProcessor("sprintf", function(val, key, opts) {
  17330. if (!opts.sprintf) return val;
  17331. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  17332. return vsprintf(val, opts.sprintf);
  17333. } else if (typeof opts.sprintf === 'object') {
  17334. return sprintf(val, opts.sprintf);
  17335. }
  17336. return val;
  17337. });
  17338. // public api interface
  17339. i18n.init = init;
  17340. i18n.setLng = setLng;
  17341. i18n.preload = preload;
  17342. i18n.addResourceBundle = addResourceBundle;
  17343. i18n.hasResourceBundle = hasResourceBundle;
  17344. i18n.addResource = addResource;
  17345. i18n.addResources = addResources;
  17346. i18n.removeResourceBundle = removeResourceBundle;
  17347. i18n.loadNamespace = loadNamespace;
  17348. i18n.loadNamespaces = loadNamespaces;
  17349. i18n.setDefaultNamespace = setDefaultNamespace;
  17350. i18n.t = translate;
  17351. i18n.translate = translate;
  17352. i18n.exists = exists;
  17353. i18n.detectLanguage = f.detectLanguage;
  17354. i18n.pluralExtensions = pluralExtensions;
  17355. i18n.sync = sync;
  17356. i18n.functions = f;
  17357. i18n.lng = lng;
  17358. i18n.addPostProcessor = addPostProcessor;
  17359. i18n.options = o;
  17360. })();
  17361. },{"jquery":"jquery"}],64:[function(require,module,exports){
  17362. // Top level file is just a mixin of submodules & constants
  17363. 'use strict';
  17364. var assign = require('./lib/utils/common').assign;
  17365. var deflate = require('./lib/deflate');
  17366. var inflate = require('./lib/inflate');
  17367. var constants = require('./lib/zlib/constants');
  17368. var pako = {};
  17369. assign(pako, deflate, inflate, constants);
  17370. module.exports = pako;
  17371. },{"./lib/deflate":65,"./lib/inflate":66,"./lib/utils/common":67,"./lib/zlib/constants":70}],65:[function(require,module,exports){
  17372. 'use strict';
  17373. var zlib_deflate = require('./zlib/deflate.js');
  17374. var utils = require('./utils/common');
  17375. var strings = require('./utils/strings');
  17376. var msg = require('./zlib/messages');
  17377. var zstream = require('./zlib/zstream');
  17378. var toString = Object.prototype.toString;
  17379. /* Public constants ==========================================================*/
  17380. /* ===========================================================================*/
  17381. var Z_NO_FLUSH = 0;
  17382. var Z_FINISH = 4;
  17383. var Z_OK = 0;
  17384. var Z_STREAM_END = 1;
  17385. var Z_DEFAULT_COMPRESSION = -1;
  17386. var Z_DEFAULT_STRATEGY = 0;
  17387. var Z_DEFLATED = 8;
  17388. /* ===========================================================================*/
  17389. /**
  17390. * class Deflate
  17391. *
  17392. * Generic JS-style wrapper for zlib calls. If you don't need
  17393. * streaming behaviour - use more simple functions: [[deflate]],
  17394. * [[deflateRaw]] and [[gzip]].
  17395. **/
  17396. /* internal
  17397. * Deflate.chunks -> Array
  17398. *
  17399. * Chunks of output data, if [[Deflate#onData]] not overriden.
  17400. **/
  17401. /**
  17402. * Deflate.result -> Uint8Array|Array
  17403. *
  17404. * Compressed result, generated by default [[Deflate#onData]]
  17405. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  17406. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  17407. **/
  17408. /**
  17409. * Deflate.err -> Number
  17410. *
  17411. * Error code after deflate finished. 0 (Z_OK) on success.
  17412. * You will not need it in real life, because deflate errors
  17413. * are possible only on wrong options or bad `onData` / `onEnd`
  17414. * custom handlers.
  17415. **/
  17416. /**
  17417. * Deflate.msg -> String
  17418. *
  17419. * Error message, if [[Deflate.err]] != 0
  17420. **/
  17421. /**
  17422. * new Deflate(options)
  17423. * - options (Object): zlib deflate options.
  17424. *
  17425. * Creates new deflator instance with specified params. Throws exception
  17426. * on bad params. Supported options:
  17427. *
  17428. * - `level`
  17429. * - `windowBits`
  17430. * - `memLevel`
  17431. * - `strategy`
  17432. *
  17433. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17434. * for more information on these.
  17435. *
  17436. * Additional options, for internal needs:
  17437. *
  17438. * - `chunkSize` - size of generated data chunks (16K by default)
  17439. * - `raw` (Boolean) - do raw deflate
  17440. * - `gzip` (Boolean) - create gzip wrapper
  17441. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17442. * (each char code [0..255])
  17443. * - `header` (Object) - custom header for gzip
  17444. * - `text` (Boolean) - true if compressed data believed to be text
  17445. * - `time` (Number) - modification time, unix timestamp
  17446. * - `os` (Number) - operation system code
  17447. * - `extra` (Array) - array of bytes with extra data (max 65536)
  17448. * - `name` (String) - file name (binary string)
  17449. * - `comment` (String) - comment (binary string)
  17450. * - `hcrc` (Boolean) - true if header crc should be added
  17451. *
  17452. * ##### Example:
  17453. *
  17454. * ```javascript
  17455. * var pako = require('pako')
  17456. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17457. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17458. *
  17459. * var deflate = new pako.Deflate({ level: 3});
  17460. *
  17461. * deflate.push(chunk1, false);
  17462. * deflate.push(chunk2, true); // true -> last chunk
  17463. *
  17464. * if (deflate.err) { throw new Error(deflate.err); }
  17465. *
  17466. * console.log(deflate.result);
  17467. * ```
  17468. **/
  17469. var Deflate = function(options) {
  17470. this.options = utils.assign({
  17471. level: Z_DEFAULT_COMPRESSION,
  17472. method: Z_DEFLATED,
  17473. chunkSize: 16384,
  17474. windowBits: 15,
  17475. memLevel: 8,
  17476. strategy: Z_DEFAULT_STRATEGY,
  17477. to: ''
  17478. }, options || {});
  17479. var opt = this.options;
  17480. if (opt.raw && (opt.windowBits > 0)) {
  17481. opt.windowBits = -opt.windowBits;
  17482. }
  17483. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17484. opt.windowBits += 16;
  17485. }
  17486. this.err = 0; // error code, if happens (0 = Z_OK)
  17487. this.msg = ''; // error message
  17488. this.ended = false; // used to avoid multiple onEnd() calls
  17489. this.chunks = []; // chunks of compressed data
  17490. this.strm = new zstream();
  17491. this.strm.avail_out = 0;
  17492. var status = zlib_deflate.deflateInit2(
  17493. this.strm,
  17494. opt.level,
  17495. opt.method,
  17496. opt.windowBits,
  17497. opt.memLevel,
  17498. opt.strategy
  17499. );
  17500. if (status !== Z_OK) {
  17501. throw new Error(msg[status]);
  17502. }
  17503. if (opt.header) {
  17504. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  17505. }
  17506. };
  17507. /**
  17508. * Deflate#push(data[, mode]) -> Boolean
  17509. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  17510. * converted to utf8 byte sequence.
  17511. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17512. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17513. *
  17514. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  17515. * new compressed chunks. Returns `true` on success. The last data block must have
  17516. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17517. * [[Deflate#onEnd]].
  17518. *
  17519. * On fail call [[Deflate#onEnd]] with error code and return false.
  17520. *
  17521. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17522. * array format is detected automatically). Also, don't skip last param and always
  17523. * use the same type in your code (boolean or number). That will improve JS speed.
  17524. *
  17525. * For regular `Array`-s make sure all elements are [0..255].
  17526. *
  17527. * ##### Example
  17528. *
  17529. * ```javascript
  17530. * push(chunk, false); // push one of data chunks
  17531. * ...
  17532. * push(chunk, true); // push last chunk
  17533. * ```
  17534. **/
  17535. Deflate.prototype.push = function(data, mode) {
  17536. var strm = this.strm;
  17537. var chunkSize = this.options.chunkSize;
  17538. var status, _mode;
  17539. if (this.ended) { return false; }
  17540. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17541. // Convert data if needed
  17542. if (typeof data === 'string') {
  17543. // If we need to compress text, change encoding to utf8.
  17544. strm.input = strings.string2buf(data);
  17545. } else if (toString.call(data) === '[object ArrayBuffer]') {
  17546. strm.input = new Uint8Array(data);
  17547. } else {
  17548. strm.input = data;
  17549. }
  17550. strm.next_in = 0;
  17551. strm.avail_in = strm.input.length;
  17552. do {
  17553. if (strm.avail_out === 0) {
  17554. strm.output = new utils.Buf8(chunkSize);
  17555. strm.next_out = 0;
  17556. strm.avail_out = chunkSize;
  17557. }
  17558. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17559. if (status !== Z_STREAM_END && status !== Z_OK) {
  17560. this.onEnd(status);
  17561. this.ended = true;
  17562. return false;
  17563. }
  17564. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17565. if (this.options.to === 'string') {
  17566. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17567. } else {
  17568. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17569. }
  17570. }
  17571. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17572. // Finalize on the last chunk.
  17573. if (_mode === Z_FINISH) {
  17574. status = zlib_deflate.deflateEnd(this.strm);
  17575. this.onEnd(status);
  17576. this.ended = true;
  17577. return status === Z_OK;
  17578. }
  17579. return true;
  17580. };
  17581. /**
  17582. * Deflate#onData(chunk) -> Void
  17583. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17584. * on js engine support. When string output requested, each chunk
  17585. * will be string.
  17586. *
  17587. * By default, stores data blocks in `chunks[]` property and glue
  17588. * those in `onEnd`. Override this handler, if you need another behaviour.
  17589. **/
  17590. Deflate.prototype.onData = function(chunk) {
  17591. this.chunks.push(chunk);
  17592. };
  17593. /**
  17594. * Deflate#onEnd(status) -> Void
  17595. * - status (Number): deflate status. 0 (Z_OK) on success,
  17596. * other if not.
  17597. *
  17598. * Called once after you tell deflate that input stream complete
  17599. * or error happenned. By default - join collected chunks,
  17600. * free memory and fill `results` / `err` properties.
  17601. **/
  17602. Deflate.prototype.onEnd = function(status) {
  17603. // On success - join
  17604. if (status === Z_OK) {
  17605. if (this.options.to === 'string') {
  17606. this.result = this.chunks.join('');
  17607. } else {
  17608. this.result = utils.flattenChunks(this.chunks);
  17609. }
  17610. }
  17611. this.chunks = [];
  17612. this.err = status;
  17613. this.msg = this.strm.msg;
  17614. };
  17615. /**
  17616. * deflate(data[, options]) -> Uint8Array|Array|String
  17617. * - data (Uint8Array|Array|String): input data to compress.
  17618. * - options (Object): zlib deflate options.
  17619. *
  17620. * Compress `data` with deflate alrorythm and `options`.
  17621. *
  17622. * Supported options are:
  17623. *
  17624. * - level
  17625. * - windowBits
  17626. * - memLevel
  17627. * - strategy
  17628. *
  17629. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17630. * for more information on these.
  17631. *
  17632. * Sugar (options):
  17633. *
  17634. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17635. * negative windowBits implicitly.
  17636. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17637. * (each char code [0..255])
  17638. *
  17639. * ##### Example:
  17640. *
  17641. * ```javascript
  17642. * var pako = require('pako')
  17643. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17644. *
  17645. * console.log(pako.deflate(data));
  17646. * ```
  17647. **/
  17648. function deflate(input, options) {
  17649. var deflator = new Deflate(options);
  17650. deflator.push(input, true);
  17651. // That will never happens, if you don't cheat with options :)
  17652. if (deflator.err) { throw deflator.msg; }
  17653. return deflator.result;
  17654. }
  17655. /**
  17656. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17657. * - data (Uint8Array|Array|String): input data to compress.
  17658. * - options (Object): zlib deflate options.
  17659. *
  17660. * The same as [[deflate]], but creates raw data, without wrapper
  17661. * (header and adler32 crc).
  17662. **/
  17663. function deflateRaw(input, options) {
  17664. options = options || {};
  17665. options.raw = true;
  17666. return deflate(input, options);
  17667. }
  17668. /**
  17669. * gzip(data[, options]) -> Uint8Array|Array|String
  17670. * - data (Uint8Array|Array|String): input data to compress.
  17671. * - options (Object): zlib deflate options.
  17672. *
  17673. * The same as [[deflate]], but create gzip wrapper instead of
  17674. * deflate one.
  17675. **/
  17676. function gzip(input, options) {
  17677. options = options || {};
  17678. options.gzip = true;
  17679. return deflate(input, options);
  17680. }
  17681. exports.Deflate = Deflate;
  17682. exports.deflate = deflate;
  17683. exports.deflateRaw = deflateRaw;
  17684. exports.gzip = gzip;
  17685. },{"./utils/common":67,"./utils/strings":68,"./zlib/deflate.js":72,"./zlib/messages":77,"./zlib/zstream":79}],66:[function(require,module,exports){
  17686. 'use strict';
  17687. var zlib_inflate = require('./zlib/inflate.js');
  17688. var utils = require('./utils/common');
  17689. var strings = require('./utils/strings');
  17690. var c = require('./zlib/constants');
  17691. var msg = require('./zlib/messages');
  17692. var zstream = require('./zlib/zstream');
  17693. var gzheader = require('./zlib/gzheader');
  17694. var toString = Object.prototype.toString;
  17695. /**
  17696. * class Inflate
  17697. *
  17698. * Generic JS-style wrapper for zlib calls. If you don't need
  17699. * streaming behaviour - use more simple functions: [[inflate]]
  17700. * and [[inflateRaw]].
  17701. **/
  17702. /* internal
  17703. * inflate.chunks -> Array
  17704. *
  17705. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17706. **/
  17707. /**
  17708. * Inflate.result -> Uint8Array|Array|String
  17709. *
  17710. * Uncompressed result, generated by default [[Inflate#onData]]
  17711. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17712. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17713. **/
  17714. /**
  17715. * Inflate.err -> Number
  17716. *
  17717. * Error code after inflate finished. 0 (Z_OK) on success.
  17718. * Should be checked if broken data possible.
  17719. **/
  17720. /**
  17721. * Inflate.msg -> String
  17722. *
  17723. * Error message, if [[Inflate.err]] != 0
  17724. **/
  17725. /**
  17726. * new Inflate(options)
  17727. * - options (Object): zlib inflate options.
  17728. *
  17729. * Creates new inflator instance with specified params. Throws exception
  17730. * on bad params. Supported options:
  17731. *
  17732. * - `windowBits`
  17733. *
  17734. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17735. * for more information on these.
  17736. *
  17737. * Additional options, for internal needs:
  17738. *
  17739. * - `chunkSize` - size of generated data chunks (16K by default)
  17740. * - `raw` (Boolean) - do raw inflate
  17741. * - `to` (String) - if equal to 'string', then result will be converted
  17742. * from utf8 to utf16 (javascript) string. When string output requested,
  17743. * chunk length can differ from `chunkSize`, depending on content.
  17744. *
  17745. * By default, when no options set, autodetect deflate/gzip data format via
  17746. * wrapper header.
  17747. *
  17748. * ##### Example:
  17749. *
  17750. * ```javascript
  17751. * var pako = require('pako')
  17752. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17753. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17754. *
  17755. * var inflate = new pako.Inflate({ level: 3});
  17756. *
  17757. * inflate.push(chunk1, false);
  17758. * inflate.push(chunk2, true); // true -> last chunk
  17759. *
  17760. * if (inflate.err) { throw new Error(inflate.err); }
  17761. *
  17762. * console.log(inflate.result);
  17763. * ```
  17764. **/
  17765. var Inflate = function(options) {
  17766. this.options = utils.assign({
  17767. chunkSize: 16384,
  17768. windowBits: 0,
  17769. to: ''
  17770. }, options || {});
  17771. var opt = this.options;
  17772. // Force window size for `raw` data, if not set directly,
  17773. // because we have no header for autodetect.
  17774. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17775. opt.windowBits = -opt.windowBits;
  17776. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17777. }
  17778. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17779. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17780. !(options && options.windowBits)) {
  17781. opt.windowBits += 32;
  17782. }
  17783. // Gzip header has no info about windows size, we can do autodetect only
  17784. // for deflate. So, if window size not set, force it to max when gzip possible
  17785. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17786. // bit 3 (16) -> gzipped data
  17787. // bit 4 (32) -> autodetect gzip/deflate
  17788. if ((opt.windowBits & 15) === 0) {
  17789. opt.windowBits |= 15;
  17790. }
  17791. }
  17792. this.err = 0; // error code, if happens (0 = Z_OK)
  17793. this.msg = ''; // error message
  17794. this.ended = false; // used to avoid multiple onEnd() calls
  17795. this.chunks = []; // chunks of compressed data
  17796. this.strm = new zstream();
  17797. this.strm.avail_out = 0;
  17798. var status = zlib_inflate.inflateInit2(
  17799. this.strm,
  17800. opt.windowBits
  17801. );
  17802. if (status !== c.Z_OK) {
  17803. throw new Error(msg[status]);
  17804. }
  17805. this.header = new gzheader();
  17806. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17807. };
  17808. /**
  17809. * Inflate#push(data[, mode]) -> Boolean
  17810. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  17811. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17812. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17813. *
  17814. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17815. * new output chunks. Returns `true` on success. The last data block must have
  17816. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17817. * [[Inflate#onEnd]].
  17818. *
  17819. * On fail call [[Inflate#onEnd]] with error code and return false.
  17820. *
  17821. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17822. * format is detected automatically). Also, don't skip last param and always
  17823. * use the same type in your code (boolean or number). That will improve JS speed.
  17824. *
  17825. * For regular `Array`-s make sure all elements are [0..255].
  17826. *
  17827. * ##### Example
  17828. *
  17829. * ```javascript
  17830. * push(chunk, false); // push one of data chunks
  17831. * ...
  17832. * push(chunk, true); // push last chunk
  17833. * ```
  17834. **/
  17835. Inflate.prototype.push = function(data, mode) {
  17836. var strm = this.strm;
  17837. var chunkSize = this.options.chunkSize;
  17838. var status, _mode;
  17839. var next_out_utf8, tail, utf8str;
  17840. if (this.ended) { return false; }
  17841. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17842. // Convert data if needed
  17843. if (typeof data === 'string') {
  17844. // Only binary strings can be decompressed on practice
  17845. strm.input = strings.binstring2buf(data);
  17846. } else if (toString.call(data) === '[object ArrayBuffer]') {
  17847. strm.input = new Uint8Array(data);
  17848. } else {
  17849. strm.input = data;
  17850. }
  17851. strm.next_in = 0;
  17852. strm.avail_in = strm.input.length;
  17853. do {
  17854. if (strm.avail_out === 0) {
  17855. strm.output = new utils.Buf8(chunkSize);
  17856. strm.next_out = 0;
  17857. strm.avail_out = chunkSize;
  17858. }
  17859. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17860. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17861. this.onEnd(status);
  17862. this.ended = true;
  17863. return false;
  17864. }
  17865. if (strm.next_out) {
  17866. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17867. if (this.options.to === 'string') {
  17868. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17869. tail = strm.next_out - next_out_utf8;
  17870. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17871. // move tail
  17872. strm.next_out = tail;
  17873. strm.avail_out = chunkSize - tail;
  17874. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17875. this.onData(utf8str);
  17876. } else {
  17877. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17878. }
  17879. }
  17880. }
  17881. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17882. if (status === c.Z_STREAM_END) {
  17883. _mode = c.Z_FINISH;
  17884. }
  17885. // Finalize on the last chunk.
  17886. if (_mode === c.Z_FINISH) {
  17887. status = zlib_inflate.inflateEnd(this.strm);
  17888. this.onEnd(status);
  17889. this.ended = true;
  17890. return status === c.Z_OK;
  17891. }
  17892. return true;
  17893. };
  17894. /**
  17895. * Inflate#onData(chunk) -> Void
  17896. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17897. * on js engine support. When string output requested, each chunk
  17898. * will be string.
  17899. *
  17900. * By default, stores data blocks in `chunks[]` property and glue
  17901. * those in `onEnd`. Override this handler, if you need another behaviour.
  17902. **/
  17903. Inflate.prototype.onData = function(chunk) {
  17904. this.chunks.push(chunk);
  17905. };
  17906. /**
  17907. * Inflate#onEnd(status) -> Void
  17908. * - status (Number): inflate status. 0 (Z_OK) on success,
  17909. * other if not.
  17910. *
  17911. * Called once after you tell inflate that input stream complete
  17912. * or error happenned. By default - join collected chunks,
  17913. * free memory and fill `results` / `err` properties.
  17914. **/
  17915. Inflate.prototype.onEnd = function(status) {
  17916. // On success - join
  17917. if (status === c.Z_OK) {
  17918. if (this.options.to === 'string') {
  17919. // Glue & convert here, until we teach pako to send
  17920. // utf8 alligned strings to onData
  17921. this.result = this.chunks.join('');
  17922. } else {
  17923. this.result = utils.flattenChunks(this.chunks);
  17924. }
  17925. }
  17926. this.chunks = [];
  17927. this.err = status;
  17928. this.msg = this.strm.msg;
  17929. };
  17930. /**
  17931. * inflate(data[, options]) -> Uint8Array|Array|String
  17932. * - data (Uint8Array|Array|String): input data to decompress.
  17933. * - options (Object): zlib inflate options.
  17934. *
  17935. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17936. * format via wrapper header by default. That's why we don't provide
  17937. * separate `ungzip` method.
  17938. *
  17939. * Supported options are:
  17940. *
  17941. * - windowBits
  17942. *
  17943. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17944. * for more information.
  17945. *
  17946. * Sugar (options):
  17947. *
  17948. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17949. * negative windowBits implicitly.
  17950. * - `to` (String) - if equal to 'string', then result will be converted
  17951. * from utf8 to utf16 (javascript) string. When string output requested,
  17952. * chunk length can differ from `chunkSize`, depending on content.
  17953. *
  17954. *
  17955. * ##### Example:
  17956. *
  17957. * ```javascript
  17958. * var pako = require('pako')
  17959. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17960. * , output;
  17961. *
  17962. * try {
  17963. * output = pako.inflate(input);
  17964. * } catch (err)
  17965. * console.log(err);
  17966. * }
  17967. * ```
  17968. **/
  17969. function inflate(input, options) {
  17970. var inflator = new Inflate(options);
  17971. inflator.push(input, true);
  17972. // That will never happens, if you don't cheat with options :)
  17973. if (inflator.err) { throw inflator.msg; }
  17974. return inflator.result;
  17975. }
  17976. /**
  17977. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17978. * - data (Uint8Array|Array|String): input data to decompress.
  17979. * - options (Object): zlib inflate options.
  17980. *
  17981. * The same as [[inflate]], but creates raw data, without wrapper
  17982. * (header and adler32 crc).
  17983. **/
  17984. function inflateRaw(input, options) {
  17985. options = options || {};
  17986. options.raw = true;
  17987. return inflate(input, options);
  17988. }
  17989. /**
  17990. * ungzip(data[, options]) -> Uint8Array|Array|String
  17991. * - data (Uint8Array|Array|String): input data to decompress.
  17992. * - options (Object): zlib inflate options.
  17993. *
  17994. * Just shortcut to [[inflate]], because it autodetects format
  17995. * by header.content. Done for convenience.
  17996. **/
  17997. exports.Inflate = Inflate;
  17998. exports.inflate = inflate;
  17999. exports.inflateRaw = inflateRaw;
  18000. exports.ungzip = inflate;
  18001. },{"./utils/common":67,"./utils/strings":68,"./zlib/constants":70,"./zlib/gzheader":73,"./zlib/inflate.js":75,"./zlib/messages":77,"./zlib/zstream":79}],67:[function(require,module,exports){
  18002. 'use strict';
  18003. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  18004. (typeof Uint16Array !== 'undefined') &&
  18005. (typeof Int32Array !== 'undefined');
  18006. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  18007. var sources = Array.prototype.slice.call(arguments, 1);
  18008. while (sources.length) {
  18009. var source = sources.shift();
  18010. if (!source) { continue; }
  18011. if (typeof(source) !== 'object') {
  18012. throw new TypeError(source + 'must be non-object');
  18013. }
  18014. for (var p in source) {
  18015. if (source.hasOwnProperty(p)) {
  18016. obj[p] = source[p];
  18017. }
  18018. }
  18019. }
  18020. return obj;
  18021. };
  18022. // reduce buffer size, avoiding mem copy
  18023. exports.shrinkBuf = function (buf, size) {
  18024. if (buf.length === size) { return buf; }
  18025. if (buf.subarray) { return buf.subarray(0, size); }
  18026. buf.length = size;
  18027. return buf;
  18028. };
  18029. var fnTyped = {
  18030. arraySet: function (dest, src, src_offs, len, dest_offs) {
  18031. if (src.subarray && dest.subarray) {
  18032. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  18033. return;
  18034. }
  18035. // Fallback to ordinary array
  18036. for(var i=0; i<len; i++) {
  18037. dest[dest_offs + i] = src[src_offs + i];
  18038. }
  18039. },
  18040. // Join array of chunks to single array.
  18041. flattenChunks: function(chunks) {
  18042. var i, l, len, pos, chunk, result;
  18043. // calculate data length
  18044. len = 0;
  18045. for (i=0, l=chunks.length; i<l; i++) {
  18046. len += chunks[i].length;
  18047. }
  18048. // join chunks
  18049. result = new Uint8Array(len);
  18050. pos = 0;
  18051. for (i=0, l=chunks.length; i<l; i++) {
  18052. chunk = chunks[i];
  18053. result.set(chunk, pos);
  18054. pos += chunk.length;
  18055. }
  18056. return result;
  18057. }
  18058. };
  18059. var fnUntyped = {
  18060. arraySet: function (dest, src, src_offs, len, dest_offs) {
  18061. for(var i=0; i<len; i++) {
  18062. dest[dest_offs + i] = src[src_offs + i];
  18063. }
  18064. },
  18065. // Join array of chunks to single array.
  18066. flattenChunks: function(chunks) {
  18067. return [].concat.apply([], chunks);
  18068. }
  18069. };
  18070. // Enable/Disable typed arrays use, for testing
  18071. //
  18072. exports.setTyped = function (on) {
  18073. if (on) {
  18074. exports.Buf8 = Uint8Array;
  18075. exports.Buf16 = Uint16Array;
  18076. exports.Buf32 = Int32Array;
  18077. exports.assign(exports, fnTyped);
  18078. } else {
  18079. exports.Buf8 = Array;
  18080. exports.Buf16 = Array;
  18081. exports.Buf32 = Array;
  18082. exports.assign(exports, fnUntyped);
  18083. }
  18084. };
  18085. exports.setTyped(TYPED_OK);
  18086. },{}],68:[function(require,module,exports){
  18087. // String encode/decode helpers
  18088. 'use strict';
  18089. var utils = require('./common');
  18090. // Quick check if we can use fast array to bin string conversion
  18091. //
  18092. // - apply(Array) can fail on Android 2.2
  18093. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  18094. //
  18095. var STR_APPLY_OK = true;
  18096. var STR_APPLY_UIA_OK = true;
  18097. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  18098. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  18099. // Table with utf8 lengths (calculated by first byte of sequence)
  18100. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  18101. // because max possible codepoint is 0x10ffff
  18102. var _utf8len = new utils.Buf8(256);
  18103. for (var i=0; i<256; i++) {
  18104. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  18105. }
  18106. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  18107. // convert string to array (typed, when possible)
  18108. exports.string2buf = function (str) {
  18109. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  18110. // count binary size
  18111. for (m_pos = 0; m_pos < str_len; m_pos++) {
  18112. c = str.charCodeAt(m_pos);
  18113. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  18114. c2 = str.charCodeAt(m_pos+1);
  18115. if ((c2 & 0xfc00) === 0xdc00) {
  18116. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  18117. m_pos++;
  18118. }
  18119. }
  18120. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  18121. }
  18122. // allocate buffer
  18123. buf = new utils.Buf8(buf_len);
  18124. // convert
  18125. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  18126. c = str.charCodeAt(m_pos);
  18127. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  18128. c2 = str.charCodeAt(m_pos+1);
  18129. if ((c2 & 0xfc00) === 0xdc00) {
  18130. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  18131. m_pos++;
  18132. }
  18133. }
  18134. if (c < 0x80) {
  18135. /* one byte */
  18136. buf[i++] = c;
  18137. } else if (c < 0x800) {
  18138. /* two bytes */
  18139. buf[i++] = 0xC0 | (c >>> 6);
  18140. buf[i++] = 0x80 | (c & 0x3f);
  18141. } else if (c < 0x10000) {
  18142. /* three bytes */
  18143. buf[i++] = 0xE0 | (c >>> 12);
  18144. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  18145. buf[i++] = 0x80 | (c & 0x3f);
  18146. } else {
  18147. /* four bytes */
  18148. buf[i++] = 0xf0 | (c >>> 18);
  18149. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  18150. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  18151. buf[i++] = 0x80 | (c & 0x3f);
  18152. }
  18153. }
  18154. return buf;
  18155. };
  18156. // Helper (used in 2 places)
  18157. function buf2binstring(buf, len) {
  18158. // use fallback for big arrays to avoid stack overflow
  18159. if (len < 65537) {
  18160. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  18161. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  18162. }
  18163. }
  18164. var result = '';
  18165. for(var i=0; i < len; i++) {
  18166. result += String.fromCharCode(buf[i]);
  18167. }
  18168. return result;
  18169. }
  18170. // Convert byte array to binary string
  18171. exports.buf2binstring = function(buf) {
  18172. return buf2binstring(buf, buf.length);
  18173. };
  18174. // Convert binary string (typed, when possible)
  18175. exports.binstring2buf = function(str) {
  18176. var buf = new utils.Buf8(str.length);
  18177. for(var i=0, len=buf.length; i < len; i++) {
  18178. buf[i] = str.charCodeAt(i);
  18179. }
  18180. return buf;
  18181. };
  18182. // convert array to string
  18183. exports.buf2string = function (buf, max) {
  18184. var i, out, c, c_len;
  18185. var len = max || buf.length;
  18186. // Reserve max possible length (2 words per char)
  18187. // NB: by unknown reasons, Array is significantly faster for
  18188. // String.fromCharCode.apply than Uint16Array.
  18189. var utf16buf = new Array(len*2);
  18190. for (out=0, i=0; i<len;) {
  18191. c = buf[i++];
  18192. // quick process ascii
  18193. if (c < 0x80) { utf16buf[out++] = c; continue; }
  18194. c_len = _utf8len[c];
  18195. // skip 5 & 6 byte codes
  18196. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  18197. // apply mask on first byte
  18198. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  18199. // join the rest
  18200. while (c_len > 1 && i < len) {
  18201. c = (c << 6) | (buf[i++] & 0x3f);
  18202. c_len--;
  18203. }
  18204. // terminated by end of string?
  18205. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  18206. if (c < 0x10000) {
  18207. utf16buf[out++] = c;
  18208. } else {
  18209. c -= 0x10000;
  18210. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  18211. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  18212. }
  18213. }
  18214. return buf2binstring(utf16buf, out);
  18215. };
  18216. // Calculate max possible position in utf8 buffer,
  18217. // that will not break sequence. If that's not possible
  18218. // - (very small limits) return max size as is.
  18219. //
  18220. // buf[] - utf8 bytes array
  18221. // max - length limit (mandatory);
  18222. exports.utf8border = function(buf, max) {
  18223. var pos;
  18224. max = max || buf.length;
  18225. if (max > buf.length) { max = buf.length; }
  18226. // go back from last position, until start of sequence found
  18227. pos = max-1;
  18228. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  18229. // Fuckup - very small and broken sequence,
  18230. // return max, because we should return something anyway.
  18231. if (pos < 0) { return max; }
  18232. // If we came to start of buffer - that means vuffer is too small,
  18233. // return max too.
  18234. if (pos === 0) { return max; }
  18235. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  18236. };
  18237. },{"./common":67}],69:[function(require,module,exports){
  18238. 'use strict';
  18239. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  18240. // It doesn't worth to make additional optimizationa as in original.
  18241. // Small size is preferable.
  18242. function adler32(adler, buf, len, pos) {
  18243. var s1 = (adler & 0xffff) |0
  18244. , s2 = ((adler >>> 16) & 0xffff) |0
  18245. , n = 0;
  18246. while (len !== 0) {
  18247. // Set limit ~ twice less than 5552, to keep
  18248. // s2 in 31-bits, because we force signed ints.
  18249. // in other case %= will fail.
  18250. n = len > 2000 ? 2000 : len;
  18251. len -= n;
  18252. do {
  18253. s1 = (s1 + buf[pos++]) |0;
  18254. s2 = (s2 + s1) |0;
  18255. } while (--n);
  18256. s1 %= 65521;
  18257. s2 %= 65521;
  18258. }
  18259. return (s1 | (s2 << 16)) |0;
  18260. }
  18261. module.exports = adler32;
  18262. },{}],70:[function(require,module,exports){
  18263. module.exports = {
  18264. /* Allowed flush values; see deflate() and inflate() below for details */
  18265. Z_NO_FLUSH: 0,
  18266. Z_PARTIAL_FLUSH: 1,
  18267. Z_SYNC_FLUSH: 2,
  18268. Z_FULL_FLUSH: 3,
  18269. Z_FINISH: 4,
  18270. Z_BLOCK: 5,
  18271. Z_TREES: 6,
  18272. /* Return codes for the compression/decompression functions. Negative values
  18273. * are errors, positive values are used for special but normal events.
  18274. */
  18275. Z_OK: 0,
  18276. Z_STREAM_END: 1,
  18277. Z_NEED_DICT: 2,
  18278. Z_ERRNO: -1,
  18279. Z_STREAM_ERROR: -2,
  18280. Z_DATA_ERROR: -3,
  18281. //Z_MEM_ERROR: -4,
  18282. Z_BUF_ERROR: -5,
  18283. //Z_VERSION_ERROR: -6,
  18284. /* compression levels */
  18285. Z_NO_COMPRESSION: 0,
  18286. Z_BEST_SPEED: 1,
  18287. Z_BEST_COMPRESSION: 9,
  18288. Z_DEFAULT_COMPRESSION: -1,
  18289. Z_FILTERED: 1,
  18290. Z_HUFFMAN_ONLY: 2,
  18291. Z_RLE: 3,
  18292. Z_FIXED: 4,
  18293. Z_DEFAULT_STRATEGY: 0,
  18294. /* Possible values of the data_type field (though see inflate()) */
  18295. Z_BINARY: 0,
  18296. Z_TEXT: 1,
  18297. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  18298. Z_UNKNOWN: 2,
  18299. /* The deflate compression method */
  18300. Z_DEFLATED: 8
  18301. //Z_NULL: null // Use -1 or null inline, depending on var type
  18302. };
  18303. },{}],71:[function(require,module,exports){
  18304. 'use strict';
  18305. // Note: we can't get significant speed boost here.
  18306. // So write code to minimize size - no pregenerated tables
  18307. // and array tools dependencies.
  18308. // Use ordinary array, since untyped makes no boost here
  18309. function makeTable() {
  18310. var c, table = [];
  18311. for(var n =0; n < 256; n++){
  18312. c = n;
  18313. for(var k =0; k < 8; k++){
  18314. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  18315. }
  18316. table[n] = c;
  18317. }
  18318. return table;
  18319. }
  18320. // Create table on load. Just 255 signed longs. Not a problem.
  18321. var crcTable = makeTable();
  18322. function crc32(crc, buf, len, pos) {
  18323. var t = crcTable
  18324. , end = pos + len;
  18325. crc = crc ^ (-1);
  18326. for (var i = pos; i < end; i++ ) {
  18327. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  18328. }
  18329. return (crc ^ (-1)); // >>> 0;
  18330. }
  18331. module.exports = crc32;
  18332. },{}],72:[function(require,module,exports){
  18333. 'use strict';
  18334. var utils = require('../utils/common');
  18335. var trees = require('./trees');
  18336. var adler32 = require('./adler32');
  18337. var crc32 = require('./crc32');
  18338. var msg = require('./messages');
  18339. /* Public constants ==========================================================*/
  18340. /* ===========================================================================*/
  18341. /* Allowed flush values; see deflate() and inflate() below for details */
  18342. var Z_NO_FLUSH = 0;
  18343. var Z_PARTIAL_FLUSH = 1;
  18344. //var Z_SYNC_FLUSH = 2;
  18345. var Z_FULL_FLUSH = 3;
  18346. var Z_FINISH = 4;
  18347. var Z_BLOCK = 5;
  18348. //var Z_TREES = 6;
  18349. /* Return codes for the compression/decompression functions. Negative values
  18350. * are errors, positive values are used for special but normal events.
  18351. */
  18352. var Z_OK = 0;
  18353. var Z_STREAM_END = 1;
  18354. //var Z_NEED_DICT = 2;
  18355. //var Z_ERRNO = -1;
  18356. var Z_STREAM_ERROR = -2;
  18357. var Z_DATA_ERROR = -3;
  18358. //var Z_MEM_ERROR = -4;
  18359. var Z_BUF_ERROR = -5;
  18360. //var Z_VERSION_ERROR = -6;
  18361. /* compression levels */
  18362. //var Z_NO_COMPRESSION = 0;
  18363. //var Z_BEST_SPEED = 1;
  18364. //var Z_BEST_COMPRESSION = 9;
  18365. var Z_DEFAULT_COMPRESSION = -1;
  18366. var Z_FILTERED = 1;
  18367. var Z_HUFFMAN_ONLY = 2;
  18368. var Z_RLE = 3;
  18369. var Z_FIXED = 4;
  18370. var Z_DEFAULT_STRATEGY = 0;
  18371. /* Possible values of the data_type field (though see inflate()) */
  18372. //var Z_BINARY = 0;
  18373. //var Z_TEXT = 1;
  18374. //var Z_ASCII = 1; // = Z_TEXT
  18375. var Z_UNKNOWN = 2;
  18376. /* The deflate compression method */
  18377. var Z_DEFLATED = 8;
  18378. /*============================================================================*/
  18379. var MAX_MEM_LEVEL = 9;
  18380. /* Maximum value for memLevel in deflateInit2 */
  18381. var MAX_WBITS = 15;
  18382. /* 32K LZ77 window */
  18383. var DEF_MEM_LEVEL = 8;
  18384. var LENGTH_CODES = 29;
  18385. /* number of length codes, not counting the special END_BLOCK code */
  18386. var LITERALS = 256;
  18387. /* number of literal bytes 0..255 */
  18388. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18389. /* number of Literal or Length codes, including the END_BLOCK code */
  18390. var D_CODES = 30;
  18391. /* number of distance codes */
  18392. var BL_CODES = 19;
  18393. /* number of codes used to transfer the bit lengths */
  18394. var HEAP_SIZE = 2*L_CODES + 1;
  18395. /* maximum heap size */
  18396. var MAX_BITS = 15;
  18397. /* All codes must not exceed MAX_BITS bits */
  18398. var MIN_MATCH = 3;
  18399. var MAX_MATCH = 258;
  18400. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  18401. var PRESET_DICT = 0x20;
  18402. var INIT_STATE = 42;
  18403. var EXTRA_STATE = 69;
  18404. var NAME_STATE = 73;
  18405. var COMMENT_STATE = 91;
  18406. var HCRC_STATE = 103;
  18407. var BUSY_STATE = 113;
  18408. var FINISH_STATE = 666;
  18409. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  18410. var BS_BLOCK_DONE = 2; /* block flush performed */
  18411. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  18412. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  18413. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  18414. function err(strm, errorCode) {
  18415. strm.msg = msg[errorCode];
  18416. return errorCode;
  18417. }
  18418. function rank(f) {
  18419. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  18420. }
  18421. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18422. /* =========================================================================
  18423. * Flush as much pending output as possible. All deflate() output goes
  18424. * through this function so some applications may wish to modify it
  18425. * to avoid allocating a large strm->output buffer and copying into it.
  18426. * (See also read_buf()).
  18427. */
  18428. function flush_pending(strm) {
  18429. var s = strm.state;
  18430. //_tr_flush_bits(s);
  18431. var len = s.pending;
  18432. if (len > strm.avail_out) {
  18433. len = strm.avail_out;
  18434. }
  18435. if (len === 0) { return; }
  18436. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  18437. strm.next_out += len;
  18438. s.pending_out += len;
  18439. strm.total_out += len;
  18440. strm.avail_out -= len;
  18441. s.pending -= len;
  18442. if (s.pending === 0) {
  18443. s.pending_out = 0;
  18444. }
  18445. }
  18446. function flush_block_only (s, last) {
  18447. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  18448. s.block_start = s.strstart;
  18449. flush_pending(s.strm);
  18450. }
  18451. function put_byte(s, b) {
  18452. s.pending_buf[s.pending++] = b;
  18453. }
  18454. /* =========================================================================
  18455. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  18456. * IN assertion: the stream state is correct and there is enough room in
  18457. * pending_buf.
  18458. */
  18459. function putShortMSB(s, b) {
  18460. // put_byte(s, (Byte)(b >> 8));
  18461. // put_byte(s, (Byte)(b & 0xff));
  18462. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  18463. s.pending_buf[s.pending++] = b & 0xff;
  18464. }
  18465. /* ===========================================================================
  18466. * Read a new buffer from the current input stream, update the adler32
  18467. * and total number of bytes read. All deflate() input goes through
  18468. * this function so some applications may wish to modify it to avoid
  18469. * allocating a large strm->input buffer and copying from it.
  18470. * (See also flush_pending()).
  18471. */
  18472. function read_buf(strm, buf, start, size) {
  18473. var len = strm.avail_in;
  18474. if (len > size) { len = size; }
  18475. if (len === 0) { return 0; }
  18476. strm.avail_in -= len;
  18477. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18478. if (strm.state.wrap === 1) {
  18479. strm.adler = adler32(strm.adler, buf, len, start);
  18480. }
  18481. else if (strm.state.wrap === 2) {
  18482. strm.adler = crc32(strm.adler, buf, len, start);
  18483. }
  18484. strm.next_in += len;
  18485. strm.total_in += len;
  18486. return len;
  18487. }
  18488. /* ===========================================================================
  18489. * Set match_start to the longest match starting at the given string and
  18490. * return its length. Matches shorter or equal to prev_length are discarded,
  18491. * in which case the result is equal to prev_length and match_start is
  18492. * garbage.
  18493. * IN assertions: cur_match is the head of the hash chain for the current
  18494. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18495. * OUT assertion: the match length is not greater than s->lookahead.
  18496. */
  18497. function longest_match(s, cur_match) {
  18498. var chain_length = s.max_chain_length; /* max hash chain length */
  18499. var scan = s.strstart; /* current string */
  18500. var match; /* matched string */
  18501. var len; /* length of current match */
  18502. var best_len = s.prev_length; /* best match length so far */
  18503. var nice_match = s.nice_match; /* stop if match long enough */
  18504. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  18505. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  18506. var _win = s.window; // shortcut
  18507. var wmask = s.w_mask;
  18508. var prev = s.prev;
  18509. /* Stop when cur_match becomes <= limit. To simplify the code,
  18510. * we prevent matches with the string of window index 0.
  18511. */
  18512. var strend = s.strstart + MAX_MATCH;
  18513. var scan_end1 = _win[scan + best_len - 1];
  18514. var scan_end = _win[scan + best_len];
  18515. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  18516. * It is easy to get rid of this optimization if necessary.
  18517. */
  18518. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  18519. /* Do not waste too much time if we already have a good match: */
  18520. if (s.prev_length >= s.good_match) {
  18521. chain_length >>= 2;
  18522. }
  18523. /* Do not look for matches beyond the end of the input. This is necessary
  18524. * to make deflate deterministic.
  18525. */
  18526. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  18527. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  18528. do {
  18529. // Assert(cur_match < s->strstart, "no future");
  18530. match = cur_match;
  18531. /* Skip to next match if the match length cannot increase
  18532. * or if the match length is less than 2. Note that the checks below
  18533. * for insufficient lookahead only occur occasionally for performance
  18534. * reasons. Therefore uninitialized memory will be accessed, and
  18535. * conditional jumps will be made that depend on those values.
  18536. * However the length of the match is limited to the lookahead, so
  18537. * the output of deflate is not affected by the uninitialized values.
  18538. */
  18539. if (_win[match + best_len] !== scan_end ||
  18540. _win[match + best_len - 1] !== scan_end1 ||
  18541. _win[match] !== _win[scan] ||
  18542. _win[++match] !== _win[scan + 1]) {
  18543. continue;
  18544. }
  18545. /* The check at best_len-1 can be removed because it will be made
  18546. * again later. (This heuristic is not always a win.)
  18547. * It is not necessary to compare scan[2] and match[2] since they
  18548. * are always equal when the other bytes match, given that
  18549. * the hash keys are equal and that HASH_BITS >= 8.
  18550. */
  18551. scan += 2;
  18552. match++;
  18553. // Assert(*scan == *match, "match[2]?");
  18554. /* We check for insufficient lookahead only every 8th comparison;
  18555. * the 256th check will be made at strstart+258.
  18556. */
  18557. do {
  18558. /*jshint noempty:false*/
  18559. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18560. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18561. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18562. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18563. scan < strend);
  18564. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18565. len = MAX_MATCH - (strend - scan);
  18566. scan = strend - MAX_MATCH;
  18567. if (len > best_len) {
  18568. s.match_start = cur_match;
  18569. best_len = len;
  18570. if (len >= nice_match) {
  18571. break;
  18572. }
  18573. scan_end1 = _win[scan + best_len - 1];
  18574. scan_end = _win[scan + best_len];
  18575. }
  18576. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18577. if (best_len <= s.lookahead) {
  18578. return best_len;
  18579. }
  18580. return s.lookahead;
  18581. }
  18582. /* ===========================================================================
  18583. * Fill the window when the lookahead becomes insufficient.
  18584. * Updates strstart and lookahead.
  18585. *
  18586. * IN assertion: lookahead < MIN_LOOKAHEAD
  18587. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18588. * At least one byte has been read, or avail_in == 0; reads are
  18589. * performed for at least two bytes (required for the zip translate_eol
  18590. * option -- not supported here).
  18591. */
  18592. function fill_window(s) {
  18593. var _w_size = s.w_size;
  18594. var p, n, m, more, str;
  18595. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18596. do {
  18597. more = s.window_size - s.lookahead - s.strstart;
  18598. // JS ints have 32 bit, block below not needed
  18599. /* Deal with !@#$% 64K limit: */
  18600. //if (sizeof(int) <= 2) {
  18601. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18602. // more = wsize;
  18603. //
  18604. // } else if (more == (unsigned)(-1)) {
  18605. // /* Very unlikely, but possible on 16 bit machine if
  18606. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18607. // */
  18608. // more--;
  18609. // }
  18610. //}
  18611. /* If the window is almost full and there is insufficient lookahead,
  18612. * move the upper half to the lower one to make room in the upper half.
  18613. */
  18614. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18615. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18616. s.match_start -= _w_size;
  18617. s.strstart -= _w_size;
  18618. /* we now have strstart >= MAX_DIST */
  18619. s.block_start -= _w_size;
  18620. /* Slide the hash table (could be avoided with 32 bit values
  18621. at the expense of memory usage). We slide even when level == 0
  18622. to keep the hash table consistent if we switch back to level > 0
  18623. later. (Using level 0 permanently is not an optimal usage of
  18624. zlib, so we don't care about this pathological case.)
  18625. */
  18626. n = s.hash_size;
  18627. p = n;
  18628. do {
  18629. m = s.head[--p];
  18630. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18631. } while (--n);
  18632. n = _w_size;
  18633. p = n;
  18634. do {
  18635. m = s.prev[--p];
  18636. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18637. /* If n is not on any hash chain, prev[n] is garbage but
  18638. * its value will never be used.
  18639. */
  18640. } while (--n);
  18641. more += _w_size;
  18642. }
  18643. if (s.strm.avail_in === 0) {
  18644. break;
  18645. }
  18646. /* If there was no sliding:
  18647. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18648. * more == window_size - lookahead - strstart
  18649. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18650. * => more >= window_size - 2*WSIZE + 2
  18651. * In the BIG_MEM or MMAP case (not yet supported),
  18652. * window_size == input_size + MIN_LOOKAHEAD &&
  18653. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18654. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18655. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18656. */
  18657. //Assert(more >= 2, "more < 2");
  18658. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18659. s.lookahead += n;
  18660. /* Initialize the hash value now that we have some input: */
  18661. if (s.lookahead + s.insert >= MIN_MATCH) {
  18662. str = s.strstart - s.insert;
  18663. s.ins_h = s.window[str];
  18664. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18665. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18666. //#if MIN_MATCH != 3
  18667. // Call update_hash() MIN_MATCH-3 more times
  18668. //#endif
  18669. while (s.insert) {
  18670. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18671. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18672. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18673. s.head[s.ins_h] = str;
  18674. str++;
  18675. s.insert--;
  18676. if (s.lookahead + s.insert < MIN_MATCH) {
  18677. break;
  18678. }
  18679. }
  18680. }
  18681. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18682. * but this is not important since only literal bytes will be emitted.
  18683. */
  18684. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18685. /* If the WIN_INIT bytes after the end of the current data have never been
  18686. * written, then zero those bytes in order to avoid memory check reports of
  18687. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18688. * the longest match routines. Update the high water mark for the next
  18689. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18690. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18691. */
  18692. // if (s.high_water < s.window_size) {
  18693. // var curr = s.strstart + s.lookahead;
  18694. // var init = 0;
  18695. //
  18696. // if (s.high_water < curr) {
  18697. // /* Previous high water mark below current data -- zero WIN_INIT
  18698. // * bytes or up to end of window, whichever is less.
  18699. // */
  18700. // init = s.window_size - curr;
  18701. // if (init > WIN_INIT)
  18702. // init = WIN_INIT;
  18703. // zmemzero(s->window + curr, (unsigned)init);
  18704. // s->high_water = curr + init;
  18705. // }
  18706. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18707. // /* High water mark at or above current data, but below current data
  18708. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18709. // * to end of window, whichever is less.
  18710. // */
  18711. // init = (ulg)curr + WIN_INIT - s->high_water;
  18712. // if (init > s->window_size - s->high_water)
  18713. // init = s->window_size - s->high_water;
  18714. // zmemzero(s->window + s->high_water, (unsigned)init);
  18715. // s->high_water += init;
  18716. // }
  18717. // }
  18718. //
  18719. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18720. // "not enough room for search");
  18721. }
  18722. /* ===========================================================================
  18723. * Copy without compression as much as possible from the input stream, return
  18724. * the current block state.
  18725. * This function does not insert new strings in the dictionary since
  18726. * uncompressible data is probably not useful. This function is used
  18727. * only for the level=0 compression option.
  18728. * NOTE: this function should be optimized to avoid extra copying from
  18729. * window to pending_buf.
  18730. */
  18731. function deflate_stored(s, flush) {
  18732. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18733. * to pending_buf_size, and each stored block has a 5 byte header:
  18734. */
  18735. var max_block_size = 0xffff;
  18736. if (max_block_size > s.pending_buf_size - 5) {
  18737. max_block_size = s.pending_buf_size - 5;
  18738. }
  18739. /* Copy as much as possible from input to output: */
  18740. for (;;) {
  18741. /* Fill the window as much as possible: */
  18742. if (s.lookahead <= 1) {
  18743. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18744. // s->block_start >= (long)s->w_size, "slide too late");
  18745. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18746. // s.block_start >= s.w_size)) {
  18747. // throw new Error("slide too late");
  18748. // }
  18749. fill_window(s);
  18750. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18751. return BS_NEED_MORE;
  18752. }
  18753. if (s.lookahead === 0) {
  18754. break;
  18755. }
  18756. /* flush the current block */
  18757. }
  18758. //Assert(s->block_start >= 0L, "block gone");
  18759. // if (s.block_start < 0) throw new Error("block gone");
  18760. s.strstart += s.lookahead;
  18761. s.lookahead = 0;
  18762. /* Emit a stored block if pending_buf will be full: */
  18763. var max_start = s.block_start + max_block_size;
  18764. if (s.strstart === 0 || s.strstart >= max_start) {
  18765. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18766. s.lookahead = s.strstart - max_start;
  18767. s.strstart = max_start;
  18768. /*** FLUSH_BLOCK(s, 0); ***/
  18769. flush_block_only(s, false);
  18770. if (s.strm.avail_out === 0) {
  18771. return BS_NEED_MORE;
  18772. }
  18773. /***/
  18774. }
  18775. /* Flush if we may have to slide, otherwise block_start may become
  18776. * negative and the data will be gone:
  18777. */
  18778. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18779. /*** FLUSH_BLOCK(s, 0); ***/
  18780. flush_block_only(s, false);
  18781. if (s.strm.avail_out === 0) {
  18782. return BS_NEED_MORE;
  18783. }
  18784. /***/
  18785. }
  18786. }
  18787. s.insert = 0;
  18788. if (flush === Z_FINISH) {
  18789. /*** FLUSH_BLOCK(s, 1); ***/
  18790. flush_block_only(s, true);
  18791. if (s.strm.avail_out === 0) {
  18792. return BS_FINISH_STARTED;
  18793. }
  18794. /***/
  18795. return BS_FINISH_DONE;
  18796. }
  18797. if (s.strstart > s.block_start) {
  18798. /*** FLUSH_BLOCK(s, 0); ***/
  18799. flush_block_only(s, false);
  18800. if (s.strm.avail_out === 0) {
  18801. return BS_NEED_MORE;
  18802. }
  18803. /***/
  18804. }
  18805. return BS_NEED_MORE;
  18806. }
  18807. /* ===========================================================================
  18808. * Compress as much as possible from the input stream, return the current
  18809. * block state.
  18810. * This function does not perform lazy evaluation of matches and inserts
  18811. * new strings in the dictionary only for unmatched strings or for short
  18812. * matches. It is used only for the fast compression options.
  18813. */
  18814. function deflate_fast(s, flush) {
  18815. var hash_head; /* head of the hash chain */
  18816. var bflush; /* set if current block must be flushed */
  18817. for (;;) {
  18818. /* Make sure that we always have enough lookahead, except
  18819. * at the end of the input file. We need MAX_MATCH bytes
  18820. * for the next match, plus MIN_MATCH bytes to insert the
  18821. * string following the next match.
  18822. */
  18823. if (s.lookahead < MIN_LOOKAHEAD) {
  18824. fill_window(s);
  18825. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18826. return BS_NEED_MORE;
  18827. }
  18828. if (s.lookahead === 0) {
  18829. break; /* flush the current block */
  18830. }
  18831. }
  18832. /* Insert the string window[strstart .. strstart+2] in the
  18833. * dictionary, and set hash_head to the head of the hash chain:
  18834. */
  18835. hash_head = 0/*NIL*/;
  18836. if (s.lookahead >= MIN_MATCH) {
  18837. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18838. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18839. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18840. s.head[s.ins_h] = s.strstart;
  18841. /***/
  18842. }
  18843. /* Find the longest match, discarding those <= prev_length.
  18844. * At this point we have always match_length < MIN_MATCH
  18845. */
  18846. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18847. /* To simplify the code, we prevent matches with the string
  18848. * of window index 0 (in particular we have to avoid a match
  18849. * of the string with itself at the start of the input file).
  18850. */
  18851. s.match_length = longest_match(s, hash_head);
  18852. /* longest_match() sets match_start */
  18853. }
  18854. if (s.match_length >= MIN_MATCH) {
  18855. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18856. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18857. s.match_length - MIN_MATCH, bflush); ***/
  18858. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18859. s.lookahead -= s.match_length;
  18860. /* Insert new strings in the hash table only if the match length
  18861. * is not too large. This saves time but degrades compression.
  18862. */
  18863. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18864. s.match_length--; /* string at strstart already in table */
  18865. do {
  18866. s.strstart++;
  18867. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18868. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18869. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18870. s.head[s.ins_h] = s.strstart;
  18871. /***/
  18872. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18873. * always MIN_MATCH bytes ahead.
  18874. */
  18875. } while (--s.match_length !== 0);
  18876. s.strstart++;
  18877. } else
  18878. {
  18879. s.strstart += s.match_length;
  18880. s.match_length = 0;
  18881. s.ins_h = s.window[s.strstart];
  18882. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18883. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18884. //#if MIN_MATCH != 3
  18885. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18886. //#endif
  18887. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18888. * matter since it will be recomputed at next deflate call.
  18889. */
  18890. }
  18891. } else {
  18892. /* No match, output a literal byte */
  18893. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18894. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18895. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18896. s.lookahead--;
  18897. s.strstart++;
  18898. }
  18899. if (bflush) {
  18900. /*** FLUSH_BLOCK(s, 0); ***/
  18901. flush_block_only(s, false);
  18902. if (s.strm.avail_out === 0) {
  18903. return BS_NEED_MORE;
  18904. }
  18905. /***/
  18906. }
  18907. }
  18908. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18909. if (flush === Z_FINISH) {
  18910. /*** FLUSH_BLOCK(s, 1); ***/
  18911. flush_block_only(s, true);
  18912. if (s.strm.avail_out === 0) {
  18913. return BS_FINISH_STARTED;
  18914. }
  18915. /***/
  18916. return BS_FINISH_DONE;
  18917. }
  18918. if (s.last_lit) {
  18919. /*** FLUSH_BLOCK(s, 0); ***/
  18920. flush_block_only(s, false);
  18921. if (s.strm.avail_out === 0) {
  18922. return BS_NEED_MORE;
  18923. }
  18924. /***/
  18925. }
  18926. return BS_BLOCK_DONE;
  18927. }
  18928. /* ===========================================================================
  18929. * Same as above, but achieves better compression. We use a lazy
  18930. * evaluation for matches: a match is finally adopted only if there is
  18931. * no better match at the next window position.
  18932. */
  18933. function deflate_slow(s, flush) {
  18934. var hash_head; /* head of hash chain */
  18935. var bflush; /* set if current block must be flushed */
  18936. var max_insert;
  18937. /* Process the input block. */
  18938. for (;;) {
  18939. /* Make sure that we always have enough lookahead, except
  18940. * at the end of the input file. We need MAX_MATCH bytes
  18941. * for the next match, plus MIN_MATCH bytes to insert the
  18942. * string following the next match.
  18943. */
  18944. if (s.lookahead < MIN_LOOKAHEAD) {
  18945. fill_window(s);
  18946. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18947. return BS_NEED_MORE;
  18948. }
  18949. if (s.lookahead === 0) { break; } /* flush the current block */
  18950. }
  18951. /* Insert the string window[strstart .. strstart+2] in the
  18952. * dictionary, and set hash_head to the head of the hash chain:
  18953. */
  18954. hash_head = 0/*NIL*/;
  18955. if (s.lookahead >= MIN_MATCH) {
  18956. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18957. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18958. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18959. s.head[s.ins_h] = s.strstart;
  18960. /***/
  18961. }
  18962. /* Find the longest match, discarding those <= prev_length.
  18963. */
  18964. s.prev_length = s.match_length;
  18965. s.prev_match = s.match_start;
  18966. s.match_length = MIN_MATCH-1;
  18967. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18968. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18969. /* To simplify the code, we prevent matches with the string
  18970. * of window index 0 (in particular we have to avoid a match
  18971. * of the string with itself at the start of the input file).
  18972. */
  18973. s.match_length = longest_match(s, hash_head);
  18974. /* longest_match() sets match_start */
  18975. if (s.match_length <= 5 &&
  18976. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18977. /* If prev_match is also MIN_MATCH, match_start is garbage
  18978. * but we will ignore the current match anyway.
  18979. */
  18980. s.match_length = MIN_MATCH-1;
  18981. }
  18982. }
  18983. /* If there was a match at the previous step and the current
  18984. * match is not better, output the previous match:
  18985. */
  18986. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18987. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18988. /* Do not insert strings in hash table beyond this. */
  18989. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18990. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18991. s.prev_length - MIN_MATCH, bflush);***/
  18992. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18993. /* Insert in hash table all strings up to the end of the match.
  18994. * strstart-1 and strstart are already inserted. If there is not
  18995. * enough lookahead, the last two strings are not inserted in
  18996. * the hash table.
  18997. */
  18998. s.lookahead -= s.prev_length-1;
  18999. s.prev_length -= 2;
  19000. do {
  19001. if (++s.strstart <= max_insert) {
  19002. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19003. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19004. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19005. s.head[s.ins_h] = s.strstart;
  19006. /***/
  19007. }
  19008. } while (--s.prev_length !== 0);
  19009. s.match_available = 0;
  19010. s.match_length = MIN_MATCH-1;
  19011. s.strstart++;
  19012. if (bflush) {
  19013. /*** FLUSH_BLOCK(s, 0); ***/
  19014. flush_block_only(s, false);
  19015. if (s.strm.avail_out === 0) {
  19016. return BS_NEED_MORE;
  19017. }
  19018. /***/
  19019. }
  19020. } else if (s.match_available) {
  19021. /* If there was no match at the previous position, output a
  19022. * single literal. If there was a match but the current match
  19023. * is longer, truncate the previous match to a single literal.
  19024. */
  19025. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  19026. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  19027. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  19028. if (bflush) {
  19029. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  19030. flush_block_only(s, false);
  19031. /***/
  19032. }
  19033. s.strstart++;
  19034. s.lookahead--;
  19035. if (s.strm.avail_out === 0) {
  19036. return BS_NEED_MORE;
  19037. }
  19038. } else {
  19039. /* There is no previous match to compare with, wait for
  19040. * the next step to decide.
  19041. */
  19042. s.match_available = 1;
  19043. s.strstart++;
  19044. s.lookahead--;
  19045. }
  19046. }
  19047. //Assert (flush != Z_NO_FLUSH, "no flush?");
  19048. if (s.match_available) {
  19049. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  19050. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  19051. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  19052. s.match_available = 0;
  19053. }
  19054. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  19055. if (flush === Z_FINISH) {
  19056. /*** FLUSH_BLOCK(s, 1); ***/
  19057. flush_block_only(s, true);
  19058. if (s.strm.avail_out === 0) {
  19059. return BS_FINISH_STARTED;
  19060. }
  19061. /***/
  19062. return BS_FINISH_DONE;
  19063. }
  19064. if (s.last_lit) {
  19065. /*** FLUSH_BLOCK(s, 0); ***/
  19066. flush_block_only(s, false);
  19067. if (s.strm.avail_out === 0) {
  19068. return BS_NEED_MORE;
  19069. }
  19070. /***/
  19071. }
  19072. return BS_BLOCK_DONE;
  19073. }
  19074. /* ===========================================================================
  19075. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  19076. * one. Do not maintain a hash table. (It will be regenerated if this run of
  19077. * deflate switches away from Z_RLE.)
  19078. */
  19079. function deflate_rle(s, flush) {
  19080. var bflush; /* set if current block must be flushed */
  19081. var prev; /* byte at distance one to match */
  19082. var scan, strend; /* scan goes up to strend for length of run */
  19083. var _win = s.window;
  19084. for (;;) {
  19085. /* Make sure that we always have enough lookahead, except
  19086. * at the end of the input file. We need MAX_MATCH bytes
  19087. * for the longest run, plus one for the unrolled loop.
  19088. */
  19089. if (s.lookahead <= MAX_MATCH) {
  19090. fill_window(s);
  19091. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  19092. return BS_NEED_MORE;
  19093. }
  19094. if (s.lookahead === 0) { break; } /* flush the current block */
  19095. }
  19096. /* See how many times the previous byte repeats */
  19097. s.match_length = 0;
  19098. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  19099. scan = s.strstart - 1;
  19100. prev = _win[scan];
  19101. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  19102. strend = s.strstart + MAX_MATCH;
  19103. do {
  19104. /*jshint noempty:false*/
  19105. } while (prev === _win[++scan] && prev === _win[++scan] &&
  19106. prev === _win[++scan] && prev === _win[++scan] &&
  19107. prev === _win[++scan] && prev === _win[++scan] &&
  19108. prev === _win[++scan] && prev === _win[++scan] &&
  19109. scan < strend);
  19110. s.match_length = MAX_MATCH - (strend - scan);
  19111. if (s.match_length > s.lookahead) {
  19112. s.match_length = s.lookahead;
  19113. }
  19114. }
  19115. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  19116. }
  19117. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  19118. if (s.match_length >= MIN_MATCH) {
  19119. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  19120. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  19121. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  19122. s.lookahead -= s.match_length;
  19123. s.strstart += s.match_length;
  19124. s.match_length = 0;
  19125. } else {
  19126. /* No match, output a literal byte */
  19127. //Tracevv((stderr,"%c", s->window[s->strstart]));
  19128. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19129. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19130. s.lookahead--;
  19131. s.strstart++;
  19132. }
  19133. if (bflush) {
  19134. /*** FLUSH_BLOCK(s, 0); ***/
  19135. flush_block_only(s, false);
  19136. if (s.strm.avail_out === 0) {
  19137. return BS_NEED_MORE;
  19138. }
  19139. /***/
  19140. }
  19141. }
  19142. s.insert = 0;
  19143. if (flush === Z_FINISH) {
  19144. /*** FLUSH_BLOCK(s, 1); ***/
  19145. flush_block_only(s, true);
  19146. if (s.strm.avail_out === 0) {
  19147. return BS_FINISH_STARTED;
  19148. }
  19149. /***/
  19150. return BS_FINISH_DONE;
  19151. }
  19152. if (s.last_lit) {
  19153. /*** FLUSH_BLOCK(s, 0); ***/
  19154. flush_block_only(s, false);
  19155. if (s.strm.avail_out === 0) {
  19156. return BS_NEED_MORE;
  19157. }
  19158. /***/
  19159. }
  19160. return BS_BLOCK_DONE;
  19161. }
  19162. /* ===========================================================================
  19163. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  19164. * (It will be regenerated if this run of deflate switches away from Huffman.)
  19165. */
  19166. function deflate_huff(s, flush) {
  19167. var bflush; /* set if current block must be flushed */
  19168. for (;;) {
  19169. /* Make sure that we have a literal to write. */
  19170. if (s.lookahead === 0) {
  19171. fill_window(s);
  19172. if (s.lookahead === 0) {
  19173. if (flush === Z_NO_FLUSH) {
  19174. return BS_NEED_MORE;
  19175. }
  19176. break; /* flush the current block */
  19177. }
  19178. }
  19179. /* Output a literal byte */
  19180. s.match_length = 0;
  19181. //Tracevv((stderr,"%c", s->window[s->strstart]));
  19182. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19183. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19184. s.lookahead--;
  19185. s.strstart++;
  19186. if (bflush) {
  19187. /*** FLUSH_BLOCK(s, 0); ***/
  19188. flush_block_only(s, false);
  19189. if (s.strm.avail_out === 0) {
  19190. return BS_NEED_MORE;
  19191. }
  19192. /***/
  19193. }
  19194. }
  19195. s.insert = 0;
  19196. if (flush === Z_FINISH) {
  19197. /*** FLUSH_BLOCK(s, 1); ***/
  19198. flush_block_only(s, true);
  19199. if (s.strm.avail_out === 0) {
  19200. return BS_FINISH_STARTED;
  19201. }
  19202. /***/
  19203. return BS_FINISH_DONE;
  19204. }
  19205. if (s.last_lit) {
  19206. /*** FLUSH_BLOCK(s, 0); ***/
  19207. flush_block_only(s, false);
  19208. if (s.strm.avail_out === 0) {
  19209. return BS_NEED_MORE;
  19210. }
  19211. /***/
  19212. }
  19213. return BS_BLOCK_DONE;
  19214. }
  19215. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  19216. * the desired pack level (0..9). The values given below have been tuned to
  19217. * exclude worst case performance for pathological files. Better values may be
  19218. * found for specific files.
  19219. */
  19220. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  19221. this.good_length = good_length;
  19222. this.max_lazy = max_lazy;
  19223. this.nice_length = nice_length;
  19224. this.max_chain = max_chain;
  19225. this.func = func;
  19226. };
  19227. var configuration_table;
  19228. configuration_table = [
  19229. /* good lazy nice chain */
  19230. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  19231. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  19232. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  19233. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  19234. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  19235. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  19236. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  19237. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  19238. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  19239. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  19240. ];
  19241. /* ===========================================================================
  19242. * Initialize the "longest match" routines for a new zlib stream
  19243. */
  19244. function lm_init(s) {
  19245. s.window_size = 2 * s.w_size;
  19246. /*** CLEAR_HASH(s); ***/
  19247. zero(s.head); // Fill with NIL (= 0);
  19248. /* Set the default configuration parameters:
  19249. */
  19250. s.max_lazy_match = configuration_table[s.level].max_lazy;
  19251. s.good_match = configuration_table[s.level].good_length;
  19252. s.nice_match = configuration_table[s.level].nice_length;
  19253. s.max_chain_length = configuration_table[s.level].max_chain;
  19254. s.strstart = 0;
  19255. s.block_start = 0;
  19256. s.lookahead = 0;
  19257. s.insert = 0;
  19258. s.match_length = s.prev_length = MIN_MATCH - 1;
  19259. s.match_available = 0;
  19260. s.ins_h = 0;
  19261. }
  19262. function DeflateState() {
  19263. this.strm = null; /* pointer back to this zlib stream */
  19264. this.status = 0; /* as the name implies */
  19265. this.pending_buf = null; /* output still pending */
  19266. this.pending_buf_size = 0; /* size of pending_buf */
  19267. this.pending_out = 0; /* next pending byte to output to the stream */
  19268. this.pending = 0; /* nb of bytes in the pending buffer */
  19269. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19270. this.gzhead = null; /* gzip header information to write */
  19271. this.gzindex = 0; /* where in extra, name, or comment */
  19272. this.method = Z_DEFLATED; /* can only be DEFLATED */
  19273. this.last_flush = -1; /* value of flush param for previous deflate call */
  19274. this.w_size = 0; /* LZ77 window size (32K by default) */
  19275. this.w_bits = 0; /* log2(w_size) (8..16) */
  19276. this.w_mask = 0; /* w_size - 1 */
  19277. this.window = null;
  19278. /* Sliding window. Input bytes are read into the second half of the window,
  19279. * and move to the first half later to keep a dictionary of at least wSize
  19280. * bytes. With this organization, matches are limited to a distance of
  19281. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  19282. * performed with a length multiple of the block size.
  19283. */
  19284. this.window_size = 0;
  19285. /* Actual size of window: 2*wSize, except when the user input buffer
  19286. * is directly used as sliding window.
  19287. */
  19288. this.prev = null;
  19289. /* Link to older string with same hash index. To limit the size of this
  19290. * array to 64K, this link is maintained only for the last 32K strings.
  19291. * An index in this array is thus a window index modulo 32K.
  19292. */
  19293. this.head = null; /* Heads of the hash chains or NIL. */
  19294. this.ins_h = 0; /* hash index of string to be inserted */
  19295. this.hash_size = 0; /* number of elements in hash table */
  19296. this.hash_bits = 0; /* log2(hash_size) */
  19297. this.hash_mask = 0; /* hash_size-1 */
  19298. this.hash_shift = 0;
  19299. /* Number of bits by which ins_h must be shifted at each input
  19300. * step. It must be such that after MIN_MATCH steps, the oldest
  19301. * byte no longer takes part in the hash key, that is:
  19302. * hash_shift * MIN_MATCH >= hash_bits
  19303. */
  19304. this.block_start = 0;
  19305. /* Window position at the beginning of the current output block. Gets
  19306. * negative when the window is moved backwards.
  19307. */
  19308. this.match_length = 0; /* length of best match */
  19309. this.prev_match = 0; /* previous match */
  19310. this.match_available = 0; /* set if previous match exists */
  19311. this.strstart = 0; /* start of string to insert */
  19312. this.match_start = 0; /* start of matching string */
  19313. this.lookahead = 0; /* number of valid bytes ahead in window */
  19314. this.prev_length = 0;
  19315. /* Length of the best match at previous step. Matches not greater than this
  19316. * are discarded. This is used in the lazy match evaluation.
  19317. */
  19318. this.max_chain_length = 0;
  19319. /* To speed up deflation, hash chains are never searched beyond this
  19320. * length. A higher limit improves compression ratio but degrades the
  19321. * speed.
  19322. */
  19323. this.max_lazy_match = 0;
  19324. /* Attempt to find a better match only when the current match is strictly
  19325. * smaller than this value. This mechanism is used only for compression
  19326. * levels >= 4.
  19327. */
  19328. // That's alias to max_lazy_match, don't use directly
  19329. //this.max_insert_length = 0;
  19330. /* Insert new strings in the hash table only if the match length is not
  19331. * greater than this length. This saves time but degrades compression.
  19332. * max_insert_length is used only for compression levels <= 3.
  19333. */
  19334. this.level = 0; /* compression level (1..9) */
  19335. this.strategy = 0; /* favor or force Huffman coding*/
  19336. this.good_match = 0;
  19337. /* Use a faster search when the previous match is longer than this */
  19338. this.nice_match = 0; /* Stop searching when current match exceeds this */
  19339. /* used by trees.c: */
  19340. /* Didn't use ct_data typedef below to suppress compiler warning */
  19341. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  19342. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  19343. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  19344. // Use flat array of DOUBLE size, with interleaved fata,
  19345. // because JS does not support effective
  19346. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  19347. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  19348. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  19349. zero(this.dyn_ltree);
  19350. zero(this.dyn_dtree);
  19351. zero(this.bl_tree);
  19352. this.l_desc = null; /* desc. for literal tree */
  19353. this.d_desc = null; /* desc. for distance tree */
  19354. this.bl_desc = null; /* desc. for bit length tree */
  19355. //ush bl_count[MAX_BITS+1];
  19356. this.bl_count = new utils.Buf16(MAX_BITS+1);
  19357. /* number of codes at each bit length for an optimal tree */
  19358. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  19359. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  19360. zero(this.heap);
  19361. this.heap_len = 0; /* number of elements in the heap */
  19362. this.heap_max = 0; /* element of largest frequency */
  19363. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  19364. * The same heap array is used to build all trees.
  19365. */
  19366. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  19367. zero(this.depth);
  19368. /* Depth of each subtree used as tie breaker for trees of equal frequency
  19369. */
  19370. this.l_buf = 0; /* buffer index for literals or lengths */
  19371. this.lit_bufsize = 0;
  19372. /* Size of match buffer for literals/lengths. There are 4 reasons for
  19373. * limiting lit_bufsize to 64K:
  19374. * - frequencies can be kept in 16 bit counters
  19375. * - if compression is not successful for the first block, all input
  19376. * data is still in the window so we can still emit a stored block even
  19377. * when input comes from standard input. (This can also be done for
  19378. * all blocks if lit_bufsize is not greater than 32K.)
  19379. * - if compression is not successful for a file smaller than 64K, we can
  19380. * even emit a stored file instead of a stored block (saving 5 bytes).
  19381. * This is applicable only for zip (not gzip or zlib).
  19382. * - creating new Huffman trees less frequently may not provide fast
  19383. * adaptation to changes in the input data statistics. (Take for
  19384. * example a binary file with poorly compressible code followed by
  19385. * a highly compressible string table.) Smaller buffer sizes give
  19386. * fast adaptation but have of course the overhead of transmitting
  19387. * trees more frequently.
  19388. * - I can't count above 4
  19389. */
  19390. this.last_lit = 0; /* running index in l_buf */
  19391. this.d_buf = 0;
  19392. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  19393. * the same number of elements. To use different lengths, an extra flag
  19394. * array would be necessary.
  19395. */
  19396. this.opt_len = 0; /* bit length of current block with optimal trees */
  19397. this.static_len = 0; /* bit length of current block with static trees */
  19398. this.matches = 0; /* number of string matches in current block */
  19399. this.insert = 0; /* bytes at end of window left to insert */
  19400. this.bi_buf = 0;
  19401. /* Output buffer. bits are inserted starting at the bottom (least
  19402. * significant bits).
  19403. */
  19404. this.bi_valid = 0;
  19405. /* Number of valid bits in bi_buf. All bits above the last valid bit
  19406. * are always zero.
  19407. */
  19408. // Used for window memory init. We safely ignore it for JS. That makes
  19409. // sense only for pointers and memory check tools.
  19410. //this.high_water = 0;
  19411. /* High water mark offset in window for initialized bytes -- bytes above
  19412. * this are set to zero in order to avoid memory check warnings when
  19413. * longest match routines access bytes past the input. This is then
  19414. * updated to the new high water mark.
  19415. */
  19416. }
  19417. function deflateResetKeep(strm) {
  19418. var s;
  19419. if (!strm || !strm.state) {
  19420. return err(strm, Z_STREAM_ERROR);
  19421. }
  19422. strm.total_in = strm.total_out = 0;
  19423. strm.data_type = Z_UNKNOWN;
  19424. s = strm.state;
  19425. s.pending = 0;
  19426. s.pending_out = 0;
  19427. if (s.wrap < 0) {
  19428. s.wrap = -s.wrap;
  19429. /* was made negative by deflate(..., Z_FINISH); */
  19430. }
  19431. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  19432. strm.adler = (s.wrap === 2) ?
  19433. 0 // crc32(0, Z_NULL, 0)
  19434. :
  19435. 1; // adler32(0, Z_NULL, 0)
  19436. s.last_flush = Z_NO_FLUSH;
  19437. trees._tr_init(s);
  19438. return Z_OK;
  19439. }
  19440. function deflateReset(strm) {
  19441. var ret = deflateResetKeep(strm);
  19442. if (ret === Z_OK) {
  19443. lm_init(strm.state);
  19444. }
  19445. return ret;
  19446. }
  19447. function deflateSetHeader(strm, head) {
  19448. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19449. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  19450. strm.state.gzhead = head;
  19451. return Z_OK;
  19452. }
  19453. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  19454. if (!strm) { // === Z_NULL
  19455. return Z_STREAM_ERROR;
  19456. }
  19457. var wrap = 1;
  19458. if (level === Z_DEFAULT_COMPRESSION) {
  19459. level = 6;
  19460. }
  19461. if (windowBits < 0) { /* suppress zlib wrapper */
  19462. wrap = 0;
  19463. windowBits = -windowBits;
  19464. }
  19465. else if (windowBits > 15) {
  19466. wrap = 2; /* write gzip wrapper instead */
  19467. windowBits -= 16;
  19468. }
  19469. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  19470. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  19471. strategy < 0 || strategy > Z_FIXED) {
  19472. return err(strm, Z_STREAM_ERROR);
  19473. }
  19474. if (windowBits === 8) {
  19475. windowBits = 9;
  19476. }
  19477. /* until 256-byte window bug fixed */
  19478. var s = new DeflateState();
  19479. strm.state = s;
  19480. s.strm = strm;
  19481. s.wrap = wrap;
  19482. s.gzhead = null;
  19483. s.w_bits = windowBits;
  19484. s.w_size = 1 << s.w_bits;
  19485. s.w_mask = s.w_size - 1;
  19486. s.hash_bits = memLevel + 7;
  19487. s.hash_size = 1 << s.hash_bits;
  19488. s.hash_mask = s.hash_size - 1;
  19489. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19490. s.window = new utils.Buf8(s.w_size * 2);
  19491. s.head = new utils.Buf16(s.hash_size);
  19492. s.prev = new utils.Buf16(s.w_size);
  19493. // Don't need mem init magic for JS.
  19494. //s.high_water = 0; /* nothing written to s->window yet */
  19495. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19496. s.pending_buf_size = s.lit_bufsize * 4;
  19497. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19498. s.d_buf = s.lit_bufsize >> 1;
  19499. s.l_buf = (1 + 2) * s.lit_bufsize;
  19500. s.level = level;
  19501. s.strategy = strategy;
  19502. s.method = method;
  19503. return deflateReset(strm);
  19504. }
  19505. function deflateInit(strm, level) {
  19506. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  19507. }
  19508. function deflate(strm, flush) {
  19509. var old_flush, s;
  19510. var beg, val; // for gzip header write only
  19511. if (!strm || !strm.state ||
  19512. flush > Z_BLOCK || flush < 0) {
  19513. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  19514. }
  19515. s = strm.state;
  19516. if (!strm.output ||
  19517. (!strm.input && strm.avail_in !== 0) ||
  19518. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  19519. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  19520. }
  19521. s.strm = strm; /* just in case */
  19522. old_flush = s.last_flush;
  19523. s.last_flush = flush;
  19524. /* Write the header */
  19525. if (s.status === INIT_STATE) {
  19526. if (s.wrap === 2) { // GZIP header
  19527. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19528. put_byte(s, 31);
  19529. put_byte(s, 139);
  19530. put_byte(s, 8);
  19531. if (!s.gzhead) { // s->gzhead == Z_NULL
  19532. put_byte(s, 0);
  19533. put_byte(s, 0);
  19534. put_byte(s, 0);
  19535. put_byte(s, 0);
  19536. put_byte(s, 0);
  19537. put_byte(s, s.level === 9 ? 2 :
  19538. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19539. 4 : 0));
  19540. put_byte(s, OS_CODE);
  19541. s.status = BUSY_STATE;
  19542. }
  19543. else {
  19544. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19545. (s.gzhead.hcrc ? 2 : 0) +
  19546. (!s.gzhead.extra ? 0 : 4) +
  19547. (!s.gzhead.name ? 0 : 8) +
  19548. (!s.gzhead.comment ? 0 : 16)
  19549. );
  19550. put_byte(s, s.gzhead.time & 0xff);
  19551. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19552. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19553. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19554. put_byte(s, s.level === 9 ? 2 :
  19555. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19556. 4 : 0));
  19557. put_byte(s, s.gzhead.os & 0xff);
  19558. if (s.gzhead.extra && s.gzhead.extra.length) {
  19559. put_byte(s, s.gzhead.extra.length & 0xff);
  19560. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19561. }
  19562. if (s.gzhead.hcrc) {
  19563. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19564. }
  19565. s.gzindex = 0;
  19566. s.status = EXTRA_STATE;
  19567. }
  19568. }
  19569. else // DEFLATE header
  19570. {
  19571. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19572. var level_flags = -1;
  19573. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19574. level_flags = 0;
  19575. } else if (s.level < 6) {
  19576. level_flags = 1;
  19577. } else if (s.level === 6) {
  19578. level_flags = 2;
  19579. } else {
  19580. level_flags = 3;
  19581. }
  19582. header |= (level_flags << 6);
  19583. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19584. header += 31 - (header % 31);
  19585. s.status = BUSY_STATE;
  19586. putShortMSB(s, header);
  19587. /* Save the adler32 of the preset dictionary: */
  19588. if (s.strstart !== 0) {
  19589. putShortMSB(s, strm.adler >>> 16);
  19590. putShortMSB(s, strm.adler & 0xffff);
  19591. }
  19592. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19593. }
  19594. }
  19595. //#ifdef GZIP
  19596. if (s.status === EXTRA_STATE) {
  19597. if (s.gzhead.extra/* != Z_NULL*/) {
  19598. beg = s.pending; /* start of bytes to update crc */
  19599. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19600. if (s.pending === s.pending_buf_size) {
  19601. if (s.gzhead.hcrc && s.pending > beg) {
  19602. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19603. }
  19604. flush_pending(strm);
  19605. beg = s.pending;
  19606. if (s.pending === s.pending_buf_size) {
  19607. break;
  19608. }
  19609. }
  19610. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19611. s.gzindex++;
  19612. }
  19613. if (s.gzhead.hcrc && s.pending > beg) {
  19614. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19615. }
  19616. if (s.gzindex === s.gzhead.extra.length) {
  19617. s.gzindex = 0;
  19618. s.status = NAME_STATE;
  19619. }
  19620. }
  19621. else {
  19622. s.status = NAME_STATE;
  19623. }
  19624. }
  19625. if (s.status === NAME_STATE) {
  19626. if (s.gzhead.name/* != Z_NULL*/) {
  19627. beg = s.pending; /* start of bytes to update crc */
  19628. //int val;
  19629. do {
  19630. if (s.pending === s.pending_buf_size) {
  19631. if (s.gzhead.hcrc && s.pending > beg) {
  19632. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19633. }
  19634. flush_pending(strm);
  19635. beg = s.pending;
  19636. if (s.pending === s.pending_buf_size) {
  19637. val = 1;
  19638. break;
  19639. }
  19640. }
  19641. // JS specific: little magic to add zero terminator to end of string
  19642. if (s.gzindex < s.gzhead.name.length) {
  19643. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19644. } else {
  19645. val = 0;
  19646. }
  19647. put_byte(s, val);
  19648. } while (val !== 0);
  19649. if (s.gzhead.hcrc && s.pending > beg){
  19650. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19651. }
  19652. if (val === 0) {
  19653. s.gzindex = 0;
  19654. s.status = COMMENT_STATE;
  19655. }
  19656. }
  19657. else {
  19658. s.status = COMMENT_STATE;
  19659. }
  19660. }
  19661. if (s.status === COMMENT_STATE) {
  19662. if (s.gzhead.comment/* != Z_NULL*/) {
  19663. beg = s.pending; /* start of bytes to update crc */
  19664. //int val;
  19665. do {
  19666. if (s.pending === s.pending_buf_size) {
  19667. if (s.gzhead.hcrc && s.pending > beg) {
  19668. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19669. }
  19670. flush_pending(strm);
  19671. beg = s.pending;
  19672. if (s.pending === s.pending_buf_size) {
  19673. val = 1;
  19674. break;
  19675. }
  19676. }
  19677. // JS specific: little magic to add zero terminator to end of string
  19678. if (s.gzindex < s.gzhead.comment.length) {
  19679. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19680. } else {
  19681. val = 0;
  19682. }
  19683. put_byte(s, val);
  19684. } while (val !== 0);
  19685. if (s.gzhead.hcrc && s.pending > beg) {
  19686. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19687. }
  19688. if (val === 0) {
  19689. s.status = HCRC_STATE;
  19690. }
  19691. }
  19692. else {
  19693. s.status = HCRC_STATE;
  19694. }
  19695. }
  19696. if (s.status === HCRC_STATE) {
  19697. if (s.gzhead.hcrc) {
  19698. if (s.pending + 2 > s.pending_buf_size) {
  19699. flush_pending(strm);
  19700. }
  19701. if (s.pending + 2 <= s.pending_buf_size) {
  19702. put_byte(s, strm.adler & 0xff);
  19703. put_byte(s, (strm.adler >> 8) & 0xff);
  19704. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19705. s.status = BUSY_STATE;
  19706. }
  19707. }
  19708. else {
  19709. s.status = BUSY_STATE;
  19710. }
  19711. }
  19712. //#endif
  19713. /* Flush as much pending output as possible */
  19714. if (s.pending !== 0) {
  19715. flush_pending(strm);
  19716. if (strm.avail_out === 0) {
  19717. /* Since avail_out is 0, deflate will be called again with
  19718. * more output space, but possibly with both pending and
  19719. * avail_in equal to zero. There won't be anything to do,
  19720. * but this is not an error situation so make sure we
  19721. * return OK instead of BUF_ERROR at next call of deflate:
  19722. */
  19723. s.last_flush = -1;
  19724. return Z_OK;
  19725. }
  19726. /* Make sure there is something to do and avoid duplicate consecutive
  19727. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19728. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19729. */
  19730. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19731. flush !== Z_FINISH) {
  19732. return err(strm, Z_BUF_ERROR);
  19733. }
  19734. /* User must not provide more input after the first FINISH: */
  19735. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19736. return err(strm, Z_BUF_ERROR);
  19737. }
  19738. /* Start a new block or continue the current one.
  19739. */
  19740. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19741. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19742. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19743. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19744. configuration_table[s.level].func(s, flush));
  19745. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19746. s.status = FINISH_STATE;
  19747. }
  19748. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19749. if (strm.avail_out === 0) {
  19750. s.last_flush = -1;
  19751. /* avoid BUF_ERROR next call, see above */
  19752. }
  19753. return Z_OK;
  19754. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19755. * of deflate should use the same flush parameter to make sure
  19756. * that the flush is complete. So we don't have to output an
  19757. * empty block here, this will be done at next call. This also
  19758. * ensures that for a very small output buffer, we emit at most
  19759. * one empty block.
  19760. */
  19761. }
  19762. if (bstate === BS_BLOCK_DONE) {
  19763. if (flush === Z_PARTIAL_FLUSH) {
  19764. trees._tr_align(s);
  19765. }
  19766. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19767. trees._tr_stored_block(s, 0, 0, false);
  19768. /* For a full flush, this empty block will be recognized
  19769. * as a special marker by inflate_sync().
  19770. */
  19771. if (flush === Z_FULL_FLUSH) {
  19772. /*** CLEAR_HASH(s); ***/ /* forget history */
  19773. zero(s.head); // Fill with NIL (= 0);
  19774. if (s.lookahead === 0) {
  19775. s.strstart = 0;
  19776. s.block_start = 0;
  19777. s.insert = 0;
  19778. }
  19779. }
  19780. }
  19781. flush_pending(strm);
  19782. if (strm.avail_out === 0) {
  19783. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19784. return Z_OK;
  19785. }
  19786. }
  19787. }
  19788. //Assert(strm->avail_out > 0, "bug2");
  19789. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19790. if (flush !== Z_FINISH) { return Z_OK; }
  19791. if (s.wrap <= 0) { return Z_STREAM_END; }
  19792. /* Write the trailer */
  19793. if (s.wrap === 2) {
  19794. put_byte(s, strm.adler & 0xff);
  19795. put_byte(s, (strm.adler >> 8) & 0xff);
  19796. put_byte(s, (strm.adler >> 16) & 0xff);
  19797. put_byte(s, (strm.adler >> 24) & 0xff);
  19798. put_byte(s, strm.total_in & 0xff);
  19799. put_byte(s, (strm.total_in >> 8) & 0xff);
  19800. put_byte(s, (strm.total_in >> 16) & 0xff);
  19801. put_byte(s, (strm.total_in >> 24) & 0xff);
  19802. }
  19803. else
  19804. {
  19805. putShortMSB(s, strm.adler >>> 16);
  19806. putShortMSB(s, strm.adler & 0xffff);
  19807. }
  19808. flush_pending(strm);
  19809. /* If avail_out is zero, the application will call deflate again
  19810. * to flush the rest.
  19811. */
  19812. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19813. /* write the trailer only once! */
  19814. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19815. }
  19816. function deflateEnd(strm) {
  19817. var status;
  19818. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19819. return Z_STREAM_ERROR;
  19820. }
  19821. status = strm.state.status;
  19822. if (status !== INIT_STATE &&
  19823. status !== EXTRA_STATE &&
  19824. status !== NAME_STATE &&
  19825. status !== COMMENT_STATE &&
  19826. status !== HCRC_STATE &&
  19827. status !== BUSY_STATE &&
  19828. status !== FINISH_STATE
  19829. ) {
  19830. return err(strm, Z_STREAM_ERROR);
  19831. }
  19832. strm.state = null;
  19833. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19834. }
  19835. /* =========================================================================
  19836. * Copy the source state to the destination state
  19837. */
  19838. //function deflateCopy(dest, source) {
  19839. //
  19840. //}
  19841. exports.deflateInit = deflateInit;
  19842. exports.deflateInit2 = deflateInit2;
  19843. exports.deflateReset = deflateReset;
  19844. exports.deflateResetKeep = deflateResetKeep;
  19845. exports.deflateSetHeader = deflateSetHeader;
  19846. exports.deflate = deflate;
  19847. exports.deflateEnd = deflateEnd;
  19848. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19849. /* Not implemented
  19850. exports.deflateBound = deflateBound;
  19851. exports.deflateCopy = deflateCopy;
  19852. exports.deflateSetDictionary = deflateSetDictionary;
  19853. exports.deflateParams = deflateParams;
  19854. exports.deflatePending = deflatePending;
  19855. exports.deflatePrime = deflatePrime;
  19856. exports.deflateTune = deflateTune;
  19857. */
  19858. },{"../utils/common":67,"./adler32":69,"./crc32":71,"./messages":77,"./trees":78}],73:[function(require,module,exports){
  19859. 'use strict';
  19860. function GZheader() {
  19861. /* true if compressed data believed to be text */
  19862. this.text = 0;
  19863. /* modification time */
  19864. this.time = 0;
  19865. /* extra flags (not used when writing a gzip file) */
  19866. this.xflags = 0;
  19867. /* operating system */
  19868. this.os = 0;
  19869. /* pointer to extra field or Z_NULL if none */
  19870. this.extra = null;
  19871. /* extra field length (valid if extra != Z_NULL) */
  19872. this.extra_len = 0; // Actually, we don't need it in JS,
  19873. // but leave for few code modifications
  19874. //
  19875. // Setup limits is not necessary because in js we should not preallocate memory
  19876. // for inflate use constant limit in 65536 bytes
  19877. //
  19878. /* space at extra (only when reading header) */
  19879. // this.extra_max = 0;
  19880. /* pointer to zero-terminated file name or Z_NULL */
  19881. this.name = '';
  19882. /* space at name (only when reading header) */
  19883. // this.name_max = 0;
  19884. /* pointer to zero-terminated comment or Z_NULL */
  19885. this.comment = '';
  19886. /* space at comment (only when reading header) */
  19887. // this.comm_max = 0;
  19888. /* true if there was or will be a header crc */
  19889. this.hcrc = 0;
  19890. /* true when done reading gzip header (not used when writing a gzip file) */
  19891. this.done = false;
  19892. }
  19893. module.exports = GZheader;
  19894. },{}],74:[function(require,module,exports){
  19895. 'use strict';
  19896. // See state defs from inflate.js
  19897. var BAD = 30; /* got a data error -- remain here until reset */
  19898. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19899. /*
  19900. Decode literal, length, and distance codes and write out the resulting
  19901. literal and match bytes until either not enough input or output is
  19902. available, an end-of-block is encountered, or a data error is encountered.
  19903. When large enough input and output buffers are supplied to inflate(), for
  19904. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19905. inflate execution time is spent in this routine.
  19906. Entry assumptions:
  19907. state.mode === LEN
  19908. strm.avail_in >= 6
  19909. strm.avail_out >= 258
  19910. start >= strm.avail_out
  19911. state.bits < 8
  19912. On return, state.mode is one of:
  19913. LEN -- ran out of enough output space or enough available input
  19914. TYPE -- reached end of block code, inflate() to interpret next block
  19915. BAD -- error in block data
  19916. Notes:
  19917. - The maximum input bits used by a length/distance pair is 15 bits for the
  19918. length code, 5 bits for the length extra, 15 bits for the distance code,
  19919. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19920. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19921. checking for available input while decoding.
  19922. - The maximum bytes that a single length/distance pair can output is 258
  19923. bytes, which is the maximum length that can be coded. inflate_fast()
  19924. requires strm.avail_out >= 258 for each loop to avoid checking for
  19925. output space.
  19926. */
  19927. module.exports = function inflate_fast(strm, start) {
  19928. var state;
  19929. var _in; /* local strm.input */
  19930. var last; /* have enough input while in < last */
  19931. var _out; /* local strm.output */
  19932. var beg; /* inflate()'s initial strm.output */
  19933. var end; /* while out < end, enough space available */
  19934. //#ifdef INFLATE_STRICT
  19935. var dmax; /* maximum distance from zlib header */
  19936. //#endif
  19937. var wsize; /* window size or zero if not using window */
  19938. var whave; /* valid bytes in the window */
  19939. var wnext; /* window write index */
  19940. var window; /* allocated sliding window, if wsize != 0 */
  19941. var hold; /* local strm.hold */
  19942. var bits; /* local strm.bits */
  19943. var lcode; /* local strm.lencode */
  19944. var dcode; /* local strm.distcode */
  19945. var lmask; /* mask for first level of length codes */
  19946. var dmask; /* mask for first level of distance codes */
  19947. var here; /* retrieved table entry */
  19948. var op; /* code bits, operation, extra bits, or */
  19949. /* window position, window bytes to copy */
  19950. var len; /* match length, unused bytes */
  19951. var dist; /* match distance */
  19952. var from; /* where to copy match from */
  19953. var from_source;
  19954. var input, output; // JS specific, because we have no pointers
  19955. /* copy state to local variables */
  19956. state = strm.state;
  19957. //here = state.here;
  19958. _in = strm.next_in;
  19959. input = strm.input;
  19960. last = _in + (strm.avail_in - 5);
  19961. _out = strm.next_out;
  19962. output = strm.output;
  19963. beg = _out - (start - strm.avail_out);
  19964. end = _out + (strm.avail_out - 257);
  19965. //#ifdef INFLATE_STRICT
  19966. dmax = state.dmax;
  19967. //#endif
  19968. wsize = state.wsize;
  19969. whave = state.whave;
  19970. wnext = state.wnext;
  19971. window = state.window;
  19972. hold = state.hold;
  19973. bits = state.bits;
  19974. lcode = state.lencode;
  19975. dcode = state.distcode;
  19976. lmask = (1 << state.lenbits) - 1;
  19977. dmask = (1 << state.distbits) - 1;
  19978. /* decode literals and length/distances until end-of-block or not enough
  19979. input data or output space */
  19980. top:
  19981. do {
  19982. if (bits < 15) {
  19983. hold += input[_in++] << bits;
  19984. bits += 8;
  19985. hold += input[_in++] << bits;
  19986. bits += 8;
  19987. }
  19988. here = lcode[hold & lmask];
  19989. dolen:
  19990. for (;;) { // Goto emulation
  19991. op = here >>> 24/*here.bits*/;
  19992. hold >>>= op;
  19993. bits -= op;
  19994. op = (here >>> 16) & 0xff/*here.op*/;
  19995. if (op === 0) { /* literal */
  19996. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19997. // "inflate: literal '%c'\n" :
  19998. // "inflate: literal 0x%02x\n", here.val));
  19999. output[_out++] = here & 0xffff/*here.val*/;
  20000. }
  20001. else if (op & 16) { /* length base */
  20002. len = here & 0xffff/*here.val*/;
  20003. op &= 15; /* number of extra bits */
  20004. if (op) {
  20005. if (bits < op) {
  20006. hold += input[_in++] << bits;
  20007. bits += 8;
  20008. }
  20009. len += hold & ((1 << op) - 1);
  20010. hold >>>= op;
  20011. bits -= op;
  20012. }
  20013. //Tracevv((stderr, "inflate: length %u\n", len));
  20014. if (bits < 15) {
  20015. hold += input[_in++] << bits;
  20016. bits += 8;
  20017. hold += input[_in++] << bits;
  20018. bits += 8;
  20019. }
  20020. here = dcode[hold & dmask];
  20021. dodist:
  20022. for (;;) { // goto emulation
  20023. op = here >>> 24/*here.bits*/;
  20024. hold >>>= op;
  20025. bits -= op;
  20026. op = (here >>> 16) & 0xff/*here.op*/;
  20027. if (op & 16) { /* distance base */
  20028. dist = here & 0xffff/*here.val*/;
  20029. op &= 15; /* number of extra bits */
  20030. if (bits < op) {
  20031. hold += input[_in++] << bits;
  20032. bits += 8;
  20033. if (bits < op) {
  20034. hold += input[_in++] << bits;
  20035. bits += 8;
  20036. }
  20037. }
  20038. dist += hold & ((1 << op) - 1);
  20039. //#ifdef INFLATE_STRICT
  20040. if (dist > dmax) {
  20041. strm.msg = 'invalid distance too far back';
  20042. state.mode = BAD;
  20043. break top;
  20044. }
  20045. //#endif
  20046. hold >>>= op;
  20047. bits -= op;
  20048. //Tracevv((stderr, "inflate: distance %u\n", dist));
  20049. op = _out - beg; /* max distance in output */
  20050. if (dist > op) { /* see if copy from window */
  20051. op = dist - op; /* distance back in window */
  20052. if (op > whave) {
  20053. if (state.sane) {
  20054. strm.msg = 'invalid distance too far back';
  20055. state.mode = BAD;
  20056. break top;
  20057. }
  20058. // (!) This block is disabled in zlib defailts,
  20059. // don't enable it for binary compatibility
  20060. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20061. // if (len <= op - whave) {
  20062. // do {
  20063. // output[_out++] = 0;
  20064. // } while (--len);
  20065. // continue top;
  20066. // }
  20067. // len -= op - whave;
  20068. // do {
  20069. // output[_out++] = 0;
  20070. // } while (--op > whave);
  20071. // if (op === 0) {
  20072. // from = _out - dist;
  20073. // do {
  20074. // output[_out++] = output[from++];
  20075. // } while (--len);
  20076. // continue top;
  20077. // }
  20078. //#endif
  20079. }
  20080. from = 0; // window index
  20081. from_source = window;
  20082. if (wnext === 0) { /* very common case */
  20083. from += wsize - op;
  20084. if (op < len) { /* some from window */
  20085. len -= op;
  20086. do {
  20087. output[_out++] = window[from++];
  20088. } while (--op);
  20089. from = _out - dist; /* rest from output */
  20090. from_source = output;
  20091. }
  20092. }
  20093. else if (wnext < op) { /* wrap around window */
  20094. from += wsize + wnext - op;
  20095. op -= wnext;
  20096. if (op < len) { /* some from end of window */
  20097. len -= op;
  20098. do {
  20099. output[_out++] = window[from++];
  20100. } while (--op);
  20101. from = 0;
  20102. if (wnext < len) { /* some from start of window */
  20103. op = wnext;
  20104. len -= op;
  20105. do {
  20106. output[_out++] = window[from++];
  20107. } while (--op);
  20108. from = _out - dist; /* rest from output */
  20109. from_source = output;
  20110. }
  20111. }
  20112. }
  20113. else { /* contiguous in window */
  20114. from += wnext - op;
  20115. if (op < len) { /* some from window */
  20116. len -= op;
  20117. do {
  20118. output[_out++] = window[from++];
  20119. } while (--op);
  20120. from = _out - dist; /* rest from output */
  20121. from_source = output;
  20122. }
  20123. }
  20124. while (len > 2) {
  20125. output[_out++] = from_source[from++];
  20126. output[_out++] = from_source[from++];
  20127. output[_out++] = from_source[from++];
  20128. len -= 3;
  20129. }
  20130. if (len) {
  20131. output[_out++] = from_source[from++];
  20132. if (len > 1) {
  20133. output[_out++] = from_source[from++];
  20134. }
  20135. }
  20136. }
  20137. else {
  20138. from = _out - dist; /* copy direct from output */
  20139. do { /* minimum length is three */
  20140. output[_out++] = output[from++];
  20141. output[_out++] = output[from++];
  20142. output[_out++] = output[from++];
  20143. len -= 3;
  20144. } while (len > 2);
  20145. if (len) {
  20146. output[_out++] = output[from++];
  20147. if (len > 1) {
  20148. output[_out++] = output[from++];
  20149. }
  20150. }
  20151. }
  20152. }
  20153. else if ((op & 64) === 0) { /* 2nd level distance code */
  20154. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  20155. continue dodist;
  20156. }
  20157. else {
  20158. strm.msg = 'invalid distance code';
  20159. state.mode = BAD;
  20160. break top;
  20161. }
  20162. break; // need to emulate goto via "continue"
  20163. }
  20164. }
  20165. else if ((op & 64) === 0) { /* 2nd level length code */
  20166. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  20167. continue dolen;
  20168. }
  20169. else if (op & 32) { /* end-of-block */
  20170. //Tracevv((stderr, "inflate: end of block\n"));
  20171. state.mode = TYPE;
  20172. break top;
  20173. }
  20174. else {
  20175. strm.msg = 'invalid literal/length code';
  20176. state.mode = BAD;
  20177. break top;
  20178. }
  20179. break; // need to emulate goto via "continue"
  20180. }
  20181. } while (_in < last && _out < end);
  20182. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  20183. len = bits >> 3;
  20184. _in -= len;
  20185. bits -= len << 3;
  20186. hold &= (1 << bits) - 1;
  20187. /* update state and return */
  20188. strm.next_in = _in;
  20189. strm.next_out = _out;
  20190. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  20191. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  20192. state.hold = hold;
  20193. state.bits = bits;
  20194. return;
  20195. };
  20196. },{}],75:[function(require,module,exports){
  20197. 'use strict';
  20198. var utils = require('../utils/common');
  20199. var adler32 = require('./adler32');
  20200. var crc32 = require('./crc32');
  20201. var inflate_fast = require('./inffast');
  20202. var inflate_table = require('./inftrees');
  20203. var CODES = 0;
  20204. var LENS = 1;
  20205. var DISTS = 2;
  20206. /* Public constants ==========================================================*/
  20207. /* ===========================================================================*/
  20208. /* Allowed flush values; see deflate() and inflate() below for details */
  20209. //var Z_NO_FLUSH = 0;
  20210. //var Z_PARTIAL_FLUSH = 1;
  20211. //var Z_SYNC_FLUSH = 2;
  20212. //var Z_FULL_FLUSH = 3;
  20213. var Z_FINISH = 4;
  20214. var Z_BLOCK = 5;
  20215. var Z_TREES = 6;
  20216. /* Return codes for the compression/decompression functions. Negative values
  20217. * are errors, positive values are used for special but normal events.
  20218. */
  20219. var Z_OK = 0;
  20220. var Z_STREAM_END = 1;
  20221. var Z_NEED_DICT = 2;
  20222. //var Z_ERRNO = -1;
  20223. var Z_STREAM_ERROR = -2;
  20224. var Z_DATA_ERROR = -3;
  20225. var Z_MEM_ERROR = -4;
  20226. var Z_BUF_ERROR = -5;
  20227. //var Z_VERSION_ERROR = -6;
  20228. /* The deflate compression method */
  20229. var Z_DEFLATED = 8;
  20230. /* STATES ====================================================================*/
  20231. /* ===========================================================================*/
  20232. var HEAD = 1; /* i: waiting for magic header */
  20233. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  20234. var TIME = 3; /* i: waiting for modification time (gzip) */
  20235. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  20236. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  20237. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  20238. var NAME = 7; /* i: waiting for end of file name (gzip) */
  20239. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  20240. var HCRC = 9; /* i: waiting for header crc (gzip) */
  20241. var DICTID = 10; /* i: waiting for dictionary check value */
  20242. var DICT = 11; /* waiting for inflateSetDictionary() call */
  20243. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  20244. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  20245. var STORED = 14; /* i: waiting for stored size (length and complement) */
  20246. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  20247. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  20248. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  20249. var LENLENS = 18; /* i: waiting for code length code lengths */
  20250. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  20251. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  20252. var LEN = 21; /* i: waiting for length/lit/eob code */
  20253. var LENEXT = 22; /* i: waiting for length extra bits */
  20254. var DIST = 23; /* i: waiting for distance code */
  20255. var DISTEXT = 24; /* i: waiting for distance extra bits */
  20256. var MATCH = 25; /* o: waiting for output space to copy string */
  20257. var LIT = 26; /* o: waiting for output space to write literal */
  20258. var CHECK = 27; /* i: waiting for 32-bit check value */
  20259. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  20260. var DONE = 29; /* finished check, done -- remain here until reset */
  20261. var BAD = 30; /* got a data error -- remain here until reset */
  20262. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  20263. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  20264. /* ===========================================================================*/
  20265. var ENOUGH_LENS = 852;
  20266. var ENOUGH_DISTS = 592;
  20267. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20268. var MAX_WBITS = 15;
  20269. /* 32K LZ77 window */
  20270. var DEF_WBITS = MAX_WBITS;
  20271. function ZSWAP32(q) {
  20272. return (((q >>> 24) & 0xff) +
  20273. ((q >>> 8) & 0xff00) +
  20274. ((q & 0xff00) << 8) +
  20275. ((q & 0xff) << 24));
  20276. }
  20277. function InflateState() {
  20278. this.mode = 0; /* current inflate mode */
  20279. this.last = false; /* true if processing last block */
  20280. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20281. this.havedict = false; /* true if dictionary provided */
  20282. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  20283. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  20284. this.check = 0; /* protected copy of check value */
  20285. this.total = 0; /* protected copy of output count */
  20286. // TODO: may be {}
  20287. this.head = null; /* where to save gzip header information */
  20288. /* sliding window */
  20289. this.wbits = 0; /* log base 2 of requested window size */
  20290. this.wsize = 0; /* window size or zero if not using window */
  20291. this.whave = 0; /* valid bytes in the window */
  20292. this.wnext = 0; /* window write index */
  20293. this.window = null; /* allocated sliding window, if needed */
  20294. /* bit accumulator */
  20295. this.hold = 0; /* input bit accumulator */
  20296. this.bits = 0; /* number of bits in "in" */
  20297. /* for string and stored block copying */
  20298. this.length = 0; /* literal or length of data to copy */
  20299. this.offset = 0; /* distance back to copy string from */
  20300. /* for table and code decoding */
  20301. this.extra = 0; /* extra bits needed */
  20302. /* fixed and dynamic code tables */
  20303. this.lencode = null; /* starting table for length/literal codes */
  20304. this.distcode = null; /* starting table for distance codes */
  20305. this.lenbits = 0; /* index bits for lencode */
  20306. this.distbits = 0; /* index bits for distcode */
  20307. /* dynamic table building */
  20308. this.ncode = 0; /* number of code length code lengths */
  20309. this.nlen = 0; /* number of length code lengths */
  20310. this.ndist = 0; /* number of distance code lengths */
  20311. this.have = 0; /* number of code lengths in lens[] */
  20312. this.next = null; /* next available space in codes[] */
  20313. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  20314. this.work = new utils.Buf16(288); /* work area for code table building */
  20315. /*
  20316. because we don't have pointers in js, we use lencode and distcode directly
  20317. as buffers so we don't need codes
  20318. */
  20319. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  20320. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  20321. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  20322. this.sane = 0; /* if false, allow invalid distance too far */
  20323. this.back = 0; /* bits back of last unprocessed length/lit */
  20324. this.was = 0; /* initial length of match */
  20325. }
  20326. function inflateResetKeep(strm) {
  20327. var state;
  20328. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20329. state = strm.state;
  20330. strm.total_in = strm.total_out = state.total = 0;
  20331. strm.msg = ''; /*Z_NULL*/
  20332. if (state.wrap) { /* to support ill-conceived Java test suite */
  20333. strm.adler = state.wrap & 1;
  20334. }
  20335. state.mode = HEAD;
  20336. state.last = 0;
  20337. state.havedict = 0;
  20338. state.dmax = 32768;
  20339. state.head = null/*Z_NULL*/;
  20340. state.hold = 0;
  20341. state.bits = 0;
  20342. //state.lencode = state.distcode = state.next = state.codes;
  20343. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  20344. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  20345. state.sane = 1;
  20346. state.back = -1;
  20347. //Tracev((stderr, "inflate: reset\n"));
  20348. return Z_OK;
  20349. }
  20350. function inflateReset(strm) {
  20351. var state;
  20352. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20353. state = strm.state;
  20354. state.wsize = 0;
  20355. state.whave = 0;
  20356. state.wnext = 0;
  20357. return inflateResetKeep(strm);
  20358. }
  20359. function inflateReset2(strm, windowBits) {
  20360. var wrap;
  20361. var state;
  20362. /* get the state */
  20363. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20364. state = strm.state;
  20365. /* extract wrap request from windowBits parameter */
  20366. if (windowBits < 0) {
  20367. wrap = 0;
  20368. windowBits = -windowBits;
  20369. }
  20370. else {
  20371. wrap = (windowBits >> 4) + 1;
  20372. if (windowBits < 48) {
  20373. windowBits &= 15;
  20374. }
  20375. }
  20376. /* set number of window bits, free window if different */
  20377. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  20378. return Z_STREAM_ERROR;
  20379. }
  20380. if (state.window !== null && state.wbits !== windowBits) {
  20381. state.window = null;
  20382. }
  20383. /* update state and reset the rest of it */
  20384. state.wrap = wrap;
  20385. state.wbits = windowBits;
  20386. return inflateReset(strm);
  20387. }
  20388. function inflateInit2(strm, windowBits) {
  20389. var ret;
  20390. var state;
  20391. if (!strm) { return Z_STREAM_ERROR; }
  20392. //strm.msg = Z_NULL; /* in case we return an error */
  20393. state = new InflateState();
  20394. //if (state === Z_NULL) return Z_MEM_ERROR;
  20395. //Tracev((stderr, "inflate: allocated\n"));
  20396. strm.state = state;
  20397. state.window = null/*Z_NULL*/;
  20398. ret = inflateReset2(strm, windowBits);
  20399. if (ret !== Z_OK) {
  20400. strm.state = null/*Z_NULL*/;
  20401. }
  20402. return ret;
  20403. }
  20404. function inflateInit(strm) {
  20405. return inflateInit2(strm, DEF_WBITS);
  20406. }
  20407. /*
  20408. Return state with length and distance decoding tables and index sizes set to
  20409. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  20410. If BUILDFIXED is defined, then instead this routine builds the tables the
  20411. first time it's called, and returns those tables the first time and
  20412. thereafter. This reduces the size of the code by about 2K bytes, in
  20413. exchange for a little execution time. However, BUILDFIXED should not be
  20414. used for threaded applications, since the rewriting of the tables and virgin
  20415. may not be thread-safe.
  20416. */
  20417. var virgin = true;
  20418. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  20419. function fixedtables(state) {
  20420. /* build fixed huffman tables if first call (may not be thread safe) */
  20421. if (virgin) {
  20422. var sym;
  20423. lenfix = new utils.Buf32(512);
  20424. distfix = new utils.Buf32(32);
  20425. /* literal/length table */
  20426. sym = 0;
  20427. while (sym < 144) { state.lens[sym++] = 8; }
  20428. while (sym < 256) { state.lens[sym++] = 9; }
  20429. while (sym < 280) { state.lens[sym++] = 7; }
  20430. while (sym < 288) { state.lens[sym++] = 8; }
  20431. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  20432. /* distance table */
  20433. sym = 0;
  20434. while (sym < 32) { state.lens[sym++] = 5; }
  20435. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  20436. /* do this just once */
  20437. virgin = false;
  20438. }
  20439. state.lencode = lenfix;
  20440. state.lenbits = 9;
  20441. state.distcode = distfix;
  20442. state.distbits = 5;
  20443. }
  20444. /*
  20445. Update the window with the last wsize (normally 32K) bytes written before
  20446. returning. If window does not exist yet, create it. This is only called
  20447. when a window is already in use, or when output has been written during this
  20448. inflate call, but the end of the deflate stream has not been reached yet.
  20449. It is also called to create a window for dictionary data when a dictionary
  20450. is loaded.
  20451. Providing output buffers larger than 32K to inflate() should provide a speed
  20452. advantage, since only the last 32K of output is copied to the sliding window
  20453. upon return from inflate(), and since all distances after the first 32K of
  20454. output will fall in the output data, making match copies simpler and faster.
  20455. The advantage may be dependent on the size of the processor's data caches.
  20456. */
  20457. function updatewindow(strm, src, end, copy) {
  20458. var dist;
  20459. var state = strm.state;
  20460. /* if it hasn't been done already, allocate space for the window */
  20461. if (state.window === null) {
  20462. state.wsize = 1 << state.wbits;
  20463. state.wnext = 0;
  20464. state.whave = 0;
  20465. state.window = new utils.Buf8(state.wsize);
  20466. }
  20467. /* copy state->wsize or less output bytes into the circular window */
  20468. if (copy >= state.wsize) {
  20469. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  20470. state.wnext = 0;
  20471. state.whave = state.wsize;
  20472. }
  20473. else {
  20474. dist = state.wsize - state.wnext;
  20475. if (dist > copy) {
  20476. dist = copy;
  20477. }
  20478. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20479. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20480. copy -= dist;
  20481. if (copy) {
  20482. //zmemcpy(state->window, end - copy, copy);
  20483. utils.arraySet(state.window,src, end - copy, copy, 0);
  20484. state.wnext = copy;
  20485. state.whave = state.wsize;
  20486. }
  20487. else {
  20488. state.wnext += dist;
  20489. if (state.wnext === state.wsize) { state.wnext = 0; }
  20490. if (state.whave < state.wsize) { state.whave += dist; }
  20491. }
  20492. }
  20493. return 0;
  20494. }
  20495. function inflate(strm, flush) {
  20496. var state;
  20497. var input, output; // input/output buffers
  20498. var next; /* next input INDEX */
  20499. var put; /* next output INDEX */
  20500. var have, left; /* available input and output */
  20501. var hold; /* bit buffer */
  20502. var bits; /* bits in bit buffer */
  20503. var _in, _out; /* save starting available input and output */
  20504. var copy; /* number of stored or match bytes to copy */
  20505. var from; /* where to copy match bytes from */
  20506. var from_source;
  20507. var here = 0; /* current decoding table entry */
  20508. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  20509. //var last; /* parent table entry */
  20510. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  20511. var len; /* length to copy for repeats, bits to drop */
  20512. var ret; /* return code */
  20513. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  20514. var opts;
  20515. var n; // temporary var for NEED_BITS
  20516. var order = /* permutation of code lengths */
  20517. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  20518. if (!strm || !strm.state || !strm.output ||
  20519. (!strm.input && strm.avail_in !== 0)) {
  20520. return Z_STREAM_ERROR;
  20521. }
  20522. state = strm.state;
  20523. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  20524. //--- LOAD() ---
  20525. put = strm.next_out;
  20526. output = strm.output;
  20527. left = strm.avail_out;
  20528. next = strm.next_in;
  20529. input = strm.input;
  20530. have = strm.avail_in;
  20531. hold = state.hold;
  20532. bits = state.bits;
  20533. //---
  20534. _in = have;
  20535. _out = left;
  20536. ret = Z_OK;
  20537. inf_leave: // goto emulation
  20538. for (;;) {
  20539. switch (state.mode) {
  20540. case HEAD:
  20541. if (state.wrap === 0) {
  20542. state.mode = TYPEDO;
  20543. break;
  20544. }
  20545. //=== NEEDBITS(16);
  20546. while (bits < 16) {
  20547. if (have === 0) { break inf_leave; }
  20548. have--;
  20549. hold += input[next++] << bits;
  20550. bits += 8;
  20551. }
  20552. //===//
  20553. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20554. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20555. //=== CRC2(state.check, hold);
  20556. hbuf[0] = hold & 0xff;
  20557. hbuf[1] = (hold >>> 8) & 0xff;
  20558. state.check = crc32(state.check, hbuf, 2, 0);
  20559. //===//
  20560. //=== INITBITS();
  20561. hold = 0;
  20562. bits = 0;
  20563. //===//
  20564. state.mode = FLAGS;
  20565. break;
  20566. }
  20567. state.flags = 0; /* expect zlib header */
  20568. if (state.head) {
  20569. state.head.done = false;
  20570. }
  20571. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20572. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20573. strm.msg = 'incorrect header check';
  20574. state.mode = BAD;
  20575. break;
  20576. }
  20577. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20578. strm.msg = 'unknown compression method';
  20579. state.mode = BAD;
  20580. break;
  20581. }
  20582. //--- DROPBITS(4) ---//
  20583. hold >>>= 4;
  20584. bits -= 4;
  20585. //---//
  20586. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20587. if (state.wbits === 0) {
  20588. state.wbits = len;
  20589. }
  20590. else if (len > state.wbits) {
  20591. strm.msg = 'invalid window size';
  20592. state.mode = BAD;
  20593. break;
  20594. }
  20595. state.dmax = 1 << len;
  20596. //Tracev((stderr, "inflate: zlib header ok\n"));
  20597. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20598. state.mode = hold & 0x200 ? DICTID : TYPE;
  20599. //=== INITBITS();
  20600. hold = 0;
  20601. bits = 0;
  20602. //===//
  20603. break;
  20604. case FLAGS:
  20605. //=== NEEDBITS(16); */
  20606. while (bits < 16) {
  20607. if (have === 0) { break inf_leave; }
  20608. have--;
  20609. hold += input[next++] << bits;
  20610. bits += 8;
  20611. }
  20612. //===//
  20613. state.flags = hold;
  20614. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20615. strm.msg = 'unknown compression method';
  20616. state.mode = BAD;
  20617. break;
  20618. }
  20619. if (state.flags & 0xe000) {
  20620. strm.msg = 'unknown header flags set';
  20621. state.mode = BAD;
  20622. break;
  20623. }
  20624. if (state.head) {
  20625. state.head.text = ((hold >> 8) & 1);
  20626. }
  20627. if (state.flags & 0x0200) {
  20628. //=== CRC2(state.check, hold);
  20629. hbuf[0] = hold & 0xff;
  20630. hbuf[1] = (hold >>> 8) & 0xff;
  20631. state.check = crc32(state.check, hbuf, 2, 0);
  20632. //===//
  20633. }
  20634. //=== INITBITS();
  20635. hold = 0;
  20636. bits = 0;
  20637. //===//
  20638. state.mode = TIME;
  20639. /* falls through */
  20640. case TIME:
  20641. //=== NEEDBITS(32); */
  20642. while (bits < 32) {
  20643. if (have === 0) { break inf_leave; }
  20644. have--;
  20645. hold += input[next++] << bits;
  20646. bits += 8;
  20647. }
  20648. //===//
  20649. if (state.head) {
  20650. state.head.time = hold;
  20651. }
  20652. if (state.flags & 0x0200) {
  20653. //=== CRC4(state.check, hold)
  20654. hbuf[0] = hold & 0xff;
  20655. hbuf[1] = (hold >>> 8) & 0xff;
  20656. hbuf[2] = (hold >>> 16) & 0xff;
  20657. hbuf[3] = (hold >>> 24) & 0xff;
  20658. state.check = crc32(state.check, hbuf, 4, 0);
  20659. //===
  20660. }
  20661. //=== INITBITS();
  20662. hold = 0;
  20663. bits = 0;
  20664. //===//
  20665. state.mode = OS;
  20666. /* falls through */
  20667. case OS:
  20668. //=== NEEDBITS(16); */
  20669. while (bits < 16) {
  20670. if (have === 0) { break inf_leave; }
  20671. have--;
  20672. hold += input[next++] << bits;
  20673. bits += 8;
  20674. }
  20675. //===//
  20676. if (state.head) {
  20677. state.head.xflags = (hold & 0xff);
  20678. state.head.os = (hold >> 8);
  20679. }
  20680. if (state.flags & 0x0200) {
  20681. //=== CRC2(state.check, hold);
  20682. hbuf[0] = hold & 0xff;
  20683. hbuf[1] = (hold >>> 8) & 0xff;
  20684. state.check = crc32(state.check, hbuf, 2, 0);
  20685. //===//
  20686. }
  20687. //=== INITBITS();
  20688. hold = 0;
  20689. bits = 0;
  20690. //===//
  20691. state.mode = EXLEN;
  20692. /* falls through */
  20693. case EXLEN:
  20694. if (state.flags & 0x0400) {
  20695. //=== NEEDBITS(16); */
  20696. while (bits < 16) {
  20697. if (have === 0) { break inf_leave; }
  20698. have--;
  20699. hold += input[next++] << bits;
  20700. bits += 8;
  20701. }
  20702. //===//
  20703. state.length = hold;
  20704. if (state.head) {
  20705. state.head.extra_len = hold;
  20706. }
  20707. if (state.flags & 0x0200) {
  20708. //=== CRC2(state.check, hold);
  20709. hbuf[0] = hold & 0xff;
  20710. hbuf[1] = (hold >>> 8) & 0xff;
  20711. state.check = crc32(state.check, hbuf, 2, 0);
  20712. //===//
  20713. }
  20714. //=== INITBITS();
  20715. hold = 0;
  20716. bits = 0;
  20717. //===//
  20718. }
  20719. else if (state.head) {
  20720. state.head.extra = null/*Z_NULL*/;
  20721. }
  20722. state.mode = EXTRA;
  20723. /* falls through */
  20724. case EXTRA:
  20725. if (state.flags & 0x0400) {
  20726. copy = state.length;
  20727. if (copy > have) { copy = have; }
  20728. if (copy) {
  20729. if (state.head) {
  20730. len = state.head.extra_len - state.length;
  20731. if (!state.head.extra) {
  20732. // Use untyped array for more conveniend processing later
  20733. state.head.extra = new Array(state.head.extra_len);
  20734. }
  20735. utils.arraySet(
  20736. state.head.extra,
  20737. input,
  20738. next,
  20739. // extra field is limited to 65536 bytes
  20740. // - no need for additional size check
  20741. copy,
  20742. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20743. len
  20744. );
  20745. //zmemcpy(state.head.extra + len, next,
  20746. // len + copy > state.head.extra_max ?
  20747. // state.head.extra_max - len : copy);
  20748. }
  20749. if (state.flags & 0x0200) {
  20750. state.check = crc32(state.check, input, copy, next);
  20751. }
  20752. have -= copy;
  20753. next += copy;
  20754. state.length -= copy;
  20755. }
  20756. if (state.length) { break inf_leave; }
  20757. }
  20758. state.length = 0;
  20759. state.mode = NAME;
  20760. /* falls through */
  20761. case NAME:
  20762. if (state.flags & 0x0800) {
  20763. if (have === 0) { break inf_leave; }
  20764. copy = 0;
  20765. do {
  20766. // TODO: 2 or 1 bytes?
  20767. len = input[next + copy++];
  20768. /* use constant limit because in js we should not preallocate memory */
  20769. if (state.head && len &&
  20770. (state.length < 65536 /*state.head.name_max*/)) {
  20771. state.head.name += String.fromCharCode(len);
  20772. }
  20773. } while (len && copy < have);
  20774. if (state.flags & 0x0200) {
  20775. state.check = crc32(state.check, input, copy, next);
  20776. }
  20777. have -= copy;
  20778. next += copy;
  20779. if (len) { break inf_leave; }
  20780. }
  20781. else if (state.head) {
  20782. state.head.name = null;
  20783. }
  20784. state.length = 0;
  20785. state.mode = COMMENT;
  20786. /* falls through */
  20787. case COMMENT:
  20788. if (state.flags & 0x1000) {
  20789. if (have === 0) { break inf_leave; }
  20790. copy = 0;
  20791. do {
  20792. len = input[next + copy++];
  20793. /* use constant limit because in js we should not preallocate memory */
  20794. if (state.head && len &&
  20795. (state.length < 65536 /*state.head.comm_max*/)) {
  20796. state.head.comment += String.fromCharCode(len);
  20797. }
  20798. } while (len && copy < have);
  20799. if (state.flags & 0x0200) {
  20800. state.check = crc32(state.check, input, copy, next);
  20801. }
  20802. have -= copy;
  20803. next += copy;
  20804. if (len) { break inf_leave; }
  20805. }
  20806. else if (state.head) {
  20807. state.head.comment = null;
  20808. }
  20809. state.mode = HCRC;
  20810. /* falls through */
  20811. case HCRC:
  20812. if (state.flags & 0x0200) {
  20813. //=== NEEDBITS(16); */
  20814. while (bits < 16) {
  20815. if (have === 0) { break inf_leave; }
  20816. have--;
  20817. hold += input[next++] << bits;
  20818. bits += 8;
  20819. }
  20820. //===//
  20821. if (hold !== (state.check & 0xffff)) {
  20822. strm.msg = 'header crc mismatch';
  20823. state.mode = BAD;
  20824. break;
  20825. }
  20826. //=== INITBITS();
  20827. hold = 0;
  20828. bits = 0;
  20829. //===//
  20830. }
  20831. if (state.head) {
  20832. state.head.hcrc = ((state.flags >> 9) & 1);
  20833. state.head.done = true;
  20834. }
  20835. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20836. state.mode = TYPE;
  20837. break;
  20838. case DICTID:
  20839. //=== NEEDBITS(32); */
  20840. while (bits < 32) {
  20841. if (have === 0) { break inf_leave; }
  20842. have--;
  20843. hold += input[next++] << bits;
  20844. bits += 8;
  20845. }
  20846. //===//
  20847. strm.adler = state.check = ZSWAP32(hold);
  20848. //=== INITBITS();
  20849. hold = 0;
  20850. bits = 0;
  20851. //===//
  20852. state.mode = DICT;
  20853. /* falls through */
  20854. case DICT:
  20855. if (state.havedict === 0) {
  20856. //--- RESTORE() ---
  20857. strm.next_out = put;
  20858. strm.avail_out = left;
  20859. strm.next_in = next;
  20860. strm.avail_in = have;
  20861. state.hold = hold;
  20862. state.bits = bits;
  20863. //---
  20864. return Z_NEED_DICT;
  20865. }
  20866. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20867. state.mode = TYPE;
  20868. /* falls through */
  20869. case TYPE:
  20870. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20871. /* falls through */
  20872. case TYPEDO:
  20873. if (state.last) {
  20874. //--- BYTEBITS() ---//
  20875. hold >>>= bits & 7;
  20876. bits -= bits & 7;
  20877. //---//
  20878. state.mode = CHECK;
  20879. break;
  20880. }
  20881. //=== NEEDBITS(3); */
  20882. while (bits < 3) {
  20883. if (have === 0) { break inf_leave; }
  20884. have--;
  20885. hold += input[next++] << bits;
  20886. bits += 8;
  20887. }
  20888. //===//
  20889. state.last = (hold & 0x01)/*BITS(1)*/;
  20890. //--- DROPBITS(1) ---//
  20891. hold >>>= 1;
  20892. bits -= 1;
  20893. //---//
  20894. switch ((hold & 0x03)/*BITS(2)*/) {
  20895. case 0: /* stored block */
  20896. //Tracev((stderr, "inflate: stored block%s\n",
  20897. // state.last ? " (last)" : ""));
  20898. state.mode = STORED;
  20899. break;
  20900. case 1: /* fixed block */
  20901. fixedtables(state);
  20902. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20903. // state.last ? " (last)" : ""));
  20904. state.mode = LEN_; /* decode codes */
  20905. if (flush === Z_TREES) {
  20906. //--- DROPBITS(2) ---//
  20907. hold >>>= 2;
  20908. bits -= 2;
  20909. //---//
  20910. break inf_leave;
  20911. }
  20912. break;
  20913. case 2: /* dynamic block */
  20914. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20915. // state.last ? " (last)" : ""));
  20916. state.mode = TABLE;
  20917. break;
  20918. case 3:
  20919. strm.msg = 'invalid block type';
  20920. state.mode = BAD;
  20921. }
  20922. //--- DROPBITS(2) ---//
  20923. hold >>>= 2;
  20924. bits -= 2;
  20925. //---//
  20926. break;
  20927. case STORED:
  20928. //--- BYTEBITS() ---// /* go to byte boundary */
  20929. hold >>>= bits & 7;
  20930. bits -= bits & 7;
  20931. //---//
  20932. //=== NEEDBITS(32); */
  20933. while (bits < 32) {
  20934. if (have === 0) { break inf_leave; }
  20935. have--;
  20936. hold += input[next++] << bits;
  20937. bits += 8;
  20938. }
  20939. //===//
  20940. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20941. strm.msg = 'invalid stored block lengths';
  20942. state.mode = BAD;
  20943. break;
  20944. }
  20945. state.length = hold & 0xffff;
  20946. //Tracev((stderr, "inflate: stored length %u\n",
  20947. // state.length));
  20948. //=== INITBITS();
  20949. hold = 0;
  20950. bits = 0;
  20951. //===//
  20952. state.mode = COPY_;
  20953. if (flush === Z_TREES) { break inf_leave; }
  20954. /* falls through */
  20955. case COPY_:
  20956. state.mode = COPY;
  20957. /* falls through */
  20958. case COPY:
  20959. copy = state.length;
  20960. if (copy) {
  20961. if (copy > have) { copy = have; }
  20962. if (copy > left) { copy = left; }
  20963. if (copy === 0) { break inf_leave; }
  20964. //--- zmemcpy(put, next, copy); ---
  20965. utils.arraySet(output, input, next, copy, put);
  20966. //---//
  20967. have -= copy;
  20968. next += copy;
  20969. left -= copy;
  20970. put += copy;
  20971. state.length -= copy;
  20972. break;
  20973. }
  20974. //Tracev((stderr, "inflate: stored end\n"));
  20975. state.mode = TYPE;
  20976. break;
  20977. case TABLE:
  20978. //=== NEEDBITS(14); */
  20979. while (bits < 14) {
  20980. if (have === 0) { break inf_leave; }
  20981. have--;
  20982. hold += input[next++] << bits;
  20983. bits += 8;
  20984. }
  20985. //===//
  20986. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20987. //--- DROPBITS(5) ---//
  20988. hold >>>= 5;
  20989. bits -= 5;
  20990. //---//
  20991. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20992. //--- DROPBITS(5) ---//
  20993. hold >>>= 5;
  20994. bits -= 5;
  20995. //---//
  20996. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20997. //--- DROPBITS(4) ---//
  20998. hold >>>= 4;
  20999. bits -= 4;
  21000. //---//
  21001. //#ifndef PKZIP_BUG_WORKAROUND
  21002. if (state.nlen > 286 || state.ndist > 30) {
  21003. strm.msg = 'too many length or distance symbols';
  21004. state.mode = BAD;
  21005. break;
  21006. }
  21007. //#endif
  21008. //Tracev((stderr, "inflate: table sizes ok\n"));
  21009. state.have = 0;
  21010. state.mode = LENLENS;
  21011. /* falls through */
  21012. case LENLENS:
  21013. while (state.have < state.ncode) {
  21014. //=== NEEDBITS(3);
  21015. while (bits < 3) {
  21016. if (have === 0) { break inf_leave; }
  21017. have--;
  21018. hold += input[next++] << bits;
  21019. bits += 8;
  21020. }
  21021. //===//
  21022. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  21023. //--- DROPBITS(3) ---//
  21024. hold >>>= 3;
  21025. bits -= 3;
  21026. //---//
  21027. }
  21028. while (state.have < 19) {
  21029. state.lens[order[state.have++]] = 0;
  21030. }
  21031. // We have separate tables & no pointers. 2 commented lines below not needed.
  21032. //state.next = state.codes;
  21033. //state.lencode = state.next;
  21034. // Switch to use dynamic table
  21035. state.lencode = state.lendyn;
  21036. state.lenbits = 7;
  21037. opts = {bits: state.lenbits};
  21038. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  21039. state.lenbits = opts.bits;
  21040. if (ret) {
  21041. strm.msg = 'invalid code lengths set';
  21042. state.mode = BAD;
  21043. break;
  21044. }
  21045. //Tracev((stderr, "inflate: code lengths ok\n"));
  21046. state.have = 0;
  21047. state.mode = CODELENS;
  21048. /* falls through */
  21049. case CODELENS:
  21050. while (state.have < state.nlen + state.ndist) {
  21051. for (;;) {
  21052. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  21053. here_bits = here >>> 24;
  21054. here_op = (here >>> 16) & 0xff;
  21055. here_val = here & 0xffff;
  21056. if ((here_bits) <= bits) { break; }
  21057. //--- PULLBYTE() ---//
  21058. if (have === 0) { break inf_leave; }
  21059. have--;
  21060. hold += input[next++] << bits;
  21061. bits += 8;
  21062. //---//
  21063. }
  21064. if (here_val < 16) {
  21065. //--- DROPBITS(here.bits) ---//
  21066. hold >>>= here_bits;
  21067. bits -= here_bits;
  21068. //---//
  21069. state.lens[state.have++] = here_val;
  21070. }
  21071. else {
  21072. if (here_val === 16) {
  21073. //=== NEEDBITS(here.bits + 2);
  21074. n = here_bits + 2;
  21075. while (bits < n) {
  21076. if (have === 0) { break inf_leave; }
  21077. have--;
  21078. hold += input[next++] << bits;
  21079. bits += 8;
  21080. }
  21081. //===//
  21082. //--- DROPBITS(here.bits) ---//
  21083. hold >>>= here_bits;
  21084. bits -= here_bits;
  21085. //---//
  21086. if (state.have === 0) {
  21087. strm.msg = 'invalid bit length repeat';
  21088. state.mode = BAD;
  21089. break;
  21090. }
  21091. len = state.lens[state.have - 1];
  21092. copy = 3 + (hold & 0x03);//BITS(2);
  21093. //--- DROPBITS(2) ---//
  21094. hold >>>= 2;
  21095. bits -= 2;
  21096. //---//
  21097. }
  21098. else if (here_val === 17) {
  21099. //=== NEEDBITS(here.bits + 3);
  21100. n = here_bits + 3;
  21101. while (bits < n) {
  21102. if (have === 0) { break inf_leave; }
  21103. have--;
  21104. hold += input[next++] << bits;
  21105. bits += 8;
  21106. }
  21107. //===//
  21108. //--- DROPBITS(here.bits) ---//
  21109. hold >>>= here_bits;
  21110. bits -= here_bits;
  21111. //---//
  21112. len = 0;
  21113. copy = 3 + (hold & 0x07);//BITS(3);
  21114. //--- DROPBITS(3) ---//
  21115. hold >>>= 3;
  21116. bits -= 3;
  21117. //---//
  21118. }
  21119. else {
  21120. //=== NEEDBITS(here.bits + 7);
  21121. n = here_bits + 7;
  21122. while (bits < n) {
  21123. if (have === 0) { break inf_leave; }
  21124. have--;
  21125. hold += input[next++] << bits;
  21126. bits += 8;
  21127. }
  21128. //===//
  21129. //--- DROPBITS(here.bits) ---//
  21130. hold >>>= here_bits;
  21131. bits -= here_bits;
  21132. //---//
  21133. len = 0;
  21134. copy = 11 + (hold & 0x7f);//BITS(7);
  21135. //--- DROPBITS(7) ---//
  21136. hold >>>= 7;
  21137. bits -= 7;
  21138. //---//
  21139. }
  21140. if (state.have + copy > state.nlen + state.ndist) {
  21141. strm.msg = 'invalid bit length repeat';
  21142. state.mode = BAD;
  21143. break;
  21144. }
  21145. while (copy--) {
  21146. state.lens[state.have++] = len;
  21147. }
  21148. }
  21149. }
  21150. /* handle error breaks in while */
  21151. if (state.mode === BAD) { break; }
  21152. /* check for end-of-block code (better have one) */
  21153. if (state.lens[256] === 0) {
  21154. strm.msg = 'invalid code -- missing end-of-block';
  21155. state.mode = BAD;
  21156. break;
  21157. }
  21158. /* build code tables -- note: do not change the lenbits or distbits
  21159. values here (9 and 6) without reading the comments in inftrees.h
  21160. concerning the ENOUGH constants, which depend on those values */
  21161. state.lenbits = 9;
  21162. opts = {bits: state.lenbits};
  21163. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  21164. // We have separate tables & no pointers. 2 commented lines below not needed.
  21165. // state.next_index = opts.table_index;
  21166. state.lenbits = opts.bits;
  21167. // state.lencode = state.next;
  21168. if (ret) {
  21169. strm.msg = 'invalid literal/lengths set';
  21170. state.mode = BAD;
  21171. break;
  21172. }
  21173. state.distbits = 6;
  21174. //state.distcode.copy(state.codes);
  21175. // Switch to use dynamic table
  21176. state.distcode = state.distdyn;
  21177. opts = {bits: state.distbits};
  21178. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  21179. // We have separate tables & no pointers. 2 commented lines below not needed.
  21180. // state.next_index = opts.table_index;
  21181. state.distbits = opts.bits;
  21182. // state.distcode = state.next;
  21183. if (ret) {
  21184. strm.msg = 'invalid distances set';
  21185. state.mode = BAD;
  21186. break;
  21187. }
  21188. //Tracev((stderr, 'inflate: codes ok\n'));
  21189. state.mode = LEN_;
  21190. if (flush === Z_TREES) { break inf_leave; }
  21191. /* falls through */
  21192. case LEN_:
  21193. state.mode = LEN;
  21194. /* falls through */
  21195. case LEN:
  21196. if (have >= 6 && left >= 258) {
  21197. //--- RESTORE() ---
  21198. strm.next_out = put;
  21199. strm.avail_out = left;
  21200. strm.next_in = next;
  21201. strm.avail_in = have;
  21202. state.hold = hold;
  21203. state.bits = bits;
  21204. //---
  21205. inflate_fast(strm, _out);
  21206. //--- LOAD() ---
  21207. put = strm.next_out;
  21208. output = strm.output;
  21209. left = strm.avail_out;
  21210. next = strm.next_in;
  21211. input = strm.input;
  21212. have = strm.avail_in;
  21213. hold = state.hold;
  21214. bits = state.bits;
  21215. //---
  21216. if (state.mode === TYPE) {
  21217. state.back = -1;
  21218. }
  21219. break;
  21220. }
  21221. state.back = 0;
  21222. for (;;) {
  21223. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  21224. here_bits = here >>> 24;
  21225. here_op = (here >>> 16) & 0xff;
  21226. here_val = here & 0xffff;
  21227. if (here_bits <= bits) { break; }
  21228. //--- PULLBYTE() ---//
  21229. if (have === 0) { break inf_leave; }
  21230. have--;
  21231. hold += input[next++] << bits;
  21232. bits += 8;
  21233. //---//
  21234. }
  21235. if (here_op && (here_op & 0xf0) === 0) {
  21236. last_bits = here_bits;
  21237. last_op = here_op;
  21238. last_val = here_val;
  21239. for (;;) {
  21240. here = state.lencode[last_val +
  21241. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  21242. here_bits = here >>> 24;
  21243. here_op = (here >>> 16) & 0xff;
  21244. here_val = here & 0xffff;
  21245. if ((last_bits + here_bits) <= bits) { break; }
  21246. //--- PULLBYTE() ---//
  21247. if (have === 0) { break inf_leave; }
  21248. have--;
  21249. hold += input[next++] << bits;
  21250. bits += 8;
  21251. //---//
  21252. }
  21253. //--- DROPBITS(last.bits) ---//
  21254. hold >>>= last_bits;
  21255. bits -= last_bits;
  21256. //---//
  21257. state.back += last_bits;
  21258. }
  21259. //--- DROPBITS(here.bits) ---//
  21260. hold >>>= here_bits;
  21261. bits -= here_bits;
  21262. //---//
  21263. state.back += here_bits;
  21264. state.length = here_val;
  21265. if (here_op === 0) {
  21266. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21267. // "inflate: literal '%c'\n" :
  21268. // "inflate: literal 0x%02x\n", here.val));
  21269. state.mode = LIT;
  21270. break;
  21271. }
  21272. if (here_op & 32) {
  21273. //Tracevv((stderr, "inflate: end of block\n"));
  21274. state.back = -1;
  21275. state.mode = TYPE;
  21276. break;
  21277. }
  21278. if (here_op & 64) {
  21279. strm.msg = 'invalid literal/length code';
  21280. state.mode = BAD;
  21281. break;
  21282. }
  21283. state.extra = here_op & 15;
  21284. state.mode = LENEXT;
  21285. /* falls through */
  21286. case LENEXT:
  21287. if (state.extra) {
  21288. //=== NEEDBITS(state.extra);
  21289. n = state.extra;
  21290. while (bits < n) {
  21291. if (have === 0) { break inf_leave; }
  21292. have--;
  21293. hold += input[next++] << bits;
  21294. bits += 8;
  21295. }
  21296. //===//
  21297. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21298. //--- DROPBITS(state.extra) ---//
  21299. hold >>>= state.extra;
  21300. bits -= state.extra;
  21301. //---//
  21302. state.back += state.extra;
  21303. }
  21304. //Tracevv((stderr, "inflate: length %u\n", state.length));
  21305. state.was = state.length;
  21306. state.mode = DIST;
  21307. /* falls through */
  21308. case DIST:
  21309. for (;;) {
  21310. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  21311. here_bits = here >>> 24;
  21312. here_op = (here >>> 16) & 0xff;
  21313. here_val = here & 0xffff;
  21314. if ((here_bits) <= bits) { break; }
  21315. //--- PULLBYTE() ---//
  21316. if (have === 0) { break inf_leave; }
  21317. have--;
  21318. hold += input[next++] << bits;
  21319. bits += 8;
  21320. //---//
  21321. }
  21322. if ((here_op & 0xf0) === 0) {
  21323. last_bits = here_bits;
  21324. last_op = here_op;
  21325. last_val = here_val;
  21326. for (;;) {
  21327. here = state.distcode[last_val +
  21328. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  21329. here_bits = here >>> 24;
  21330. here_op = (here >>> 16) & 0xff;
  21331. here_val = here & 0xffff;
  21332. if ((last_bits + here_bits) <= bits) { break; }
  21333. //--- PULLBYTE() ---//
  21334. if (have === 0) { break inf_leave; }
  21335. have--;
  21336. hold += input[next++] << bits;
  21337. bits += 8;
  21338. //---//
  21339. }
  21340. //--- DROPBITS(last.bits) ---//
  21341. hold >>>= last_bits;
  21342. bits -= last_bits;
  21343. //---//
  21344. state.back += last_bits;
  21345. }
  21346. //--- DROPBITS(here.bits) ---//
  21347. hold >>>= here_bits;
  21348. bits -= here_bits;
  21349. //---//
  21350. state.back += here_bits;
  21351. if (here_op & 64) {
  21352. strm.msg = 'invalid distance code';
  21353. state.mode = BAD;
  21354. break;
  21355. }
  21356. state.offset = here_val;
  21357. state.extra = (here_op) & 15;
  21358. state.mode = DISTEXT;
  21359. /* falls through */
  21360. case DISTEXT:
  21361. if (state.extra) {
  21362. //=== NEEDBITS(state.extra);
  21363. n = state.extra;
  21364. while (bits < n) {
  21365. if (have === 0) { break inf_leave; }
  21366. have--;
  21367. hold += input[next++] << bits;
  21368. bits += 8;
  21369. }
  21370. //===//
  21371. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21372. //--- DROPBITS(state.extra) ---//
  21373. hold >>>= state.extra;
  21374. bits -= state.extra;
  21375. //---//
  21376. state.back += state.extra;
  21377. }
  21378. //#ifdef INFLATE_STRICT
  21379. if (state.offset > state.dmax) {
  21380. strm.msg = 'invalid distance too far back';
  21381. state.mode = BAD;
  21382. break;
  21383. }
  21384. //#endif
  21385. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  21386. state.mode = MATCH;
  21387. /* falls through */
  21388. case MATCH:
  21389. if (left === 0) { break inf_leave; }
  21390. copy = _out - left;
  21391. if (state.offset > copy) { /* copy from window */
  21392. copy = state.offset - copy;
  21393. if (copy > state.whave) {
  21394. if (state.sane) {
  21395. strm.msg = 'invalid distance too far back';
  21396. state.mode = BAD;
  21397. break;
  21398. }
  21399. // (!) This block is disabled in zlib defailts,
  21400. // don't enable it for binary compatibility
  21401. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21402. // Trace((stderr, "inflate.c too far\n"));
  21403. // copy -= state.whave;
  21404. // if (copy > state.length) { copy = state.length; }
  21405. // if (copy > left) { copy = left; }
  21406. // left -= copy;
  21407. // state.length -= copy;
  21408. // do {
  21409. // output[put++] = 0;
  21410. // } while (--copy);
  21411. // if (state.length === 0) { state.mode = LEN; }
  21412. // break;
  21413. //#endif
  21414. }
  21415. if (copy > state.wnext) {
  21416. copy -= state.wnext;
  21417. from = state.wsize - copy;
  21418. }
  21419. else {
  21420. from = state.wnext - copy;
  21421. }
  21422. if (copy > state.length) { copy = state.length; }
  21423. from_source = state.window;
  21424. }
  21425. else { /* copy from output */
  21426. from_source = output;
  21427. from = put - state.offset;
  21428. copy = state.length;
  21429. }
  21430. if (copy > left) { copy = left; }
  21431. left -= copy;
  21432. state.length -= copy;
  21433. do {
  21434. output[put++] = from_source[from++];
  21435. } while (--copy);
  21436. if (state.length === 0) { state.mode = LEN; }
  21437. break;
  21438. case LIT:
  21439. if (left === 0) { break inf_leave; }
  21440. output[put++] = state.length;
  21441. left--;
  21442. state.mode = LEN;
  21443. break;
  21444. case CHECK:
  21445. if (state.wrap) {
  21446. //=== NEEDBITS(32);
  21447. while (bits < 32) {
  21448. if (have === 0) { break inf_leave; }
  21449. have--;
  21450. // Use '|' insdead of '+' to make sure that result is signed
  21451. hold |= input[next++] << bits;
  21452. bits += 8;
  21453. }
  21454. //===//
  21455. _out -= left;
  21456. strm.total_out += _out;
  21457. state.total += _out;
  21458. if (_out) {
  21459. strm.adler = state.check =
  21460. /*UPDATE(state.check, put - _out, _out);*/
  21461. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  21462. }
  21463. _out = left;
  21464. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  21465. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  21466. strm.msg = 'incorrect data check';
  21467. state.mode = BAD;
  21468. break;
  21469. }
  21470. //=== INITBITS();
  21471. hold = 0;
  21472. bits = 0;
  21473. //===//
  21474. //Tracev((stderr, "inflate: check matches trailer\n"));
  21475. }
  21476. state.mode = LENGTH;
  21477. /* falls through */
  21478. case LENGTH:
  21479. if (state.wrap && state.flags) {
  21480. //=== NEEDBITS(32);
  21481. while (bits < 32) {
  21482. if (have === 0) { break inf_leave; }
  21483. have--;
  21484. hold += input[next++] << bits;
  21485. bits += 8;
  21486. }
  21487. //===//
  21488. if (hold !== (state.total & 0xffffffff)) {
  21489. strm.msg = 'incorrect length check';
  21490. state.mode = BAD;
  21491. break;
  21492. }
  21493. //=== INITBITS();
  21494. hold = 0;
  21495. bits = 0;
  21496. //===//
  21497. //Tracev((stderr, "inflate: length matches trailer\n"));
  21498. }
  21499. state.mode = DONE;
  21500. /* falls through */
  21501. case DONE:
  21502. ret = Z_STREAM_END;
  21503. break inf_leave;
  21504. case BAD:
  21505. ret = Z_DATA_ERROR;
  21506. break inf_leave;
  21507. case MEM:
  21508. return Z_MEM_ERROR;
  21509. case SYNC:
  21510. /* falls through */
  21511. default:
  21512. return Z_STREAM_ERROR;
  21513. }
  21514. }
  21515. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  21516. /*
  21517. Return from inflate(), updating the total counts and the check value.
  21518. If there was no progress during the inflate() call, return a buffer
  21519. error. Call updatewindow() to create and/or update the window state.
  21520. Note: a memory error from inflate() is non-recoverable.
  21521. */
  21522. //--- RESTORE() ---
  21523. strm.next_out = put;
  21524. strm.avail_out = left;
  21525. strm.next_in = next;
  21526. strm.avail_in = have;
  21527. state.hold = hold;
  21528. state.bits = bits;
  21529. //---
  21530. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  21531. (state.mode < CHECK || flush !== Z_FINISH))) {
  21532. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  21533. state.mode = MEM;
  21534. return Z_MEM_ERROR;
  21535. }
  21536. }
  21537. _in -= strm.avail_in;
  21538. _out -= strm.avail_out;
  21539. strm.total_in += _in;
  21540. strm.total_out += _out;
  21541. state.total += _out;
  21542. if (state.wrap && _out) {
  21543. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21544. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21545. }
  21546. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21547. (state.mode === TYPE ? 128 : 0) +
  21548. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21549. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21550. ret = Z_BUF_ERROR;
  21551. }
  21552. return ret;
  21553. }
  21554. function inflateEnd(strm) {
  21555. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21556. return Z_STREAM_ERROR;
  21557. }
  21558. var state = strm.state;
  21559. if (state.window) {
  21560. state.window = null;
  21561. }
  21562. strm.state = null;
  21563. return Z_OK;
  21564. }
  21565. function inflateGetHeader(strm, head) {
  21566. var state;
  21567. /* check state */
  21568. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21569. state = strm.state;
  21570. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21571. /* save header structure */
  21572. state.head = head;
  21573. head.done = false;
  21574. return Z_OK;
  21575. }
  21576. exports.inflateReset = inflateReset;
  21577. exports.inflateReset2 = inflateReset2;
  21578. exports.inflateResetKeep = inflateResetKeep;
  21579. exports.inflateInit = inflateInit;
  21580. exports.inflateInit2 = inflateInit2;
  21581. exports.inflate = inflate;
  21582. exports.inflateEnd = inflateEnd;
  21583. exports.inflateGetHeader = inflateGetHeader;
  21584. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21585. /* Not implemented
  21586. exports.inflateCopy = inflateCopy;
  21587. exports.inflateGetDictionary = inflateGetDictionary;
  21588. exports.inflateMark = inflateMark;
  21589. exports.inflatePrime = inflatePrime;
  21590. exports.inflateSetDictionary = inflateSetDictionary;
  21591. exports.inflateSync = inflateSync;
  21592. exports.inflateSyncPoint = inflateSyncPoint;
  21593. exports.inflateUndermine = inflateUndermine;
  21594. */
  21595. },{"../utils/common":67,"./adler32":69,"./crc32":71,"./inffast":74,"./inftrees":76}],76:[function(require,module,exports){
  21596. 'use strict';
  21597. var utils = require('../utils/common');
  21598. var MAXBITS = 15;
  21599. var ENOUGH_LENS = 852;
  21600. var ENOUGH_DISTS = 592;
  21601. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21602. var CODES = 0;
  21603. var LENS = 1;
  21604. var DISTS = 2;
  21605. var lbase = [ /* Length codes 257..285 base */
  21606. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21607. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21608. ];
  21609. var lext = [ /* Length codes 257..285 extra */
  21610. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21611. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21612. ];
  21613. var dbase = [ /* Distance codes 0..29 base */
  21614. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21615. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21616. 8193, 12289, 16385, 24577, 0, 0
  21617. ];
  21618. var dext = [ /* Distance codes 0..29 extra */
  21619. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21620. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21621. 28, 28, 29, 29, 64, 64
  21622. ];
  21623. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21624. {
  21625. var bits = opts.bits;
  21626. //here = opts.here; /* table entry for duplication */
  21627. var len = 0; /* a code's length in bits */
  21628. var sym = 0; /* index of code symbols */
  21629. var min = 0, max = 0; /* minimum and maximum code lengths */
  21630. var root = 0; /* number of index bits for root table */
  21631. var curr = 0; /* number of index bits for current table */
  21632. var drop = 0; /* code bits to drop for sub-table */
  21633. var left = 0; /* number of prefix codes available */
  21634. var used = 0; /* code entries in table used */
  21635. var huff = 0; /* Huffman code */
  21636. var incr; /* for incrementing code, index */
  21637. var fill; /* index for replicating entries */
  21638. var low; /* low bits for current root entry */
  21639. var mask; /* mask for low root bits */
  21640. var next; /* next available space in table */
  21641. var base = null; /* base value table to use */
  21642. var base_index = 0;
  21643. // var shoextra; /* extra bits table to use */
  21644. var end; /* use base and extra for symbol > end */
  21645. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21646. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21647. var extra = null;
  21648. var extra_index = 0;
  21649. var here_bits, here_op, here_val;
  21650. /*
  21651. Process a set of code lengths to create a canonical Huffman code. The
  21652. code lengths are lens[0..codes-1]. Each length corresponds to the
  21653. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21654. symbols by length from short to long, and retaining the symbol order
  21655. for codes with equal lengths. Then the code starts with all zero bits
  21656. for the first code of the shortest length, and the codes are integer
  21657. increments for the same length, and zeros are appended as the length
  21658. increases. For the deflate format, these bits are stored backwards
  21659. from their more natural integer increment ordering, and so when the
  21660. decoding tables are built in the large loop below, the integer codes
  21661. are incremented backwards.
  21662. This routine assumes, but does not check, that all of the entries in
  21663. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21664. 1..MAXBITS is interpreted as that code length. zero means that that
  21665. symbol does not occur in this code.
  21666. The codes are sorted by computing a count of codes for each length,
  21667. creating from that a table of starting indices for each length in the
  21668. sorted table, and then entering the symbols in order in the sorted
  21669. table. The sorted table is work[], with that space being provided by
  21670. the caller.
  21671. The length counts are used for other purposes as well, i.e. finding
  21672. the minimum and maximum length codes, determining if there are any
  21673. codes at all, checking for a valid set of lengths, and looking ahead
  21674. at length counts to determine sub-table sizes when building the
  21675. decoding tables.
  21676. */
  21677. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21678. for (len = 0; len <= MAXBITS; len++) {
  21679. count[len] = 0;
  21680. }
  21681. for (sym = 0; sym < codes; sym++) {
  21682. count[lens[lens_index + sym]]++;
  21683. }
  21684. /* bound code lengths, force root to be within code lengths */
  21685. root = bits;
  21686. for (max = MAXBITS; max >= 1; max--) {
  21687. if (count[max] !== 0) { break; }
  21688. }
  21689. if (root > max) {
  21690. root = max;
  21691. }
  21692. if (max === 0) { /* no symbols to code at all */
  21693. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21694. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21695. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21696. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21697. //table.op[opts.table_index] = 64;
  21698. //table.bits[opts.table_index] = 1;
  21699. //table.val[opts.table_index++] = 0;
  21700. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21701. opts.bits = 1;
  21702. return 0; /* no symbols, but wait for decoding to report error */
  21703. }
  21704. for (min = 1; min < max; min++) {
  21705. if (count[min] !== 0) { break; }
  21706. }
  21707. if (root < min) {
  21708. root = min;
  21709. }
  21710. /* check for an over-subscribed or incomplete set of lengths */
  21711. left = 1;
  21712. for (len = 1; len <= MAXBITS; len++) {
  21713. left <<= 1;
  21714. left -= count[len];
  21715. if (left < 0) {
  21716. return -1;
  21717. } /* over-subscribed */
  21718. }
  21719. if (left > 0 && (type === CODES || max !== 1)) {
  21720. return -1; /* incomplete set */
  21721. }
  21722. /* generate offsets into symbol table for each length for sorting */
  21723. offs[1] = 0;
  21724. for (len = 1; len < MAXBITS; len++) {
  21725. offs[len + 1] = offs[len] + count[len];
  21726. }
  21727. /* sort symbols by length, by symbol order within each length */
  21728. for (sym = 0; sym < codes; sym++) {
  21729. if (lens[lens_index + sym] !== 0) {
  21730. work[offs[lens[lens_index + sym]]++] = sym;
  21731. }
  21732. }
  21733. /*
  21734. Create and fill in decoding tables. In this loop, the table being
  21735. filled is at next and has curr index bits. The code being used is huff
  21736. with length len. That code is converted to an index by dropping drop
  21737. bits off of the bottom. For codes where len is less than drop + curr,
  21738. those top drop + curr - len bits are incremented through all values to
  21739. fill the table with replicated entries.
  21740. root is the number of index bits for the root table. When len exceeds
  21741. root, sub-tables are created pointed to by the root entry with an index
  21742. of the low root bits of huff. This is saved in low to check for when a
  21743. new sub-table should be started. drop is zero when the root table is
  21744. being filled, and drop is root when sub-tables are being filled.
  21745. When a new sub-table is needed, it is necessary to look ahead in the
  21746. code lengths to determine what size sub-table is needed. The length
  21747. counts are used for this, and so count[] is decremented as codes are
  21748. entered in the tables.
  21749. used keeps track of how many table entries have been allocated from the
  21750. provided *table space. It is checked for LENS and DIST tables against
  21751. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21752. the initial root table size constants. See the comments in inftrees.h
  21753. for more information.
  21754. sym increments through all symbols, and the loop terminates when
  21755. all codes of length max, i.e. all codes, have been processed. This
  21756. routine permits incomplete codes, so another loop after this one fills
  21757. in the rest of the decoding tables with invalid code markers.
  21758. */
  21759. /* set up for code type */
  21760. // poor man optimization - use if-else instead of switch,
  21761. // to avoid deopts in old v8
  21762. if (type === CODES) {
  21763. base = extra = work; /* dummy value--not used */
  21764. end = 19;
  21765. } else if (type === LENS) {
  21766. base = lbase;
  21767. base_index -= 257;
  21768. extra = lext;
  21769. extra_index -= 257;
  21770. end = 256;
  21771. } else { /* DISTS */
  21772. base = dbase;
  21773. extra = dext;
  21774. end = -1;
  21775. }
  21776. /* initialize opts for loop */
  21777. huff = 0; /* starting code */
  21778. sym = 0; /* starting code symbol */
  21779. len = min; /* starting code length */
  21780. next = table_index; /* current table to fill in */
  21781. curr = root; /* current table index bits */
  21782. drop = 0; /* current bits to drop from code for index */
  21783. low = -1; /* trigger new sub-table when len > root */
  21784. used = 1 << root; /* use root table entries */
  21785. mask = used - 1; /* mask for comparing low */
  21786. /* check available table space */
  21787. if ((type === LENS && used > ENOUGH_LENS) ||
  21788. (type === DISTS && used > ENOUGH_DISTS)) {
  21789. return 1;
  21790. }
  21791. var i=0;
  21792. /* process all codes and make table entries */
  21793. for (;;) {
  21794. i++;
  21795. /* create table entry */
  21796. here_bits = len - drop;
  21797. if (work[sym] < end) {
  21798. here_op = 0;
  21799. here_val = work[sym];
  21800. }
  21801. else if (work[sym] > end) {
  21802. here_op = extra[extra_index + work[sym]];
  21803. here_val = base[base_index + work[sym]];
  21804. }
  21805. else {
  21806. here_op = 32 + 64; /* end of block */
  21807. here_val = 0;
  21808. }
  21809. /* replicate for those indices with low len bits equal to huff */
  21810. incr = 1 << (len - drop);
  21811. fill = 1 << curr;
  21812. min = fill; /* save offset to next table */
  21813. do {
  21814. fill -= incr;
  21815. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21816. } while (fill !== 0);
  21817. /* backwards increment the len-bit code huff */
  21818. incr = 1 << (len - 1);
  21819. while (huff & incr) {
  21820. incr >>= 1;
  21821. }
  21822. if (incr !== 0) {
  21823. huff &= incr - 1;
  21824. huff += incr;
  21825. } else {
  21826. huff = 0;
  21827. }
  21828. /* go to next symbol, update count, len */
  21829. sym++;
  21830. if (--count[len] === 0) {
  21831. if (len === max) { break; }
  21832. len = lens[lens_index + work[sym]];
  21833. }
  21834. /* create new sub-table if needed */
  21835. if (len > root && (huff & mask) !== low) {
  21836. /* if first time, transition to sub-tables */
  21837. if (drop === 0) {
  21838. drop = root;
  21839. }
  21840. /* increment past last table */
  21841. next += min; /* here min is 1 << curr */
  21842. /* determine length of next table */
  21843. curr = len - drop;
  21844. left = 1 << curr;
  21845. while (curr + drop < max) {
  21846. left -= count[curr + drop];
  21847. if (left <= 0) { break; }
  21848. curr++;
  21849. left <<= 1;
  21850. }
  21851. /* check for enough space */
  21852. used += 1 << curr;
  21853. if ((type === LENS && used > ENOUGH_LENS) ||
  21854. (type === DISTS && used > ENOUGH_DISTS)) {
  21855. return 1;
  21856. }
  21857. /* point entry in root table to sub-table */
  21858. low = huff & mask;
  21859. /*table.op[low] = curr;
  21860. table.bits[low] = root;
  21861. table.val[low] = next - opts.table_index;*/
  21862. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21863. }
  21864. }
  21865. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21866. at most one remaining entry, since if the code is incomplete, the
  21867. maximum code length that was allowed to get this far is one bit) */
  21868. if (huff !== 0) {
  21869. //table.op[next + huff] = 64; /* invalid code marker */
  21870. //table.bits[next + huff] = len - drop;
  21871. //table.val[next + huff] = 0;
  21872. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21873. }
  21874. /* set return parameters */
  21875. //opts.table_index += used;
  21876. opts.bits = root;
  21877. return 0;
  21878. };
  21879. },{"../utils/common":67}],77:[function(require,module,exports){
  21880. 'use strict';
  21881. module.exports = {
  21882. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21883. '1': 'stream end', /* Z_STREAM_END 1 */
  21884. '0': '', /* Z_OK 0 */
  21885. '-1': 'file error', /* Z_ERRNO (-1) */
  21886. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21887. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21888. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21889. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21890. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21891. };
  21892. },{}],78:[function(require,module,exports){
  21893. 'use strict';
  21894. var utils = require('../utils/common');
  21895. /* Public constants ==========================================================*/
  21896. /* ===========================================================================*/
  21897. //var Z_FILTERED = 1;
  21898. //var Z_HUFFMAN_ONLY = 2;
  21899. //var Z_RLE = 3;
  21900. var Z_FIXED = 4;
  21901. //var Z_DEFAULT_STRATEGY = 0;
  21902. /* Possible values of the data_type field (though see inflate()) */
  21903. var Z_BINARY = 0;
  21904. var Z_TEXT = 1;
  21905. //var Z_ASCII = 1; // = Z_TEXT
  21906. var Z_UNKNOWN = 2;
  21907. /*============================================================================*/
  21908. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21909. // From zutil.h
  21910. var STORED_BLOCK = 0;
  21911. var STATIC_TREES = 1;
  21912. var DYN_TREES = 2;
  21913. /* The three kinds of block type */
  21914. var MIN_MATCH = 3;
  21915. var MAX_MATCH = 258;
  21916. /* The minimum and maximum match lengths */
  21917. // From deflate.h
  21918. /* ===========================================================================
  21919. * Internal compression state.
  21920. */
  21921. var LENGTH_CODES = 29;
  21922. /* number of length codes, not counting the special END_BLOCK code */
  21923. var LITERALS = 256;
  21924. /* number of literal bytes 0..255 */
  21925. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21926. /* number of Literal or Length codes, including the END_BLOCK code */
  21927. var D_CODES = 30;
  21928. /* number of distance codes */
  21929. var BL_CODES = 19;
  21930. /* number of codes used to transfer the bit lengths */
  21931. var HEAP_SIZE = 2*L_CODES + 1;
  21932. /* maximum heap size */
  21933. var MAX_BITS = 15;
  21934. /* All codes must not exceed MAX_BITS bits */
  21935. var Buf_size = 16;
  21936. /* size of bit buffer in bi_buf */
  21937. /* ===========================================================================
  21938. * Constants
  21939. */
  21940. var MAX_BL_BITS = 7;
  21941. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21942. var END_BLOCK = 256;
  21943. /* end of block literal code */
  21944. var REP_3_6 = 16;
  21945. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21946. var REPZ_3_10 = 17;
  21947. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21948. var REPZ_11_138 = 18;
  21949. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21950. var extra_lbits = /* extra bits for each length code */
  21951. [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];
  21952. var extra_dbits = /* extra bits for each distance code */
  21953. [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];
  21954. var extra_blbits = /* extra bits for each bit length code */
  21955. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21956. var bl_order =
  21957. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21958. /* The lengths of the bit length codes are sent in order of decreasing
  21959. * probability, to avoid transmitting the lengths for unused bit length codes.
  21960. */
  21961. /* ===========================================================================
  21962. * Local data. These are initialized only once.
  21963. */
  21964. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21965. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21966. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21967. var static_ltree = new Array((L_CODES+2) * 2);
  21968. zero(static_ltree);
  21969. /* The static literal tree. Since the bit lengths are imposed, there is no
  21970. * need for the L_CODES extra codes used during heap construction. However
  21971. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21972. * below).
  21973. */
  21974. var static_dtree = new Array(D_CODES * 2);
  21975. zero(static_dtree);
  21976. /* The static distance tree. (Actually a trivial tree since all codes use
  21977. * 5 bits.)
  21978. */
  21979. var _dist_code = new Array(DIST_CODE_LEN);
  21980. zero(_dist_code);
  21981. /* Distance codes. The first 256 values correspond to the distances
  21982. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21983. * the 15 bit distances.
  21984. */
  21985. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21986. zero(_length_code);
  21987. /* length code for each normalized match length (0 == MIN_MATCH) */
  21988. var base_length = new Array(LENGTH_CODES);
  21989. zero(base_length);
  21990. /* First normalized length for each code (0 = MIN_MATCH) */
  21991. var base_dist = new Array(D_CODES);
  21992. zero(base_dist);
  21993. /* First normalized distance for each code (0 = distance of 1) */
  21994. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21995. this.static_tree = static_tree; /* static tree or NULL */
  21996. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21997. this.extra_base = extra_base; /* base index for extra_bits */
  21998. this.elems = elems; /* max number of elements in the tree */
  21999. this.max_length = max_length; /* max bit length for the codes */
  22000. // show if `static_tree` has data or dummy - needed for monomorphic objects
  22001. this.has_stree = static_tree && static_tree.length;
  22002. };
  22003. var static_l_desc;
  22004. var static_d_desc;
  22005. var static_bl_desc;
  22006. var TreeDesc = function(dyn_tree, stat_desc) {
  22007. this.dyn_tree = dyn_tree; /* the dynamic tree */
  22008. this.max_code = 0; /* largest code with non zero frequency */
  22009. this.stat_desc = stat_desc; /* the corresponding static tree */
  22010. };
  22011. function d_code(dist) {
  22012. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  22013. }
  22014. /* ===========================================================================
  22015. * Output a short LSB first on the stream.
  22016. * IN assertion: there is enough room in pendingBuf.
  22017. */
  22018. function put_short (s, w) {
  22019. // put_byte(s, (uch)((w) & 0xff));
  22020. // put_byte(s, (uch)((ush)(w) >> 8));
  22021. s.pending_buf[s.pending++] = (w) & 0xff;
  22022. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  22023. }
  22024. /* ===========================================================================
  22025. * Send a value on a given number of bits.
  22026. * IN assertion: length <= 16 and value fits in length bits.
  22027. */
  22028. function send_bits(s, value, length) {
  22029. if (s.bi_valid > (Buf_size - length)) {
  22030. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22031. put_short(s, s.bi_buf);
  22032. s.bi_buf = value >> (Buf_size - s.bi_valid);
  22033. s.bi_valid += length - Buf_size;
  22034. } else {
  22035. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22036. s.bi_valid += length;
  22037. }
  22038. }
  22039. function send_code(s, c, tree) {
  22040. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  22041. }
  22042. /* ===========================================================================
  22043. * Reverse the first len bits of a code, using straightforward code (a faster
  22044. * method would use a table)
  22045. * IN assertion: 1 <= len <= 15
  22046. */
  22047. function bi_reverse(code, len) {
  22048. var res = 0;
  22049. do {
  22050. res |= code & 1;
  22051. code >>>= 1;
  22052. res <<= 1;
  22053. } while (--len > 0);
  22054. return res >>> 1;
  22055. }
  22056. /* ===========================================================================
  22057. * Flush the bit buffer, keeping at most 7 bits in it.
  22058. */
  22059. function bi_flush(s) {
  22060. if (s.bi_valid === 16) {
  22061. put_short(s, s.bi_buf);
  22062. s.bi_buf = 0;
  22063. s.bi_valid = 0;
  22064. } else if (s.bi_valid >= 8) {
  22065. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  22066. s.bi_buf >>= 8;
  22067. s.bi_valid -= 8;
  22068. }
  22069. }
  22070. /* ===========================================================================
  22071. * Compute the optimal bit lengths for a tree and update the total bit length
  22072. * for the current block.
  22073. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  22074. * above are the tree nodes sorted by increasing frequency.
  22075. * OUT assertions: the field len is set to the optimal bit length, the
  22076. * array bl_count contains the frequencies for each bit length.
  22077. * The length opt_len is updated; static_len is also updated if stree is
  22078. * not null.
  22079. */
  22080. function gen_bitlen(s, desc)
  22081. // deflate_state *s;
  22082. // tree_desc *desc; /* the tree descriptor */
  22083. {
  22084. var tree = desc.dyn_tree;
  22085. var max_code = desc.max_code;
  22086. var stree = desc.stat_desc.static_tree;
  22087. var has_stree = desc.stat_desc.has_stree;
  22088. var extra = desc.stat_desc.extra_bits;
  22089. var base = desc.stat_desc.extra_base;
  22090. var max_length = desc.stat_desc.max_length;
  22091. var h; /* heap index */
  22092. var n, m; /* iterate over the tree elements */
  22093. var bits; /* bit length */
  22094. var xbits; /* extra bits */
  22095. var f; /* frequency */
  22096. var overflow = 0; /* number of elements with bit length too large */
  22097. for (bits = 0; bits <= MAX_BITS; bits++) {
  22098. s.bl_count[bits] = 0;
  22099. }
  22100. /* In a first pass, compute the optimal bit lengths (which may
  22101. * overflow in the case of the bit length tree).
  22102. */
  22103. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  22104. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  22105. n = s.heap[h];
  22106. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  22107. if (bits > max_length) {
  22108. bits = max_length;
  22109. overflow++;
  22110. }
  22111. tree[n*2 + 1]/*.Len*/ = bits;
  22112. /* We overwrite tree[n].Dad which is no longer needed */
  22113. if (n > max_code) { continue; } /* not a leaf node */
  22114. s.bl_count[bits]++;
  22115. xbits = 0;
  22116. if (n >= base) {
  22117. xbits = extra[n-base];
  22118. }
  22119. f = tree[n * 2]/*.Freq*/;
  22120. s.opt_len += f * (bits + xbits);
  22121. if (has_stree) {
  22122. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  22123. }
  22124. }
  22125. if (overflow === 0) { return; }
  22126. // Trace((stderr,"\nbit length overflow\n"));
  22127. /* This happens for example on obj2 and pic of the Calgary corpus */
  22128. /* Find the first bit length which could increase: */
  22129. do {
  22130. bits = max_length-1;
  22131. while (s.bl_count[bits] === 0) { bits--; }
  22132. s.bl_count[bits]--; /* move one leaf down the tree */
  22133. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  22134. s.bl_count[max_length]--;
  22135. /* The brother of the overflow item also moves one step up,
  22136. * but this does not affect bl_count[max_length]
  22137. */
  22138. overflow -= 2;
  22139. } while (overflow > 0);
  22140. /* Now recompute all bit lengths, scanning in increasing frequency.
  22141. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  22142. * lengths instead of fixing only the wrong ones. This idea is taken
  22143. * from 'ar' written by Haruhiko Okumura.)
  22144. */
  22145. for (bits = max_length; bits !== 0; bits--) {
  22146. n = s.bl_count[bits];
  22147. while (n !== 0) {
  22148. m = s.heap[--h];
  22149. if (m > max_code) { continue; }
  22150. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  22151. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  22152. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  22153. tree[m*2 + 1]/*.Len*/ = bits;
  22154. }
  22155. n--;
  22156. }
  22157. }
  22158. }
  22159. /* ===========================================================================
  22160. * Generate the codes for a given tree and bit counts (which need not be
  22161. * optimal).
  22162. * IN assertion: the array bl_count contains the bit length statistics for
  22163. * the given tree and the field len is set for all tree elements.
  22164. * OUT assertion: the field code is set for all tree elements of non
  22165. * zero code length.
  22166. */
  22167. function gen_codes(tree, max_code, bl_count)
  22168. // ct_data *tree; /* the tree to decorate */
  22169. // int max_code; /* largest code with non zero frequency */
  22170. // ushf *bl_count; /* number of codes at each bit length */
  22171. {
  22172. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  22173. var code = 0; /* running code value */
  22174. var bits; /* bit index */
  22175. var n; /* code index */
  22176. /* The distribution counts are first used to generate the code values
  22177. * without bit reversal.
  22178. */
  22179. for (bits = 1; bits <= MAX_BITS; bits++) {
  22180. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  22181. }
  22182. /* Check that the bit counts in bl_count are consistent. The last code
  22183. * must be all ones.
  22184. */
  22185. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  22186. // "inconsistent bit counts");
  22187. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  22188. for (n = 0; n <= max_code; n++) {
  22189. var len = tree[n*2 + 1]/*.Len*/;
  22190. if (len === 0) { continue; }
  22191. /* Now reverse the bits */
  22192. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  22193. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  22194. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  22195. }
  22196. }
  22197. /* ===========================================================================
  22198. * Initialize the various 'constant' tables.
  22199. */
  22200. function tr_static_init() {
  22201. var n; /* iterates over tree elements */
  22202. var bits; /* bit counter */
  22203. var length; /* length value */
  22204. var code; /* code value */
  22205. var dist; /* distance index */
  22206. var bl_count = new Array(MAX_BITS+1);
  22207. /* number of codes at each bit length for an optimal tree */
  22208. // do check in _tr_init()
  22209. //if (static_init_done) return;
  22210. /* For some embedded targets, global variables are not initialized: */
  22211. /*#ifdef NO_INIT_GLOBAL_POINTERS
  22212. static_l_desc.static_tree = static_ltree;
  22213. static_l_desc.extra_bits = extra_lbits;
  22214. static_d_desc.static_tree = static_dtree;
  22215. static_d_desc.extra_bits = extra_dbits;
  22216. static_bl_desc.extra_bits = extra_blbits;
  22217. #endif*/
  22218. /* Initialize the mapping length (0..255) -> length code (0..28) */
  22219. length = 0;
  22220. for (code = 0; code < LENGTH_CODES-1; code++) {
  22221. base_length[code] = length;
  22222. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  22223. _length_code[length++] = code;
  22224. }
  22225. }
  22226. //Assert (length == 256, "tr_static_init: length != 256");
  22227. /* Note that the length 255 (match length 258) can be represented
  22228. * in two different ways: code 284 + 5 bits or code 285, so we
  22229. * overwrite length_code[255] to use the best encoding:
  22230. */
  22231. _length_code[length-1] = code;
  22232. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  22233. dist = 0;
  22234. for (code = 0 ; code < 16; code++) {
  22235. base_dist[code] = dist;
  22236. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  22237. _dist_code[dist++] = code;
  22238. }
  22239. }
  22240. //Assert (dist == 256, "tr_static_init: dist != 256");
  22241. dist >>= 7; /* from now on, all distances are divided by 128 */
  22242. for ( ; code < D_CODES; code++) {
  22243. base_dist[code] = dist << 7;
  22244. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  22245. _dist_code[256 + dist++] = code;
  22246. }
  22247. }
  22248. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  22249. /* Construct the codes of the static literal tree */
  22250. for (bits = 0; bits <= MAX_BITS; bits++) {
  22251. bl_count[bits] = 0;
  22252. }
  22253. n = 0;
  22254. while (n <= 143) {
  22255. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22256. n++;
  22257. bl_count[8]++;
  22258. }
  22259. while (n <= 255) {
  22260. static_ltree[n*2 + 1]/*.Len*/ = 9;
  22261. n++;
  22262. bl_count[9]++;
  22263. }
  22264. while (n <= 279) {
  22265. static_ltree[n*2 + 1]/*.Len*/ = 7;
  22266. n++;
  22267. bl_count[7]++;
  22268. }
  22269. while (n <= 287) {
  22270. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22271. n++;
  22272. bl_count[8]++;
  22273. }
  22274. /* Codes 286 and 287 do not exist, but we must include them in the
  22275. * tree construction to get a canonical Huffman tree (longest code
  22276. * all ones)
  22277. */
  22278. gen_codes(static_ltree, L_CODES+1, bl_count);
  22279. /* The static distance tree is trivial: */
  22280. for (n = 0; n < D_CODES; n++) {
  22281. static_dtree[n*2 + 1]/*.Len*/ = 5;
  22282. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  22283. }
  22284. // Now data ready and we can init static trees
  22285. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  22286. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  22287. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  22288. //static_init_done = true;
  22289. }
  22290. /* ===========================================================================
  22291. * Initialize a new block.
  22292. */
  22293. function init_block(s) {
  22294. var n; /* iterates over tree elements */
  22295. /* Initialize the trees. */
  22296. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  22297. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  22298. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  22299. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  22300. s.opt_len = s.static_len = 0;
  22301. s.last_lit = s.matches = 0;
  22302. }
  22303. /* ===========================================================================
  22304. * Flush the bit buffer and align the output on a byte boundary
  22305. */
  22306. function bi_windup(s)
  22307. {
  22308. if (s.bi_valid > 8) {
  22309. put_short(s, s.bi_buf);
  22310. } else if (s.bi_valid > 0) {
  22311. //put_byte(s, (Byte)s->bi_buf);
  22312. s.pending_buf[s.pending++] = s.bi_buf;
  22313. }
  22314. s.bi_buf = 0;
  22315. s.bi_valid = 0;
  22316. }
  22317. /* ===========================================================================
  22318. * Copy a stored block, storing first the length and its
  22319. * one's complement if requested.
  22320. */
  22321. function copy_block(s, buf, len, header)
  22322. //DeflateState *s;
  22323. //charf *buf; /* the input data */
  22324. //unsigned len; /* its length */
  22325. //int header; /* true if block header must be written */
  22326. {
  22327. bi_windup(s); /* align on byte boundary */
  22328. if (header) {
  22329. put_short(s, len);
  22330. put_short(s, ~len);
  22331. }
  22332. // while (len--) {
  22333. // put_byte(s, *buf++);
  22334. // }
  22335. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  22336. s.pending += len;
  22337. }
  22338. /* ===========================================================================
  22339. * Compares to subtrees, using the tree depth as tie breaker when
  22340. * the subtrees have equal frequency. This minimizes the worst case length.
  22341. */
  22342. function smaller(tree, n, m, depth) {
  22343. var _n2 = n*2;
  22344. var _m2 = m*2;
  22345. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  22346. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  22347. }
  22348. /* ===========================================================================
  22349. * Restore the heap property by moving down the tree starting at node k,
  22350. * exchanging a node with the smallest of its two sons if necessary, stopping
  22351. * when the heap property is re-established (each father smaller than its
  22352. * two sons).
  22353. */
  22354. function pqdownheap(s, tree, k)
  22355. // deflate_state *s;
  22356. // ct_data *tree; /* the tree to restore */
  22357. // int k; /* node to move down */
  22358. {
  22359. var v = s.heap[k];
  22360. var j = k << 1; /* left son of k */
  22361. while (j <= s.heap_len) {
  22362. /* Set j to the smallest of the two sons: */
  22363. if (j < s.heap_len &&
  22364. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  22365. j++;
  22366. }
  22367. /* Exit if v is smaller than both sons */
  22368. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  22369. /* Exchange v with the smallest son */
  22370. s.heap[k] = s.heap[j];
  22371. k = j;
  22372. /* And continue down the tree, setting j to the left son of k */
  22373. j <<= 1;
  22374. }
  22375. s.heap[k] = v;
  22376. }
  22377. // inlined manually
  22378. // var SMALLEST = 1;
  22379. /* ===========================================================================
  22380. * Send the block data compressed using the given Huffman trees
  22381. */
  22382. function compress_block(s, ltree, dtree)
  22383. // deflate_state *s;
  22384. // const ct_data *ltree; /* literal tree */
  22385. // const ct_data *dtree; /* distance tree */
  22386. {
  22387. var dist; /* distance of matched string */
  22388. var lc; /* match length or unmatched char (if dist == 0) */
  22389. var lx = 0; /* running index in l_buf */
  22390. var code; /* the code to send */
  22391. var extra; /* number of extra bits to send */
  22392. if (s.last_lit !== 0) {
  22393. do {
  22394. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  22395. lc = s.pending_buf[s.l_buf + lx];
  22396. lx++;
  22397. if (dist === 0) {
  22398. send_code(s, lc, ltree); /* send a literal byte */
  22399. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  22400. } else {
  22401. /* Here, lc is the match length - MIN_MATCH */
  22402. code = _length_code[lc];
  22403. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  22404. extra = extra_lbits[code];
  22405. if (extra !== 0) {
  22406. lc -= base_length[code];
  22407. send_bits(s, lc, extra); /* send the extra length bits */
  22408. }
  22409. dist--; /* dist is now the match distance - 1 */
  22410. code = d_code(dist);
  22411. //Assert (code < D_CODES, "bad d_code");
  22412. send_code(s, code, dtree); /* send the distance code */
  22413. extra = extra_dbits[code];
  22414. if (extra !== 0) {
  22415. dist -= base_dist[code];
  22416. send_bits(s, dist, extra); /* send the extra distance bits */
  22417. }
  22418. } /* literal or match pair ? */
  22419. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  22420. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  22421. // "pendingBuf overflow");
  22422. } while (lx < s.last_lit);
  22423. }
  22424. send_code(s, END_BLOCK, ltree);
  22425. }
  22426. /* ===========================================================================
  22427. * Construct one Huffman tree and assigns the code bit strings and lengths.
  22428. * Update the total bit length for the current block.
  22429. * IN assertion: the field freq is set for all tree elements.
  22430. * OUT assertions: the fields len and code are set to the optimal bit length
  22431. * and corresponding code. The length opt_len is updated; static_len is
  22432. * also updated if stree is not null. The field max_code is set.
  22433. */
  22434. function build_tree(s, desc)
  22435. // deflate_state *s;
  22436. // tree_desc *desc; /* the tree descriptor */
  22437. {
  22438. var tree = desc.dyn_tree;
  22439. var stree = desc.stat_desc.static_tree;
  22440. var has_stree = desc.stat_desc.has_stree;
  22441. var elems = desc.stat_desc.elems;
  22442. var n, m; /* iterate over heap elements */
  22443. var max_code = -1; /* largest code with non zero frequency */
  22444. var node; /* new node being created */
  22445. /* Construct the initial heap, with least frequent element in
  22446. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  22447. * heap[0] is not used.
  22448. */
  22449. s.heap_len = 0;
  22450. s.heap_max = HEAP_SIZE;
  22451. for (n = 0; n < elems; n++) {
  22452. if (tree[n * 2]/*.Freq*/ !== 0) {
  22453. s.heap[++s.heap_len] = max_code = n;
  22454. s.depth[n] = 0;
  22455. } else {
  22456. tree[n*2 + 1]/*.Len*/ = 0;
  22457. }
  22458. }
  22459. /* The pkzip format requires that at least one distance code exists,
  22460. * and that at least one bit should be sent even if there is only one
  22461. * possible code. So to avoid special checks later on we force at least
  22462. * two codes of non zero frequency.
  22463. */
  22464. while (s.heap_len < 2) {
  22465. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22466. tree[node * 2]/*.Freq*/ = 1;
  22467. s.depth[node] = 0;
  22468. s.opt_len--;
  22469. if (has_stree) {
  22470. s.static_len -= stree[node*2 + 1]/*.Len*/;
  22471. }
  22472. /* node is 0 or 1 so it does not have extra bits */
  22473. }
  22474. desc.max_code = max_code;
  22475. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22476. * establish sub-heaps of increasing lengths:
  22477. */
  22478. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22479. /* Construct the Huffman tree by repeatedly combining the least two
  22480. * frequent nodes.
  22481. */
  22482. node = elems; /* next internal node of the tree */
  22483. do {
  22484. //pqremove(s, tree, n); /* n = node of least frequency */
  22485. /*** pqremove ***/
  22486. n = s.heap[1/*SMALLEST*/];
  22487. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22488. pqdownheap(s, tree, 1/*SMALLEST*/);
  22489. /***/
  22490. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22491. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22492. s.heap[--s.heap_max] = m;
  22493. /* Create a new node father of n and m */
  22494. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22495. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22496. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22497. /* and insert the new node in the heap */
  22498. s.heap[1/*SMALLEST*/] = node++;
  22499. pqdownheap(s, tree, 1/*SMALLEST*/);
  22500. } while (s.heap_len >= 2);
  22501. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22502. /* At this point, the fields freq and dad are set. We can now
  22503. * generate the bit lengths.
  22504. */
  22505. gen_bitlen(s, desc);
  22506. /* The field len is now set, we can generate the bit codes */
  22507. gen_codes(tree, max_code, s.bl_count);
  22508. }
  22509. /* ===========================================================================
  22510. * Scan a literal or distance tree to determine the frequencies of the codes
  22511. * in the bit length tree.
  22512. */
  22513. function scan_tree(s, tree, max_code)
  22514. // deflate_state *s;
  22515. // ct_data *tree; /* the tree to be scanned */
  22516. // int max_code; /* and its largest code of non zero frequency */
  22517. {
  22518. var n; /* iterates over all tree elements */
  22519. var prevlen = -1; /* last emitted length */
  22520. var curlen; /* length of current code */
  22521. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22522. var count = 0; /* repeat count of the current code */
  22523. var max_count = 7; /* max repeat count */
  22524. var min_count = 4; /* min repeat count */
  22525. if (nextlen === 0) {
  22526. max_count = 138;
  22527. min_count = 3;
  22528. }
  22529. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  22530. for (n = 0; n <= max_code; n++) {
  22531. curlen = nextlen;
  22532. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22533. if (++count < max_count && curlen === nextlen) {
  22534. continue;
  22535. } else if (count < min_count) {
  22536. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22537. } else if (curlen !== 0) {
  22538. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22539. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22540. } else if (count <= 10) {
  22541. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22542. } else {
  22543. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22544. }
  22545. count = 0;
  22546. prevlen = curlen;
  22547. if (nextlen === 0) {
  22548. max_count = 138;
  22549. min_count = 3;
  22550. } else if (curlen === nextlen) {
  22551. max_count = 6;
  22552. min_count = 3;
  22553. } else {
  22554. max_count = 7;
  22555. min_count = 4;
  22556. }
  22557. }
  22558. }
  22559. /* ===========================================================================
  22560. * Send a literal or distance tree in compressed form, using the codes in
  22561. * bl_tree.
  22562. */
  22563. function send_tree(s, tree, max_code)
  22564. // deflate_state *s;
  22565. // ct_data *tree; /* the tree to be scanned */
  22566. // int max_code; /* and its largest code of non zero frequency */
  22567. {
  22568. var n; /* iterates over all tree elements */
  22569. var prevlen = -1; /* last emitted length */
  22570. var curlen; /* length of current code */
  22571. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22572. var count = 0; /* repeat count of the current code */
  22573. var max_count = 7; /* max repeat count */
  22574. var min_count = 4; /* min repeat count */
  22575. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22576. if (nextlen === 0) {
  22577. max_count = 138;
  22578. min_count = 3;
  22579. }
  22580. for (n = 0; n <= max_code; n++) {
  22581. curlen = nextlen;
  22582. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22583. if (++count < max_count && curlen === nextlen) {
  22584. continue;
  22585. } else if (count < min_count) {
  22586. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22587. } else if (curlen !== 0) {
  22588. if (curlen !== prevlen) {
  22589. send_code(s, curlen, s.bl_tree);
  22590. count--;
  22591. }
  22592. //Assert(count >= 3 && count <= 6, " 3_6?");
  22593. send_code(s, REP_3_6, s.bl_tree);
  22594. send_bits(s, count-3, 2);
  22595. } else if (count <= 10) {
  22596. send_code(s, REPZ_3_10, s.bl_tree);
  22597. send_bits(s, count-3, 3);
  22598. } else {
  22599. send_code(s, REPZ_11_138, s.bl_tree);
  22600. send_bits(s, count-11, 7);
  22601. }
  22602. count = 0;
  22603. prevlen = curlen;
  22604. if (nextlen === 0) {
  22605. max_count = 138;
  22606. min_count = 3;
  22607. } else if (curlen === nextlen) {
  22608. max_count = 6;
  22609. min_count = 3;
  22610. } else {
  22611. max_count = 7;
  22612. min_count = 4;
  22613. }
  22614. }
  22615. }
  22616. /* ===========================================================================
  22617. * Construct the Huffman tree for the bit lengths and return the index in
  22618. * bl_order of the last bit length code to send.
  22619. */
  22620. function build_bl_tree(s) {
  22621. var max_blindex; /* index of last bit length code of non zero freq */
  22622. /* Determine the bit length frequencies for literal and distance trees */
  22623. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22624. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22625. /* Build the bit length tree: */
  22626. build_tree(s, s.bl_desc);
  22627. /* opt_len now includes the length of the tree representations, except
  22628. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22629. */
  22630. /* Determine the number of bit length codes to send. The pkzip format
  22631. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22632. * 3 but the actual value used is 4.)
  22633. */
  22634. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22635. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22636. break;
  22637. }
  22638. }
  22639. /* Update opt_len to include the bit length tree and counts */
  22640. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22641. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22642. // s->opt_len, s->static_len));
  22643. return max_blindex;
  22644. }
  22645. /* ===========================================================================
  22646. * Send the header for a block using dynamic Huffman trees: the counts, the
  22647. * lengths of the bit length codes, the literal tree and the distance tree.
  22648. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22649. */
  22650. function send_all_trees(s, lcodes, dcodes, blcodes)
  22651. // deflate_state *s;
  22652. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22653. {
  22654. var rank; /* index in bl_order */
  22655. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22656. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22657. // "too many codes");
  22658. //Tracev((stderr, "\nbl counts: "));
  22659. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22660. send_bits(s, dcodes-1, 5);
  22661. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22662. for (rank = 0; rank < blcodes; rank++) {
  22663. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22664. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22665. }
  22666. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22667. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22668. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22669. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22670. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22671. }
  22672. /* ===========================================================================
  22673. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22674. * - TEXT if the two conditions below are satisfied:
  22675. * a) There are no non-portable control characters belonging to the
  22676. * "black list" (0..6, 14..25, 28..31).
  22677. * b) There is at least one printable character belonging to the
  22678. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22679. * - BINARY otherwise.
  22680. * - The following partially-portable control characters form a
  22681. * "gray list" that is ignored in this detection algorithm:
  22682. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22683. * IN assertion: the fields Freq of dyn_ltree are set.
  22684. */
  22685. function detect_data_type(s) {
  22686. /* black_mask is the bit mask of black-listed bytes
  22687. * set bits 0..6, 14..25, and 28..31
  22688. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22689. */
  22690. var black_mask = 0xf3ffc07f;
  22691. var n;
  22692. /* Check for non-textual ("black-listed") bytes. */
  22693. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22694. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22695. return Z_BINARY;
  22696. }
  22697. }
  22698. /* Check for textual ("white-listed") bytes. */
  22699. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22700. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22701. return Z_TEXT;
  22702. }
  22703. for (n = 32; n < LITERALS; n++) {
  22704. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22705. return Z_TEXT;
  22706. }
  22707. }
  22708. /* There are no "black-listed" or "white-listed" bytes:
  22709. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22710. */
  22711. return Z_BINARY;
  22712. }
  22713. var static_init_done = false;
  22714. /* ===========================================================================
  22715. * Initialize the tree data structures for a new zlib stream.
  22716. */
  22717. function _tr_init(s)
  22718. {
  22719. if (!static_init_done) {
  22720. tr_static_init();
  22721. static_init_done = true;
  22722. }
  22723. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22724. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22725. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22726. s.bi_buf = 0;
  22727. s.bi_valid = 0;
  22728. /* Initialize the first block of the first file: */
  22729. init_block(s);
  22730. }
  22731. /* ===========================================================================
  22732. * Send a stored block
  22733. */
  22734. function _tr_stored_block(s, buf, stored_len, last)
  22735. //DeflateState *s;
  22736. //charf *buf; /* input block */
  22737. //ulg stored_len; /* length of input block */
  22738. //int last; /* one if this is the last block for a file */
  22739. {
  22740. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22741. copy_block(s, buf, stored_len, true); /* with header */
  22742. }
  22743. /* ===========================================================================
  22744. * Send one empty static block to give enough lookahead for inflate.
  22745. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22746. */
  22747. function _tr_align(s) {
  22748. send_bits(s, STATIC_TREES<<1, 3);
  22749. send_code(s, END_BLOCK, static_ltree);
  22750. bi_flush(s);
  22751. }
  22752. /* ===========================================================================
  22753. * Determine the best encoding for the current block: dynamic trees, static
  22754. * trees or store, and output the encoded block to the zip file.
  22755. */
  22756. function _tr_flush_block(s, buf, stored_len, last)
  22757. //DeflateState *s;
  22758. //charf *buf; /* input block, or NULL if too old */
  22759. //ulg stored_len; /* length of input block */
  22760. //int last; /* one if this is the last block for a file */
  22761. {
  22762. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22763. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22764. /* Build the Huffman trees unless a stored block is forced */
  22765. if (s.level > 0) {
  22766. /* Check if the file is binary or text */
  22767. if (s.strm.data_type === Z_UNKNOWN) {
  22768. s.strm.data_type = detect_data_type(s);
  22769. }
  22770. /* Construct the literal and distance trees */
  22771. build_tree(s, s.l_desc);
  22772. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22773. // s->static_len));
  22774. build_tree(s, s.d_desc);
  22775. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22776. // s->static_len));
  22777. /* At this point, opt_len and static_len are the total bit lengths of
  22778. * the compressed block data, excluding the tree representations.
  22779. */
  22780. /* Build the bit length tree for the above two trees, and get the index
  22781. * in bl_order of the last bit length code to send.
  22782. */
  22783. max_blindex = build_bl_tree(s);
  22784. /* Determine the best encoding. Compute the block lengths in bytes. */
  22785. opt_lenb = (s.opt_len+3+7) >>> 3;
  22786. static_lenb = (s.static_len+3+7) >>> 3;
  22787. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22788. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22789. // s->last_lit));
  22790. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22791. } else {
  22792. // Assert(buf != (char*)0, "lost buf");
  22793. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22794. }
  22795. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22796. /* 4: two words for the lengths */
  22797. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22798. * Otherwise we can't have processed more than WSIZE input bytes since
  22799. * the last block flush, because compression would have been
  22800. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22801. * transform a block into a stored block.
  22802. */
  22803. _tr_stored_block(s, buf, stored_len, last);
  22804. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22805. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22806. compress_block(s, static_ltree, static_dtree);
  22807. } else {
  22808. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22809. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22810. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22811. }
  22812. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22813. /* The above check is made mod 2^32, for files larger than 512 MB
  22814. * and uLong implemented on 32 bits.
  22815. */
  22816. init_block(s);
  22817. if (last) {
  22818. bi_windup(s);
  22819. }
  22820. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22821. // s->compressed_len-7*last));
  22822. }
  22823. /* ===========================================================================
  22824. * Save the match info and tally the frequency counts. Return true if
  22825. * the current block must be flushed.
  22826. */
  22827. function _tr_tally(s, dist, lc)
  22828. // deflate_state *s;
  22829. // unsigned dist; /* distance of matched string */
  22830. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22831. {
  22832. //var out_length, in_length, dcode;
  22833. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22834. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22835. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22836. s.last_lit++;
  22837. if (dist === 0) {
  22838. /* lc is the unmatched char */
  22839. s.dyn_ltree[lc*2]/*.Freq*/++;
  22840. } else {
  22841. s.matches++;
  22842. /* Here, lc is the match length - MIN_MATCH */
  22843. dist--; /* dist = match distance - 1 */
  22844. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22845. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22846. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22847. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22848. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22849. }
  22850. // (!) This block is disabled in zlib defailts,
  22851. // don't enable it for binary compatibility
  22852. //#ifdef TRUNCATE_BLOCK
  22853. // /* Try to guess if it is profitable to stop the current block here */
  22854. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22855. // /* Compute an upper bound for the compressed length */
  22856. // out_length = s.last_lit*8;
  22857. // in_length = s.strstart - s.block_start;
  22858. //
  22859. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22860. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22861. // }
  22862. // out_length >>>= 3;
  22863. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22864. // // s->last_lit, in_length, out_length,
  22865. // // 100L - out_length*100L/in_length));
  22866. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22867. // return true;
  22868. // }
  22869. // }
  22870. //#endif
  22871. return (s.last_lit === s.lit_bufsize-1);
  22872. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22873. * on 16 bit machines and because stored blocks are restricted to
  22874. * 64K-1 bytes.
  22875. */
  22876. }
  22877. exports._tr_init = _tr_init;
  22878. exports._tr_stored_block = _tr_stored_block;
  22879. exports._tr_flush_block = _tr_flush_block;
  22880. exports._tr_tally = _tr_tally;
  22881. exports._tr_align = _tr_align;
  22882. },{"../utils/common":67}],79:[function(require,module,exports){
  22883. 'use strict';
  22884. function ZStream() {
  22885. /* next input byte */
  22886. this.input = null; // JS specific, because we have no pointers
  22887. this.next_in = 0;
  22888. /* number of bytes available at input */
  22889. this.avail_in = 0;
  22890. /* total number of input bytes read so far */
  22891. this.total_in = 0;
  22892. /* next output byte should be put there */
  22893. this.output = null; // JS specific, because we have no pointers
  22894. this.next_out = 0;
  22895. /* remaining free space at output */
  22896. this.avail_out = 0;
  22897. /* total number of bytes output so far */
  22898. this.total_out = 0;
  22899. /* last error message, NULL if no error */
  22900. this.msg = ''/*Z_NULL*/;
  22901. /* not visible by applications */
  22902. this.state = null;
  22903. /* best guess about the data type: binary or text */
  22904. this.data_type = 2/*Z_UNKNOWN*/;
  22905. /* adler32 value of the uncompressed data */
  22906. this.adler = 0;
  22907. }
  22908. module.exports = ZStream;
  22909. },{}],80:[function(require,module,exports){
  22910. module.exports = function arrayEquals(array) {
  22911. // if the other array is a falsy value, return
  22912. if (!array)
  22913. return false;
  22914. // compare lengths - can save a lot of time
  22915. if (this.length != array.length)
  22916. return false;
  22917. for (var i = 0, l = this.length; i < l; i++) {
  22918. // Check if we have nested arrays
  22919. if (this[i] instanceof Array && array[i] instanceof Array) {
  22920. // recurse into the nested arrays
  22921. if (!arrayEquals.apply(this[i], [array[i]]))
  22922. return false;
  22923. } else if (this[i] != array[i]) {
  22924. // Warning - two different object instances will never be equal:
  22925. // {x:20} != {x:20}
  22926. return false;
  22927. }
  22928. }
  22929. return true;
  22930. }
  22931. },{}],81:[function(require,module,exports){
  22932. exports.Interop = require('./interop');
  22933. },{"./interop":82}],82:[function(require,module,exports){
  22934. var transform = require('./transform');
  22935. var arrayEquals = require('./array-equals');
  22936. function Interop() { }
  22937. module.exports = Interop;
  22938. /**
  22939. * This map holds the most recent Plan A offer/answer SDP that was converted
  22940. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22941. * string as values.
  22942. *
  22943. * @type {{}}
  22944. */
  22945. var cache = {};
  22946. /**
  22947. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22948. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22949. * application.
  22950. *
  22951. * @param desc
  22952. * @returns {*}
  22953. */
  22954. Interop.prototype.toPlanB = function(desc) {
  22955. //#region Preliminary input validation.
  22956. if (typeof desc !== 'object' || desc === null ||
  22957. typeof desc.sdp !== 'string') {
  22958. console.warn('An empty description was passed as an argument.');
  22959. return desc;
  22960. }
  22961. // Objectify the SDP for easier manipulation.
  22962. var session = transform.parse(desc.sdp);
  22963. // If the SDP contains no media, there's nothing to transform.
  22964. if (typeof session.media === 'undefined' ||
  22965. !Array.isArray(session.media) || session.media.length === 0) {
  22966. console.warn('The description has no media.');
  22967. return desc;
  22968. }
  22969. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22970. // a video, an audio and a data "channel" at most.
  22971. if (session.media.length <= 3 && session.media.every(function(m) {
  22972. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22973. })) {
  22974. console.warn('This description does not look like Plan A.');
  22975. return desc;
  22976. }
  22977. //#endregion
  22978. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22979. // Plan A transformation.
  22980. cache[desc.type] = desc.sdp;
  22981. //#region Convert from Plan A to Plan B.
  22982. // We rebuild the session.media array.
  22983. var media = session.media;
  22984. session.media = [];
  22985. // Associative array that maps channel types to channel objects for fast
  22986. // access to channel objects by their type, e.g. channels['audio']->channel
  22987. // obj.
  22988. var channels = {};
  22989. // Used to build the group:BUNDLE value after the channels construction
  22990. // loop.
  22991. var types = [];
  22992. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22993. media.forEach(function(mLine) {
  22994. // rtcp-mux is required in the Plan B SDP.
  22995. if (typeof mLine.rtcpMux !== 'string' ||
  22996. mLine.rtcpMux !== 'rtcp-mux') {
  22997. throw new Error('Cannot convert to Plan B because m-lines ' +
  22998. 'without the rtcp-mux attribute were found.');
  22999. }
  23000. // If we don't have a channel for this mLine.type, then use this mLine
  23001. // as the channel basis.
  23002. if (typeof channels[mLine.type] === 'undefined') {
  23003. channels[mLine.type] = mLine;
  23004. }
  23005. // Add sources to the channel and handle a=msid.
  23006. if (typeof mLine.sources === 'object') {
  23007. Object.keys(mLine.sources).forEach(function(ssrc) {
  23008. // Assign the sources to the channel.
  23009. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  23010. // In Plan B the msid is an SSRC attribute. Also, we don't care
  23011. // about the obsolete label and mslabel attributes.
  23012. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  23013. // NOTE ssrcs in ssrc groups will share msids, as
  23014. // draft-uberti-rtcweb-plan-00 mandates.
  23015. });
  23016. }
  23017. // Add ssrc groups to the channel.
  23018. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23019. Array.isArray(mLine.ssrcGroups)) {
  23020. // Create the ssrcGroups array, if it's not defined.
  23021. if (typeof channel.ssrcGroups === 'undefined' ||
  23022. !Array.isArray(channel.ssrcGroups)) {
  23023. channel.ssrcGroups = [];
  23024. }
  23025. channel.ssrcGroups = channel.ssrcGroups.concat(mLine.ssrcGroups);
  23026. }
  23027. if (channels[mLine.type] === mLine) {
  23028. // Copy ICE related stuff from the principal media line.
  23029. mLine.candidates = media[0].candidates;
  23030. mLine.iceUfrag = media[0].iceUfrag;
  23031. mLine.icePwd = media[0].icePwd;
  23032. mLine.fingerprint = media[0].fingerprint;
  23033. // Plan B mids are in ['audio', 'video', 'data']
  23034. mLine.mid = mLine.type;
  23035. // Plan B doesn't support/need the bundle-only attribute.
  23036. delete mLine.bundleOnly;
  23037. // In Plan B the msid is an SSRC attribute.
  23038. delete mLine.msid;
  23039. // Used to build the group:BUNDLE value after this loop.
  23040. types.push(mLine.type);
  23041. // Add the channel to the new media array.
  23042. session.media.push(mLine);
  23043. }
  23044. });
  23045. // We regenerate the BUNDLE group with the new mids.
  23046. session.groups.every(function(group) {
  23047. if (group.type === 'BUNDLE') {
  23048. group.mids = types.join(' ');
  23049. return false;
  23050. } else {
  23051. return true;
  23052. }
  23053. });
  23054. // msid semantic
  23055. session.msidSemantic = {
  23056. semantic: 'WMS',
  23057. token: '*'
  23058. };
  23059. var resStr = transform.write(session);
  23060. return new RTCSessionDescription({
  23061. type: desc.type,
  23062. sdp: resStr
  23063. });
  23064. //#endregion
  23065. };
  23066. /**
  23067. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  23068. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  23069. *
  23070. * @param desc
  23071. * @returns {*}
  23072. */
  23073. Interop.prototype.toPlanA = function(desc) {
  23074. //#region Preliminary input validation.
  23075. if (typeof desc !== 'object' || desc === null ||
  23076. typeof desc.sdp !== 'string') {
  23077. console.warn('An empty description was passed as an argument.');
  23078. return desc;
  23079. }
  23080. var session = transform.parse(desc.sdp);
  23081. // If the SDP contains no media, there's nothing to transform.
  23082. if (typeof session.media === 'undefined' ||
  23083. !Array.isArray(session.media) || session.media.length === 0) {
  23084. console.warn('The description has no media.');
  23085. return desc;
  23086. }
  23087. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  23088. // a video, an audio and a data "channel" at most.
  23089. if (session.media.length > 3 || !session.media.every(function(m) {
  23090. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  23091. })) {
  23092. console.warn('This description does not look like Plan B.');
  23093. return desc;
  23094. }
  23095. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  23096. var mids = [];
  23097. session.media.forEach(function(m) {
  23098. mids.push(m.mid);
  23099. });
  23100. var hasBundle = false;
  23101. if (typeof session.groups !== 'undefined' &&
  23102. Array.isArray(session.groups)) {
  23103. hasBundle = session.groups.every(function(g) {
  23104. return g.type !== 'BUNDLE' ||
  23105. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  23106. });
  23107. }
  23108. if (!hasBundle) {
  23109. throw new Error("Cannot convert to Plan A because m-lines that are " +
  23110. "not bundled were found.");
  23111. }
  23112. //#endregion
  23113. //#region Convert from Plan B to Plan A.
  23114. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  23115. // rebuild an equivalent Plan A offer/answer.
  23116. //
  23117. // For example, if this is a local answer (in Plan A style) that we convert
  23118. // to Plan B prior to handing it over to the application (the
  23119. // PeerConnection wrapper called us, for instance, after a successful
  23120. // createAnswer), we want to remember the m-line at which we've seen the
  23121. // (local) SSRC. That's because when the application wants to do call the
  23122. // SLD method, forcing us to do the inverse transformation (from Plan B to
  23123. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  23124. // also need to know all the other m-lines that the original answer had and
  23125. // include them in the transformed answer as well.
  23126. //
  23127. // Another example is if this is a remote offer that we convert to Plan B
  23128. // prior to giving it to the application, we want to remember the mid at
  23129. // which we've seen the (remote) SSRC.
  23130. //
  23131. // In the iteration that follows, we use the cached Plan A (if it exists)
  23132. // to assign mids to ssrcs.
  23133. var cached;
  23134. if (typeof cache[desc.type] !== 'undefined') {
  23135. cached = transform.parse(cache[desc.type]);
  23136. }
  23137. // A helper map that sends mids to m-line objects. We use it later to
  23138. // rebuild the Plan A style session.media array.
  23139. var media = {};
  23140. session.media.forEach(function(channel) {
  23141. if (typeof channel.rtcpMux !== 'string' ||
  23142. channel.rtcpMux !== 'rtcp-mux') {
  23143. throw new Error("Cannot convert to Plan A because m-lines " +
  23144. "without the rtcp-mux attribute were found.");
  23145. }
  23146. // With rtcp-mux and bundle all the channels should have the same ICE
  23147. // stuff.
  23148. var sources = channel.sources;
  23149. var ssrcGroups = channel.ssrcGroups;
  23150. var candidates = channel.candidates;
  23151. var iceUfrag = channel.iceUfrag;
  23152. var icePwd = channel.icePwd;
  23153. var fingerprint = channel.fingerprint;
  23154. var port = channel.port;
  23155. // We'll use the "channel" object as a prototype for each new "mLine"
  23156. // that we create, but first we need to clean it up a bit.
  23157. delete channel.sources;
  23158. delete channel.ssrcGroups;
  23159. delete channel.candidates;
  23160. delete channel.iceUfrag;
  23161. delete channel.icePwd;
  23162. delete channel.fingerprint;
  23163. delete channel.port;
  23164. delete channel.mid;
  23165. // inverted ssrc group map
  23166. var invertedGroups = {};
  23167. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  23168. ssrcGroups.forEach(function (ssrcGroup) {
  23169. // TODO(gp) find out how to receive simulcast with FF. For the
  23170. // time being, hide it.
  23171. if (ssrcGroup.semantics === 'SIM') {
  23172. return;
  23173. }
  23174. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  23175. Array.isArray(ssrcGroup.ssrcs)) {
  23176. ssrcGroup.ssrcs.forEach(function (ssrc) {
  23177. if (typeof invertedGroups[ssrc] === 'undefined') {
  23178. invertedGroups[ssrc] = [];
  23179. }
  23180. invertedGroups[ssrc].push(ssrcGroup);
  23181. });
  23182. }
  23183. });
  23184. }
  23185. // ssrc to m-line index.
  23186. var mLines = {};
  23187. if (typeof sources === 'object') {
  23188. // Explode the Plan B channel sources with one m-line per source.
  23189. Object.keys(sources).forEach(function(ssrc) {
  23190. var mLine;
  23191. if (typeof invertedGroups[ssrc] !== 'undefined' &&
  23192. Array.isArray(invertedGroups[ssrc])) {
  23193. invertedGroups[ssrc].every(function (ssrcGroup) {
  23194. // ssrcGroup.ssrcs *is* an Array, no need to check
  23195. // again here.
  23196. return ssrcGroup.ssrcs.every(function (related) {
  23197. if (typeof mLines[related] === 'object') {
  23198. mLine = mLines[related];
  23199. return false;
  23200. } else {
  23201. return true;
  23202. }
  23203. });
  23204. });
  23205. }
  23206. if (typeof mLine === 'object') {
  23207. // the m-line already exists. Just add the source.
  23208. mLine.sources[ssrc] = sources[ssrc];
  23209. delete sources[ssrc].msid;
  23210. } else {
  23211. // Use the "channel" as a prototype for the "mLine".
  23212. mLine = Object.create(channel);
  23213. mLines[ssrc] = mLine;
  23214. // Assign the msid of the source to the m-line.
  23215. mLine.msid = sources[ssrc].msid;
  23216. delete sources[ssrc].msid;
  23217. // We assign one SSRC per media line.
  23218. mLine.sources = {};
  23219. mLine.sources[ssrc] = sources[ssrc];
  23220. mLine.ssrcGroups = invertedGroups[ssrc];
  23221. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  23222. // mids.
  23223. if (typeof cached !== 'undefined' &&
  23224. typeof cached.media !== 'undefined' &&
  23225. Array.isArray(cached.media)) {
  23226. cached.media.forEach(function(m) {
  23227. if (typeof m.sources === 'object') {
  23228. Object.keys(m.sources).forEach(function(s) {
  23229. if (s === ssrc) {
  23230. mLine.mid = m.mid;
  23231. }
  23232. });
  23233. }
  23234. });
  23235. }
  23236. if (typeof mLine.mid === 'undefined') {
  23237. // If this is an SSRC that we see for the first time assign
  23238. // it a new mid. This is typically the case when this
  23239. // method is called to transform a remote description for
  23240. // the first time or when there is a new SSRC in the remote
  23241. // description because a new peer has joined the
  23242. // conference. Local SSRCs should have already been added
  23243. // to the map in the toPlanB method.
  23244. //
  23245. // Because FF generates answers in Plan A style, we MUST
  23246. // already have a cached answer with all the local SSRCs
  23247. // mapped to some mLine/mid.
  23248. if (desc.type === 'answer') {
  23249. throw new Error("An unmapped SSRC was found.");
  23250. }
  23251. mLine.mid = [channel.type, '-', ssrc].join('');
  23252. }
  23253. // Include the candidates in the 1st media line.
  23254. mLine.candidates = candidates;
  23255. mLine.iceUfrag = iceUfrag;
  23256. mLine.icePwd = icePwd;
  23257. mLine.fingerprint = fingerprint;
  23258. mLine.port = port;
  23259. media[mLine.mid] = mLine;
  23260. }
  23261. });
  23262. }
  23263. });
  23264. // Rebuild the media array in the right order and add the missing mLines
  23265. // (missing from the Plan B SDP).
  23266. session.media = [];
  23267. mids = []; // reuse
  23268. if (desc.type === 'answer') {
  23269. // The media lines in the answer must match the media lines in the
  23270. // offer. The order is important too. Here we use the cached offer to
  23271. // find the m-lines that are missing (from the converted answer), and
  23272. // use the cached answer to complete the converted answer.
  23273. if (typeof cache['offer'] === 'undefined') {
  23274. throw new Error("An answer is being processed but we couldn't " +
  23275. "find a cached offer.");
  23276. }
  23277. var cachedOffer = transform.parse(cache['offer']);
  23278. if (typeof cachedOffer === 'undefined' ||
  23279. typeof cachedOffer.media === 'undefined' ||
  23280. !Array.isArray(cachedOffer.media)) {
  23281. // FIXME(gp) is this really a problem in the general case?
  23282. throw new Error("The cached offer has no media.");
  23283. }
  23284. cachedOffer.media.forEach(function(mo) {
  23285. var mLine;
  23286. if (typeof media[mo.mid] === 'undefined') {
  23287. // This is probably an m-line containing a remote track only.
  23288. // It MUST exist in the cached answer as a remote track only
  23289. // mLine.
  23290. cached.media.every(function(ma) {
  23291. if (mo.mid == ma.mid) {
  23292. mLine = ma;
  23293. return false;
  23294. } else {
  23295. return true;
  23296. }
  23297. });
  23298. } else {
  23299. mLine = media[mo.mid];
  23300. }
  23301. if (typeof mLine === 'undefined') {
  23302. throw new Error("The cached offer contains an m-line that " +
  23303. "doesn't exist neither in the cached answer nor in " +
  23304. "the converted answer.");
  23305. }
  23306. session.media.push(mLine);
  23307. mids.push(mLine.mid);
  23308. });
  23309. } else {
  23310. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  23311. // under any circumstances. If we are no longer interested in sending a
  23312. // track, we just remove the msid and ssrc attributes and set it to
  23313. // either a=recvonly (as the reofferer, we must use recvonly if the
  23314. // other side was previously sending on the m-section, but we can also
  23315. // leave the possibility open if it wasn't previously in use), or
  23316. // a=inacive.
  23317. if (typeof cached !== 'undefined' &&
  23318. typeof cached.media !== 'undefined' &&
  23319. Array.isArray(cached.media)) {
  23320. cached.media.forEach(function(pm) {
  23321. mids.push(pm.mid);
  23322. if (typeof media[pm.mid] !== 'undefined') {
  23323. session.media.push(media[pm.mid]);
  23324. } else {
  23325. delete pm.msid;
  23326. delete pm.sources;
  23327. delete pm.ssrcGroups;
  23328. pm.direction = 'recvonly';
  23329. session.media.push(pm);
  23330. }
  23331. });
  23332. }
  23333. // Add all the remaining (new) m-lines of the transformed SDP.
  23334. Object.keys(media).forEach(function(mid) {
  23335. if (mids.indexOf(mid) === -1) {
  23336. mids.push(mid);
  23337. session.media.push(media[mid]);
  23338. }
  23339. });
  23340. }
  23341. // We regenerate the BUNDLE group (since we regenerated the mids)
  23342. session.groups.every(function(group) {
  23343. if (group.type === 'BUNDLE') {
  23344. group.mids = mids.join(' ');
  23345. return false;
  23346. } else {
  23347. return true;
  23348. }
  23349. });
  23350. // msid semantic
  23351. session.msidSemantic = {
  23352. semantic: 'WMS',
  23353. token: '*'
  23354. };
  23355. var resStr = transform.write(session);
  23356. // Cache the transformed SDP (Plan A) for later re-use in this function.
  23357. cache[desc.type] = resStr;
  23358. return new RTCSessionDescription({
  23359. type: desc.type,
  23360. sdp: resStr
  23361. });
  23362. //#endregion
  23363. };
  23364. },{"./array-equals":80,"./transform":83}],83:[function(require,module,exports){
  23365. var transform = require('sdp-transform');
  23366. exports.write = function(session, opts) {
  23367. if (typeof session !== 'undefined' &&
  23368. typeof session.media !== 'undefined' &&
  23369. Array.isArray(session.media)) {
  23370. session.media.forEach(function (mLine) {
  23371. // expand sources to ssrcs
  23372. if (typeof mLine.sources !== 'undefined' &&
  23373. Object.keys(mLine.sources).length !== 0) {
  23374. mLine.ssrcs = [];
  23375. Object.keys(mLine.sources).forEach(function (ssrc) {
  23376. var source = mLine.sources[ssrc];
  23377. Object.keys(source).forEach(function (attribute) {
  23378. mLine.ssrcs.push({
  23379. id: ssrc,
  23380. attribute: attribute,
  23381. value: source[attribute]
  23382. });
  23383. });
  23384. });
  23385. delete mLine.sources;
  23386. }
  23387. // join ssrcs in ssrc groups
  23388. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23389. Array.isArray(mLine.ssrcGroups)) {
  23390. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  23391. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  23392. Array.isArray(ssrcGroup.ssrcs)) {
  23393. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  23394. }
  23395. });
  23396. }
  23397. });
  23398. }
  23399. // join group mids
  23400. if (typeof session !== 'undefined' &&
  23401. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23402. session.groups.forEach(function (g) {
  23403. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  23404. g.mids = g.mids.join(' ');
  23405. }
  23406. });
  23407. }
  23408. return transform.write(session, opts);
  23409. };
  23410. exports.parse = function(sdp) {
  23411. var session = transform.parse(sdp);
  23412. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  23413. Array.isArray(session.media)) {
  23414. session.media.forEach(function (mLine) {
  23415. // group sources attributes by ssrc
  23416. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  23417. mLine.sources = {};
  23418. mLine.ssrcs.forEach(function (ssrc) {
  23419. if (!mLine.sources[ssrc.id])
  23420. mLine.sources[ssrc.id] = {};
  23421. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  23422. });
  23423. delete mLine.ssrcs;
  23424. }
  23425. // split ssrcs in ssrc groups
  23426. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23427. Array.isArray(mLine.ssrcGroups)) {
  23428. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  23429. if (typeof ssrcGroup.ssrcs === 'string') {
  23430. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  23431. }
  23432. });
  23433. }
  23434. });
  23435. }
  23436. // split group mids
  23437. if (typeof session !== 'undefined' &&
  23438. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23439. session.groups.forEach(function (g) {
  23440. if (typeof g.mids === 'string') {
  23441. g.mids = g.mids.split(' ');
  23442. }
  23443. });
  23444. }
  23445. return session;
  23446. };
  23447. },{"sdp-transform":85}],84:[function(require,module,exports){
  23448. var grammar = module.exports = {
  23449. v: [{
  23450. name: 'version',
  23451. reg: /^(\d*)$/
  23452. }],
  23453. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  23454. // NB: sessionId will be a String in most cases because it is huge
  23455. name: 'origin',
  23456. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  23457. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  23458. format: "%s %s %d %s IP%d %s"
  23459. }],
  23460. // default parsing of these only (though some of these feel outdated)
  23461. s: [{ name: 'name' }],
  23462. i: [{ name: 'description' }],
  23463. u: [{ name: 'uri' }],
  23464. e: [{ name: 'email' }],
  23465. p: [{ name: 'phone' }],
  23466. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  23467. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  23468. //k: [{}], // outdated thing ignored
  23469. t: [{ //t=0 0
  23470. name: 'timing',
  23471. reg: /^(\d*) (\d*)/,
  23472. names: ['start', 'stop'],
  23473. format: "%d %d"
  23474. }],
  23475. c: [{ //c=IN IP4 10.47.197.26
  23476. name: 'connection',
  23477. reg: /^IN IP(\d) (\S*)/,
  23478. names: ['version', 'ip'],
  23479. format: "IN IP%d %s"
  23480. }],
  23481. b: [{ //b=AS:4000
  23482. push: 'bandwidth',
  23483. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  23484. names: ['type', 'limit'],
  23485. format: "%s:%s"
  23486. }],
  23487. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  23488. // NB: special - pushes to session
  23489. // TODO: rtp/fmtp should be filtered by the payloads found here?
  23490. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  23491. names: ['type', 'port', 'protocol', 'payloads'],
  23492. format: "%s %d %s %s"
  23493. }],
  23494. a: [
  23495. { //a=rtpmap:110 opus/48000/2
  23496. push: 'rtp',
  23497. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  23498. names: ['payload', 'codec', 'rate', 'encoding'],
  23499. format: function (o) {
  23500. return (o.encoding) ?
  23501. "rtpmap:%d %s/%s/%s":
  23502. "rtpmap:%d %s/%s";
  23503. }
  23504. },
  23505. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  23506. push: 'fmtp',
  23507. reg: /^fmtp:(\d*) (\S*)/,
  23508. names: ['payload', 'config'],
  23509. format: "fmtp:%d %s"
  23510. },
  23511. { //a=control:streamid=0
  23512. name: 'control',
  23513. reg: /^control:(.*)/,
  23514. format: "control:%s"
  23515. },
  23516. { //a=rtcp:65179 IN IP4 193.84.77.194
  23517. name: 'rtcp',
  23518. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  23519. names: ['port', 'netType', 'ipVer', 'address'],
  23520. format: function (o) {
  23521. return (o.address != null) ?
  23522. "rtcp:%d %s IP%d %s":
  23523. "rtcp:%d";
  23524. }
  23525. },
  23526. { //a=rtcp-fb:98 trr-int 100
  23527. push: 'rtcpFbTrrInt',
  23528. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  23529. names: ['payload', 'value'],
  23530. format: "rtcp-fb:%d trr-int %d"
  23531. },
  23532. { //a=rtcp-fb:98 nack rpsi
  23533. push: 'rtcpFb',
  23534. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  23535. names: ['payload', 'type', 'subtype'],
  23536. format: function (o) {
  23537. return (o.subtype != null) ?
  23538. "rtcp-fb:%s %s %s":
  23539. "rtcp-fb:%s %s";
  23540. }
  23541. },
  23542. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  23543. //a=extmap:1/recvonly URI-gps-string
  23544. push: 'ext',
  23545. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  23546. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  23547. format: function (o) {
  23548. return (o.config != null) ?
  23549. "extmap:%s %s %s":
  23550. "extmap:%s %s";
  23551. }
  23552. },
  23553. {
  23554. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  23555. push: 'crypto',
  23556. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  23557. names: ['id', 'suite', 'config', 'sessionConfig'],
  23558. format: function (o) {
  23559. return (o.sessionConfig != null) ?
  23560. "crypto:%d %s %s %s":
  23561. "crypto:%d %s %s";
  23562. }
  23563. },
  23564. { //a=setup:actpass
  23565. name: 'setup',
  23566. reg: /^setup:(\w*)/,
  23567. format: "setup:%s"
  23568. },
  23569. { //a=mid:1
  23570. name: 'mid',
  23571. reg: /^mid:([^\s]*)/,
  23572. format: "mid:%s"
  23573. },
  23574. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  23575. name: 'msid',
  23576. reg: /^msid:(.*)/,
  23577. format: "msid:%s"
  23578. },
  23579. { //a=ptime:20
  23580. name: 'ptime',
  23581. reg: /^ptime:(\d*)/,
  23582. format: "ptime:%d"
  23583. },
  23584. { //a=maxptime:60
  23585. name: 'maxptime',
  23586. reg: /^maxptime:(\d*)/,
  23587. format: "maxptime:%d"
  23588. },
  23589. { //a=sendrecv
  23590. name: 'direction',
  23591. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  23592. },
  23593. { //a=ice-lite
  23594. name: 'icelite',
  23595. reg: /^(ice-lite)/
  23596. },
  23597. { //a=ice-ufrag:F7gI
  23598. name: 'iceUfrag',
  23599. reg: /^ice-ufrag:(\S*)/,
  23600. format: "ice-ufrag:%s"
  23601. },
  23602. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  23603. name: 'icePwd',
  23604. reg: /^ice-pwd:(\S*)/,
  23605. format: "ice-pwd:%s"
  23606. },
  23607. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  23608. name: 'fingerprint',
  23609. reg: /^fingerprint:(\S*) (\S*)/,
  23610. names: ['type', 'hash'],
  23611. format: "fingerprint:%s %s"
  23612. },
  23613. {
  23614. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  23615. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  23616. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  23617. push:'candidates',
  23618. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  23619. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  23620. format: function (o) {
  23621. var str = "candidate:%s %d %s %d %s %d typ %s";
  23622. // NB: candidate has two optional chunks, so %void middle one if it's missing
  23623. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  23624. if (o.generation != null) {
  23625. str += " generation %d";
  23626. }
  23627. return str;
  23628. }
  23629. },
  23630. { //a=end-of-candidates (keep after the candidates line for readability)
  23631. name: 'endOfCandidates',
  23632. reg: /^(end-of-candidates)/
  23633. },
  23634. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  23635. name: 'remoteCandidates',
  23636. reg: /^remote-candidates:(.*)/,
  23637. format: "remote-candidates:%s"
  23638. },
  23639. { //a=ice-options:google-ice
  23640. name: 'iceOptions',
  23641. reg: /^ice-options:(\S*)/,
  23642. format: "ice-options:%s"
  23643. },
  23644. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  23645. push: "ssrcs",
  23646. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  23647. names: ['id', 'attribute', 'value'],
  23648. format: "ssrc:%d %s:%s"
  23649. },
  23650. { //a=ssrc-group:FEC 1 2
  23651. push: "ssrcGroups",
  23652. reg: /^ssrc-group:(\w*) (.*)/,
  23653. names: ['semantics', 'ssrcs'],
  23654. format: "ssrc-group:%s %s"
  23655. },
  23656. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  23657. name: "msidSemantic",
  23658. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  23659. names: ['semantic', 'token'],
  23660. format: "msid-semantic: %s %s" // space after ":" is not accidental
  23661. },
  23662. { //a=group:BUNDLE audio video
  23663. push: 'groups',
  23664. reg: /^group:(\w*) (.*)/,
  23665. names: ['type', 'mids'],
  23666. format: "group:%s %s"
  23667. },
  23668. { //a=rtcp-mux
  23669. name: 'rtcpMux',
  23670. reg: /^(rtcp-mux)/
  23671. },
  23672. { // any a= that we don't understand is kepts verbatim on media.invalid
  23673. push: 'invalid',
  23674. names: ["value"]
  23675. }
  23676. ]
  23677. };
  23678. // set sensible defaults to avoid polluting the grammar with boring details
  23679. Object.keys(grammar).forEach(function (key) {
  23680. var objs = grammar[key];
  23681. objs.forEach(function (obj) {
  23682. if (!obj.reg) {
  23683. obj.reg = /(.*)/;
  23684. }
  23685. if (!obj.format) {
  23686. obj.format = "%s";
  23687. }
  23688. });
  23689. });
  23690. },{}],85:[function(require,module,exports){
  23691. var parser = require('./parser');
  23692. var writer = require('./writer');
  23693. exports.write = writer;
  23694. exports.parse = parser.parse;
  23695. exports.parseFmtpConfig = parser.parseFmtpConfig;
  23696. exports.parsePayloads = parser.parsePayloads;
  23697. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  23698. },{"./parser":86,"./writer":87}],86:[function(require,module,exports){
  23699. var toIntIfInt = function (v) {
  23700. return String(Number(v)) === v ? Number(v) : v;
  23701. };
  23702. var attachProperties = function (match, location, names, rawName) {
  23703. if (rawName && !names) {
  23704. location[rawName] = toIntIfInt(match[1]);
  23705. }
  23706. else {
  23707. for (var i = 0; i < names.length; i += 1) {
  23708. if (match[i+1] != null) {
  23709. location[names[i]] = toIntIfInt(match[i+1]);
  23710. }
  23711. }
  23712. }
  23713. };
  23714. var parseReg = function (obj, location, content) {
  23715. var needsBlank = obj.name && obj.names;
  23716. if (obj.push && !location[obj.push]) {
  23717. location[obj.push] = [];
  23718. }
  23719. else if (needsBlank && !location[obj.name]) {
  23720. location[obj.name] = {};
  23721. }
  23722. var keyLocation = obj.push ?
  23723. {} : // blank object that will be pushed
  23724. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  23725. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  23726. if (obj.push) {
  23727. location[obj.push].push(keyLocation);
  23728. }
  23729. };
  23730. var grammar = require('./grammar');
  23731. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  23732. exports.parse = function (sdp) {
  23733. var session = {}
  23734. , media = []
  23735. , location = session; // points at where properties go under (one of the above)
  23736. // parse lines we understand
  23737. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  23738. var type = l[0];
  23739. var content = l.slice(2);
  23740. if (type === 'm') {
  23741. media.push({rtp: [], fmtp: []});
  23742. location = media[media.length-1]; // point at latest media line
  23743. }
  23744. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  23745. var obj = grammar[type][j];
  23746. if (obj.reg.test(content)) {
  23747. return parseReg(obj, location, content);
  23748. }
  23749. }
  23750. });
  23751. session.media = media; // link it up
  23752. return session;
  23753. };
  23754. var fmtpReducer = function (acc, expr) {
  23755. var s = expr.split('=');
  23756. if (s.length === 2) {
  23757. acc[s[0]] = toIntIfInt(s[1]);
  23758. }
  23759. return acc;
  23760. };
  23761. exports.parseFmtpConfig = function (str) {
  23762. return str.split(';').reduce(fmtpReducer, {});
  23763. };
  23764. exports.parsePayloads = function (str) {
  23765. return str.split(' ').map(Number);
  23766. };
  23767. exports.parseRemoteCandidates = function (str) {
  23768. var candidates = [];
  23769. var parts = str.split(' ').map(toIntIfInt);
  23770. for (var i = 0; i < parts.length; i += 3) {
  23771. candidates.push({
  23772. component: parts[i],
  23773. ip: parts[i + 1],
  23774. port: parts[i + 2]
  23775. });
  23776. }
  23777. return candidates;
  23778. };
  23779. },{"./grammar":84}],87:[function(require,module,exports){
  23780. var grammar = require('./grammar');
  23781. // customized util.format - discards excess arguments and can void middle ones
  23782. var formatRegExp = /%[sdv%]/g;
  23783. var format = function (formatStr) {
  23784. var i = 1;
  23785. var args = arguments;
  23786. var len = args.length;
  23787. return formatStr.replace(formatRegExp, function (x) {
  23788. if (i >= len) {
  23789. return x; // missing argument
  23790. }
  23791. var arg = args[i];
  23792. i += 1;
  23793. switch (x) {
  23794. case '%%':
  23795. return '%';
  23796. case '%s':
  23797. return String(arg);
  23798. case '%d':
  23799. return Number(arg);
  23800. case '%v':
  23801. return '';
  23802. }
  23803. });
  23804. // NB: we discard excess arguments - they are typically undefined from makeLine
  23805. };
  23806. var makeLine = function (type, obj, location) {
  23807. var str = obj.format instanceof Function ?
  23808. (obj.format(obj.push ? location : location[obj.name])) :
  23809. obj.format;
  23810. var args = [type + '=' + str];
  23811. if (obj.names) {
  23812. for (var i = 0; i < obj.names.length; i += 1) {
  23813. var n = obj.names[i];
  23814. if (obj.name) {
  23815. args.push(location[obj.name][n]);
  23816. }
  23817. else { // for mLine and push attributes
  23818. args.push(location[obj.names[i]]);
  23819. }
  23820. }
  23821. }
  23822. else {
  23823. args.push(location[obj.name]);
  23824. }
  23825. return format.apply(null, args);
  23826. };
  23827. // RFC specified order
  23828. // TODO: extend this with all the rest
  23829. var defaultOuterOrder = [
  23830. 'v', 'o', 's', 'i',
  23831. 'u', 'e', 'p', 'c',
  23832. 'b', 't', 'r', 'z', 'a'
  23833. ];
  23834. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23835. module.exports = function (session, opts) {
  23836. opts = opts || {};
  23837. // ensure certain properties exist
  23838. if (session.version == null) {
  23839. session.version = 0; // "v=0" must be there (only defined version atm)
  23840. }
  23841. if (session.name == null) {
  23842. session.name = " "; // "s= " must be there if no meaningful name set
  23843. }
  23844. session.media.forEach(function (mLine) {
  23845. if (mLine.payloads == null) {
  23846. mLine.payloads = "";
  23847. }
  23848. });
  23849. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23850. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23851. var sdp = [];
  23852. // loop through outerOrder for matching properties on session
  23853. outerOrder.forEach(function (type) {
  23854. grammar[type].forEach(function (obj) {
  23855. if (obj.name in session && session[obj.name] != null) {
  23856. sdp.push(makeLine(type, obj, session));
  23857. }
  23858. else if (obj.push in session && session[obj.push] != null) {
  23859. session[obj.push].forEach(function (el) {
  23860. sdp.push(makeLine(type, obj, el));
  23861. });
  23862. }
  23863. });
  23864. });
  23865. // then for each media line, follow the innerOrder
  23866. session.media.forEach(function (mLine) {
  23867. sdp.push(makeLine('m', grammar.m[0], mLine));
  23868. innerOrder.forEach(function (type) {
  23869. grammar[type].forEach(function (obj) {
  23870. if (obj.name in mLine && mLine[obj.name] != null) {
  23871. sdp.push(makeLine(type, obj, mLine));
  23872. }
  23873. else if (obj.push in mLine && mLine[obj.push] != null) {
  23874. mLine[obj.push].forEach(function (el) {
  23875. sdp.push(makeLine(type, obj, el));
  23876. });
  23877. }
  23878. });
  23879. });
  23880. });
  23881. return sdp.join('\r\n') + '\r\n';
  23882. };
  23883. },{"./grammar":84}],88:[function(require,module,exports){
  23884. var MediaStreamType = {
  23885. VIDEO_TYPE: "Video",
  23886. AUDIO_TYPE: "Audio"
  23887. };
  23888. module.exports = MediaStreamType;
  23889. },{}],89:[function(require,module,exports){
  23890. var RTCBrowserType = {
  23891. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23892. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23893. };
  23894. module.exports = RTCBrowserType;
  23895. },{}],90:[function(require,module,exports){
  23896. var RTCEvents = {
  23897. LASTN_CHANGED: "rtc.lastn_changed",
  23898. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23899. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23900. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23901. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23902. SIMULCAST_START: "rtc.simlcast_start",
  23903. SIMULCAST_STOP: "rtc.simlcast_stop",
  23904. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  23905. };
  23906. module.exports = RTCEvents;
  23907. },{}],91:[function(require,module,exports){
  23908. var Resolutions = {
  23909. "1080": {
  23910. width: 1920,
  23911. height: 1080,
  23912. order: 7
  23913. },
  23914. "fullhd": {
  23915. width: 1920,
  23916. height: 1080,
  23917. order: 7
  23918. },
  23919. "720": {
  23920. width: 1280,
  23921. height: 720,
  23922. order: 6
  23923. },
  23924. "hd": {
  23925. width: 1280,
  23926. height: 720,
  23927. order: 6
  23928. },
  23929. "960": {
  23930. width: 960,
  23931. height: 720,
  23932. order: 5
  23933. },
  23934. "640": {
  23935. width: 640,
  23936. height: 480,
  23937. order: 4
  23938. },
  23939. "vga": {
  23940. width: 640,
  23941. height: 480,
  23942. order: 4
  23943. },
  23944. "360": {
  23945. width: 640,
  23946. height: 360,
  23947. order: 3
  23948. },
  23949. "320": {
  23950. width: 320,
  23951. height: 240,
  23952. order: 2
  23953. },
  23954. "180": {
  23955. width: 320,
  23956. height: 180,
  23957. order: 1
  23958. }
  23959. };
  23960. module.exports = Resolutions;
  23961. },{}],92:[function(require,module,exports){
  23962. var StreamEventTypes = {
  23963. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23964. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23965. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23966. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23967. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  23968. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  23969. };
  23970. module.exports = StreamEventTypes;
  23971. },{}],93:[function(require,module,exports){
  23972. var UIEvents = {
  23973. NICKNAME_CHANGED: "UI.nickname_changed",
  23974. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23975. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23976. };
  23977. module.exports = UIEvents;
  23978. },{}],94:[function(require,module,exports){
  23979. var AuthenticationEvents = {
  23980. /**
  23981. * Event callback arguments:
  23982. * function(authenticationEnabled, userIdentity)
  23983. * authenticationEnabled - indicates whether authentication has been enabled
  23984. * in this session
  23985. * userIdentity - if user has been logged in then it contains user name. If
  23986. * contains 'null' or 'undefined' then user is not logged in.
  23987. */
  23988. IDENTITY_UPDATED: "authentication.identity_updated"
  23989. };
  23990. module.exports = AuthenticationEvents;
  23991. },{}],95:[function(require,module,exports){
  23992. var CQEvents = {
  23993. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23994. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23995. STOP: "cq.stop"
  23996. };
  23997. module.exports = CQEvents;
  23998. },{}],96:[function(require,module,exports){
  23999. var DesktopSharingEventTypes = {
  24000. INIT: "ds.init",
  24001. SWITCHING_DONE: "ds.switching_done",
  24002. NEW_STREAM_CREATED: "ds.new_stream_created"
  24003. };
  24004. module.exports = DesktopSharingEventTypes;
  24005. },{}],97:[function(require,module,exports){
  24006. module.exports = {
  24007. getLanguages : function () {
  24008. var languages = [];
  24009. for(var lang in this)
  24010. {
  24011. if(typeof this[lang] === "string")
  24012. languages.push(this[lang]);
  24013. }
  24014. return languages;
  24015. },
  24016. EN: "en",
  24017. BG: "bg",
  24018. DE: "de",
  24019. TR: "tr"
  24020. }
  24021. },{}],98:[function(require,module,exports){
  24022. var XMPPEvents = {
  24023. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  24024. CALL_TERMINATED: "xmpp.callterminated.jingle",
  24025. CALL_INCOMING: "xmpp.callincoming.jingle",
  24026. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  24027. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  24028. KICKED: "xmpp.kicked",
  24029. BRIDGE_DOWN: "xmpp.bridge_down",
  24030. USER_ID_CHANGED: "xmpp.user_id_changed",
  24031. CHANGED_STREAMS: "xmpp.changed_streams",
  24032. MUC_JOINED: "xmpp.muc_joined",
  24033. MUC_ENTER: "xmpp.muc_enter",
  24034. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  24035. MUC_LEFT: "xmpp.muc_left",
  24036. MUC_DESTROYED: "xmpp.muc_destroyed",
  24037. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  24038. REMOTE_STATS: "xmpp.remote_stats",
  24039. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  24040. PRESENCE_STATUS: "xmpp.presence_status",
  24041. RESERVATION_ERROR: "xmpp.room_reservation_error",
  24042. SUBJECT_CHANGED: "xmpp.subject_changed",
  24043. MESSAGE_RECEIVED: "xmpp.message_received",
  24044. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  24045. PASSWORD_REQUIRED: "xmpp.password_required",
  24046. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  24047. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  24048. ETHERPAD: "xmpp.etherpad",
  24049. DEVICE_AVAILABLE: "xmpp.device_available"
  24050. };
  24051. module.exports = XMPPEvents;
  24052. },{}]},{},[1])(1)
  24053. });