您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

lib-jitsi-meet.js 754KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $ */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var RTCEvents = require("./service/RTC/RTCEvents");
  9. var EventEmitter = require("events");
  10. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  11. var JitsiParticipant = require("./JitsiParticipant");
  12. var Statistics = require("./modules/statistics/statistics");
  13. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  14. var JitsiTrackEvents = require("./JitsiTrackEvents");
  15. /**
  16. * Creates a JitsiConference object with the given name and properties.
  17. * Note: this constructor is not a part of the public API (objects should be
  18. * created using JitsiConnection.createConference).
  19. * @param options.config properties / settings related to the conference that will be created.
  20. * @param options.name the name of the conference
  21. * @param options.connection the JitsiConnection object for this JitsiConference.
  22. * @constructor
  23. */
  24. function JitsiConference(options) {
  25. if(!options.name || options.name.toLowerCase() !== options.name) {
  26. logger.error("Invalid conference name (no conference name passed or it"
  27. + "contains invalid characters like capital letters)!");
  28. return;
  29. }
  30. this.options = options;
  31. this.connection = this.options.connection;
  32. this.xmpp = this.connection.xmpp;
  33. this.eventEmitter = new EventEmitter();
  34. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  35. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  36. this.rtc = new RTC(this.room, options);
  37. if(!RTC.options.disableAudioLevels)
  38. this.statistics = new Statistics();
  39. setupListeners(this);
  40. this.participants = {};
  41. this.lastActiveSpeaker = null;
  42. this.dtmfManager = null;
  43. this.somebodySupportsDTMF = false;
  44. }
  45. /**
  46. * Joins the conference.
  47. * @param password {string} the password
  48. */
  49. JitsiConference.prototype.join = function (password) {
  50. if(this.room)
  51. this.room.join(password, this.connection.tokenPassword);
  52. };
  53. /**
  54. * Leaves the conference.
  55. */
  56. JitsiConference.prototype.leave = function () {
  57. if(this.xmpp && this.room)
  58. this.xmpp.leaveRoom(this.room.roomjid);
  59. this.room = null;
  60. };
  61. /**
  62. * Returns the local tracks.
  63. */
  64. JitsiConference.prototype.getLocalTracks = function () {
  65. if (this.rtc) {
  66. return this.rtc.localStreams;
  67. } else {
  68. return [];
  69. }
  70. };
  71. /**
  72. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  73. * in JitsiConferenceEvents.
  74. * @param eventId the event ID.
  75. * @param handler handler for the event.
  76. *
  77. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  78. */
  79. JitsiConference.prototype.on = function (eventId, handler) {
  80. if(this.eventEmitter)
  81. this.eventEmitter.on(eventId, handler);
  82. };
  83. /**
  84. * Removes event listener
  85. * @param eventId the event ID.
  86. * @param [handler] optional, the specific handler to unbind
  87. *
  88. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  89. */
  90. JitsiConference.prototype.off = function (eventId, handler) {
  91. if(this.eventEmitter)
  92. this.eventEmitter.removeListener(eventId, handler);
  93. };
  94. // Common aliases for event emitter
  95. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  96. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  97. /**
  98. * Receives notifications from another participants for commands / custom events
  99. * (send by sendPresenceCommand method).
  100. * @param command {String} the name of the command
  101. * @param handler {Function} handler for the command
  102. */
  103. JitsiConference.prototype.addCommandListener = function (command, handler) {
  104. if(this.room)
  105. this.room.addPresenceListener(command, handler);
  106. };
  107. /**
  108. * Removes command listener
  109. * @param command {String} the name of the command
  110. */
  111. JitsiConference.prototype.removeCommandListener = function (command) {
  112. if(this.room)
  113. this.room.removePresenceListener(command);
  114. };
  115. /**
  116. * Sends text message to the other participants in the conference
  117. * @param message the text message.
  118. */
  119. JitsiConference.prototype.sendTextMessage = function (message) {
  120. if(this.room)
  121. this.room.sendMessage(message);
  122. };
  123. /**
  124. * Send presence command.
  125. * @param name the name of the command.
  126. * @param values Object with keys and values that will be send.
  127. **/
  128. JitsiConference.prototype.sendCommand = function (name, values) {
  129. if(this.room) {
  130. this.room.addToPresence(name, values);
  131. this.room.sendPresence();
  132. }
  133. };
  134. /**
  135. * Send presence command one time.
  136. * @param name the name of the command.
  137. * @param values Object with keys and values that will be send.
  138. **/
  139. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  140. this.sendCommand(name, values);
  141. this.removeCommand(name);
  142. };
  143. /**
  144. * Send presence command.
  145. * @param name the name of the command.
  146. * @param values Object with keys and values that will be send.
  147. * @param persistent if false the command will be sent only one time
  148. **/
  149. JitsiConference.prototype.removeCommand = function (name) {
  150. if(this.room)
  151. this.room.removeFromPresence(name);
  152. };
  153. /**
  154. * Sets the display name for this conference.
  155. * @param name the display name to set
  156. */
  157. JitsiConference.prototype.setDisplayName = function(name) {
  158. if(this.room){
  159. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  160. this.room.sendPresence();
  161. }
  162. };
  163. /**
  164. * Adds JitsiLocalTrack object to the conference.
  165. * @param track the JitsiLocalTrack object.
  166. */
  167. JitsiConference.prototype.addTrack = function (track) {
  168. this.room.addStream(track.getOriginalStream(), function () {
  169. this.rtc.addLocalStream(track);
  170. var muteHandler = this._fireMuteChangeEvent.bind(this, track);
  171. var stopHandler = this.removeTrack.bind(this, track);
  172. var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  173. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  174. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  175. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  176. this.addEventListener(JitsiConferenceEvents.TRACK_REMOVED, function (someTrack) {
  177. if (someTrack !== track) {
  178. return;
  179. }
  180. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  181. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  182. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  183. });
  184. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  185. }.bind(this));
  186. };
  187. /**
  188. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  189. * @param audioLevel the audio level
  190. */
  191. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  192. this.eventEmitter.emit(
  193. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  194. this.myUserId(), audioLevel);
  195. };
  196. /**
  197. * Fires TRACK_MUTE_CHANGED change conference event.
  198. * @param track the JitsiTrack object related to the event.
  199. */
  200. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  201. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  202. };
  203. /**
  204. * Removes JitsiLocalTrack object to the conference.
  205. * @param track the JitsiLocalTrack object.
  206. */
  207. JitsiConference.prototype.removeTrack = function (track) {
  208. this.room.removeStream(track.getOriginalStream(), function(){
  209. this.rtc.removeLocalStream(track);
  210. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  211. }.bind(this));
  212. };
  213. /**
  214. * Get role of the local user.
  215. * @returns {string} user role: 'moderator' or 'none'
  216. */
  217. JitsiConference.prototype.getRole = function () {
  218. return this.room.role;
  219. };
  220. /**
  221. * Check if local user is moderator.
  222. * @returns {boolean} true if local user is moderator, false otherwise.
  223. */
  224. JitsiConference.prototype.isModerator = function () {
  225. return this.room.isModerator();
  226. };
  227. /**
  228. * Elects the participant with the given id to be the selected participant or the speaker.
  229. * @param id the identifier of the participant
  230. */
  231. JitsiConference.prototype.selectParticipant = function(participantId) {
  232. if (this.rtc) {
  233. this.rtc.selectedEndpoint(participantId);
  234. }
  235. };
  236. /**
  237. *
  238. * @param id the identifier of the participant
  239. */
  240. JitsiConference.prototype.pinParticipant = function(participantId) {
  241. if (this.rtc) {
  242. this.rtc.pinEndpoint(participantId);
  243. }
  244. };
  245. /**
  246. * Returns the list of participants for this conference.
  247. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  248. */
  249. JitsiConference.prototype.getParticipants = function() {
  250. return Object.keys(this.participants).map(function (key) {
  251. return this.participants[key];
  252. }, this);
  253. };
  254. /**
  255. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  256. * undefined if there isn't one).
  257. * @param id the id of the participant.
  258. */
  259. JitsiConference.prototype.getParticipantById = function(id) {
  260. return this.participants[id];
  261. };
  262. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  263. var id = Strophe.getResourceFromJid(jid);
  264. var participant = new JitsiParticipant(id, this, nick);
  265. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id);
  266. this.participants[id] = participant;
  267. this.connection.xmpp.connection.disco.info(
  268. jid, "node", function(iq) {
  269. participant._supportsDTMF = $(iq).find(
  270. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  271. this.updateDTMFSupport();
  272. }.bind(this)
  273. );
  274. };
  275. JitsiConference.prototype.onMemberLeft = function (jid) {
  276. var id = Strophe.getResourceFromJid(jid);
  277. delete this.participants[id];
  278. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id);
  279. };
  280. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  281. var id = Strophe.getResourceFromJid(jid);
  282. var participant = this.getParticipantById(id);
  283. if (!participant) {
  284. return;
  285. }
  286. participant._role = role;
  287. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  288. };
  289. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  290. var id = Strophe.getResourceFromJid(jid);
  291. var participant = this.getParticipantById(id);
  292. if (!participant) {
  293. return;
  294. }
  295. participant._displayName = displayName;
  296. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  297. };
  298. JitsiConference.prototype.onTrackAdded = function (track) {
  299. var id = track.getParticipantId();
  300. var participant = this.getParticipantById(id);
  301. if (!participant) {
  302. return;
  303. }
  304. // add track to JitsiParticipant
  305. participant._tracks.push(track);
  306. var emitter = this.eventEmitter;
  307. track.addEventListener(
  308. JitsiTrackEvents.TRACK_STOPPED,
  309. function () {
  310. // remove track from JitsiParticipant
  311. var pos = participant._tracks.indexOf(track);
  312. if (pos > -1) {
  313. participant._tracks.splice(pos, 1);
  314. }
  315. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  316. }
  317. );
  318. track.addEventListener(
  319. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  320. function () {
  321. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  322. }
  323. );
  324. track.addEventListener(
  325. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  326. function (audioLevel) {
  327. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  328. }
  329. );
  330. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  331. };
  332. JitsiConference.prototype.updateDTMFSupport = function () {
  333. var somebodySupportsDTMF = false;
  334. var participants = this.getParticipants();
  335. // check if at least 1 participant supports DTMF
  336. for (var i = 0; i < participants.length; i += 1) {
  337. if (participants[i].supportsDTMF()) {
  338. somebodySupportsDTMF = true;
  339. break;
  340. }
  341. }
  342. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  343. this.somebodySupportsDTMF = somebodySupportsDTMF;
  344. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  345. }
  346. };
  347. /**
  348. * Allows to check if there is at least one user in the conference
  349. * that supports DTMF.
  350. * @returns {boolean} true if somebody supports DTMF, false otherwise
  351. */
  352. JitsiConference.prototype.isDTMFSupported = function () {
  353. return this.somebodySupportsDTMF;
  354. };
  355. /**
  356. * Returns the local user's ID
  357. * @return {string} local user's ID
  358. */
  359. JitsiConference.prototype.myUserId = function () {
  360. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  361. };
  362. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  363. if (!this.dtmfManager) {
  364. var connection = this.connection.xmpp.connection.jingle.activecall.peerconnection;
  365. if (!connection) {
  366. logger.warn("cannot sendTones: no conneciton");
  367. return;
  368. }
  369. var tracks = this.getLocalTracks().filter(function (track) {
  370. return track.isAudioTrack();
  371. });
  372. if (!tracks.length) {
  373. logger.warn("cannot sendTones: no local audio stream");
  374. return;
  375. }
  376. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  377. }
  378. this.dtmfManager.sendTones(tones, duration, pause);
  379. };
  380. /**
  381. * Returns true if the recording is supproted and false if not.
  382. */
  383. JitsiConference.prototype.isRecordingSupported = function () {
  384. if(this.room)
  385. return this.room.isRecordingSupported();
  386. return false;
  387. };
  388. /**
  389. * Returns null if the recording is not supported, "on" if the recording started
  390. * and "off" if the recording is not started.
  391. */
  392. JitsiConference.prototype.getRecordingState = function () {
  393. if(this.room)
  394. return this.room.getRecordingState();
  395. return "off";
  396. }
  397. /**
  398. * Returns the url of the recorded video.
  399. */
  400. JitsiConference.prototype.getRecordingURL = function () {
  401. if(this.room)
  402. return this.room.getRecordingURL();
  403. return null;
  404. }
  405. /**
  406. * Starts/stops the recording
  407. * @param token a token for authentication.
  408. */
  409. JitsiConference.prototype.toggleRecording = function (token) {
  410. if(this.room)
  411. return this.room.toggleRecording(token);
  412. return new Promise(function(resolve, reject){
  413. reject(new Error("The conference is not created yet!"))});
  414. }
  415. /**
  416. * Dials a number.
  417. * @param number the number
  418. */
  419. JitsiConference.prototype.dial = function (number) {
  420. if(this.room)
  421. return this.room.dial(number);
  422. return new Promise(function(resolve, reject){
  423. reject(new Error("The conference is not created yet!"))});
  424. }
  425. /**
  426. * Hangup an existing call
  427. */
  428. JitsiConference.prototype.hangup = function () {
  429. if(this.room)
  430. return this.room.hangup();
  431. return new Promise(function(resolve, reject){
  432. reject(new Error("The conference is not created yet!"))});
  433. }
  434. /**
  435. * Returns the phone number for joining the conference.
  436. */
  437. JitsiConference.prototype.getPhoneNumber = function () {
  438. if(this.room)
  439. return this.room.getPhoneNumber();
  440. return null;
  441. }
  442. /**
  443. * Returns the pin for joining the conference with phone.
  444. */
  445. JitsiConference.prototype.getPhonePin = function () {
  446. if(this.room)
  447. return this.room.getPhonePin();
  448. return null;
  449. }
  450. /**
  451. * Setups the listeners needed for the conference.
  452. * @param conference the conference
  453. */
  454. function setupListeners(conference) {
  455. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  456. conference.rtc.onIncommingCall(event);
  457. if(conference.statistics)
  458. conference.statistics.startRemoteStats(event.peerconnection);
  459. });
  460. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  461. function (data, sid, thessrc) {
  462. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  463. if (track) {
  464. conference.onTrackAdded(track);
  465. }
  466. }
  467. );
  468. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  469. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  470. });
  471. // FIXME
  472. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  473. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  474. // });
  475. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  476. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  477. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  478. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  479. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  480. });
  481. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  482. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  483. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  484. });
  485. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  486. function () {
  487. conference.eventEmitter.emit(
  488. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  489. });
  490. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  491. conference.eventEmitter.emit(
  492. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  493. });
  494. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  495. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  496. });
  497. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  498. conference.eventEmitter.emit(JitsiConferenceEvents.SETUP_FAILED);
  499. });
  500. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  501. if(conference.lastActiveSpeaker !== id && conference.room) {
  502. conference.lastActiveSpeaker = id;
  503. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  504. }
  505. });
  506. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  507. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  508. });
  509. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  510. function (lastNEndpoints, endpointsEnteringLastN) {
  511. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  512. lastNEndpoints, endpointsEnteringLastN);
  513. });
  514. if(conference.statistics) {
  515. //FIXME: Maybe remove event should not be associated with the conference.
  516. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  517. var userId = null;
  518. var jid = conference.room.getJidBySSRC(ssrc);
  519. if (!jid)
  520. return;
  521. conference.rtc.setAudioLevel(jid, level);
  522. });
  523. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  524. function () {
  525. conference.statistics.dispose();
  526. });
  527. // FIXME: Maybe we should move this.
  528. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  529. // conference.room.updateDeviceAvailability(devices);
  530. // });
  531. }
  532. }
  533. module.exports = JitsiConference;
  534. }).call(this,"/JitsiConference.js")
  535. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":84,"./service/xmpp/XMPPEvents":91,"events":44,"jitsi-meet-logger":48}],2:[function(require,module,exports){
  536. /**
  537. * Enumeration with the errors for the conference.
  538. * @type {{string: string}}
  539. */
  540. var JitsiConferenceErrors = {
  541. /**
  542. * Indicates that a password is required in order to join the conference.
  543. */
  544. PASSWORD_REQUIRED: "conference.passwordRequired",
  545. /**
  546. * Indicates that a connection error occurred when trying to join a
  547. * conference.
  548. */
  549. CONNECTION_ERROR: "conference.connectionError",
  550. /**
  551. * Indicates that there is no available videobridge.
  552. */
  553. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  554. /**
  555. * Many more errors TBD here.
  556. */
  557. };
  558. module.exports = JitsiConferenceErrors;
  559. },{}],3:[function(require,module,exports){
  560. /**
  561. * Enumeration with the events for the conference.
  562. * @type {{string: string}}
  563. */
  564. var JitsiConferenceEvents = {
  565. /**
  566. * A new media track was added to the conference.
  567. */
  568. TRACK_ADDED: "conference.trackAdded",
  569. /**
  570. * The media track was removed from the conference.
  571. */
  572. TRACK_REMOVED: "conference.trackRemoved",
  573. /**
  574. * The active speaker was changed.
  575. */
  576. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  577. /**
  578. * A new user joinned the conference.
  579. */
  580. USER_JOINED: "conference.userJoined",
  581. /**
  582. * A user has left the conference.
  583. */
  584. USER_LEFT: "conference.userLeft",
  585. /**
  586. * User role changed.
  587. */
  588. USER_ROLE_CHANGED: "conference.roleChanged",
  589. /**
  590. * New text message was received.
  591. */
  592. MESSAGE_RECEIVED: "conference.messageReceived",
  593. /**
  594. * A user has changed it display name
  595. */
  596. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  597. /**
  598. * A participant avatar has changed.
  599. */
  600. AVATAR_CHANGED: "conference.avatarChanged",
  601. /**
  602. * New connection statistics are received.
  603. */
  604. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  605. /**
  606. * The Last N set is changed.
  607. */
  608. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  609. /**
  610. * You are included / excluded in somebody's last N set
  611. */
  612. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  613. /**
  614. * A media track ( attached to the conference) mute status was changed.
  615. */
  616. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  617. /**
  618. * Audio levels of a media track ( attached to the conference) was changed.
  619. */
  620. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  621. /**
  622. * Indicates that the connection to the conference has been interrupted
  623. * for some reason.
  624. */
  625. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  626. /**
  627. * Indicates that the connection to the conference has been restored.
  628. */
  629. CONNECTION_RESTORED: "conference.connectionRestored",
  630. /**
  631. * Indicates that the conference setup failed.
  632. */
  633. SETUP_FAILED: "conference.setup_failed",
  634. /**
  635. * Indicates that conference has been joined.
  636. */
  637. CONFERENCE_JOINED: "conference.joined",
  638. /**
  639. * Indicates that conference has been left.
  640. */
  641. CONFERENCE_LEFT: "conference.left",
  642. /**
  643. * Indicates that DTMF support changed.
  644. */
  645. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  646. /**
  647. * Indicates that recording state changed.
  648. */
  649. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  650. /**
  651. * Indicates that phone number changed.
  652. */
  653. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  654. };
  655. module.exports = JitsiConferenceEvents;
  656. },{}],4:[function(require,module,exports){
  657. var JitsiConference = require("./JitsiConference");
  658. var XMPP = require("./modules/xmpp/xmpp");
  659. var RandomUtil = require("./modules/util/RandomUtil");
  660. /**
  661. * Utility method that generates user name based on random hex values.
  662. * Eg. 12345678-1234-1234-12345678
  663. * @returns {string}
  664. */
  665. function generateUserName() {
  666. return RandomUtil.random8digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" +
  667. RandomUtil.random4digitsHex() + "-" + RandomUtil.random8digitsHex();
  668. }
  669. /**
  670. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  671. * JitsiConference interface.
  672. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  673. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  674. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  675. * The format is:
  676. * passwordToken = token + "_" + roomName + "_" + ts
  677. * See doc/tokens.md for more info on how tokens are generated.
  678. * @param options Object with properties / settings related to connection with the server.
  679. * @constructor
  680. */
  681. function JitsiConnection(appID, tokenPassword, options) {
  682. this.appID = appID;
  683. this.tokenPassword = tokenPassword;
  684. this.options = options;
  685. this.xmpp = new XMPP(options);
  686. this.conferences = {};
  687. }
  688. /**
  689. * Connect the client with the server.
  690. * @param options {object} connecting options (for example authentications parameters).
  691. */
  692. JitsiConnection.prototype.connect = function (options) {
  693. if(!options)
  694. options = {};
  695. // If we have token provided use it as a password and generate random username
  696. if (this.tokenPassword) {
  697. options.password = this.tokenPassword;
  698. if (!options.id) {
  699. options.id = generateUserName() + "@" + this.options.hosts.domain;
  700. }
  701. }
  702. this.xmpp.connect(options.id, options.password);
  703. }
  704. /**
  705. * Disconnect the client from the server.
  706. */
  707. JitsiConnection.prototype.disconnect = function () {
  708. this.xmpp.disconnect();
  709. }
  710. /**
  711. * This method allows renewal of the tokens if they are expiring.
  712. * @param token the new token.
  713. */
  714. JitsiConnection.prototype.setToken = function (token) {
  715. this.token = token;
  716. }
  717. /**
  718. * Creates and joins new conference.
  719. * @param name the name of the conference; if null - a generated name will be provided from the api
  720. * @param options Object with properties / settings related to the conference that will be created.
  721. * @returns {JitsiConference} returns the new conference object.
  722. */
  723. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  724. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  725. return this.conferences[name];
  726. }
  727. /**
  728. * Subscribes the passed listener to the event.
  729. * @param event {JitsiConnectionEvents} the connection event.
  730. * @param listener {Function} the function that will receive the event
  731. */
  732. JitsiConnection.prototype.addEventListener = function (event, listener) {
  733. this.xmpp.addListener(event, listener);
  734. }
  735. /**
  736. * Unsubscribes the passed handler.
  737. * @param event {JitsiConnectionEvents} the connection event.
  738. * @param listener {Function} the function that will receive the event
  739. */
  740. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  741. this.xmpp.removeListener(event, listener);
  742. }
  743. module.exports = JitsiConnection;
  744. },{"./JitsiConference":1,"./modules/util/RandomUtil":25,"./modules/xmpp/xmpp":42}],5:[function(require,module,exports){
  745. /**
  746. * Enumeration with the errors for the connection.
  747. * @type {{string: string}}
  748. */
  749. var JitsiConnectionErrors = {
  750. /**
  751. * Indicates that a password is required in order to join the conference.
  752. */
  753. PASSWORD_REQUIRED: "connection.passwordRequired",
  754. /**
  755. * Indicates that a connection error occurred when trying to join a
  756. * conference.
  757. */
  758. CONNECTION_ERROR: "connection.connectionError",
  759. /**
  760. * Not specified errors.
  761. */
  762. OTHER_ERROR: "connection.otherError"
  763. };
  764. module.exports = JitsiConnectionErrors;
  765. },{}],6:[function(require,module,exports){
  766. /**
  767. * Enumeration with the events for the connection.
  768. * @type {{string: string}}
  769. */
  770. var JitsiConnnectionEvents = {
  771. /**
  772. * Indicates that the connection has been failed for some reason.
  773. */
  774. CONNECTION_FAILED: "connection.connectionFailed",
  775. /**
  776. * Indicates that the connection has been established.
  777. */
  778. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  779. /**
  780. * Indicates that the connection has been disconnected.
  781. */
  782. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  783. /**
  784. * Indicates that the perfomed action cannot be executed because the
  785. * connection is not in the correct state(connected, disconnected, etc.)
  786. */
  787. WRONG_STATE: "connection.wrongState"
  788. };
  789. module.exports = JitsiConnnectionEvents;
  790. },{}],7:[function(require,module,exports){
  791. var JitsiConnection = require("./JitsiConnection");
  792. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  793. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  794. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  795. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  796. var JitsiTrackEvents = require("./JitsiTrackEvents");
  797. var JitsiTrackErrors = require("./JitsiTrackErrors");
  798. var Logger = require("jitsi-meet-logger");
  799. var RTC = require("./modules/RTC/RTC");
  800. var Statistics = require("./modules/statistics/statistics");
  801. /**
  802. * Namespace for the interface of Jitsi Meet Library.
  803. */
  804. var LibJitsiMeet = {
  805. JitsiConnection: JitsiConnection,
  806. events: {
  807. conference: JitsiConferenceEvents,
  808. connection: JitsiConnectionEvents,
  809. track: JitsiTrackEvents
  810. },
  811. errors: {
  812. conference: JitsiConferenceErrors,
  813. connection: JitsiConnectionErrors,
  814. track: JitsiTrackErrors
  815. },
  816. logLevels: Logger.levels,
  817. init: function (options) {
  818. return RTC.init(options || {});
  819. },
  820. setLogLevel: function (level) {
  821. Logger.setLogLevel(level);
  822. },
  823. /**
  824. * Creates the media tracks and returns them trough the callback.
  825. * @param options Object with properties / settings specifying the tracks which should be created.
  826. * should be created or some additional configurations about resolution for example.
  827. * @param {Array} options.devices the devices that will be requested
  828. * @param {string} options.resolution resolution constraints
  829. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  830. * type: "audio" or "video", videoType: "camera" or "desktop"}
  831. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  832. * @param {string} options.cameraDeviceId
  833. * @param {string} options.micDeviceId
  834. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  835. * A promise that returns an array of created JitsiTracks if resolved,
  836. * or a JitsiConferenceError if rejected.
  837. */
  838. createLocalTracks: function (options) {
  839. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  840. function(tracks) {
  841. if(!RTC.options.disableAudioLevels)
  842. for(var i = 0; i < tracks.length; i++) {
  843. var track = tracks[i];
  844. var mStream = track.getOriginalStream();
  845. if(track.getType() === "audio"){
  846. Statistics.startLocalStats(mStream,
  847. track.setAudioLevel.bind(track));
  848. track.addEventListener(
  849. JitsiTrackEvents.TRACK_STOPPED,
  850. function(){
  851. Statistics.stopLocalStats(mStream);
  852. });
  853. }
  854. }
  855. return tracks;
  856. });
  857. },
  858. isDeviceListAvailable: function () {
  859. return RTC.isDeviceListAvailable();
  860. },
  861. enumerateDevices: function (callback) {
  862. RTC.enumerateDevices(callback);
  863. }
  864. };
  865. require("es6-promise").polyfill()
  866. //Setups the promise object.
  867. window.Promise = window.Promise || require("es6-promise").Promise;
  868. module.exports = LibJitsiMeet;
  869. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"es6-promise":46,"jitsi-meet-logger":48}],8:[function(require,module,exports){
  870. /**
  871. * Represents a participant in (a member of) a conference.
  872. */
  873. function JitsiParticipant(id, conference, displayName){
  874. this._id = id;
  875. this._conference = conference;
  876. this._displayName = displayName;
  877. this._supportsDTMF = false;
  878. this._tracks = [];
  879. this._role = 'none';
  880. }
  881. /**
  882. * @returns {JitsiConference} The conference that this participant belongs to.
  883. */
  884. JitsiParticipant.prototype.getConference = function() {
  885. return this._conference;
  886. };
  887. /**
  888. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  889. */
  890. JitsiParticipant.prototype.getTracks = function() {
  891. return this._tracks;
  892. };
  893. /**
  894. * @returns {String} The ID (i.e. JID) of this participant.
  895. */
  896. JitsiParticipant.prototype.getId = function() {
  897. return this._id;
  898. };
  899. /**
  900. * @returns {String} The human-readable display name of this participant.
  901. */
  902. JitsiParticipant.prototype.getDisplayName = function() {
  903. return this._displayName;
  904. };
  905. /**
  906. * @returns {Boolean} Whether this participant is a moderator or not.
  907. */
  908. JitsiParticipant.prototype.isModerator = function() {
  909. return this._role === 'moderator';
  910. };
  911. // Gets a link to an etherpad instance advertised by the participant?
  912. //JitsiParticipant.prototype.getEtherpad = function() {
  913. //
  914. //}
  915. /*
  916. * @returns {Boolean} Whether this participant has muted their audio.
  917. */
  918. JitsiParticipant.prototype.isAudioMuted = function() {
  919. return this.getTracks().reduce(function (track, isAudioMuted) {
  920. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  921. }, true);
  922. };
  923. /*
  924. * @returns {Boolean} Whether this participant has muted their video.
  925. */
  926. JitsiParticipant.prototype.isVideoMuted = function() {
  927. return this.getTracks().reduce(function (track, isVideoMuted) {
  928. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  929. }, true);
  930. };
  931. /*
  932. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  933. * TODO: do we expose this or handle it internally?
  934. */
  935. JitsiParticipant.prototype.getLatestStats = function() {
  936. };
  937. /**
  938. * @returns {String} The role of this participant.
  939. */
  940. JitsiParticipant.prototype.getRole = function() {
  941. return this._role;
  942. };
  943. /*
  944. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  945. */
  946. JitsiParticipant.prototype.isFocus = function() {
  947. };
  948. /*
  949. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  950. */
  951. JitsiParticipant.prototype.isRecorder = function() {
  952. };
  953. /*
  954. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  955. */
  956. JitsiParticipant.prototype.isSipGateway = function() {
  957. };
  958. /**
  959. * @returns {Boolean} Whether this participant is currently sharing their screen.
  960. */
  961. JitsiParticipant.prototype.isScreenSharing = function() {
  962. };
  963. /**
  964. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  965. */
  966. JitsiParticipant.prototype.getUserAgent = function() {
  967. };
  968. /**
  969. * Kicks the participant from the conference (requires certain privileges).
  970. */
  971. JitsiParticipant.prototype.kick = function() {
  972. };
  973. /**
  974. * Asks this participant to mute themselves.
  975. */
  976. JitsiParticipant.prototype.askToMute = function() {
  977. };
  978. JitsiParticipant.prototype.supportsDTMF = function () {
  979. return this._supportsDTMF;
  980. };
  981. module.exports = JitsiParticipant;
  982. },{}],9:[function(require,module,exports){
  983. module.exports = {
  984. /**
  985. * Returns JitsiTrackErrors based on the error object passed by GUM
  986. * @param error the error
  987. * @param {Object} options the options object given to GUM.
  988. */
  989. parseError: function (error, options) {
  990. options = options || {};
  991. if (typeof error == "object" && error.constraintName && error.name
  992. && (error.name == "ConstraintNotSatisfiedError" ||
  993. error.name == "OverconstrainedError") &&
  994. (error.constraintName == "minWidth" ||
  995. error.constraintName == "maxWidth" ||
  996. error.constraintName == "minHeight" ||
  997. error.constraintName == "maxHeight") &&
  998. options.devices.indexOf("video") !== -1) {
  999. return this.UNSUPPORTED_RESOLUTION;
  1000. } else {
  1001. return this.GENERAL;
  1002. }
  1003. },
  1004. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1005. GENERAL: "gum.general"
  1006. };
  1007. },{}],10:[function(require,module,exports){
  1008. var JitsiTrackEvents = {
  1009. /**
  1010. * A media track mute status was changed.
  1011. */
  1012. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1013. /**
  1014. * Audio levels of a this track was changed.
  1015. */
  1016. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1017. /**
  1018. * The media track was removed to the conference.
  1019. */
  1020. TRACK_STOPPED: "track.stopped"
  1021. };
  1022. module.exports = JitsiTrackEvents;
  1023. },{}],11:[function(require,module,exports){
  1024. (function (__filename){
  1025. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1026. function JitsiDTMFManager (localAudio, peerConnection) {
  1027. var tracks = localAudio._getTracks();
  1028. if (!tracks.length) {
  1029. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1030. }
  1031. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1032. logger.debug("Initialized DTMFSender");
  1033. }
  1034. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1035. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1036. };
  1037. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1038. },{"jitsi-meet-logger":48}],12:[function(require,module,exports){
  1039. (function (__filename){
  1040. /* global config, APP, Strophe */
  1041. // cache datachannels to avoid garbage collection
  1042. // https://code.google.com/p/chromium/issues/detail?id=405545
  1043. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1044. var RTCEvents = require("../../service/RTC/RTCEvents");
  1045. /**
  1046. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1047. * @param peerConnection WebRTC peer connection instance.
  1048. */
  1049. function DataChannels(peerConnection, emitter) {
  1050. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1051. this.eventEmitter = emitter;
  1052. this._dataChannels = [];
  1053. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1054. // Although it's not a requirement to open separate channels from both bridge
  1055. // and peer as single channel can be used for sending and receiving data.
  1056. // So either channel opened by the bridge or the one opened here is enough
  1057. // for communication with the bridge.
  1058. /*var dataChannelOptions =
  1059. {
  1060. reliable: true
  1061. };
  1062. var dataChannel
  1063. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1064. // Can be used only when is in open state
  1065. dataChannel.onopen = function ()
  1066. {
  1067. dataChannel.send("My channel !!!");
  1068. };
  1069. dataChannel.onmessage = function (event)
  1070. {
  1071. var msgData = event.data;
  1072. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1073. };*/
  1074. };
  1075. /**
  1076. * Callback triggered by PeerConnection when new data channel is opened
  1077. * on the bridge.
  1078. * @param event the event info object.
  1079. */
  1080. DataChannels.prototype.onDataChannel = function (event) {
  1081. var dataChannel = event.channel;
  1082. var self = this;
  1083. dataChannel.onopen = function () {
  1084. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1085. // Code sample for sending string and/or binary data
  1086. // Sends String message to the bridge
  1087. //dataChannel.send("Hello bridge!");
  1088. // Sends 12 bytes binary message to the bridge
  1089. //dataChannel.send(new ArrayBuffer(12));
  1090. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1091. };
  1092. dataChannel.onerror = function (error) {
  1093. logger.error("Data Channel Error:", error, dataChannel);
  1094. };
  1095. dataChannel.onmessage = function (event) {
  1096. var data = event.data;
  1097. // JSON
  1098. var obj;
  1099. try {
  1100. obj = JSON.parse(data);
  1101. }
  1102. catch (e) {
  1103. logger.error(
  1104. "Failed to parse data channel message as JSON: ",
  1105. data,
  1106. dataChannel);
  1107. }
  1108. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1109. var colibriClass = obj.colibriClass;
  1110. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1111. // Endpoint ID from the Videobridge.
  1112. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1113. logger.info(
  1114. "Data channel new dominant speaker event: ",
  1115. dominantSpeakerEndpoint);
  1116. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1117. }
  1118. else if ("InLastNChangeEvent" === colibriClass) {
  1119. var oldValue = obj.oldValue;
  1120. var newValue = obj.newValue;
  1121. // Make sure that oldValue and newValue are of type boolean.
  1122. var type;
  1123. if ((type = typeof oldValue) !== 'boolean') {
  1124. if (type === 'string') {
  1125. oldValue = (oldValue == "true");
  1126. } else {
  1127. oldValue = new Boolean(oldValue).valueOf();
  1128. }
  1129. }
  1130. if ((type = typeof newValue) !== 'boolean') {
  1131. if (type === 'string') {
  1132. newValue = (newValue == "true");
  1133. } else {
  1134. newValue = new Boolean(newValue).valueOf();
  1135. }
  1136. }
  1137. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1138. }
  1139. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1140. // The new/latest list of last-n endpoint IDs.
  1141. var lastNEndpoints = obj.lastNEndpoints;
  1142. // The list of endpoint IDs which are entering the list of
  1143. // last-n at this time i.e. were not in the old list of last-n
  1144. // endpoint IDs.
  1145. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1146. logger.info(
  1147. "Data channel new last-n event: ",
  1148. lastNEndpoints, endpointsEnteringLastN, obj);
  1149. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1150. lastNEndpoints, endpointsEnteringLastN, obj);
  1151. }
  1152. else {
  1153. logger.debug("Data channel JSON-formatted message: ", obj);
  1154. // The received message appears to be appropriately formatted
  1155. // (i.e. is a JSON object which assigns a value to the mandatory
  1156. // property colibriClass) so don't just swallow it, expose it to
  1157. // public consumption.
  1158. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1159. }
  1160. }
  1161. };
  1162. dataChannel.onclose = function () {
  1163. logger.info("The Data Channel closed", dataChannel);
  1164. var idx = self._dataChannels.indexOf(dataChannel);
  1165. if (idx > -1)
  1166. self._dataChannels = self._dataChannels.splice(idx, 1);
  1167. };
  1168. this._dataChannels.push(dataChannel);
  1169. };
  1170. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1171. this._onXXXEndpointChanged("selected", userResource);
  1172. }
  1173. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1174. this._onXXXEndpointChanged("pinnned", userResource);
  1175. }
  1176. /**
  1177. * Notifies Videobridge about a change in the value of a specific
  1178. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1179. *
  1180. * @param xxx the name of the endpoint-related property whose value changed
  1181. * @param userResource the new value of the endpoint-related property after the
  1182. * change
  1183. */
  1184. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1185. // Derive the correct words from xxx such as selected and Selected, pinned
  1186. // and Pinned.
  1187. var head = xxx.charAt(0);
  1188. var tail = xxx.substring(1);
  1189. var lower = head.toLowerCase() + tail;
  1190. var upper = head.toUpperCase() + tail;
  1191. // Notify Videobridge about the specified endpoint change.
  1192. console.log(lower + ' endpoint changed: ', userResource);
  1193. this._some(function (dataChannel) {
  1194. if (dataChannel.readyState == 'open') {
  1195. console.log(
  1196. 'sending ' + lower
  1197. + ' endpoint changed notification to the bridge: ',
  1198. userResource);
  1199. var jsonObject = {};
  1200. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1201. jsonObject[lower + "Endpoint"]
  1202. = (userResource ? userResource : null);
  1203. dataChannel.send(JSON.stringify(jsonObject));
  1204. return true;
  1205. }
  1206. });
  1207. }
  1208. DataChannels.prototype._some = function (callback, thisArg) {
  1209. var dataChannels = this._dataChannels;
  1210. if (dataChannels && dataChannels.length !== 0) {
  1211. if (thisArg)
  1212. return dataChannels.some(callback, thisArg);
  1213. else
  1214. return dataChannels.some(callback);
  1215. } else {
  1216. return false;
  1217. }
  1218. }
  1219. module.exports = DataChannels;
  1220. }).call(this,"/modules/RTC/DataChannels.js")
  1221. },{"../../service/RTC/RTCEvents":84,"jitsi-meet-logger":48}],13:[function(require,module,exports){
  1222. var JitsiTrack = require("./JitsiTrack");
  1223. var RTCBrowserType = require("./RTCBrowserType");
  1224. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1225. var RTC = require("./RTCUtils");
  1226. /**
  1227. * Represents a single media track (either audio or video).
  1228. * @constructor
  1229. */
  1230. function JitsiLocalTrack(stream, videoType,
  1231. resolution)
  1232. {
  1233. this.videoType = videoType;
  1234. this.dontFireRemoveEvent = false;
  1235. this.resolution = resolution;
  1236. this.startMuted = false;
  1237. var self = this;
  1238. JitsiTrack.call(this, null, stream,
  1239. function () {
  1240. if(!this.dontFireRemoveEvent)
  1241. this.eventEmitter.emit(
  1242. JitsiTrackEvents.TRACK_STOPPED);
  1243. this.dontFireRemoveEvent = false;
  1244. }.bind(this));
  1245. }
  1246. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1247. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1248. /**
  1249. * Mutes / unmutes the track.
  1250. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1251. */
  1252. JitsiLocalTrack.prototype._setMute = function (mute) {
  1253. if(!this.rtc) {
  1254. this.startMuted = mute;
  1255. return;
  1256. }
  1257. var isAudio = this.type === JitsiTrack.AUDIO;
  1258. this.dontFireRemoveEvent = false;
  1259. if ((window.location.protocol != "https:") ||
  1260. (isAudio) || this.videoType === "desktop" ||
  1261. // FIXME FF does not support 'removeStream' method used to mute
  1262. RTCBrowserType.isFirefox()) {
  1263. var tracks = this._getTracks();
  1264. for (var idx = 0; idx < tracks.length; idx++) {
  1265. tracks[idx].enabled = !mute;
  1266. }
  1267. if(isAudio)
  1268. this.rtc.room.setAudioMute(mute);
  1269. else
  1270. this.rtc.room.setVideoMute(mute);
  1271. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1272. } else {
  1273. if (mute) {
  1274. this.dontFireRemoveEvent = true;
  1275. this.rtc.room.removeStream(this.stream, function () {});
  1276. RTC.stopMediaStream(this.stream);
  1277. if(isAudio)
  1278. this.rtc.room.setAudioMute(mute);
  1279. else
  1280. this.rtc.room.setVideoMute(mute);
  1281. this.stream = null;
  1282. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1283. //FIXME: Maybe here we should set the SRC for the containers to something
  1284. } else {
  1285. var self = this;
  1286. RTC.obtainAudioAndVideoPermissions({
  1287. devices: (isAudio ? ["audio"] : ["video"]),
  1288. resolution: self.resolution})
  1289. .then(function (streams) {
  1290. var stream = null;
  1291. for(var i = 0; i < streams.length; i++) {
  1292. stream = streams[i];
  1293. if(stream.type === self.type) {
  1294. self.stream = stream.stream;
  1295. self.videoType = stream.videoType;
  1296. break;
  1297. }
  1298. }
  1299. if(!stream)
  1300. return;
  1301. for(var i = 0; i < self.containers.length; i++)
  1302. {
  1303. RTC.attachMediaStream(self.containers[i], self.stream);
  1304. }
  1305. self.rtc.room.addStream(stream.stream,
  1306. function () {
  1307. if(isAudio)
  1308. self.rtc.room.setAudioMute(mute);
  1309. else
  1310. self.rtc.room.setVideoMute(mute);
  1311. self.eventEmitter.emit(
  1312. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1313. });
  1314. });
  1315. }
  1316. }
  1317. }
  1318. /**
  1319. * Stops sending the media track. And removes it from the HTML.
  1320. * NOTE: Works for local tracks only.
  1321. */
  1322. JitsiLocalTrack.prototype.stop = function () {
  1323. if(!this.stream)
  1324. return;
  1325. if(this.rtc)
  1326. this.rtc.room.removeStream(this.stream, function () {});
  1327. RTC.stopMediaStream(this.stream);
  1328. this.detach();
  1329. }
  1330. /**
  1331. * Returns <tt>true</tt> - if the stream is muted
  1332. * and <tt>false</tt> otherwise.
  1333. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1334. * and <tt>false</tt> otherwise.
  1335. */
  1336. JitsiLocalTrack.prototype.isMuted = function () {
  1337. if (!this.stream)
  1338. return true;
  1339. var tracks = [];
  1340. var isAudio = this.type === JitsiTrack.AUDIO;
  1341. if (isAudio) {
  1342. tracks = this.stream.getAudioTracks();
  1343. } else {
  1344. if (!this.isActive())
  1345. return true;
  1346. tracks = this.stream.getVideoTracks();
  1347. }
  1348. for (var idx = 0; idx < tracks.length; idx++) {
  1349. if(tracks[idx].enabled)
  1350. return false;
  1351. }
  1352. return true;
  1353. };
  1354. /**
  1355. * Private method. Updates rtc property of the track.
  1356. * @param rtc the rtc instance.
  1357. */
  1358. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1359. this.rtc = rtc;
  1360. };
  1361. /**
  1362. * Return true;
  1363. */
  1364. JitsiLocalTrack.prototype.isLocal = function () {
  1365. return true;
  1366. }
  1367. module.exports = JitsiLocalTrack;
  1368. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1369. var JitsiTrack = require("./JitsiTrack");
  1370. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1371. /**
  1372. * Represents a single media track (either audio or video).
  1373. * @param RTC the rtc instance.
  1374. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1375. * @param sid sid for the Media Stream
  1376. * @param ssrc ssrc for the Media Stream
  1377. * @param eventEmitter the event emitter
  1378. * @constructor
  1379. */
  1380. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1381. JitsiTrack.call(this, RTC, data.stream,
  1382. function () {
  1383. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1384. }.bind(this));
  1385. this.rtc = RTC;
  1386. this.sid = sid;
  1387. this.stream = data.stream;
  1388. this.peerjid = data.peerjid;
  1389. this.videoType = data.videoType;
  1390. this.ssrc = ssrc;
  1391. this.muted = false;
  1392. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1393. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1394. this.muted = true;
  1395. }
  1396. }
  1397. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1398. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1399. /**
  1400. * Sets current muted status and fires an events for the change.
  1401. * @param value the muted status.
  1402. */
  1403. JitsiRemoteTrack.prototype.setMute = function (value) {
  1404. this.stream.muted = value;
  1405. this.muted = value;
  1406. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1407. };
  1408. /**
  1409. * Returns the current muted status of the track.
  1410. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1411. */
  1412. JitsiRemoteTrack.prototype.isMuted = function () {
  1413. return this.muted;
  1414. }
  1415. /**
  1416. * Returns the participant id which owns the track.
  1417. * @returns {string} the id of the participants.
  1418. */
  1419. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1420. return Strophe.getResourceFromJid(this.peerjid);
  1421. };
  1422. /**
  1423. * Return false;
  1424. */
  1425. JitsiRemoteTrack.prototype.isLocal = function () {
  1426. return false;
  1427. }
  1428. delete JitsiRemoteTrack.prototype.stop;
  1429. delete JitsiRemoteTrack.prototype.start;
  1430. module.exports = JitsiRemoteTrack;
  1431. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1432. var RTCBrowserType = require("./RTCBrowserType");
  1433. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1434. var EventEmitter = require("events");
  1435. /**
  1436. * This implements 'onended' callback normally fired by WebRTC after the stream
  1437. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1438. * @param jitsiTrack our track object holding the original WebRTC stream object
  1439. * to which 'onended' handling will be added.
  1440. */
  1441. function implementOnEndedHandling(jitsiTrack) {
  1442. var stream = jitsiTrack.getOriginalStream();
  1443. var originalStop = stream.stop;
  1444. stream.stop = function () {
  1445. originalStop.apply(stream);
  1446. if (jitsiTrack.isActive()) {
  1447. stream.onended();
  1448. }
  1449. };
  1450. }
  1451. /**
  1452. * Adds onended/oninactive handler to a MediaStream.
  1453. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1454. * @param handler the handler
  1455. */
  1456. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1457. if(RTCBrowserType.isTemasysPluginUsed()) {
  1458. // themasys
  1459. //FIXME: Seems that not working properly.
  1460. if(mediaStream.onended) {
  1461. mediaStream.onended = handler;
  1462. } else if(mediaStream.addEventListener) {
  1463. mediaStream.addEventListener('ended', function () {
  1464. handler(mediaStream);
  1465. });
  1466. } else if(mediaStream.attachEvent) {
  1467. mediaStream.attachEvent('ended', function () {
  1468. handler(mediaStream);
  1469. });
  1470. }
  1471. }
  1472. else {
  1473. if(typeof mediaStream.active !== "undefined")
  1474. mediaStream.oninactive = handler;
  1475. else
  1476. mediaStream.onended = handler;
  1477. }
  1478. }
  1479. /**
  1480. * Represents a single media track (either audio or video).
  1481. * @constructor
  1482. * @param rtc the rtc instance
  1483. * @param stream the stream
  1484. * @param streamInactiveHandler the function that will handle
  1485. * onended/oninactive events of the stream.
  1486. */
  1487. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1488. {
  1489. /**
  1490. * Array with the HTML elements that are displaying the streams.
  1491. * @type {Array}
  1492. */
  1493. this.containers = [];
  1494. this.rtc = rtc;
  1495. this.stream = stream;
  1496. this.eventEmitter = new EventEmitter();
  1497. this.audioLevel = -1;
  1498. this.type = (this.stream.getVideoTracks().length > 0)?
  1499. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1500. if(this.type == "audio") {
  1501. this._getTracks = function () {
  1502. return this.stream.getAudioTracks();
  1503. }.bind(this);
  1504. } else {
  1505. this._getTracks = function () {
  1506. return this.stream.getVideoTracks();
  1507. }.bind(this);
  1508. }
  1509. if (RTCBrowserType.isFirefox() && this.stream) {
  1510. implementOnEndedHandling(this);
  1511. }
  1512. if(stream)
  1513. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1514. }
  1515. /**
  1516. * JitsiTrack video type.
  1517. * @type {string}
  1518. */
  1519. JitsiTrack.VIDEO = "video";
  1520. /**
  1521. * JitsiTrack audio type.
  1522. * @type {string}
  1523. */
  1524. JitsiTrack.AUDIO = "audio";
  1525. /**
  1526. * Returns the type (audio or video) of this track.
  1527. */
  1528. JitsiTrack.prototype.getType = function() {
  1529. return this.type;
  1530. };
  1531. /**
  1532. * Check if this is audiotrack.
  1533. */
  1534. JitsiTrack.prototype.isAudioTrack = function () {
  1535. return this.getType() === JitsiTrack.AUDIO;
  1536. };
  1537. /**
  1538. * Check if this is videotrack.
  1539. */
  1540. JitsiTrack.prototype.isVideoTrack = function () {
  1541. return this.getType() === JitsiTrack.VIDEO;
  1542. };
  1543. /**
  1544. * Returns the RTCMediaStream from the browser (?).
  1545. */
  1546. JitsiTrack.prototype.getOriginalStream = function() {
  1547. return this.stream;
  1548. }
  1549. /**
  1550. * Mutes the track.
  1551. */
  1552. JitsiTrack.prototype.mute = function () {
  1553. this._setMute(true);
  1554. }
  1555. /**
  1556. * Unmutes the stream.
  1557. */
  1558. JitsiTrack.prototype.unmute = function () {
  1559. this._setMute(false);
  1560. }
  1561. /**
  1562. * Attaches the MediaStream of this track to an HTML container (?).
  1563. * Adds the container to the list of containers that are displaying the track.
  1564. * @param container the HTML container
  1565. */
  1566. JitsiTrack.prototype.attach = function (container) {
  1567. if(this.stream)
  1568. require("./RTCUtils").attachMediaStream(container, this.stream);
  1569. this.containers.push(container);
  1570. }
  1571. /**
  1572. * Removes the track from the passed HTML container.
  1573. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1574. */
  1575. JitsiTrack.prototype.detach = function (container) {
  1576. for(var i = 0; i < this.containers.length; i++)
  1577. {
  1578. if(this.containers[i].is(container))
  1579. {
  1580. this.containers.splice(i,1);
  1581. }
  1582. if(!container)
  1583. {
  1584. this.containers[i].find(">video").remove();
  1585. }
  1586. }
  1587. if(container)
  1588. $(container).find(">video").remove();
  1589. }
  1590. /**
  1591. * Stops sending the media track. And removes it from the HTML.
  1592. * NOTE: Works for local tracks only.
  1593. */
  1594. JitsiTrack.prototype.stop = function () {
  1595. }
  1596. /**
  1597. * Returns true if this is a video track and the source of the video is a
  1598. * screen capture as opposed to a camera.
  1599. */
  1600. JitsiTrack.prototype.isScreenSharing = function(){
  1601. }
  1602. /**
  1603. * Returns id of the track.
  1604. * @returns {string} id of the track or null if this is fake track.
  1605. */
  1606. JitsiTrack.prototype.getId = function () {
  1607. var tracks = this.stream.getTracks();
  1608. if(!tracks || tracks.length === 0)
  1609. return null;
  1610. return tracks[0].id;
  1611. };
  1612. /**
  1613. * Checks whether the MediaStream is avtive/not ended.
  1614. * When there is no check for active we don't have information and so
  1615. * will return that stream is active (in case of FF).
  1616. * @returns {boolean} whether MediaStream is active.
  1617. */
  1618. JitsiTrack.prototype.isActive = function () {
  1619. if((typeof this.stream.active !== "undefined"))
  1620. return this.stream.active;
  1621. else
  1622. return true;
  1623. };
  1624. /**
  1625. * Attaches a handler for events(For example - "audio level changed".).
  1626. * All possible event are defined in JitsiTrackEvents.
  1627. * @param eventId the event ID.
  1628. * @param handler handler for the event.
  1629. */
  1630. JitsiTrack.prototype.on = function (eventId, handler) {
  1631. if(this.eventEmitter)
  1632. this.eventEmitter.on(eventId, handler);
  1633. }
  1634. /**
  1635. * Removes event listener
  1636. * @param eventId the event ID.
  1637. * @param [handler] optional, the specific handler to unbind
  1638. */
  1639. JitsiTrack.prototype.off = function (eventId, handler) {
  1640. if(this.eventEmitter)
  1641. this.eventEmitter.removeListener(eventId, handler);
  1642. }
  1643. // Common aliases for event emitter
  1644. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1645. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1646. /**
  1647. * Sets the audio level for the stream
  1648. * @param audioLevel the new audio level
  1649. */
  1650. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  1651. if(this.audioLevel !== audioLevel) {
  1652. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1653. audioLevel);
  1654. this.audioLevel = audioLevel;
  1655. }
  1656. }
  1657. module.exports = JitsiTrack;
  1658. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":44}],16:[function(require,module,exports){
  1659. /* global APP */
  1660. var EventEmitter = require("events");
  1661. var RTCBrowserType = require("./RTCBrowserType");
  1662. var RTCUtils = require("./RTCUtils.js");
  1663. var JitsiTrack = require("./JitsiTrack");
  1664. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1665. var DataChannels = require("./DataChannels");
  1666. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1667. var DesktopSharingEventTypes
  1668. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1669. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1670. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1671. function createLocalTracks(streams) {
  1672. var newStreams = []
  1673. for (var i = 0; i < streams.length; i++) {
  1674. var localStream = new JitsiLocalTrack(streams[i].stream,
  1675. streams[i].videoType, streams[i].resolution);
  1676. newStreams.push(localStream);
  1677. if (streams[i].isMuted === true)
  1678. localStream.setMute(true);
  1679. }
  1680. return newStreams;
  1681. }
  1682. function RTC(room, options) {
  1683. this.room = room;
  1684. this.localStreams = [];
  1685. //FIXME: we should start removing those streams.
  1686. //FIXME: We should support multiple streams per jid.
  1687. this.remoteStreams = {};
  1688. this.localAudio = null;
  1689. this.localVideo = null;
  1690. this.eventEmitter = new EventEmitter();
  1691. var self = this;
  1692. this.options = options || {};
  1693. room.addPresenceListener("videomuted", function (values, from) {
  1694. if(self.remoteStreams[from]) {
  1695. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1696. }
  1697. });
  1698. room.addPresenceListener("audiomuted", function (values, from) {
  1699. if(self.remoteStreams[from]) {
  1700. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1701. }
  1702. });
  1703. }
  1704. /**
  1705. * Creates the local MediaStreams.
  1706. * @param {Object} [options] optional parameters
  1707. * @param {Array} options.devices the devices that will be requested
  1708. * @param {string} options.resolution resolution constraints
  1709. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1710. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1711. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1712. * @param {string} options.cameraDeviceId
  1713. * @param {string} options.micDeviceId
  1714. * @returns {*} Promise object that will receive the new JitsiTracks
  1715. */
  1716. RTC.obtainAudioAndVideoPermissions = function (options) {
  1717. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1718. }
  1719. RTC.prototype.onIncommingCall = function(event) {
  1720. if(this.options.config.openSctp)
  1721. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1722. for(var i = 0; i < this.localStreams.length; i++)
  1723. if(this.localStreams[i])
  1724. {
  1725. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1726. }
  1727. }
  1728. RTC.prototype.selectedEndpoint = function (id) {
  1729. if(this.dataChannels)
  1730. this.dataChannels.handleSelectedEndpointEvent(id);
  1731. }
  1732. RTC.prototype.pinEndpoint = function (id) {
  1733. if(this.dataChannels)
  1734. this.dataChannels.handlePinnedEndpointEvent(id);
  1735. }
  1736. RTC.prototype.addListener = function (type, listener) {
  1737. this.eventEmitter.on(type, listener);
  1738. };
  1739. RTC.prototype.removeListener = function (eventType, listener) {
  1740. this.eventEmitter.removeListener(eventType, listener);
  1741. };
  1742. RTC.addListener = function (eventType, listener) {
  1743. RTCUtils.addListener(eventType, listener);
  1744. }
  1745. RTC.removeListener = function (eventType, listener) {
  1746. RTCUtils.removeListener(eventType, listener)
  1747. }
  1748. RTC.isRTCReady = function () {
  1749. return RTCUtils.isRTCReady();
  1750. }
  1751. RTC.init = function (options) {
  1752. this.options = options || {};
  1753. return RTCUtils.init(this.options);
  1754. }
  1755. RTC.getDeviceAvailability = function () {
  1756. return RTCUtils.getDeviceAvailability();
  1757. }
  1758. RTC.prototype.addLocalStream = function (stream) {
  1759. this.localStreams.push(stream);
  1760. stream._setRTC(this);
  1761. if (stream.type == "audio") {
  1762. this.localAudio = stream;
  1763. } else {
  1764. this.localVideo = stream;
  1765. }
  1766. };
  1767. RTC.prototype.removeLocalStream = function (stream) {
  1768. for(var i = 0; i < this.localStreams.length; i++) {
  1769. if(this.localStreams[i].getOriginalStream() === stream) {
  1770. delete this.localStreams[i];
  1771. return;
  1772. }
  1773. }
  1774. };
  1775. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1776. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  1777. if(!data.peerjid)
  1778. return;
  1779. var jid = data.peerjid;
  1780. if(!this.remoteStreams[jid]) {
  1781. this.remoteStreams[jid] = {};
  1782. }
  1783. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1784. return remoteStream;
  1785. };
  1786. RTC.getPCConstraints = function () {
  1787. return RTCUtils.pc_constraints;
  1788. };
  1789. RTC.attachMediaStream = function (elSelector, stream) {
  1790. RTCUtils.attachMediaStream(elSelector, stream);
  1791. };
  1792. RTC.getStreamID = function (stream) {
  1793. return RTCUtils.getStreamID(stream);
  1794. };
  1795. RTC.getVideoSrc = function (element) {
  1796. return RTCUtils.getVideoSrc(element);
  1797. };
  1798. RTC.isDeviceListAvailable = function () {
  1799. return RTCUtils.isDeviceListAvailable();
  1800. };
  1801. /**
  1802. * Allows to receive list of available cameras/microphones.
  1803. * @param {function} callback would receive array of devices as an argument
  1804. */
  1805. RTC.enumerateDevices = function (callback) {
  1806. RTCUtils.enumerateDevices(callback);
  1807. };
  1808. RTC.setVideoSrc = function (element, src) {
  1809. RTCUtils.setVideoSrc(element, src);
  1810. };
  1811. /**
  1812. * A method to handle stopping of the stream.
  1813. * One point to handle the differences in various implementations.
  1814. * @param mediaStream MediaStream object to stop.
  1815. */
  1816. RTC.stopMediaStream = function (mediaStream) {
  1817. RTCUtils.stopMediaStream(mediaStream);
  1818. };
  1819. RTC.prototype.getVideoElementName = function () {
  1820. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1821. };
  1822. RTC.prototype.dispose = function() {
  1823. };
  1824. RTC.prototype.switchVideoStreams = function (newStream) {
  1825. this.localVideo.stream = newStream;
  1826. this.localStreams = [];
  1827. //in firefox we have only one stream object
  1828. if (this.localAudio.getOriginalStream() != newStream)
  1829. this.localStreams.push(this.localAudio);
  1830. this.localStreams.push(this.localVideo);
  1831. };
  1832. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  1833. if(this.remoteStreams[jid] && this.remoteStreams[jid][JitsiTrack.AUDIO])
  1834. this.remoteStreams[jid][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  1835. }
  1836. module.exports = RTC;
  1837. },{"../../service/RTC/MediaStreamTypes":83,"../../service/RTC/RTCEvents.js":84,"../../service/desktopsharing/DesktopSharingEventTypes":88,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":44}],17:[function(require,module,exports){
  1838. var currentBrowser;
  1839. var browserVersion;
  1840. var isAndroid;
  1841. var RTCBrowserType = {
  1842. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1843. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1844. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1845. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1846. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1847. getBrowserType: function () {
  1848. return currentBrowser;
  1849. },
  1850. isChrome: function () {
  1851. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1852. },
  1853. isOpera: function () {
  1854. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1855. },
  1856. isFirefox: function () {
  1857. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1858. },
  1859. isIExplorer: function () {
  1860. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1861. },
  1862. isSafari: function () {
  1863. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1864. },
  1865. isTemasysPluginUsed: function () {
  1866. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1867. },
  1868. getFirefoxVersion: function () {
  1869. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1870. },
  1871. getChromeVersion: function () {
  1872. return RTCBrowserType.isChrome() ? browserVersion : null;
  1873. },
  1874. usesPlanB: function() {
  1875. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1876. RTCBrowserType.isTemasysPluginUsed();
  1877. },
  1878. usesUnifiedPlan: function() {
  1879. return RTCBrowserType.isFirefox();
  1880. },
  1881. /**
  1882. * Whether the browser is running on an android device.
  1883. */
  1884. isAndroid: function() {
  1885. return isAndroid;
  1886. }
  1887. // Add version getters for other browsers when needed
  1888. };
  1889. // detectOpera() must be called before detectChrome() !!!
  1890. // otherwise Opera wil be detected as Chrome
  1891. function detectChrome() {
  1892. if (navigator.webkitGetUserMedia) {
  1893. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1894. var userAgent = navigator.userAgent.toLowerCase();
  1895. // We can assume that user agent is chrome, because it's
  1896. // enforced when 'ext' streaming method is set
  1897. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1898. console.log("This appears to be Chrome, ver: " + ver);
  1899. return ver;
  1900. }
  1901. return null;
  1902. }
  1903. function detectOpera() {
  1904. var userAgent = navigator.userAgent;
  1905. if (userAgent.match(/Opera|OPR/)) {
  1906. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1907. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1908. console.info("This appears to be Opera, ver: " + version);
  1909. return version;
  1910. }
  1911. return null;
  1912. }
  1913. function detectFirefox() {
  1914. if (navigator.mozGetUserMedia) {
  1915. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1916. var version = parseInt(
  1917. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1918. console.log('This appears to be Firefox, ver: ' + version);
  1919. return version;
  1920. }
  1921. return null;
  1922. }
  1923. function detectSafari() {
  1924. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1925. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1926. console.info("This appears to be Safari");
  1927. // FIXME detect Safari version when needed
  1928. return 1;
  1929. }
  1930. return null;
  1931. }
  1932. function detectIE() {
  1933. var version;
  1934. var ua = window.navigator.userAgent;
  1935. var msie = ua.indexOf('MSIE ');
  1936. if (msie > 0) {
  1937. // IE 10 or older => return version number
  1938. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1939. }
  1940. var trident = ua.indexOf('Trident/');
  1941. if (!version && trident > 0) {
  1942. // IE 11 => return version number
  1943. var rv = ua.indexOf('rv:');
  1944. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1945. }
  1946. var edge = ua.indexOf('Edge/');
  1947. if (!version && edge > 0) {
  1948. // IE 12 => return version number
  1949. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1950. }
  1951. if (version) {
  1952. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1953. console.info("This appears to be IExplorer, ver: " + version);
  1954. }
  1955. return version;
  1956. }
  1957. function detectBrowser() {
  1958. var version;
  1959. var detectors = [
  1960. detectOpera,
  1961. detectChrome,
  1962. detectFirefox,
  1963. detectIE,
  1964. detectSafari
  1965. ];
  1966. // Try all browser detectors
  1967. for (var i = 0; i < detectors.length; i++) {
  1968. version = detectors[i]();
  1969. if (version)
  1970. return version;
  1971. }
  1972. console.error("Failed to detect browser type");
  1973. return undefined;
  1974. }
  1975. browserVersion = detectBrowser();
  1976. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1977. module.exports = RTCBrowserType;
  1978. },{}],18:[function(require,module,exports){
  1979. (function (__filename){
  1980. /* global config, require, attachMediaStream, getUserMedia,
  1981. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  1982. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  1983. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  1984. */
  1985. /* jshint -W101 */
  1986. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1987. var RTCBrowserType = require("./RTCBrowserType");
  1988. var Resolutions = require("../../service/RTC/Resolutions");
  1989. var RTCEvents = require("../../service/RTC/RTCEvents");
  1990. var AdapterJS = require("./adapter.screenshare");
  1991. var SDPUtil = require("../xmpp/SDPUtil");
  1992. var EventEmitter = require("events");
  1993. var screenObtainer = require("./ScreenObtainer");
  1994. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  1995. var eventEmitter = new EventEmitter();
  1996. var devices = {
  1997. audio: true,
  1998. video: true
  1999. };
  2000. var rtcReady = false;
  2001. function setResolutionConstraints(constraints, resolution) {
  2002. var isAndroid = RTCBrowserType.isAndroid();
  2003. if (Resolutions[resolution]) {
  2004. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2005. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2006. }
  2007. else if (isAndroid) {
  2008. // FIXME can't remember if the purpose of this was to always request
  2009. // low resolution on Android ? if yes it should be moved up front
  2010. constraints.video.mandatory.minWidth = 320;
  2011. constraints.video.mandatory.minHeight = 240;
  2012. constraints.video.mandatory.maxFrameRate = 15;
  2013. }
  2014. if (constraints.video.mandatory.minWidth)
  2015. constraints.video.mandatory.maxWidth =
  2016. constraints.video.mandatory.minWidth;
  2017. if (constraints.video.mandatory.minHeight)
  2018. constraints.video.mandatory.maxHeight =
  2019. constraints.video.mandatory.minHeight;
  2020. }
  2021. /**
  2022. * @param {string[]} um required user media types
  2023. *
  2024. * @param {Object} [options={}] optional parameters
  2025. * @param {string} options.resolution
  2026. * @param {number} options.bandwidth
  2027. * @param {number} options.fps
  2028. * @param {string} options.desktopStream
  2029. * @param {string} options.cameraDeviceId
  2030. * @param {string} options.micDeviceId
  2031. * @param {bool} firefox_fake_device
  2032. */
  2033. function getConstraints(um, options) {
  2034. var constraints = {audio: false, video: false};
  2035. if (um.indexOf('video') >= 0) {
  2036. // same behaviour as true
  2037. constraints.video = { mandatory: {}, optional: [] };
  2038. if (options.cameraDeviceId) {
  2039. constraints.video.optional.push({
  2040. sourceId: options.cameraDeviceId
  2041. });
  2042. }
  2043. constraints.video.optional.push({ googLeakyBucket: true });
  2044. setResolutionConstraints(constraints, options.resolution);
  2045. }
  2046. if (um.indexOf('audio') >= 0) {
  2047. if (!RTCBrowserType.isFirefox()) {
  2048. // same behaviour as true
  2049. constraints.audio = { mandatory: {}, optional: []};
  2050. if (options.micDeviceId) {
  2051. constraints.audio.optional.push({
  2052. sourceId: options.micDeviceId
  2053. });
  2054. }
  2055. // if it is good enough for hangouts...
  2056. constraints.audio.optional.push(
  2057. {googEchoCancellation: true},
  2058. {googAutoGainControl: true},
  2059. {googNoiseSupression: true},
  2060. {googHighpassFilter: true},
  2061. {googNoisesuppression2: true},
  2062. {googEchoCancellation2: true},
  2063. {googAutoGainControl2: true}
  2064. );
  2065. } else {
  2066. if (options.micDeviceId) {
  2067. constraints.audio = {
  2068. mandatory: {},
  2069. optional: [{
  2070. sourceId: options.micDeviceId
  2071. }]};
  2072. } else {
  2073. constraints.audio = true;
  2074. }
  2075. }
  2076. }
  2077. if (um.indexOf('screen') >= 0) {
  2078. if (RTCBrowserType.isChrome()) {
  2079. constraints.video = {
  2080. mandatory: {
  2081. chromeMediaSource: "screen",
  2082. googLeakyBucket: true,
  2083. maxWidth: window.screen.width,
  2084. maxHeight: window.screen.height,
  2085. maxFrameRate: 3
  2086. },
  2087. optional: []
  2088. };
  2089. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2090. constraints.video = {
  2091. optional: [
  2092. {
  2093. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2094. }
  2095. ]
  2096. };
  2097. } else if (RTCBrowserType.isFirefox()) {
  2098. constraints.video = {
  2099. mozMediaSource: "window",
  2100. mediaSource: "window"
  2101. };
  2102. } else {
  2103. logger.error(
  2104. "'screen' WebRTC media source is supported only in Chrome" +
  2105. " and with Temasys plugin");
  2106. }
  2107. }
  2108. if (um.indexOf('desktop') >= 0) {
  2109. constraints.video = {
  2110. mandatory: {
  2111. chromeMediaSource: "desktop",
  2112. chromeMediaSourceId: options.desktopStream,
  2113. googLeakyBucket: true,
  2114. maxWidth: window.screen.width,
  2115. maxHeight: window.screen.height,
  2116. maxFrameRate: 3
  2117. },
  2118. optional: []
  2119. };
  2120. }
  2121. if (options.bandwidth) {
  2122. if (!constraints.video) {
  2123. //same behaviour as true
  2124. constraints.video = {mandatory: {}, optional: []};
  2125. }
  2126. constraints.video.optional.push({bandwidth: options.bandwidth});
  2127. }
  2128. if (options.fps) {
  2129. // for some cameras it might be necessary to request 30fps
  2130. // so they choose 30fps mjpg over 10fps yuy2
  2131. if (!constraints.video) {
  2132. // same behaviour as true;
  2133. constraints.video = {mandatory: {}, optional: []};
  2134. }
  2135. constraints.video.mandatory.minFrameRate = options.fps;
  2136. }
  2137. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2138. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2139. // this later can be a problem with some of the tests
  2140. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2141. {
  2142. // seems to be fixed now, removing this experimental fix, as having
  2143. // multiple audio tracks brake the tests
  2144. //constraints.audio = true;
  2145. constraints.fake = true;
  2146. }
  2147. return constraints;
  2148. }
  2149. function setAvailableDevices(um, available) {
  2150. if (um.indexOf("video") != -1) {
  2151. devices.video = available;
  2152. }
  2153. if (um.indexOf("audio") != -1) {
  2154. devices.audio = available;
  2155. }
  2156. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2157. }
  2158. // In case of IE we continue from 'onReady' callback
  2159. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2160. // once it is initialized.
  2161. function onReady (options, GUM) {
  2162. rtcReady = true;
  2163. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2164. screenObtainer.init(eventEmitter, options, GUM);
  2165. }
  2166. /**
  2167. * Apply function with arguments if function exists.
  2168. * Do nothing if function not provided.
  2169. * @param {function} [fn] function to apply
  2170. * @param {Array} [args=[]] arguments for function
  2171. */
  2172. function maybeApply(fn, args) {
  2173. if (fn) {
  2174. fn.apply(null, args || []);
  2175. }
  2176. }
  2177. var getUserMediaStatus = {
  2178. initialized: false,
  2179. callbacks: []
  2180. };
  2181. /**
  2182. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2183. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2184. * @param {Function} getUserMedia native function
  2185. * @returns {Function} wrapped function
  2186. */
  2187. function wrapGetUserMedia(getUserMedia) {
  2188. return function (constraints, successCallback, errorCallback) {
  2189. getUserMedia(constraints, function (stream) {
  2190. maybeApply(successCallback, [stream]);
  2191. if (!getUserMediaStatus.initialized) {
  2192. getUserMediaStatus.initialized = true;
  2193. getUserMediaStatus.callbacks.forEach(function (callback) {
  2194. callback();
  2195. });
  2196. getUserMediaStatus.callbacks.length = 0;
  2197. }
  2198. }, function (error) {
  2199. maybeApply(errorCallback, [error]);
  2200. });
  2201. };
  2202. }
  2203. /**
  2204. * Create stub device which equals to auto selected device.
  2205. * @param {string} kind if that should be `audio` or `video` device
  2206. * @returns {Object} stub device description in `enumerateDevices` format
  2207. */
  2208. function createAutoDeviceInfo(kind) {
  2209. return {
  2210. facing: null,
  2211. label: 'Auto',
  2212. kind: kind,
  2213. deviceId: '',
  2214. groupId: null
  2215. };
  2216. }
  2217. /**
  2218. * Execute function after getUserMedia was executed at least once.
  2219. * @param {Function} callback function to execute after getUserMedia
  2220. */
  2221. function afterUserMediaInitialized(callback) {
  2222. if (getUserMediaStatus.initialized) {
  2223. callback();
  2224. } else {
  2225. getUserMediaStatus.callbacks.push(callback);
  2226. }
  2227. }
  2228. /**
  2229. * Wrapper function which makes enumerateDevices to wait
  2230. * until someone executes getUserMedia first time.
  2231. * @param {Function} enumerateDevices native function
  2232. * @returns {Funtion} wrapped function
  2233. */
  2234. function wrapEnumerateDevices(enumerateDevices) {
  2235. return function (callback) {
  2236. // enumerate devices only after initial getUserMedia
  2237. afterUserMediaInitialized(function () {
  2238. enumerateDevices().then(function (devices) {
  2239. //add auto devices
  2240. devices.unshift(
  2241. createAutoDeviceInfo('audioinput'),
  2242. createAutoDeviceInfo('videoinput')
  2243. );
  2244. callback(devices);
  2245. }, function (err) {
  2246. console.error('cannot enumerate devices: ', err);
  2247. // return only auto devices
  2248. callback([createAutoDeviceInfo('audioInput'),
  2249. createAutoDeviceInfo('videoinput')]);
  2250. });
  2251. });
  2252. };
  2253. }
  2254. /**
  2255. * Use old MediaStreamTrack to get devices list and
  2256. * convert it to enumerateDevices format.
  2257. * @param {Function} callback function to call when received devices list.
  2258. */
  2259. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2260. MediaStreamTrack.getSources(function (sources) {
  2261. var devices = sources.map(function (source) {
  2262. var kind = (source.kind || '').toLowerCase();
  2263. return {
  2264. facing: source.facing || null,
  2265. label: source.label,
  2266. kind: kind ? kind + 'input': null,
  2267. deviceId: source.id,
  2268. groupId: source.groupId || null
  2269. };
  2270. });
  2271. //add auto devices
  2272. devices.unshift(
  2273. createAutoDeviceInfo('audioinput'),
  2274. createAutoDeviceInfo('videoinput')
  2275. );
  2276. callback(devices);
  2277. });
  2278. }
  2279. function obtainDevices(options) {
  2280. if(!options.devices || options.devices.length === 0) {
  2281. return options.successCallback(options.streams || {});
  2282. }
  2283. var device = options.devices.splice(0, 1);
  2284. options.deviceGUM[device](function (stream) {
  2285. options.streams = options.streams || {};
  2286. options.streams[device] = stream;
  2287. obtainDevices(options);
  2288. },
  2289. function (error) {
  2290. logger.error(
  2291. "failed to obtain " + device + " stream - stop", error);
  2292. options.errorCallback(JitsiTrackErrors.parseError(error));
  2293. });
  2294. }
  2295. /**
  2296. * Handles the newly created Media Streams.
  2297. * @param streams the new Media Streams
  2298. * @param resolution the resolution of the video streams
  2299. * @returns {*[]} object that describes the new streams
  2300. */
  2301. function handleLocalStream(streams, resolution) {
  2302. var audioStream, videoStream, desktopStream, res = [];
  2303. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2304. // an object with two properties: audioStream, videoStream.
  2305. if (window.webkitMediaStream) {
  2306. var audioVideo = streams.audioVideo;
  2307. if (audioVideo) {
  2308. var audioTracks = audioVideo.getAudioTracks();
  2309. if(audioTracks.length) {
  2310. audioStream = new webkitMediaStream();
  2311. for (var i = 0; i < audioTracks.length; i++) {
  2312. audioStream.addTrack(audioTracks[i]);
  2313. }
  2314. }
  2315. var videoTracks = audioVideo.getVideoTracks();
  2316. if(videoTracks.length) {
  2317. videoStream = new webkitMediaStream();
  2318. for (var j = 0; j < videoTracks.length; j++) {
  2319. videoStream.addTrack(videoTracks[j]);
  2320. }
  2321. }
  2322. }
  2323. if (streams && streams.desktopStream)
  2324. desktopStream = streams.desktopStream;
  2325. }
  2326. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2327. if (streams && streams.audio)
  2328. audioStream = streams.audio;
  2329. if (streams && streams.video)
  2330. videoStream = streams.video;
  2331. if(streams && streams.desktop)
  2332. desktopStream = streams.desktop;
  2333. }
  2334. if (desktopStream)
  2335. res.push({stream: desktopStream,
  2336. type: "video", videoType: "desktop"});
  2337. if(audioStream)
  2338. res.push({stream: audioStream, type: "audio", videoType: null});
  2339. if(videoStream)
  2340. res.push({stream: videoStream, type: "video", videoType: "camera",
  2341. resolution: resolution});
  2342. return res;
  2343. }
  2344. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2345. var RTCUtils = {
  2346. init: function (options) {
  2347. return new Promise(function(resolve, reject) {
  2348. if (RTCBrowserType.isFirefox()) {
  2349. var FFversion = RTCBrowserType.getFirefoxVersion();
  2350. if (FFversion < 40) {
  2351. logger.error(
  2352. "Firefox version too old: " + FFversion +
  2353. ". Required >= 40.");
  2354. reject(new Error("Firefox version too old: " + FFversion +
  2355. ". Required >= 40."));
  2356. return;
  2357. }
  2358. this.peerconnection = mozRTCPeerConnection;
  2359. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2360. this.enumerateDevices = wrapEnumerateDevices(
  2361. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2362. );
  2363. this.pc_constraints = {};
  2364. this.attachMediaStream = function (element, stream) {
  2365. // srcObject is being standardized and FF will eventually
  2366. // support that unprefixed. FF also supports the
  2367. // "element.src = URL.createObjectURL(...)" combo, but that
  2368. // will be deprecated in favour of srcObject.
  2369. //
  2370. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2371. // https://github.com/webrtc/samples/issues/302
  2372. if (!element[0])
  2373. return;
  2374. element[0].mozSrcObject = stream;
  2375. element[0].play();
  2376. };
  2377. this.getStreamID = function (stream) {
  2378. var id = stream.id;
  2379. if (!id) {
  2380. var tracks = stream.getVideoTracks();
  2381. if (!tracks || tracks.length === 0) {
  2382. tracks = stream.getAudioTracks();
  2383. }
  2384. id = tracks[0].id;
  2385. }
  2386. return SDPUtil.filter_special_chars(id);
  2387. };
  2388. this.getVideoSrc = function (element) {
  2389. if (!element)
  2390. return null;
  2391. return element.mozSrcObject;
  2392. };
  2393. this.setVideoSrc = function (element, src) {
  2394. if (element)
  2395. element.mozSrcObject = src;
  2396. };
  2397. RTCSessionDescription = mozRTCSessionDescription;
  2398. RTCIceCandidate = mozRTCIceCandidate;
  2399. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2400. this.peerconnection = webkitRTCPeerConnection;
  2401. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2402. if (navigator.mediaDevices) {
  2403. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2404. this.enumerateDevices = wrapEnumerateDevices(
  2405. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2406. );
  2407. } else {
  2408. this.getUserMedia = getUserMedia;
  2409. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2410. }
  2411. this.attachMediaStream = function (element, stream) {
  2412. element.attr('src', webkitURL.createObjectURL(stream));
  2413. };
  2414. this.getStreamID = function (stream) {
  2415. // streams from FF endpoints have the characters '{' and '}'
  2416. // that make jQuery choke.
  2417. return SDPUtil.filter_special_chars(stream.id);
  2418. };
  2419. this.getVideoSrc = function (element) {
  2420. if (!element)
  2421. return null;
  2422. return element.getAttribute("src");
  2423. };
  2424. this.setVideoSrc = function (element, src) {
  2425. if (element)
  2426. element.setAttribute("src", src);
  2427. };
  2428. // DTLS should now be enabled by default but..
  2429. this.pc_constraints = {'optional': [
  2430. {'DtlsSrtpKeyAgreement': 'true'}
  2431. ]};
  2432. if (options.useIPv6) {
  2433. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2434. this.pc_constraints.optional.push({googIPv6: true});
  2435. }
  2436. if (RTCBrowserType.isAndroid()) {
  2437. this.pc_constraints = {}; // disable DTLS on Android
  2438. }
  2439. if (!webkitMediaStream.prototype.getVideoTracks) {
  2440. webkitMediaStream.prototype.getVideoTracks = function () {
  2441. return this.videoTracks;
  2442. };
  2443. }
  2444. if (!webkitMediaStream.prototype.getAudioTracks) {
  2445. webkitMediaStream.prototype.getAudioTracks = function () {
  2446. return this.audioTracks;
  2447. };
  2448. }
  2449. }
  2450. // Detect IE/Safari
  2451. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2452. //AdapterJS.WebRTCPlugin.setLogLevel(
  2453. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2454. var self = this;
  2455. AdapterJS.webRTCReady(function (isPlugin) {
  2456. self.peerconnection = RTCPeerConnection;
  2457. self.getUserMedia = window.getUserMedia;
  2458. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2459. self.attachMediaStream = function (elSel, stream) {
  2460. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2461. return;
  2462. }
  2463. attachMediaStream(elSel[0], stream);
  2464. };
  2465. self.getStreamID = function (stream) {
  2466. var id = SDPUtil.filter_special_chars(stream.label);
  2467. return id;
  2468. };
  2469. self.getVideoSrc = function (element) {
  2470. if (!element) {
  2471. logger.warn("Attempt to get video SRC of null element");
  2472. return null;
  2473. }
  2474. var children = element.children;
  2475. for (var i = 0; i !== children.length; ++i) {
  2476. if (children[i].name === 'streamId') {
  2477. return children[i].value;
  2478. }
  2479. }
  2480. //logger.info(element.id + " SRC: " + src);
  2481. return null;
  2482. };
  2483. self.setVideoSrc = function (element, src) {
  2484. //logger.info("Set video src: ", element, src);
  2485. if (!src) {
  2486. logger.warn("Not attaching video stream, 'src' is null");
  2487. return;
  2488. }
  2489. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2490. var stream = AdapterJS.WebRTCPlugin.plugin
  2491. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2492. attachMediaStream(element, stream);
  2493. };
  2494. onReady(options, self.getUserMediaWithConstraints);
  2495. resolve();
  2496. });
  2497. } else {
  2498. try {
  2499. logger.error('Browser does not appear to be WebRTC-capable');
  2500. } catch (e) {
  2501. }
  2502. reject('Browser does not appear to be WebRTC-capable');
  2503. return;
  2504. }
  2505. // Call onReady() if Temasys plugin is not used
  2506. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2507. onReady(options, this.getUserMediaWithConstraints);
  2508. resolve();
  2509. }
  2510. }.bind(this));
  2511. },
  2512. /**
  2513. * @param {string[]} um required user media types
  2514. * @param {function} success_callback
  2515. * @param {Function} failure_callback
  2516. * @param {Object} [options] optional parameters
  2517. * @param {string} options.resolution
  2518. * @param {number} options.bandwidth
  2519. * @param {number} options.fps
  2520. * @param {string} options.desktopStream
  2521. * @param {string} options.cameraDeviceId
  2522. * @param {string} options.micDeviceId
  2523. **/
  2524. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2525. options = options || {};
  2526. var resolution = options.resolution;
  2527. var constraints = getConstraints(um, options);
  2528. logger.info("Get media constraints", constraints);
  2529. try {
  2530. this.getUserMedia(constraints,
  2531. function (stream) {
  2532. logger.log('onUserMediaSuccess');
  2533. setAvailableDevices(um, true);
  2534. success_callback(stream);
  2535. },
  2536. function (error) {
  2537. setAvailableDevices(um, false);
  2538. logger.warn('Failed to get access to local media. Error ',
  2539. error, constraints);
  2540. if (failure_callback) {
  2541. failure_callback(error, resolution);
  2542. }
  2543. });
  2544. } catch (e) {
  2545. logger.error('GUM failed: ', e);
  2546. if (failure_callback) {
  2547. failure_callback(e);
  2548. }
  2549. }
  2550. },
  2551. /**
  2552. * Creates the local MediaStreams.
  2553. * @param {Object} [options] optional parameters
  2554. * @param {Array} options.devices the devices that will be requested
  2555. * @param {string} options.resolution resolution constraints
  2556. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2557. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2558. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2559. * @param {string} options.cameraDeviceId
  2560. * @param {string} options.micDeviceId
  2561. * @returns {*} Promise object that will receive the new JitsiTracks
  2562. */
  2563. obtainAudioAndVideoPermissions: function (options) {
  2564. var self = this;
  2565. options = options || {};
  2566. return new Promise(function (resolve, reject) {
  2567. var successCallback = function (stream) {
  2568. resolve(handleLocalStream(stream, options.resolution));
  2569. };
  2570. options.devices = options.devices || ['audio', 'video'];
  2571. if(!screenObtainer.isSupported()
  2572. && options.devices.indexOf("desktop") !== -1){
  2573. reject(new Error("Desktop sharing is not supported!"));
  2574. }
  2575. if (RTCBrowserType.isFirefox() ||
  2576. RTCBrowserType.isTemasysPluginUsed()) {
  2577. var GUM = function (device, s, e) {
  2578. this.getUserMediaWithConstraints(device, s, e, options);
  2579. };
  2580. var deviceGUM = {
  2581. "audio": GUM.bind(self, ["audio"]),
  2582. "video": GUM.bind(self, ["video"]),
  2583. "desktop": screenObtainer.obtainStream
  2584. };
  2585. // With FF/IE we can't split the stream into audio and video because FF
  2586. // doesn't support media stream constructors. So, we need to get the
  2587. // audio stream separately from the video stream using two distinct GUM
  2588. // calls. Not very user friendly :-( but we don't have many other
  2589. // options neither.
  2590. //
  2591. // Note that we pack those 2 streams in a single object and pass it to
  2592. // the successCallback method.
  2593. obtainDevices({
  2594. devices: options.devices,
  2595. streams: [],
  2596. successCallback: successCallback,
  2597. errorCallback: reject,
  2598. deviceGUM: deviceGUM
  2599. });
  2600. } else {
  2601. var hasDesktop = options.devices.indexOf('desktop') > -1;
  2602. if (hasDesktop) {
  2603. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2604. }
  2605. options.resolution = options.resolution || '360';
  2606. if(options.devices.length) {
  2607. this.getUserMediaWithConstraints(
  2608. options.devices,
  2609. function (stream) {
  2610. if(hasDesktop) {
  2611. screenObtainer.obtainStream(
  2612. function (desktopStream) {
  2613. successCallback({audioVideo: stream,
  2614. desktopStream: desktopStream});
  2615. }, function (error) {
  2616. reject(
  2617. JitsiTrackErrors.parseError(error));
  2618. });
  2619. } else {
  2620. successCallback({audioVideo: stream});
  2621. }
  2622. },
  2623. function (error) {
  2624. reject(JitsiTrackErrors.parseError(error));
  2625. },
  2626. options);
  2627. } else if (hasDesktop) {
  2628. screenObtainer.obtainStream(
  2629. function (stream) {
  2630. successCallback({desktopStream: stream});
  2631. }, function (error) {
  2632. reject(
  2633. JitsiTrackErrors.parseError(error));
  2634. });
  2635. }
  2636. }
  2637. }.bind(this));
  2638. },
  2639. addListener: function (eventType, listener) {
  2640. eventEmitter.on(eventType, listener);
  2641. },
  2642. removeListener: function (eventType, listener) {
  2643. eventEmitter.removeListener(eventType, listener);
  2644. },
  2645. getDeviceAvailability: function () {
  2646. return devices;
  2647. },
  2648. isRTCReady: function () {
  2649. return rtcReady;
  2650. },
  2651. /**
  2652. * Checks if its possible to enumerate available cameras/micropones.
  2653. * @returns {boolean} true if available, false otherwise.
  2654. */
  2655. isDeviceListAvailable: function () {
  2656. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2657. if (isEnumerateDevicesAvailable) {
  2658. return true;
  2659. }
  2660. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2661. },
  2662. /**
  2663. * A method to handle stopping of the stream.
  2664. * One point to handle the differences in various implementations.
  2665. * @param mediaStream MediaStream object to stop.
  2666. */
  2667. stopMediaStream: function (mediaStream) {
  2668. mediaStream.getTracks().forEach(function (track) {
  2669. // stop() not supported with IE
  2670. if (track.stop) {
  2671. track.stop();
  2672. }
  2673. });
  2674. // leave stop for implementation still using it
  2675. if (mediaStream.stop) {
  2676. mediaStream.stop();
  2677. }
  2678. }
  2679. };
  2680. module.exports = RTCUtils;
  2681. }).call(this,"/modules/RTC/RTCUtils.js")
  2682. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":84,"../../service/RTC/Resolutions":85,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":44,"jitsi-meet-logger":48}],19:[function(require,module,exports){
  2683. (function (__filename){
  2684. /* global chrome, $, alert */
  2685. /* jshint -W003 */
  2686. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2687. var RTCBrowserType = require("./RTCBrowserType");
  2688. var AdapterJS = require("./adapter.screenshare");
  2689. var DesktopSharingEventTypes
  2690. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2691. /**
  2692. * Indicates whether the Chrome desktop sharing extension is installed.
  2693. * @type {boolean}
  2694. */
  2695. var chromeExtInstalled = false;
  2696. /**
  2697. * Indicates whether an update of the Chrome desktop sharing extension is
  2698. * required.
  2699. * @type {boolean}
  2700. */
  2701. var chromeExtUpdateRequired = false;
  2702. /**
  2703. * Whether the jidesha extension for firefox is installed for the domain on
  2704. * which we are running. Null designates an unknown value.
  2705. * @type {null}
  2706. */
  2707. var firefoxExtInstalled = null;
  2708. /**
  2709. * If set to true, detection of an installed firefox extension will be started
  2710. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2711. * user tries to enable screen sharing).
  2712. */
  2713. var reDetectFirefoxExtension = false;
  2714. var GUM = null;
  2715. /**
  2716. * Handles obtaining a stream from a screen capture on different browsers.
  2717. */
  2718. var ScreenObtainer = {
  2719. /**
  2720. * The EventEmitter to use to emit events.
  2721. * @type {null}
  2722. */
  2723. eventEmitter: null,
  2724. obtainStream: null,
  2725. /**
  2726. * Initializes the function used to obtain a screen capture
  2727. * (this.obtainStream).
  2728. *
  2729. * If the browser is Chrome, it uses the value of
  2730. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2731. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2732. * use the "screen" media source (if the value is 'webrtc'),
  2733. * or disable screen capture (if the value is other).
  2734. * Note that for the "screen" media source to work the
  2735. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2736. */
  2737. init: function(eventEmitter, options, gum) {
  2738. this.eventEmitter = eventEmitter;
  2739. var obtainDesktopStream = null;
  2740. this.options = options = options || {};
  2741. GUM = gum;
  2742. if (RTCBrowserType.isFirefox())
  2743. initFirefoxExtensionDetection(options);
  2744. // TODO remove this, options.desktopSharing is deprecated.
  2745. var chromeMethod =
  2746. (options.desktopSharingChromeMethod || options.desktopSharing);
  2747. if (RTCBrowserType.isTemasysPluginUsed()) {
  2748. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  2749. logger.info("Screensharing not supported by this plugin " +
  2750. "version");
  2751. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2752. logger.info(
  2753. "Screensharing not available with Temasys plugin on" +
  2754. " this site");
  2755. } else {
  2756. obtainDesktopStream = obtainWebRTCScreen;
  2757. logger.info("Using Temasys plugin for desktop sharing");
  2758. }
  2759. } else if (RTCBrowserType.isChrome()) {
  2760. if (chromeMethod == "ext") {
  2761. if (RTCBrowserType.getChromeVersion() >= 34) {
  2762. obtainDesktopStream =
  2763. this.obtainScreenFromExtension;
  2764. logger.info("Using Chrome extension for desktop sharing");
  2765. initChromeExtension(options);
  2766. } else {
  2767. logger.info("Chrome extension not supported until ver 34");
  2768. }
  2769. } else if (chromeMethod == "webrtc") {
  2770. obtainDesktopStream = obtainWebRTCScreen;
  2771. logger.info("Using Chrome WebRTC for desktop sharing");
  2772. }
  2773. } else if (RTCBrowserType.isFirefox()) {
  2774. if (options.desktopSharingFirefoxDisabled) {
  2775. obtainDesktopStream = null;
  2776. } else if (window.location.protocol === "http:"){
  2777. logger.log("Screen sharing is not supported over HTTP. " +
  2778. "Use of HTTPS is required.");
  2779. obtainDesktopStream = null;
  2780. } else {
  2781. obtainDesktopStream = this.obtainScreenOnFirefox;
  2782. }
  2783. }
  2784. if (!obtainDesktopStream) {
  2785. logger.info("Desktop sharing disabled");
  2786. }
  2787. this.obtainStream = obtainDesktopStream;
  2788. },
  2789. /**
  2790. * Checks whether obtaining a screen capture is supported in the current
  2791. * environment.
  2792. * @returns {boolean}
  2793. */
  2794. isSupported: function() {
  2795. return !!this.obtainStream;
  2796. },
  2797. /**
  2798. * Obtains a screen capture stream on Firefox.
  2799. * @param callback
  2800. * @param errorCallback
  2801. */
  2802. obtainScreenOnFirefox:
  2803. function (callback, errorCallback) {
  2804. var self = this;
  2805. var extensionRequired = false;
  2806. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  2807. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  2808. RTCBrowserType.getFirefoxVersion() <=
  2809. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  2810. extensionRequired = true;
  2811. logger.log("Jidesha extension required on firefox version " +
  2812. RTCBrowserType.getFirefoxVersion());
  2813. }
  2814. if (!extensionRequired || firefoxExtInstalled === true) {
  2815. obtainWebRTCScreen(callback, errorCallback);
  2816. return;
  2817. }
  2818. if (reDetectFirefoxExtension) {
  2819. reDetectFirefoxExtension = false;
  2820. initFirefoxExtensionDetection(this.options);
  2821. }
  2822. // Give it some (more) time to initialize, and assume lack of
  2823. // extension if it hasn't.
  2824. if (firefoxExtInstalled === null) {
  2825. window.setTimeout(
  2826. function() {
  2827. if (firefoxExtInstalled === null)
  2828. firefoxExtInstalled = false;
  2829. self.obtainScreenOnFirefox(callback, errorCallback);
  2830. },
  2831. 300
  2832. );
  2833. logger.log("Waiting for detection of jidesha on firefox to " +
  2834. "finish.");
  2835. return;
  2836. }
  2837. // We need an extension and it isn't installed.
  2838. // Make sure we check for the extension when the user clicks again.
  2839. firefoxExtInstalled = null;
  2840. reDetectFirefoxExtension = true;
  2841. // Prompt the user to install the extension
  2842. this.eventEmitter.emit(
  2843. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  2844. this.options.desktopSharingFirefoxExtensionURL);
  2845. // Make sure desktopsharing knows that we failed, so that it doesn't get
  2846. // stuck in 'switching' mode.
  2847. errorCallback('Firefox extension required.');
  2848. },
  2849. /**
  2850. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  2851. * 'desktop' stream for returned stream token.
  2852. */
  2853. obtainScreenFromExtension: function (streamCallback, failCallback) {
  2854. if (chromeExtInstalled) {
  2855. doGetStreamFromExtension(this.options, streamCallback,
  2856. failCallback);
  2857. } else {
  2858. if (chromeExtUpdateRequired) {
  2859. alert(
  2860. 'Jitsi Desktop Streamer requires update. ' +
  2861. 'Changes will take effect after next Chrome restart.');
  2862. }
  2863. chrome.webstore.install(
  2864. getWebStoreInstallUrl(this.options),
  2865. function (arg) {
  2866. logger.log("Extension installed successfully", arg);
  2867. chromeExtInstalled = true;
  2868. // We need to give a moment for the endpoint to become
  2869. // available
  2870. window.setTimeout(function () {
  2871. doGetStreamFromExtension(this.options, streamCallback,
  2872. failCallback);
  2873. }, 500);
  2874. },
  2875. function (arg) {
  2876. logger.log("Failed to install the extension", arg);
  2877. failCallback(arg);
  2878. }
  2879. );
  2880. }
  2881. }
  2882. };
  2883. /**
  2884. * Obtains a desktop stream using getUserMedia.
  2885. * For this to work on Chrome, the
  2886. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  2887. *
  2888. * On firefox, the document's domain must be white-listed in the
  2889. * 'media.getusermedia.screensharing.allowed_domains' preference in
  2890. * 'about:config'.
  2891. */
  2892. function obtainWebRTCScreen(streamCallback, failCallback) {
  2893. GUM(
  2894. ['screen'],
  2895. streamCallback,
  2896. failCallback
  2897. );
  2898. }
  2899. /**
  2900. * Constructs inline install URL for Chrome desktop streaming extension.
  2901. * The 'chromeExtensionId' must be defined in options parameter.
  2902. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2903. * @returns {string}
  2904. */
  2905. function getWebStoreInstallUrl(options)
  2906. {
  2907. //TODO remove chromeExtensionId (deprecated)
  2908. return "https://chrome.google.com/webstore/detail/" +
  2909. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  2910. }
  2911. /**
  2912. * Checks whether an update of the Chrome extension is required.
  2913. * @param minVersion minimal required version
  2914. * @param extVersion current extension version
  2915. * @returns {boolean}
  2916. */
  2917. function isUpdateRequired(minVersion, extVersion) {
  2918. try {
  2919. var s1 = minVersion.split('.');
  2920. var s2 = extVersion.split('.');
  2921. var len = Math.max(s1.length, s2.length);
  2922. for (var i = 0; i < len; i++) {
  2923. var n1 = 0,
  2924. n2 = 0;
  2925. if (i < s1.length)
  2926. n1 = parseInt(s1[i]);
  2927. if (i < s2.length)
  2928. n2 = parseInt(s2[i]);
  2929. if (isNaN(n1) || isNaN(n2)) {
  2930. return true;
  2931. } else if (n1 !== n2) {
  2932. return n1 > n2;
  2933. }
  2934. }
  2935. // will happen if both versions have identical numbers in
  2936. // their components (even if one of them is longer, has more components)
  2937. return false;
  2938. }
  2939. catch (e) {
  2940. logger.error("Failed to parse extension version", e);
  2941. return true;
  2942. }
  2943. }
  2944. function checkChromeExtInstalled(callback, options) {
  2945. if (!chrome || !chrome.runtime) {
  2946. // No API, so no extension for sure
  2947. callback(false, false);
  2948. return;
  2949. }
  2950. chrome.runtime.sendMessage(
  2951. //TODO: remove chromeExtensionId (deprecated)
  2952. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2953. { getVersion: true },
  2954. function (response) {
  2955. if (!response || !response.version) {
  2956. // Communication failure - assume that no endpoint exists
  2957. logger.warn(
  2958. "Extension not installed?: ", chrome.runtime.lastError);
  2959. callback(false, false);
  2960. return;
  2961. }
  2962. // Check installed extension version
  2963. var extVersion = response.version;
  2964. logger.log('Extension version is: ' + extVersion);
  2965. //TODO: remove minChromeExtVersion (deprecated)
  2966. var updateRequired
  2967. = isUpdateRequired(
  2968. (options.desktopSharingChromeMinExtVersion ||
  2969. options.minChromeExtVersion),
  2970. extVersion);
  2971. callback(!updateRequired, updateRequired);
  2972. }
  2973. );
  2974. }
  2975. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  2976. // Sends 'getStream' msg to the extension.
  2977. // Extension id must be defined in the config.
  2978. chrome.runtime.sendMessage(
  2979. //TODO: remove chromeExtensionId (deprecated)
  2980. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2981. {
  2982. getStream: true,
  2983. //TODO: remove desktopSharingSources (deprecated).
  2984. sources: (options.desktopSharingChromeSources ||
  2985. options.desktopSharingSources)
  2986. },
  2987. function (response) {
  2988. if (!response) {
  2989. failCallback(chrome.runtime.lastError);
  2990. return;
  2991. }
  2992. logger.log("Response from extension: " + response);
  2993. if (response.streamId) {
  2994. GUM(
  2995. ['desktop'],
  2996. function (stream) {
  2997. streamCallback(stream);
  2998. },
  2999. failCallback,
  3000. {desktopStream: response.streamId});
  3001. } else {
  3002. failCallback("Extension failed to get the stream");
  3003. }
  3004. }
  3005. );
  3006. }
  3007. /**
  3008. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3009. * config.js to support inline installs. Host site must be selected as main
  3010. * website of published extension.
  3011. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3012. */
  3013. function initInlineInstalls(options)
  3014. {
  3015. $("link[rel=chrome-webstore-item]").attr("href",
  3016. getWebStoreInstallUrl(options));
  3017. }
  3018. function initChromeExtension(options) {
  3019. // Initialize Chrome extension inline installs
  3020. initInlineInstalls(options);
  3021. // Check if extension is installed
  3022. checkChromeExtInstalled(function (installed, updateRequired) {
  3023. chromeExtInstalled = installed;
  3024. chromeExtUpdateRequired = updateRequired;
  3025. logger.info(
  3026. "Chrome extension installed: " + chromeExtInstalled +
  3027. " updateRequired: " + chromeExtUpdateRequired);
  3028. }, options);
  3029. }
  3030. /**
  3031. * Starts the detection of an installed jidesha extension for firefox.
  3032. * @param options supports "desktopSharingFirefoxDisabled",
  3033. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3034. */
  3035. function initFirefoxExtensionDetection(options) {
  3036. if (options.desktopSharingFirefoxDisabled) {
  3037. return;
  3038. }
  3039. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3040. return;
  3041. if (!options.desktopSharingFirefoxExtId) {
  3042. firefoxExtInstalled = false;
  3043. return;
  3044. }
  3045. var img = document.createElement('img');
  3046. img.onload = function(){
  3047. logger.log("Detected firefox screen sharing extension.");
  3048. firefoxExtInstalled = true;
  3049. };
  3050. img.onerror = function(){
  3051. logger.log("Detected lack of firefox screen sharing extension.");
  3052. firefoxExtInstalled = false;
  3053. };
  3054. // The jidesha extension exposes an empty image file under the url:
  3055. // "chrome://EXT_ID/content/DOMAIN.png"
  3056. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3057. // DOMAIN is a domain whitelisted by the extension.
  3058. var src = "chrome://" +
  3059. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3060. "/content/" + document.location.hostname + ".png";
  3061. img.setAttribute('src', src);
  3062. }
  3063. module.exports = ScreenObtainer;
  3064. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3065. },{"../../service/desktopsharing/DesktopSharingEventTypes":88,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":48}],20:[function(require,module,exports){
  3066. (function (__filename){
  3067. /*! adapterjs - v0.12.0 - 2015-09-04 */
  3068. var console = require("jitsi-meet-logger").getLogger(__filename);
  3069. // Adapter's interface.
  3070. var AdapterJS = AdapterJS || {};
  3071. // Browserify compatibility
  3072. if(typeof exports !== 'undefined') {
  3073. module.exports = AdapterJS;
  3074. }
  3075. AdapterJS.options = AdapterJS.options || {};
  3076. // uncomment to get virtual webcams
  3077. // AdapterJS.options.getAllCams = true;
  3078. // uncomment to prevent the install prompt when the plugin in not yet installed
  3079. // AdapterJS.options.hidePluginInstallPrompt = true;
  3080. // AdapterJS version
  3081. AdapterJS.VERSION = '0.12.0';
  3082. // This function will be called when the WebRTC API is ready to be used
  3083. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3084. // the plugin
  3085. // You may Override this function to synchronise the start of your application
  3086. // with the WebRTC API being ready.
  3087. // If you decide not to override use this synchronisation, it may result in
  3088. // an extensive CPU usage on the plugin start (once per tab loaded)
  3089. // Params:
  3090. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3091. //
  3092. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3093. // The WebRTC API is ready.
  3094. // Override me and do whatever you want here
  3095. };
  3096. // Sets a callback function to be called when the WebRTC interface is ready.
  3097. // The first argument is the function to callback.\
  3098. // Throws an error if the first argument is not a function
  3099. AdapterJS.webRTCReady = function (callback) {
  3100. if (typeof callback !== 'function') {
  3101. throw new Error('Callback provided is not a function');
  3102. }
  3103. if (true === AdapterJS.onwebrtcreadyDone) {
  3104. // All WebRTC interfaces are ready, just call the callback
  3105. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3106. } else {
  3107. // will be triggered automatically when your browser/plugin is ready.
  3108. AdapterJS.onwebrtcready = callback;
  3109. }
  3110. };
  3111. // Plugin namespace
  3112. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3113. // The object to store plugin information
  3114. AdapterJS.WebRTCPlugin.pluginInfo = {
  3115. prefix : 'Tem',
  3116. plugName : 'TemWebRTCPlugin',
  3117. pluginId : 'plugin0',
  3118. type : 'application/x-temwebrtcplugin',
  3119. onload : '__TemWebRTCReady0',
  3120. portalLink : 'http://skylink.io/plugin/',
  3121. downloadLink : null, //set below
  3122. companyName: 'Temasys'
  3123. };
  3124. if(!!navigator.platform.match(/^Mac/i)) {
  3125. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3126. }
  3127. else if(!!navigator.platform.match(/^Win/i)) {
  3128. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3129. }
  3130. AdapterJS.WebRTCPlugin.TAGS = {
  3131. NONE : 'none',
  3132. AUDIO : 'audio',
  3133. VIDEO : 'video'
  3134. };
  3135. // Unique identifier of each opened page
  3136. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3137. // Use this whenever you want to call the plugin.
  3138. AdapterJS.WebRTCPlugin.plugin = null;
  3139. // Set log level for the plugin once it is ready.
  3140. // The different values are
  3141. // This is an asynchronous function that will run when the plugin is ready
  3142. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3143. // Defines webrtc's JS interface according to the plugin's implementation.
  3144. // Define plugin Browsers as WebRTC Interface.
  3145. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3146. // This function detects whether or not a plugin is installed.
  3147. // Checks if Not IE (firefox, for example), else if it's IE,
  3148. // we're running IE and do something. If not it is not supported.
  3149. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3150. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3151. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3152. // Inject the HTML DOM object element into the page.
  3153. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3154. // States of readiness that the plugin goes through when
  3155. // being injected and stated
  3156. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3157. NONE : 0, // no plugin use
  3158. INITIALIZING : 1, // Detected need for plugin
  3159. INJECTING : 2, // Injecting plugin
  3160. INJECTED: 3, // Plugin element injected but not usable yet
  3161. READY: 4 // Plugin ready to be used
  3162. };
  3163. // Current state of the plugin. You cannot use the plugin before this is
  3164. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3165. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3166. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3167. // Used to make sure AdapterJS.onwebrtcready is only called once
  3168. AdapterJS.onwebrtcreadyDone = false;
  3169. // Log levels for the plugin.
  3170. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3171. /*
  3172. Log outputs are prefixed in some cases.
  3173. INFO: Information reported by the plugin.
  3174. ERROR: Errors originating from within the plugin.
  3175. WEBRTC: Error originating from within the libWebRTC library
  3176. */
  3177. // From the least verbose to the most verbose
  3178. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3179. NONE : 'NONE',
  3180. ERROR : 'ERROR',
  3181. WARNING : 'WARNING',
  3182. INFO: 'INFO',
  3183. VERBOSE: 'VERBOSE',
  3184. SENSITIVE: 'SENSITIVE'
  3185. };
  3186. // Does a waiting check before proceeding to load the plugin.
  3187. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3188. // This methid will use an interval to wait for the plugin to be ready.
  3189. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3190. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3191. // This function will be called when plugin is ready. It sends necessary
  3192. // details to the plugin.
  3193. // The function will wait for the document to be ready and the set the
  3194. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3195. // indicating that it can start being requested.
  3196. // This function is not in the IE/Safari condition brackets so that
  3197. // TemPluginLoaded function might be called on Chrome/Firefox.
  3198. // This function is the only private function that is not encapsulated to
  3199. // allow the plugin method to be called.
  3200. __TemWebRTCReady0 = function () {
  3201. if (document.readyState === 'complete') {
  3202. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3203. AdapterJS.maybeThroughWebRTCReady();
  3204. } else {
  3205. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3206. if (document.readyState === 'complete') {
  3207. // TODO: update comments, we wait for the document to be ready
  3208. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3209. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3210. AdapterJS.maybeThroughWebRTCReady();
  3211. }
  3212. }, 100);
  3213. }
  3214. };
  3215. AdapterJS.maybeThroughWebRTCReady = function() {
  3216. if (!AdapterJS.onwebrtcreadyDone) {
  3217. AdapterJS.onwebrtcreadyDone = true;
  3218. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3219. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3220. }
  3221. }
  3222. };
  3223. // Text namespace
  3224. AdapterJS.TEXT = {
  3225. PLUGIN: {
  3226. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3227. 'to work on this browser.',
  3228. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3229. BUTTON: 'Install Now'
  3230. },
  3231. REFRESH: {
  3232. REQUIRE_REFRESH: 'Please refresh page',
  3233. BUTTON: 'Refresh Page'
  3234. }
  3235. };
  3236. // The result of ice connection states.
  3237. // - starting: Ice connection is starting.
  3238. // - checking: Ice connection is checking.
  3239. // - connected Ice connection is connected.
  3240. // - completed Ice connection is connected.
  3241. // - done Ice connection has been completed.
  3242. // - disconnected Ice connection has been disconnected.
  3243. // - failed Ice connection has failed.
  3244. // - closed Ice connection is closed.
  3245. AdapterJS._iceConnectionStates = {
  3246. starting : 'starting',
  3247. checking : 'checking',
  3248. connected : 'connected',
  3249. completed : 'connected',
  3250. done : 'completed',
  3251. disconnected : 'disconnected',
  3252. failed : 'failed',
  3253. closed : 'closed'
  3254. };
  3255. //The IceConnection states that has been fired for each peer.
  3256. AdapterJS._iceConnectionFiredStates = [];
  3257. // Check if WebRTC Interface is defined.
  3258. AdapterJS.isDefined = null;
  3259. // This function helps to retrieve the webrtc detected browser information.
  3260. // This sets:
  3261. // - webrtcDetectedBrowser: The browser agent name.
  3262. // - webrtcDetectedVersion: The browser version.
  3263. // - webrtcDetectedType: The types of webRTC support.
  3264. // - 'moz': Mozilla implementation of webRTC.
  3265. // - 'webkit': WebKit implementation of webRTC.
  3266. // - 'plugin': Using the plugin implementation.
  3267. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3268. var hasMatch, checkMatch = navigator.userAgent.match(
  3269. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3270. if (/trident/i.test(checkMatch[1])) {
  3271. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3272. webrtcDetectedBrowser = 'IE';
  3273. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3274. } else if (checkMatch[1] === 'Chrome') {
  3275. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3276. if (hasMatch !== null) {
  3277. webrtcDetectedBrowser = 'opera';
  3278. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3279. }
  3280. }
  3281. if (navigator.userAgent.indexOf('Safari')) {
  3282. if (typeof InstallTrigger !== 'undefined') {
  3283. webrtcDetectedBrowser = 'firefox';
  3284. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3285. webrtcDetectedBrowser = 'IE';
  3286. } else if (
  3287. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3288. webrtcDetectedBrowser = 'safari';
  3289. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3290. webrtcDetectedBrowser = 'opera';
  3291. } else if (!!window.chrome) {
  3292. webrtcDetectedBrowser = 'chrome';
  3293. }
  3294. }
  3295. if (!webrtcDetectedBrowser) {
  3296. webrtcDetectedVersion = checkMatch[1];
  3297. }
  3298. if (!webrtcDetectedVersion) {
  3299. try {
  3300. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3301. [navigator.appName, navigator.appVersion, '-?'];
  3302. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3303. checkMatch.splice(1, 1, hasMatch[1]);
  3304. }
  3305. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3306. } catch (error) { }
  3307. }
  3308. };
  3309. // To fix configuration as some browsers does not support
  3310. // the 'urls' attribute.
  3311. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3312. if (pcConfig === null) {
  3313. return;
  3314. }
  3315. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3316. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3317. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3318. delete pcConfig.iceServers[i].urls;
  3319. }
  3320. }
  3321. };
  3322. AdapterJS.addEvent = function(elem, evnt, func) {
  3323. if (elem.addEventListener) { // W3C DOM
  3324. elem.addEventListener(evnt, func, false);
  3325. } else if (elem.attachEvent) {// OLD IE DOM
  3326. elem.attachEvent('on'+evnt, func);
  3327. } else { // No much to do
  3328. elem[evnt] = func;
  3329. }
  3330. };
  3331. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3332. // only inject once the page is ready
  3333. if (document.readyState !== 'complete') {
  3334. return;
  3335. }
  3336. var w = window;
  3337. var i = document.createElement('iframe');
  3338. i.style.position = 'fixed';
  3339. i.style.top = '-41px';
  3340. i.style.left = 0;
  3341. i.style.right = 0;
  3342. i.style.width = '100%';
  3343. i.style.height = '40px';
  3344. i.style.backgroundColor = '#ffffe1';
  3345. i.style.border = 'none';
  3346. i.style.borderBottom = '1px solid #888888';
  3347. i.style.zIndex = '9999999';
  3348. if(typeof i.style.webkitTransition === 'string') {
  3349. i.style.webkitTransition = 'all .5s ease-out';
  3350. } else if(typeof i.style.transition === 'string') {
  3351. i.style.transition = 'all .5s ease-out';
  3352. }
  3353. document.body.appendChild(i);
  3354. c = (i.contentWindow) ? i.contentWindow :
  3355. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3356. c.document.open();
  3357. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3358. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3359. 'middle; cursor: default;">' + text + '</span>');
  3360. if(buttonText && buttonLink) {
  3361. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3362. c.document.close();
  3363. // On click on okay
  3364. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3365. if (!!displayRefreshBar) {
  3366. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3367. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3368. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3369. }
  3370. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3371. e.preventDefault();
  3372. try {
  3373. event.cancelBubble = true;
  3374. } catch(error) { }
  3375. var pluginInstallInterval = setInterval(function(){
  3376. if(! isIE) {
  3377. navigator.plugins.refresh(false);
  3378. }
  3379. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3380. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3381. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3382. function() { // plugin now installed
  3383. clearInterval(pluginInstallInterval);
  3384. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3385. },
  3386. function() {
  3387. // still no plugin detected, nothing to do
  3388. });
  3389. } , 500);
  3390. });
  3391. // On click on Cancel
  3392. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3393. w.document.body.removeChild(i);
  3394. });
  3395. } else {
  3396. c.document.close();
  3397. }
  3398. setTimeout(function() {
  3399. if(typeof i.style.webkitTransform === 'string') {
  3400. i.style.webkitTransform = 'translateY(40px)';
  3401. } else if(typeof i.style.transform === 'string') {
  3402. i.style.transform = 'translateY(40px)';
  3403. } else {
  3404. i.style.top = '0px';
  3405. }
  3406. }, 300);
  3407. };
  3408. // -----------------------------------------------------------
  3409. // Detected webrtc implementation. Types are:
  3410. // - 'moz': Mozilla implementation of webRTC.
  3411. // - 'webkit': WebKit implementation of webRTC.
  3412. // - 'plugin': Using the plugin implementation.
  3413. webrtcDetectedType = null;
  3414. // Detected webrtc datachannel support. Types are:
  3415. // - 'SCTP': SCTP datachannel support.
  3416. // - 'RTP': RTP datachannel support.
  3417. webrtcDetectedDCSupport = null;
  3418. // Set the settings for creating DataChannels, MediaStream for
  3419. // Cross-browser compability.
  3420. // - This is only for SCTP based support browsers.
  3421. // the 'urls' attribute.
  3422. checkMediaDataChannelSettings =
  3423. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3424. if (typeof callback !== 'function') {
  3425. return;
  3426. }
  3427. var beOfferer = true;
  3428. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3429. // Nightly version does not require MozDontOfferDataChannel for interop
  3430. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3431. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3432. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3433. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3434. // Resends an updated version of constraints for MozDataChannel to work
  3435. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3436. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3437. try {
  3438. delete constraints.mandatory.MozDontOfferDataChannel;
  3439. } catch (error) {
  3440. console.error('Failed deleting MozDontOfferDataChannel');
  3441. console.error(error);
  3442. }
  3443. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3444. constraints.mandatory.MozDontOfferDataChannel = true;
  3445. }
  3446. if (!isLocalFirefox) {
  3447. // temporary measure to remove Moz* constraints in non Firefox browsers
  3448. for (var prop in constraints.mandatory) {
  3449. if (constraints.mandatory.hasOwnProperty(prop)) {
  3450. if (prop.indexOf('Moz') !== -1) {
  3451. delete constraints.mandatory[prop];
  3452. }
  3453. }
  3454. }
  3455. }
  3456. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3457. // interopability of the media stream
  3458. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3459. beOfferer = false;
  3460. }
  3461. callback(beOfferer, constraints);
  3462. };
  3463. // Handles the differences for all browsers ice connection state output.
  3464. // - Tested outcomes are:
  3465. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3466. // - Chrome (answerer) : 'checking' > 'connected'
  3467. // - Firefox (offerer) : 'checking' > 'connected'
  3468. // - Firefox (answerer): 'checking' > 'connected'
  3469. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3470. if (typeof callback !== 'function') {
  3471. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3472. return;
  3473. }
  3474. peerId = (peerId) ? peerId : 'peer';
  3475. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3476. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3477. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3478. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3479. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3480. }
  3481. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3482. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3483. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3484. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3485. setTimeout(function () {
  3486. AdapterJS._iceConnectionFiredStates[peerId]
  3487. .push(AdapterJS._iceConnectionStates.done);
  3488. callback(AdapterJS._iceConnectionStates.done);
  3489. }, 1000);
  3490. }
  3491. callback(iceConnectionState);
  3492. }
  3493. return;
  3494. };
  3495. // Firefox:
  3496. // - Creates iceServer from the url for Firefox.
  3497. // - Create iceServer with stun url.
  3498. // - Create iceServer with turn url.
  3499. // - Ignore the transport parameter from TURN url for FF version <=27.
  3500. // - Return null for createIceServer if transport=tcp.
  3501. // - FF 27 and above supports transport parameters in TURN url,
  3502. // - So passing in the full url to create iceServer.
  3503. // Chrome:
  3504. // - Creates iceServer from the url for Chrome M33 and earlier.
  3505. // - Create iceServer with stun url.
  3506. // - Chrome M28 & above uses below TURN format.
  3507. // Plugin:
  3508. // - Creates Ice Server for Plugin Browsers
  3509. // - If Stun - Create iceServer with stun url.
  3510. // - Else - Create iceServer with turn url
  3511. // - This is a WebRTC Function
  3512. createIceServer = null;
  3513. // Firefox:
  3514. // - Creates IceServers for Firefox
  3515. // - Use .url for FireFox.
  3516. // - Multiple Urls support
  3517. // Chrome:
  3518. // - Creates iceServers from the urls for Chrome M34 and above.
  3519. // - .urls is supported since Chrome M34.
  3520. // - Multiple Urls support
  3521. // Plugin:
  3522. // - Creates Ice Servers for Plugin Browsers
  3523. // - Multiple Urls support
  3524. // - This is a WebRTC Function
  3525. createIceServers = null;
  3526. //------------------------------------------------------------
  3527. //The RTCPeerConnection object.
  3528. RTCPeerConnection = null;
  3529. // Creates RTCSessionDescription object for Plugin Browsers
  3530. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3531. RTCSessionDescription : null;
  3532. // Creates RTCIceCandidate object for Plugin Browsers
  3533. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3534. RTCIceCandidate : null;
  3535. // Get UserMedia (only difference is the prefix).
  3536. // Code from Adam Barth.
  3537. getUserMedia = null;
  3538. // Attach a media stream to an element.
  3539. attachMediaStream = null;
  3540. // Re-attach a media stream to an element.
  3541. reattachMediaStream = null;
  3542. // Detected browser agent name. Types are:
  3543. // - 'firefox': Firefox browser.
  3544. // - 'chrome': Chrome browser.
  3545. // - 'opera': Opera browser.
  3546. // - 'safari': Safari browser.
  3547. // - 'IE' - Internet Explorer browser.
  3548. webrtcDetectedBrowser = null;
  3549. // Detected browser version.
  3550. webrtcDetectedVersion = null;
  3551. // Check for browser types and react accordingly
  3552. if (navigator.mozGetUserMedia) {
  3553. webrtcDetectedBrowser = 'firefox';
  3554. webrtcDetectedVersion = parseInt(navigator
  3555. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3556. webrtcDetectedType = 'moz';
  3557. webrtcDetectedDCSupport = 'SCTP';
  3558. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3559. AdapterJS.maybeFixConfiguration(pcConfig);
  3560. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3561. };
  3562. // The RTCSessionDescription object.
  3563. RTCSessionDescription = mozRTCSessionDescription;
  3564. window.RTCSessionDescription = RTCSessionDescription;
  3565. // The RTCIceCandidate object.
  3566. RTCIceCandidate = mozRTCIceCandidate;
  3567. window.RTCIceCandidate = RTCIceCandidate;
  3568. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3569. navigator.getUserMedia = window.getUserMedia;
  3570. // Shim for MediaStreamTrack.getSources.
  3571. MediaStreamTrack.getSources = function(successCb) {
  3572. setTimeout(function() {
  3573. var infos = [
  3574. { kind: 'audio', id: 'default', label:'', facing:'' },
  3575. { kind: 'video', id: 'default', label:'', facing:'' }
  3576. ];
  3577. successCb(infos);
  3578. }, 0);
  3579. };
  3580. createIceServer = function (url, username, password) {
  3581. var iceServer = null;
  3582. var url_parts = url.split(':');
  3583. if (url_parts[0].indexOf('stun') === 0) {
  3584. iceServer = { url : url };
  3585. } else if (url_parts[0].indexOf('turn') === 0) {
  3586. if (webrtcDetectedVersion < 27) {
  3587. var turn_url_parts = url.split('?');
  3588. if (turn_url_parts.length === 1 ||
  3589. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3590. iceServer = {
  3591. url : turn_url_parts[0],
  3592. credential : password,
  3593. username : username
  3594. };
  3595. }
  3596. } else {
  3597. iceServer = {
  3598. url : url,
  3599. credential : password,
  3600. username : username
  3601. };
  3602. }
  3603. }
  3604. return iceServer;
  3605. };
  3606. createIceServers = function (urls, username, password) {
  3607. var iceServers = [];
  3608. for (i = 0; i < urls.length; i++) {
  3609. var iceServer = createIceServer(urls[i], username, password);
  3610. if (iceServer !== null) {
  3611. iceServers.push(iceServer);
  3612. }
  3613. }
  3614. return iceServers;
  3615. };
  3616. attachMediaStream = function (element, stream) {
  3617. element.mozSrcObject = stream;
  3618. if (stream !== null)
  3619. element.play();
  3620. return element;
  3621. };
  3622. reattachMediaStream = function (to, from) {
  3623. to.mozSrcObject = from.mozSrcObject;
  3624. to.play();
  3625. return to;
  3626. };
  3627. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3628. if (!callback) {
  3629. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3630. ': 1 argument required, but only 0 present.');
  3631. }
  3632. return callback([]);
  3633. };
  3634. // Fake get{Video,Audio}Tracks
  3635. if (!MediaStream.prototype.getVideoTracks) {
  3636. MediaStream.prototype.getVideoTracks = function () {
  3637. return [];
  3638. };
  3639. }
  3640. if (!MediaStream.prototype.getAudioTracks) {
  3641. MediaStream.prototype.getAudioTracks = function () {
  3642. return [];
  3643. };
  3644. }
  3645. AdapterJS.maybeThroughWebRTCReady();
  3646. } else if (navigator.webkitGetUserMedia) {
  3647. webrtcDetectedBrowser = 'chrome';
  3648. webrtcDetectedType = 'webkit';
  3649. webrtcDetectedVersion = parseInt(navigator
  3650. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3651. // check if browser is opera 20+
  3652. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3653. if (checkIfOpera !== null) {
  3654. webrtcDetectedBrowser = 'opera';
  3655. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3656. }
  3657. // check browser datachannel support
  3658. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3659. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3660. webrtcDetectedDCSupport = 'SCTP';
  3661. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3662. webrtcDetectedVersion > 24) {
  3663. webrtcDetectedDCSupport = 'RTP';
  3664. } else {
  3665. webrtcDetectedDCSupport = '';
  3666. }
  3667. createIceServer = function (url, username, password) {
  3668. var iceServer = null;
  3669. var url_parts = url.split(':');
  3670. if (url_parts[0].indexOf('stun') === 0) {
  3671. iceServer = { 'url' : url };
  3672. } else if (url_parts[0].indexOf('turn') === 0) {
  3673. iceServer = {
  3674. 'url' : url,
  3675. 'credential' : password,
  3676. 'username' : username
  3677. };
  3678. }
  3679. return iceServer;
  3680. };
  3681. createIceServers = function (urls, username, password) {
  3682. var iceServers = [];
  3683. if (webrtcDetectedVersion >= 34) {
  3684. iceServers = {
  3685. 'urls' : urls,
  3686. 'credential' : password,
  3687. 'username' : username
  3688. };
  3689. } else {
  3690. for (i = 0; i < urls.length; i++) {
  3691. var iceServer = createIceServer(urls[i], username, password);
  3692. if (iceServer !== null) {
  3693. iceServers.push(iceServer);
  3694. }
  3695. }
  3696. }
  3697. return iceServers;
  3698. };
  3699. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3700. if (webrtcDetectedVersion < 34) {
  3701. AdapterJS.maybeFixConfiguration(pcConfig);
  3702. }
  3703. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3704. };
  3705. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3706. navigator.getUserMedia = window.getUserMedia;
  3707. attachMediaStream = function (element, stream) {
  3708. if (typeof element.srcObject !== 'undefined') {
  3709. element.srcObject = stream;
  3710. } else if (typeof element.mozSrcObject !== 'undefined') {
  3711. element.mozSrcObject = stream;
  3712. } else if (typeof element.src !== 'undefined') {
  3713. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3714. } else {
  3715. console.log('Error attaching stream to element.');
  3716. }
  3717. return element;
  3718. };
  3719. reattachMediaStream = function (to, from) {
  3720. to.src = from.src;
  3721. return to;
  3722. };
  3723. AdapterJS.maybeThroughWebRTCReady();
  3724. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3725. /Edge\/(\d+).(\d+)$/)) {
  3726. webrtcDetectedBrowser = 'edge';
  3727. webrtcDetectedVersion =
  3728. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3729. // the minimum version still supported by adapter.
  3730. webrtcMinimumVersion = 12;
  3731. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3732. attachMediaStream = function(element, stream) {
  3733. element.srcObject = stream;
  3734. return element;
  3735. };
  3736. reattachMediaStream = function(to, from) {
  3737. to.srcObject = from.srcObject;
  3738. return to;
  3739. };
  3740. AdapterJS.maybeThroughWebRTCReady();
  3741. } else { // TRY TO USE PLUGIN
  3742. // IE 9 is not offering an implementation of console.log until you open a console
  3743. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3744. /* jshint -W020 */
  3745. console = {} || console;
  3746. // Implemented based on console specs from MDN
  3747. // You may override these functions
  3748. console.log = function (arg) {};
  3749. console.info = function (arg) {};
  3750. console.error = function (arg) {};
  3751. console.dir = function (arg) {};
  3752. console.exception = function (arg) {};
  3753. console.trace = function (arg) {};
  3754. console.warn = function (arg) {};
  3755. console.count = function (arg) {};
  3756. console.debug = function (arg) {};
  3757. console.count = function (arg) {};
  3758. console.time = function (arg) {};
  3759. console.timeEnd = function (arg) {};
  3760. console.group = function (arg) {};
  3761. console.groupCollapsed = function (arg) {};
  3762. console.groupEnd = function (arg) {};
  3763. /* jshint +W020 */
  3764. }
  3765. webrtcDetectedType = 'plugin';
  3766. webrtcDetectedDCSupport = 'plugin';
  3767. AdapterJS.parseWebrtcDetectedBrowser();
  3768. isIE = webrtcDetectedBrowser === 'IE';
  3769. /* jshint -W035 */
  3770. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3771. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3772. /* empty because it needs to prevent the function from running. */
  3773. }
  3774. };
  3775. /* jshint +W035 */
  3776. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3777. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3778. // Call immediately if possible
  3779. // Once the plugin is set, the code will always take this path
  3780. callback();
  3781. } else {
  3782. // otherwise start a 100ms interval
  3783. var checkPluginReadyState = setInterval(function () {
  3784. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3785. clearInterval(checkPluginReadyState);
  3786. callback();
  3787. }
  3788. }, 100);
  3789. }
  3790. };
  3791. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3792. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3793. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3794. });
  3795. };
  3796. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3797. // only inject once the page is ready
  3798. if (document.readyState !== 'complete') {
  3799. return;
  3800. }
  3801. // Prevent multiple injections
  3802. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3803. return;
  3804. }
  3805. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3806. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3807. var frag = document.createDocumentFragment();
  3808. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3809. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3810. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3811. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3812. '<param name="pluginId" value="' +
  3813. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3814. '<param name="windowless" value="false" /> ' +
  3815. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3816. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3817. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3818. // uncomment to be able to use virtual cams
  3819. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3820. '</object>';
  3821. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3822. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3823. }
  3824. document.body.appendChild(frag);
  3825. // Need to re-fetch the plugin
  3826. AdapterJS.WebRTCPlugin.plugin =
  3827. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3828. } else {
  3829. // Load Plugin
  3830. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3831. AdapterJS.WebRTCPlugin.plugin.id =
  3832. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3833. // IE will only start the plugin if it's ACTUALLY visible
  3834. if (isIE) {
  3835. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3836. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3837. } else { // The size of the plugin on Safari should be 0x0px
  3838. // so that the autorisation prompt is at the top
  3839. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3840. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3841. }
  3842. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3843. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3844. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3845. '<param name="pluginId" value="' +
  3846. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3847. '<param name="windowless" value="false" /> ' +
  3848. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3849. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3850. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3851. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3852. }
  3853. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3854. };
  3855. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3856. function (comName, plugName, installedCb, notInstalledCb) {
  3857. if (!isIE) {
  3858. var pluginArray = navigator.plugins;
  3859. for (var i = 0; i < pluginArray.length; i++) {
  3860. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3861. installedCb();
  3862. return;
  3863. }
  3864. }
  3865. notInstalledCb();
  3866. } else {
  3867. try {
  3868. var axo = new ActiveXObject(comName + '.' + plugName);
  3869. } catch (e) {
  3870. notInstalledCb();
  3871. return;
  3872. }
  3873. installedCb();
  3874. }
  3875. };
  3876. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3877. if (AdapterJS.WebRTCPlugin.pluginState ===
  3878. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3879. console.error("AdapterJS - WebRTC interface has already been defined");
  3880. return;
  3881. }
  3882. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3883. AdapterJS.isDefined = function (variable) {
  3884. return variable !== null && variable !== undefined;
  3885. };
  3886. createIceServer = function (url, username, password) {
  3887. var iceServer = null;
  3888. var url_parts = url.split(':');
  3889. if (url_parts[0].indexOf('stun') === 0) {
  3890. iceServer = {
  3891. 'url' : url,
  3892. 'hasCredentials' : false
  3893. };
  3894. } else if (url_parts[0].indexOf('turn') === 0) {
  3895. iceServer = {
  3896. 'url' : url,
  3897. 'hasCredentials' : true,
  3898. 'credential' : password,
  3899. 'username' : username
  3900. };
  3901. }
  3902. return iceServer;
  3903. };
  3904. createIceServers = function (urls, username, password) {
  3905. var iceServers = [];
  3906. for (var i = 0; i < urls.length; ++i) {
  3907. iceServers.push(createIceServer(urls[i], username, password));
  3908. }
  3909. return iceServers;
  3910. };
  3911. RTCSessionDescription = function (info) {
  3912. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3913. return AdapterJS.WebRTCPlugin.plugin.
  3914. ConstructSessionDescription(info.type, info.sdp);
  3915. };
  3916. RTCPeerConnection = function (servers, constraints) {
  3917. var iceServers = null;
  3918. if (servers) {
  3919. iceServers = servers.iceServers;
  3920. for (var i = 0; i < iceServers.length; i++) {
  3921. if (iceServers[i].urls && !iceServers[i].url) {
  3922. iceServers[i].url = iceServers[i].urls;
  3923. }
  3924. iceServers[i].hasCredentials = AdapterJS.
  3925. isDefined(iceServers[i].username) &&
  3926. AdapterJS.isDefined(iceServers[i].credential);
  3927. }
  3928. }
  3929. var mandatory = (constraints && constraints.mandatory) ?
  3930. constraints.mandatory : null;
  3931. var optional = (constraints && constraints.optional) ?
  3932. constraints.optional : null;
  3933. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3934. return AdapterJS.WebRTCPlugin.plugin.
  3935. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3936. iceServers, mandatory, optional);
  3937. };
  3938. MediaStreamTrack = {};
  3939. MediaStreamTrack.getSources = function (callback) {
  3940. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3941. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  3942. });
  3943. };
  3944. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  3945. constraints.audio = constraints.audio || false;
  3946. constraints.video = constraints.video || false;
  3947. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3948. AdapterJS.WebRTCPlugin.plugin.
  3949. getUserMedia(constraints, successCallback, failureCallback);
  3950. });
  3951. };
  3952. window.navigator.getUserMedia = window.getUserMedia;
  3953. attachMediaStream = function (element, stream) {
  3954. if (!element || !element.parentNode) {
  3955. return;
  3956. }
  3957. var streamId
  3958. if (stream === null) {
  3959. streamId = '';
  3960. }
  3961. else {
  3962. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  3963. streamId = stream.id;
  3964. }
  3965. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  3966. var nodeName = element.nodeName.toLowerCase();
  3967. if (nodeName !== 'object') { // not a plugin <object> tag yet
  3968. var tag;
  3969. switch(nodeName) {
  3970. case 'audio':
  3971. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  3972. break;
  3973. case 'video':
  3974. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  3975. break;
  3976. default:
  3977. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  3978. }
  3979. var frag = document.createDocumentFragment();
  3980. var temp = document.createElement('div');
  3981. var classHTML = '';
  3982. if (element.className) {
  3983. classHTML = 'class="' + element.className + '" ';
  3984. } else if (element.attributes && element.attributes['class']) {
  3985. classHTML = 'class="' + element.attributes['class'].value + '" ';
  3986. }
  3987. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  3988. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  3989. '<param name="pluginId" value="' + elementId + '" /> ' +
  3990. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3991. '<param name="windowless" value="true" /> ' +
  3992. '<param name="streamId" value="' + streamId + '" /> ' +
  3993. '<param name="tag" value="' + tag + '" /> ' +
  3994. '</object>';
  3995. while (temp.firstChild) {
  3996. frag.appendChild(temp.firstChild);
  3997. }
  3998. var height = '';
  3999. var width = '';
  4000. if (element.getBoundingClientRect) {
  4001. var rectObject = element.getBoundingClientRect();
  4002. width = rectObject.width + 'px';
  4003. height = rectObject.height + 'px';
  4004. }
  4005. else if (element.width) {
  4006. width = element.width;
  4007. height = element.height;
  4008. } else {
  4009. // TODO: What scenario could bring us here?
  4010. }
  4011. element.parentNode.insertBefore(frag, element);
  4012. frag = document.getElementById(elementId);
  4013. frag.width = width;
  4014. frag.height = height;
  4015. element.parentNode.removeChild(element);
  4016. } else { // already an <object> tag, just change the stream id
  4017. var children = element.children;
  4018. for (var i = 0; i !== children.length; ++i) {
  4019. if (children[i].name === 'streamId') {
  4020. children[i].value = streamId;
  4021. break;
  4022. }
  4023. }
  4024. element.setStreamId(streamId);
  4025. }
  4026. var newElement = document.getElementById(elementId);
  4027. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  4028. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  4029. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  4030. if (isIE) { // on IE the event needs to be plugged manually
  4031. newElement.attachEvent('onplaying', newElement.onplaying);
  4032. newElement.attachEvent('onplay', newElement.onplay);
  4033. newElement._TemOnClick = function (id) {
  4034. var arg = {
  4035. srcElement : document.getElementById(id)
  4036. };
  4037. newElement.onclick(arg);
  4038. };
  4039. }
  4040. return newElement;
  4041. };
  4042. reattachMediaStream = function (to, from) {
  4043. var stream = null;
  4044. var children = from.children;
  4045. for (var i = 0; i !== children.length; ++i) {
  4046. if (children[i].name === 'streamId') {
  4047. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4048. stream = AdapterJS.WebRTCPlugin.plugin
  4049. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4050. break;
  4051. }
  4052. }
  4053. if (stream !== null) {
  4054. return attachMediaStream(to, stream);
  4055. } else {
  4056. console.log('Could not find the stream associated with this element');
  4057. }
  4058. };
  4059. RTCIceCandidate = function (candidate) {
  4060. if (!candidate.sdpMid) {
  4061. candidate.sdpMid = '';
  4062. }
  4063. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4064. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4065. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4066. );
  4067. };
  4068. // inject plugin
  4069. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4070. AdapterJS.WebRTCPlugin.injectPlugin();
  4071. };
  4072. // This function will be called if the plugin is needed (browser different
  4073. // from Chrome or Firefox), but the plugin is not installed.
  4074. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4075. function() {
  4076. AdapterJS.addEvent(document,
  4077. 'readystatechange',
  4078. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4079. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4080. };
  4081. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4082. if (AdapterJS.options.hidePluginInstallPrompt) {
  4083. return;
  4084. }
  4085. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4086. if(downloadLink) { // if download link
  4087. var popupString;
  4088. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4089. popupString = 'This website requires you to install the ' +
  4090. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4091. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4092. ' WebRTC Plugin</a>' +
  4093. ' to work on this browser.';
  4094. } else { // no portal link, just print a generic explanation
  4095. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4096. }
  4097. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4098. } else { // no download link, just print a generic explanation
  4099. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4100. }
  4101. };
  4102. // Try to detect the plugin and act accordingly
  4103. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4104. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4105. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4106. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4107. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4108. }
  4109. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4110. },{"jitsi-meet-logger":48}],21:[function(require,module,exports){
  4111. (function (__filename){
  4112. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4113. function supportsLocalStorage() {
  4114. try {
  4115. return 'localStorage' in window && window.localStorage !== null;
  4116. } catch (e) {
  4117. logger.log("localstorage is not supported");
  4118. return false;
  4119. }
  4120. }
  4121. function generateUniqueId() {
  4122. function _p8() {
  4123. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4124. }
  4125. return _p8() + _p8() + _p8() + _p8();
  4126. }
  4127. function Settings(conferenceID) {
  4128. this.email = '';
  4129. this.displayName = '';
  4130. this.userId;
  4131. this.language = null;
  4132. this.confSettings = null;
  4133. this.conferenceID = conferenceID;
  4134. if (supportsLocalStorage()) {
  4135. if(!window.localStorage.getItem(conferenceID))
  4136. this.confSettings = {};
  4137. else
  4138. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4139. if(!this.confSettings.jitsiMeetId) {
  4140. this.confSettings.jitsiMeetId = generateUniqueId();
  4141. logger.log("generated id",
  4142. this.confSettings.jitsiMeetId);
  4143. this.save();
  4144. }
  4145. this.userId = this.confSettings.jitsiMeetId || '';
  4146. this.email = this.confSettings.email || '';
  4147. this.displayName = this.confSettings.displayname || '';
  4148. this.language = this.confSettings.language;
  4149. } else {
  4150. logger.log("local storage is not supported");
  4151. this.userId = generateUniqueId();
  4152. }
  4153. }
  4154. Settings.prototype.save = function () {
  4155. if(!supportsLocalStorage())
  4156. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4157. }
  4158. Settings.prototype.setDisplayName = function (newDisplayName) {
  4159. this.displayName = newDisplayName;
  4160. if(this.confSettings != null)
  4161. this.confSettings.displayname = displayName;
  4162. this.save();
  4163. return this.displayName;
  4164. },
  4165. Settings.prototype.setEmail = function (newEmail) {
  4166. this.email = newEmail;
  4167. if(this.confSettings != null)
  4168. this.confSettings.email = newEmail;
  4169. this.save();
  4170. return this.email;
  4171. },
  4172. Settings.prototype.getSettings = function () {
  4173. return {
  4174. email: this.email,
  4175. displayName: this.displayName,
  4176. uid: this.userId,
  4177. language: this.language
  4178. };
  4179. },
  4180. Settings.prototype.setLanguage = function (lang) {
  4181. this.language = lang;
  4182. if(this.confSettings != null)
  4183. this.confSettings.language = lang;
  4184. this.save();
  4185. }
  4186. module.exports = Settings;
  4187. }).call(this,"/modules/settings/Settings.js")
  4188. },{"jitsi-meet-logger":48}],22:[function(require,module,exports){
  4189. /* global config */
  4190. /**
  4191. * Provides statistics for the local stream.
  4192. */
  4193. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4194. /**
  4195. * Size of the webaudio analyzer buffer.
  4196. * @type {number}
  4197. */
  4198. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4199. /**
  4200. * Value of the webaudio analyzer smoothing time parameter.
  4201. * @type {number}
  4202. */
  4203. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4204. /**
  4205. * Converts time domain data array to audio level.
  4206. * @param samples the time domain data array.
  4207. * @returns {number} the audio level
  4208. */
  4209. function timeDomainDataToAudioLevel(samples) {
  4210. var maxVolume = 0;
  4211. var length = samples.length;
  4212. for (var i = 0; i < length; i++) {
  4213. if (maxVolume < samples[i])
  4214. maxVolume = samples[i];
  4215. }
  4216. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4217. }
  4218. /**
  4219. * Animates audio level change
  4220. * @param newLevel the new audio level
  4221. * @param lastLevel the last audio level
  4222. * @returns {Number} the audio level to be set
  4223. */
  4224. function animateLevel(newLevel, lastLevel) {
  4225. var value = 0;
  4226. var diff = lastLevel - newLevel;
  4227. if(diff > 0.2) {
  4228. value = lastLevel - 0.2;
  4229. }
  4230. else if(diff < -0.4) {
  4231. value = lastLevel + 0.4;
  4232. }
  4233. else {
  4234. value = newLevel;
  4235. }
  4236. return parseFloat(value.toFixed(3));
  4237. }
  4238. /**
  4239. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4240. *
  4241. * @param stream the local stream
  4242. * @param interval stats refresh interval given in ms.
  4243. * @param callback function that receives the audio levels.
  4244. * @constructor
  4245. */
  4246. function LocalStatsCollector(stream, interval, callback) {
  4247. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4248. this.stream = stream;
  4249. this.intervalId = null;
  4250. this.intervalMilis = interval;
  4251. this.audioLevel = 0;
  4252. this.callback = callback;
  4253. }
  4254. /**
  4255. * Starts the collecting the statistics.
  4256. */
  4257. LocalStatsCollector.prototype.start = function () {
  4258. if (!window.AudioContext ||
  4259. RTCBrowserType.isTemasysPluginUsed())
  4260. return;
  4261. var context = new AudioContext();
  4262. var analyser = context.createAnalyser();
  4263. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4264. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4265. var source = context.createMediaStreamSource(this.stream);
  4266. source.connect(analyser);
  4267. var self = this;
  4268. this.intervalId = setInterval(
  4269. function () {
  4270. var array = new Uint8Array(analyser.frequencyBinCount);
  4271. analyser.getByteTimeDomainData(array);
  4272. var audioLevel = timeDomainDataToAudioLevel(array);
  4273. if (audioLevel != self.audioLevel) {
  4274. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4275. self.callback(self.audioLevel);
  4276. }
  4277. },
  4278. this.intervalMilis
  4279. );
  4280. };
  4281. /**
  4282. * Stops collecting the statistics.
  4283. */
  4284. LocalStatsCollector.prototype.stop = function () {
  4285. if (this.intervalId) {
  4286. clearInterval(this.intervalId);
  4287. this.intervalId = null;
  4288. }
  4289. };
  4290. module.exports = LocalStatsCollector;
  4291. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4292. (function (__filename){
  4293. /* global require, ssrc2jid */
  4294. /* jshint -W117 */
  4295. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4296. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4297. var StatisticsEvents = require("../../service/statistics/Events");
  4298. /* Whether we support the browser we are running into for logging statistics */
  4299. var browserSupported = RTCBrowserType.isChrome() ||
  4300. RTCBrowserType.isOpera();
  4301. var keyMap = {};
  4302. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4303. "ssrc": "ssrc",
  4304. "packetsReceived": "packetsReceived",
  4305. "packetsLost": "packetsLost",
  4306. "packetsSent": "packetsSent",
  4307. "bytesReceived": "bytesReceived",
  4308. "bytesSent": "bytesSent"
  4309. };
  4310. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4311. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4312. "sendBandwidth": "googAvailableSendBandwidth",
  4313. "remoteAddress": "googRemoteAddress",
  4314. "transportType": "googTransportType",
  4315. "localAddress": "googLocalAddress",
  4316. "activeConnection": "googActiveConnection",
  4317. "ssrc": "ssrc",
  4318. "packetsReceived": "packetsReceived",
  4319. "packetsSent": "packetsSent",
  4320. "packetsLost": "packetsLost",
  4321. "bytesReceived": "bytesReceived",
  4322. "bytesSent": "bytesSent",
  4323. "googFrameHeightReceived": "googFrameHeightReceived",
  4324. "googFrameWidthReceived": "googFrameWidthReceived",
  4325. "googFrameHeightSent": "googFrameHeightSent",
  4326. "googFrameWidthSent": "googFrameWidthSent",
  4327. "audioInputLevel": "audioInputLevel",
  4328. "audioOutputLevel": "audioOutputLevel"
  4329. };
  4330. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4331. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4332. /**
  4333. * Calculates packet lost percent using the number of lost packets and the
  4334. * number of all packet.
  4335. * @param lostPackets the number of lost packets
  4336. * @param totalPackets the number of all packets.
  4337. * @returns {number} packet loss percent
  4338. */
  4339. function calculatePacketLoss(lostPackets, totalPackets) {
  4340. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4341. return 0;
  4342. return Math.round((lostPackets/totalPackets)*100);
  4343. }
  4344. function getStatValue(item, name) {
  4345. var browserType = RTCBrowserType.getBrowserType();
  4346. if (!keyMap[browserType][name])
  4347. throw "The property isn't supported!";
  4348. var key = keyMap[browserType][name];
  4349. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4350. item.stat(key) : item[key];
  4351. }
  4352. function formatAudioLevel(audioLevel) {
  4353. return Math.min(Math.max(audioLevel, 0), 1);
  4354. }
  4355. /**
  4356. * Checks whether a certain record should be included in the logged statistics.
  4357. */
  4358. function acceptStat(reportId, reportType, statName) {
  4359. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4360. return false;
  4361. if (reportType == "ssrc") {
  4362. if (statName == "googTrackId" ||
  4363. statName == "transportId" ||
  4364. statName == "ssrc")
  4365. return false;
  4366. }
  4367. return true;
  4368. }
  4369. /**
  4370. * Checks whether a certain record should be included in the logged statistics.
  4371. */
  4372. function acceptReport(id, type) {
  4373. if (id.substring(0, 15) == "googCertificate" ||
  4374. id.substring(0, 9) == "googTrack" ||
  4375. id.substring(0, 20) == "googLibjingleSession")
  4376. return false;
  4377. if (type == "googComponent")
  4378. return false;
  4379. return true;
  4380. }
  4381. /**
  4382. * Peer statistics data holder.
  4383. * @constructor
  4384. */
  4385. function PeerStats()
  4386. {
  4387. this.ssrc2Loss = {};
  4388. this.ssrc2AudioLevel = {};
  4389. this.ssrc2bitrate = {};
  4390. this.ssrc2resolution = {};
  4391. }
  4392. /**
  4393. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4394. * represented by this instance.
  4395. * @param lossRate new packet loss rate value to be set.
  4396. */
  4397. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4398. {
  4399. this.ssrc2Loss = lossRate;
  4400. };
  4401. /**
  4402. * Sets resolution that belong to the ssrc
  4403. * represented by this instance.
  4404. * @param resolution new resolution value to be set.
  4405. */
  4406. PeerStats.prototype.setSsrcResolution = function (resolution)
  4407. {
  4408. if(resolution === null && this.ssrc2resolution[ssrc])
  4409. {
  4410. delete this.ssrc2resolution[ssrc];
  4411. }
  4412. else if(resolution !== null)
  4413. this.ssrc2resolution[ssrc] = resolution;
  4414. };
  4415. /**
  4416. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4417. * represented by this instance.
  4418. * @param ssrc audio or video RTP stream SSRC.
  4419. * @param bitrate new bitrate value to be set.
  4420. */
  4421. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4422. {
  4423. if(this.ssrc2bitrate[ssrc])
  4424. {
  4425. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4426. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4427. }
  4428. else {
  4429. this.ssrc2bitrate[ssrc] = bitrate;
  4430. }
  4431. };
  4432. /**
  4433. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4434. * the stream which belongs to the peer represented by this instance.
  4435. * @param ssrc RTP stream SSRC for which current audio level value will be
  4436. * updated.
  4437. * @param audioLevel the new audio level value to be set. Value is truncated to
  4438. * fit the range from 0 to 1.
  4439. */
  4440. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4441. {
  4442. // Range limit 0 - 1
  4443. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4444. };
  4445. function ConferenceStats() {
  4446. /**
  4447. * The bandwidth
  4448. * @type {{}}
  4449. */
  4450. this.bandwidth = {};
  4451. /**
  4452. * The bit rate
  4453. * @type {{}}
  4454. */
  4455. this.bitrate = {};
  4456. /**
  4457. * The packet loss rate
  4458. * @type {{}}
  4459. */
  4460. this.packetLoss = null;
  4461. /**
  4462. * Array with the transport information.
  4463. * @type {Array}
  4464. */
  4465. this.transport = [];
  4466. }
  4467. /**
  4468. * <tt>StatsCollector</tt> registers for stats updates of given
  4469. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4470. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4471. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4472. * instance as an event source.
  4473. *
  4474. * @param peerconnection webRTC peer connection object.
  4475. * @param interval stats refresh interval given in ms.
  4476. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4477. * called on stats update.
  4478. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4479. * @constructor
  4480. */
  4481. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4482. {
  4483. this.peerconnection = peerconnection;
  4484. this.baselineAudioLevelsReport = null;
  4485. this.currentAudioLevelsReport = null;
  4486. this.currentStatsReport = null;
  4487. this.baselineStatsReport = null;
  4488. this.audioLevelsIntervalId = null;
  4489. this.eventEmitter = eventEmitter;
  4490. this.config = config || {};
  4491. this.conferenceStats = new ConferenceStats();
  4492. /**
  4493. * Gather PeerConnection stats once every this many milliseconds.
  4494. */
  4495. this.GATHER_INTERVAL = 15000;
  4496. /**
  4497. * Log stats via the focus once every this many milliseconds.
  4498. */
  4499. this.LOG_INTERVAL = 60000;
  4500. /**
  4501. * Gather stats and store them in this.statsToBeLogged.
  4502. */
  4503. this.gatherStatsIntervalId = null;
  4504. /**
  4505. * Send the stats already saved in this.statsToBeLogged to be logged via
  4506. * the focus.
  4507. */
  4508. this.logStatsIntervalId = null;
  4509. /**
  4510. * Stores the statistics which will be send to the focus to be logged.
  4511. */
  4512. this.statsToBeLogged =
  4513. {
  4514. timestamps: [],
  4515. stats: {}
  4516. };
  4517. // Updates stats interval
  4518. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4519. this.statsIntervalId = null;
  4520. this.statsIntervalMilis = statsInterval;
  4521. // Map of ssrcs to PeerStats
  4522. this.ssrc2stats = {};
  4523. }
  4524. module.exports = StatsCollector;
  4525. /**
  4526. * Stops stats updates.
  4527. */
  4528. StatsCollector.prototype.stop = function () {
  4529. if (this.audioLevelsIntervalId) {
  4530. clearInterval(this.audioLevelsIntervalId);
  4531. this.audioLevelsIntervalId = null;
  4532. }
  4533. if (this.statsIntervalId)
  4534. {
  4535. clearInterval(this.statsIntervalId);
  4536. this.statsIntervalId = null;
  4537. }
  4538. if(this.logStatsIntervalId)
  4539. {
  4540. clearInterval(this.logStatsIntervalId);
  4541. this.logStatsIntervalId = null;
  4542. }
  4543. if(this.gatherStatsIntervalId)
  4544. {
  4545. clearInterval(this.gatherStatsIntervalId);
  4546. this.gatherStatsIntervalId = null;
  4547. }
  4548. };
  4549. /**
  4550. * Callback passed to <tt>getStats</tt> method.
  4551. * @param error an error that occurred on <tt>getStats</tt> call.
  4552. */
  4553. StatsCollector.prototype.errorCallback = function (error)
  4554. {
  4555. logger.error("Get stats error", error);
  4556. this.stop();
  4557. };
  4558. /**
  4559. * Starts stats updates.
  4560. */
  4561. StatsCollector.prototype.start = function ()
  4562. {
  4563. var self = this;
  4564. this.audioLevelsIntervalId = setInterval(
  4565. function () {
  4566. // Interval updates
  4567. self.peerconnection.getStats(
  4568. function (report) {
  4569. var results = null;
  4570. if (!report || !report.result ||
  4571. typeof report.result != 'function') {
  4572. results = report;
  4573. }
  4574. else {
  4575. results = report.result();
  4576. }
  4577. //logger.error("Got interval report", results);
  4578. self.currentAudioLevelsReport = results;
  4579. self.processAudioLevelReport();
  4580. self.baselineAudioLevelsReport =
  4581. self.currentAudioLevelsReport;
  4582. },
  4583. self.errorCallback
  4584. );
  4585. },
  4586. self.audioLevelsIntervalMilis
  4587. );
  4588. // if (!this.config.disableStats && browserSupported) {
  4589. // this.statsIntervalId = setInterval(
  4590. // function () {
  4591. // // Interval updates
  4592. // self.peerconnection.getStats(
  4593. // function (report) {
  4594. // var results = null;
  4595. // if (!report || !report.result ||
  4596. // typeof report.result != 'function') {
  4597. // //firefox
  4598. // results = report;
  4599. // }
  4600. // else {
  4601. // //chrome
  4602. // results = report.result();
  4603. // }
  4604. // //logger.error("Got interval report", results);
  4605. // self.currentStatsReport = results;
  4606. // try {
  4607. // self.processStatsReport();
  4608. // }
  4609. // catch (e) {
  4610. // logger.error("Unsupported key:" + e, e);
  4611. // }
  4612. //
  4613. // self.baselineStatsReport = self.currentStatsReport;
  4614. // },
  4615. // self.errorCallback
  4616. // );
  4617. // },
  4618. // self.statsIntervalMilis
  4619. // );
  4620. // }
  4621. //
  4622. // if (this.config.logStats && browserSupported) {
  4623. // this.gatherStatsIntervalId = setInterval(
  4624. // function () {
  4625. // self.peerconnection.getStats(
  4626. // function (report) {
  4627. // self.addStatsToBeLogged(report.result());
  4628. // },
  4629. // function () {
  4630. // }
  4631. // );
  4632. // },
  4633. // this.GATHER_INTERVAL
  4634. // );
  4635. //
  4636. // this.logStatsIntervalId = setInterval(
  4637. // function() { self.logStats(); },
  4638. // this.LOG_INTERVAL);
  4639. // }
  4640. };
  4641. /**
  4642. * Converts the stats to the format used for logging, and saves the data in
  4643. * this.statsToBeLogged.
  4644. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4645. */
  4646. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4647. var self = this;
  4648. var num_records = this.statsToBeLogged.timestamps.length;
  4649. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4650. reports.map(function (report) {
  4651. if (!acceptReport(report.id, report.type))
  4652. return;
  4653. var stat = self.statsToBeLogged.stats[report.id];
  4654. if (!stat) {
  4655. stat = self.statsToBeLogged.stats[report.id] = {};
  4656. }
  4657. stat.type = report.type;
  4658. report.names().map(function (name) {
  4659. if (!acceptStat(report.id, report.type, name))
  4660. return;
  4661. var values = stat[name];
  4662. if (!values) {
  4663. values = stat[name] = [];
  4664. }
  4665. while (values.length < num_records) {
  4666. values.push(null);
  4667. }
  4668. values.push(report.stat(name));
  4669. });
  4670. });
  4671. };
  4672. //FIXME:
  4673. //StatsCollector.prototype.logStats = function () {
  4674. //
  4675. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4676. // return;
  4677. // // Reset the stats
  4678. // this.statsToBeLogged.stats = {};
  4679. // this.statsToBeLogged.timestamps = [];
  4680. //};
  4681. /**
  4682. * Stats processing logic.
  4683. */
  4684. StatsCollector.prototype.processStatsReport = function () {
  4685. if (!this.baselineStatsReport) {
  4686. return;
  4687. }
  4688. for (var idx in this.currentStatsReport) {
  4689. var now = this.currentStatsReport[idx];
  4690. try {
  4691. if (getStatValue(now, 'receiveBandwidth') ||
  4692. getStatValue(now, 'sendBandwidth')) {
  4693. this.conferenceStats.bandwidth = {
  4694. "download": Math.round(
  4695. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4696. "upload": Math.round(
  4697. (getStatValue(now, 'sendBandwidth')) / 1000)
  4698. };
  4699. }
  4700. }
  4701. catch(e){/*not supported*/}
  4702. if(now.type == 'googCandidatePair')
  4703. {
  4704. var ip, type, localIP, active;
  4705. try {
  4706. ip = getStatValue(now, 'remoteAddress');
  4707. type = getStatValue(now, "transportType");
  4708. localIP = getStatValue(now, "localAddress");
  4709. active = getStatValue(now, "activeConnection");
  4710. }
  4711. catch(e){/*not supported*/}
  4712. if(!ip || !type || !localIP || active != "true")
  4713. continue;
  4714. var addressSaved = false;
  4715. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4716. {
  4717. if(this.conferenceStats.transport[i].ip == ip &&
  4718. this.conferenceStats.transport[i].type == type &&
  4719. this.conferenceStats.transport[i].localip == localIP)
  4720. {
  4721. addressSaved = true;
  4722. }
  4723. }
  4724. if(addressSaved)
  4725. continue;
  4726. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4727. continue;
  4728. }
  4729. if(now.type == "candidatepair")
  4730. {
  4731. if(now.state == "succeeded")
  4732. continue;
  4733. var local = this.currentStatsReport[now.localCandidateId];
  4734. var remote = this.currentStatsReport[now.remoteCandidateId];
  4735. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4736. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4737. }
  4738. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4739. now.type != "inboundrtp") {
  4740. continue;
  4741. }
  4742. var before = this.baselineStatsReport[idx];
  4743. if (!before) {
  4744. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4745. continue;
  4746. }
  4747. var ssrc = getStatValue(now, 'ssrc');
  4748. if(!ssrc)
  4749. continue;
  4750. var ssrcStats = this.ssrc2stats[ssrc];
  4751. if (!ssrcStats) {
  4752. ssrcStats = new PeerStats();
  4753. this.ssrc2stats[ssrc] = ssrcStats;
  4754. }
  4755. var isDownloadStream = true;
  4756. var key = 'packetsReceived';
  4757. var packetsNow = getStatValue(now, key);
  4758. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4759. isDownloadStream = false;
  4760. key = 'packetsSent';
  4761. packetsNow = getStatValue(now, key);
  4762. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4763. console.warn("No packetsReceived nor packetsSent stat found");
  4764. continue;
  4765. }
  4766. }
  4767. if (!packetsNow || packetsNow < 0)
  4768. packetsNow = 0;
  4769. var packetsBefore = getStatValue(before, key);
  4770. if (!packetsBefore || packetsBefore < 0)
  4771. packetsBefore = 0;
  4772. var packetRate = packetsNow - packetsBefore;
  4773. if (!packetRate || packetRate < 0)
  4774. packetRate = 0;
  4775. var currentLoss = getStatValue(now, 'packetsLost');
  4776. if (!currentLoss || currentLoss < 0)
  4777. currentLoss = 0;
  4778. var previousLoss = getStatValue(before, 'packetsLost');
  4779. if (!previousLoss || previousLoss < 0)
  4780. previousLoss = 0;
  4781. var lossRate = currentLoss - previousLoss;
  4782. if (!lossRate || lossRate < 0)
  4783. lossRate = 0;
  4784. var packetsTotal = (packetRate + lossRate);
  4785. ssrcStats.setSsrcLoss(ssrc,
  4786. {"packetsTotal": packetsTotal,
  4787. "packetsLost": lossRate,
  4788. "isDownloadStream": isDownloadStream});
  4789. var bytesReceived = 0, bytesSent = 0;
  4790. if(getStatValue(now, "bytesReceived")) {
  4791. bytesReceived = getStatValue(now, "bytesReceived") -
  4792. getStatValue(before, "bytesReceived");
  4793. }
  4794. if (getStatValue(now, "bytesSent")) {
  4795. bytesSent = getStatValue(now, "bytesSent") -
  4796. getStatValue(before, "bytesSent");
  4797. }
  4798. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4799. if (bytesReceived <= 0 || time <= 0) {
  4800. bytesReceived = 0;
  4801. } else {
  4802. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4803. }
  4804. if (bytesSent <= 0 || time <= 0) {
  4805. bytesSent = 0;
  4806. } else {
  4807. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4808. }
  4809. ssrcStats.setSsrcBitrate(ssrc, {
  4810. "download": bytesReceived,
  4811. "upload": bytesSent});
  4812. var resolution = {height: null, width: null};
  4813. try {
  4814. if (getStatValue(now, "googFrameHeightReceived") &&
  4815. getStatValue(now, "googFrameWidthReceived")) {
  4816. resolution.height =
  4817. getStatValue(now, "googFrameHeightReceived");
  4818. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4819. }
  4820. else if (getStatValue(now, "googFrameHeightSent") &&
  4821. getStatValue(now, "googFrameWidthSent")) {
  4822. resolution.height = getStatValue(now, "googFrameHeightSent");
  4823. resolution.width = getStatValue(now, "googFrameWidthSent");
  4824. }
  4825. }
  4826. catch(e){/*not supported*/}
  4827. if (resolution.height && resolution.width) {
  4828. ssrcStats.setSsrcResolution(ssrc, resolution);
  4829. } else {
  4830. ssrcStats.setSsrcResolution(ssrc, null);
  4831. }
  4832. }
  4833. var self = this;
  4834. // Jid stats
  4835. var totalPackets = {download: 0, upload: 0};
  4836. var lostPackets = {download: 0, upload: 0};
  4837. var bitrateDownload = 0;
  4838. var bitrateUpload = 0;
  4839. var resolutions = {};
  4840. Object.keys(this.ssrc2stats).forEach(
  4841. function (jid) {
  4842. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4843. function (ssrc) {
  4844. var type = "upload";
  4845. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4846. type = "download";
  4847. totalPackets[type] +=
  4848. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4849. lostPackets[type] +=
  4850. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4851. }
  4852. );
  4853. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4854. function (ssrc) {
  4855. bitrateDownload +=
  4856. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4857. bitrateUpload +=
  4858. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4859. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4860. }
  4861. );
  4862. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4863. }
  4864. );
  4865. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4866. this.conferenceStats.packetLoss = {
  4867. total:
  4868. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4869. totalPackets.download + totalPackets.upload),
  4870. download:
  4871. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4872. upload:
  4873. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4874. };
  4875. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  4876. {
  4877. "bitrate": this.conferenceStats.bitrate,
  4878. "packetLoss": this.conferenceStats.packetLoss,
  4879. "bandwidth": this.conferenceStats.bandwidth,
  4880. "resolution": resolutions,
  4881. "transport": this.conferenceStats.transport
  4882. });
  4883. this.conferenceStats.transport = [];
  4884. };
  4885. /**
  4886. * Stats processing logic.
  4887. */
  4888. StatsCollector.prototype.processAudioLevelReport = function () {
  4889. if (!this.baselineAudioLevelsReport) {
  4890. return;
  4891. }
  4892. for (var idx in this.currentAudioLevelsReport) {
  4893. var now = this.currentAudioLevelsReport[idx];
  4894. //if we don't have "packetsReceived" this is local stream
  4895. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4896. continue;
  4897. }
  4898. var before = this.baselineAudioLevelsReport[idx];
  4899. if (!before) {
  4900. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4901. continue;
  4902. }
  4903. var ssrc = getStatValue(now, 'ssrc');
  4904. if (!ssrc) {
  4905. if((Date.now() - now.timestamp) < 3000)
  4906. logger.warn("No ssrc: ");
  4907. continue;
  4908. }
  4909. var ssrcStats = this.ssrc2stats[ssrc];
  4910. if (!ssrcStats) {
  4911. ssrcStats = new PeerStats();
  4912. this.ssrc2stats[ssrc] = ssrcStats;
  4913. }
  4914. // Audio level
  4915. var audioLevel = null;
  4916. try {
  4917. audioLevel = getStatValue(now, 'audioInputLevel');
  4918. if (!audioLevel)
  4919. audioLevel = getStatValue(now, 'audioOutputLevel');
  4920. }
  4921. catch(e) {/*not supported*/
  4922. logger.warn("Audio Levels are not available in the statistics.");
  4923. clearInterval(this.audioLevelsIntervalId);
  4924. return;
  4925. }
  4926. if (audioLevel) {
  4927. // TODO: can't find specs about what this value really is,
  4928. // but it seems to vary between 0 and around 32k.
  4929. audioLevel = audioLevel / 32767;
  4930. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4931. this.eventEmitter.emit(
  4932. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  4933. }
  4934. }
  4935. };
  4936. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4937. },{"../../service/statistics/Events":89,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],24:[function(require,module,exports){
  4938. /* global require, APP */
  4939. var LocalStats = require("./LocalStatsCollector.js");
  4940. var RTPStats = require("./RTPStatsCollector.js");
  4941. var EventEmitter = require("events");
  4942. var StatisticsEvents = require("../../service/statistics/Events");
  4943. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4944. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4945. //var CallStats = require("./CallStats");
  4946. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4947. //
  4948. //function onDisposeConference(onUnload) {
  4949. // CallStats.sendTerminateEvent();
  4950. // stopRemote();
  4951. // if(onUnload) {
  4952. // stopLocal();
  4953. // eventEmitter.removeAllListeners();
  4954. // }
  4955. //}
  4956. var eventEmitter = new EventEmitter();
  4957. function Statistics() {
  4958. this.rtpStats = null;
  4959. this.eventEmitter = new EventEmitter();
  4960. }
  4961. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4962. if (this.rtpStats) {
  4963. this.rtpStats.stop();
  4964. }
  4965. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4966. this.rtpStats.start();
  4967. }
  4968. Statistics.localStats = [];
  4969. Statistics.startLocalStats = function (stream, callback) {
  4970. var localStats = new LocalStats(stream, 200, callback);
  4971. this.localStats.push(localStats);
  4972. localStats.start();
  4973. }
  4974. Statistics.prototype.addAudioLevelListener = function(listener)
  4975. {
  4976. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  4977. }
  4978. Statistics.prototype.removeAudioLevelListener = function(listener)
  4979. {
  4980. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  4981. }
  4982. Statistics.prototype.dispose = function () {
  4983. Statistics.stopAllLocalStats();
  4984. this.stopRemote();
  4985. if(this.eventEmitter)
  4986. this.eventEmitter.removeAllListeners();
  4987. if(eventEmitter)
  4988. eventEmitter.removeAllListeners();
  4989. }
  4990. Statistics.stopAllLocalStats = function () {
  4991. for(var i = 0; i < this.localStats.length; i++)
  4992. this.localStats[i].stop();
  4993. this.localStats = [];
  4994. }
  4995. Statistics.stopLocalStats = function (stream) {
  4996. for(var i = 0; i < Statistics.localStats.length; i++)
  4997. if(Statistics.localStats[i].stream === stream){
  4998. var localStats = Statistics.localStats.splice(i, 1);
  4999. localStats.stop();
  5000. break;
  5001. }
  5002. }
  5003. Statistics.prototype.stopRemote = function () {
  5004. if (this.rtpStats) {
  5005. this.rtpStats.stop();
  5006. this.eventEmitter.emit(StatisticsEvents.STOP);
  5007. this.rtpStats = null;
  5008. }
  5009. };
  5010. /**
  5011. * Obtains audio level reported in the stats for specified peer.
  5012. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5013. * audio level.
  5014. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5015. * level.
  5016. * @returns {*} a float form 0 to 1 that represents current audio level or
  5017. * <tt>null</tt> if for any reason the value is not available
  5018. * at this time.
  5019. */
  5020. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5021. var peerStats = this.rtpStats.jid2stats[peerJid];
  5022. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5023. };
  5024. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5025. //
  5026. //var statistics = {
  5027. // /**
  5028. // * Indicates that this audio level is for local jid.
  5029. // * @type {string}
  5030. // */
  5031. // LOCAL_JID: 'local',
  5032. //
  5033. // addConnectionStatsListener: function(listener)
  5034. // {
  5035. // eventEmitter.on("statistics.connectionstats", listener);
  5036. // },
  5037. //
  5038. // removeConnectionStatsListener: function(listener)
  5039. // {
  5040. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5041. // },
  5042. //
  5043. //
  5044. // addRemoteStatsStopListener: function(listener)
  5045. // {
  5046. // eventEmitter.on("statistics.stop", listener);
  5047. // },
  5048. //
  5049. // removeRemoteStatsStopListener: function(listener)
  5050. // {
  5051. // eventEmitter.removeListener("statistics.stop", listener);
  5052. // },
  5053. //
  5054. //
  5055. // stopRemoteStatistics: function()
  5056. // {
  5057. // stopRemote();
  5058. // },
  5059. //
  5060. //// Already implemented with the constructor
  5061. // start: function () {
  5062. // APP.RTC.addStreamListener(onStreamCreated,
  5063. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5064. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5065. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5066. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5067. // startRemoteStats(event.peerconnection);
  5068. //// CallStats.init(event);
  5069. // });
  5070. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5071. //// CallStats.init(session);
  5072. //// });
  5073. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5074. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5075. //// CallStats.sendMuteEvent(mute, "audio");
  5076. //// });
  5077. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5078. //// CallStats.sendSetupFailedEvent();
  5079. //// });
  5080. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5081. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5082. //// CallStats.sendMuteEvent(mute, "video");
  5083. //// });
  5084. // }
  5085. //};
  5086. module.exports = Statistics;
  5087. },{"../../service/statistics/Events":89,"../../service/statistics/constants":90,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":44}],25:[function(require,module,exports){
  5088. /**
  5089. /**
  5090. * @const
  5091. */
  5092. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5093. /**
  5094. * Hexadecimal digits.
  5095. * @const
  5096. */
  5097. var HEX_DIGITS = '0123456789abcdef';
  5098. /**
  5099. * Generates random int within the range [min, max]
  5100. * @param min the minimum value for the generated number
  5101. * @param max the maximum value for the generated number
  5102. * @returns random int number
  5103. */
  5104. function randomInt(min, max) {
  5105. return Math.floor(Math.random() * (max - min + 1)) + min;
  5106. }
  5107. /**
  5108. * Get random element from array or string.
  5109. * @param {Array|string} arr source
  5110. * @returns array element or string character
  5111. */
  5112. function randomElement(arr) {
  5113. return arr[randomInt(0, arr.length - 1)];
  5114. }
  5115. /**
  5116. * Generate random alphanumeric string.
  5117. * @param {number} length expected string length
  5118. * @returns {string} random string of specified length
  5119. */
  5120. function randomAlphanumStr(length) {
  5121. var result = '';
  5122. for (var i = 0; i < length; i += 1) {
  5123. result += randomElement(ALPHANUM);
  5124. }
  5125. return result;
  5126. }
  5127. /**
  5128. * Exported interface.
  5129. */
  5130. var RandomUtil = {
  5131. /**
  5132. * Returns a random hex digit.
  5133. * @returns {*}
  5134. */
  5135. randomHexDigit: function() {
  5136. return randomElement(HEX_DIGITS);
  5137. },
  5138. /**
  5139. * Returns a random string of hex digits with length 'len'.
  5140. * @param len the length.
  5141. */
  5142. randomHexString: function (len) {
  5143. var ret = '';
  5144. while (len--) {
  5145. ret += this.randomHexDigit();
  5146. }
  5147. return ret;
  5148. },
  5149. randomElement: randomElement,
  5150. randomAlphanumStr: randomAlphanumStr
  5151. };
  5152. module.exports = RandomUtil;
  5153. },{}],26:[function(require,module,exports){
  5154. (function (__filename){
  5155. /* global Strophe, $, $pres, $iq, $msg */
  5156. /* jshint -W101,-W069 */
  5157. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5158. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5159. var Moderator = require("./moderator");
  5160. var EventEmitter = require("events");
  5161. var Recorder = require("./recording");
  5162. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  5163. var parser = {
  5164. packet2JSON: function (packet, nodes) {
  5165. var self = this;
  5166. $(packet).children().each(function (index) {
  5167. var tagName = $(this).prop("tagName");
  5168. var node = {
  5169. tagName: tagName
  5170. };
  5171. node.attributes = {};
  5172. $($(this)[0].attributes).each(function( index, attr ) {
  5173. node.attributes[ attr.name ] = attr.value;
  5174. });
  5175. var text = Strophe.getText($(this)[0]);
  5176. if (text) {
  5177. node.value = text;
  5178. }
  5179. node.children = [];
  5180. nodes.push(node);
  5181. self.packet2JSON($(this), node.children);
  5182. });
  5183. },
  5184. JSON2packet: function (nodes, packet) {
  5185. for(var i = 0; i < nodes.length; i++) {
  5186. var node = nodes[i];
  5187. if(!node || node === null){
  5188. continue;
  5189. }
  5190. packet.c(node.tagName, node.attributes);
  5191. if(node.value)
  5192. packet.t(node.value);
  5193. if(node.children)
  5194. this.JSON2packet(node.children, packet);
  5195. packet.up();
  5196. }
  5197. // packet.up();
  5198. }
  5199. };
  5200. /**
  5201. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5202. * @param pres the presence JSON
  5203. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5204. */
  5205. function filterNodeFromPresenceJSON(pres, nodeName){
  5206. var res = [];
  5207. for(var i = 0; i < pres.length; i++)
  5208. if(pres[i].tagName === nodeName)
  5209. res.push(pres[i]);
  5210. return res;
  5211. }
  5212. function ChatRoom(connection, jid, password, XMPP, options) {
  5213. this.eventEmitter = new EventEmitter();
  5214. this.xmpp = XMPP;
  5215. this.connection = connection;
  5216. this.roomjid = Strophe.getBareJidFromJid(jid);
  5217. this.myroomjid = jid;
  5218. this.password = password;
  5219. logger.info("Joined MUC as " + this.myroomjid);
  5220. this.members = {};
  5221. this.presMap = {};
  5222. this.presHandlers = {};
  5223. this.joined = false;
  5224. this.role = 'none';
  5225. this.focusMucJid = null;
  5226. this.bridgeIsDown = false;
  5227. this.options = options || {};
  5228. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5229. this.initPresenceMap();
  5230. this.session = null;
  5231. var self = this;
  5232. this.lastPresences = {};
  5233. this.phoneNumber = null;
  5234. this.phonePin = null;
  5235. }
  5236. ChatRoom.prototype.initPresenceMap = function () {
  5237. this.presMap['to'] = this.myroomjid;
  5238. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5239. this.presMap["nodes"] = [];
  5240. this.presMap["nodes"].push( {
  5241. "tagName": "user-agent",
  5242. "value": navigator.userAgent,
  5243. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5244. });
  5245. };
  5246. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5247. this.presMap["nodes"].push( {
  5248. "tagName": "devices",
  5249. "children": [
  5250. {
  5251. "tagName": "audio",
  5252. "value": devices.audio,
  5253. },
  5254. {
  5255. "tagName": "video",
  5256. "value": devices.video,
  5257. }
  5258. ]
  5259. });
  5260. };
  5261. ChatRoom.prototype.join = function (password, tokenPassword) {
  5262. if(password)
  5263. this.password = password;
  5264. var self = this;
  5265. this.moderator.allocateConferenceFocus(function()
  5266. {
  5267. self.sendPresence(tokenPassword);
  5268. }.bind(this));
  5269. };
  5270. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  5271. if (!this.presMap['to']) {
  5272. // Too early to send presence - not initialized
  5273. return;
  5274. }
  5275. var pres = $pres({to: this.presMap['to'] });
  5276. pres.c('x', {xmlns: this.presMap['xns']});
  5277. if (this.password) {
  5278. pres.c('password').t(this.password).up();
  5279. }
  5280. pres.up();
  5281. // Send XEP-0115 'c' stanza that contains our capabilities info
  5282. if (this.connection.caps) {
  5283. this.connection.caps.node = this.xmpp.options.clientNode;
  5284. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5285. }
  5286. if (tokenPassword) {
  5287. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  5288. .t(tokenPassword).up();
  5289. }
  5290. parser.JSON2packet(this.presMap.nodes, pres);
  5291. this.connection.send(pres);
  5292. };
  5293. ChatRoom.prototype.doLeave = function () {
  5294. logger.log("do leave", this.myroomjid);
  5295. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5296. this.presMap.length = 0;
  5297. this.connection.send(pres);
  5298. };
  5299. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5300. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5301. var getForm = $iq({type: 'get', to: this.roomjid})
  5302. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5303. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5304. var self = this;
  5305. this.connection.sendIQ(getForm, function (form) {
  5306. if (!$(form).find(
  5307. '>query>x[xmlns="jabber:x:data"]' +
  5308. '>field[var="muc#roomconfig_whois"]').length) {
  5309. logger.error('non-anonymous rooms not supported');
  5310. return;
  5311. }
  5312. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5313. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5314. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5315. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5316. .c('value')
  5317. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5318. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5319. .c('value').t('anyone').up().up();
  5320. self.connection.sendIQ(formSubmit);
  5321. }, function (error) {
  5322. logger.error("Error getting room configuration form");
  5323. });
  5324. };
  5325. ChatRoom.prototype.onPresence = function (pres) {
  5326. console.log(pres);
  5327. var from = pres.getAttribute('from');
  5328. // Parse roles.
  5329. var member = {};
  5330. member.show = $(pres).find('>show').text();
  5331. member.status = $(pres).find('>status').text();
  5332. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5333. member.affiliation = tmp.attr('affiliation');
  5334. member.role = tmp.attr('role');
  5335. // Focus recognition
  5336. member.jid = tmp.attr('jid');
  5337. member.isFocus = false;
  5338. if (member.jid
  5339. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5340. member.isFocus = true;
  5341. }
  5342. $(pres).find(">x").remove();
  5343. var nodes = [];
  5344. parser.packet2JSON(pres, nodes);
  5345. this.lastPresences[from] = nodes;
  5346. var jibri = null;
  5347. for(var i = 0; i < nodes.length; i++)
  5348. {
  5349. var node = nodes[i];
  5350. switch(node.tagName)
  5351. {
  5352. case "nick":
  5353. member.nick = node.value;
  5354. if(!member.isFocus) {
  5355. var displayName = !this.xmpp.options.displayJids
  5356. ? member.nick : Strophe.getResourceFromJid(from);
  5357. if (displayName && displayName.length > 0) {
  5358. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5359. }
  5360. logger.info("Display name: " + displayName, pres);
  5361. }
  5362. break;
  5363. case "userId":
  5364. member.id = node.value;
  5365. break;
  5366. case "email":
  5367. member.email = node.value;
  5368. break;
  5369. case "bridgeIsDown":
  5370. if(!this.bridgeIsDown) {
  5371. this.bridgeIsDown = true;
  5372. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5373. }
  5374. break;
  5375. case "jibri-recording-status":
  5376. var jibri = node;
  5377. break;
  5378. case "call-control":
  5379. console.log(pres);
  5380. var att = node.attributes;
  5381. if(!att)
  5382. break;
  5383. this.phoneNumber = att.phone || null;
  5384. this.phonePin = att.pin || null;
  5385. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  5386. break;
  5387. default :
  5388. this.processNode(node, from);
  5389. }
  5390. }
  5391. if (from == this.myroomjid) {
  5392. if (member.affiliation == 'owner')
  5393. if (this.role !== member.role) {
  5394. this.role = member.role;
  5395. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5396. }
  5397. if (!this.joined) {
  5398. this.joined = true;
  5399. console.log("(TIME) MUC joined:\t", window.performance.now());
  5400. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5401. }
  5402. } else if (this.members[from] === undefined) {
  5403. // new participant
  5404. this.members[from] = member;
  5405. logger.log('entered', from, member);
  5406. if (member.isFocus) {
  5407. this.focusMucJid = from;
  5408. if(!this.recording) {
  5409. this.recording = new Recorder(this.eventEmitter, this.connection,
  5410. this.focusMucJid);
  5411. if(this.lastJibri)
  5412. this.recording.handleJibriPresence(this.lastJibri);
  5413. }
  5414. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5415. }
  5416. else {
  5417. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5418. }
  5419. } else {
  5420. // Presence update for existing participant
  5421. // Watch role change:
  5422. if (this.members[from].role != member.role) {
  5423. this.members[from].role = member.role;
  5424. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5425. }
  5426. // store the new display name
  5427. if(member.displayName)
  5428. this.members[from].displayName = member.displayName;
  5429. }
  5430. if(!member.isFocus)
  5431. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5432. // Trigger status message update
  5433. if (member.status) {
  5434. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5435. }
  5436. if(jibri)
  5437. {
  5438. this.lastJibri = jibri;
  5439. if(this.recording)
  5440. this.recording.handleJibriPresence(jibri);
  5441. }
  5442. };
  5443. ChatRoom.prototype.processNode = function (node, from) {
  5444. if(this.presHandlers[node.tagName])
  5445. this.presHandlers[node.tagName](node, from);
  5446. };
  5447. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5448. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5449. msg.c('body', body).up();
  5450. if (nickname) {
  5451. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5452. }
  5453. this.connection.send(msg);
  5454. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5455. };
  5456. ChatRoom.prototype.setSubject = function (subject) {
  5457. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5458. msg.c('subject', subject);
  5459. this.connection.send(msg);
  5460. logger.log("topic changed to " + subject);
  5461. };
  5462. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5463. delete this.lastPresences[jid];
  5464. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5465. this.moderator.onMucMemberLeft(jid);
  5466. };
  5467. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5468. // room destroyed ?
  5469. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5470. '>destroy').length) {
  5471. var reason;
  5472. var reasonSelect = $(pres).find(
  5473. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5474. '>destroy>reason');
  5475. if (reasonSelect.length) {
  5476. reason = reasonSelect.text();
  5477. }
  5478. this.xmpp.disposeConference(false);
  5479. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5480. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5481. return true;
  5482. }
  5483. // Status code 110 indicates that this notification is "self-presence".
  5484. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5485. delete this.members[from];
  5486. this.onParticipantLeft(from);
  5487. }
  5488. // If the status code is 110 this means we're leaving and we would like
  5489. // to remove everyone else from our view, so we trigger the event.
  5490. else if (Object.keys(this.members).length > 1) {
  5491. for (var i in this.members) {
  5492. var member = this.members[i];
  5493. delete this.members[i];
  5494. this.onParticipantLeft(member);
  5495. }
  5496. }
  5497. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5498. if (this.myroomjid === from) {
  5499. this.xmpp.disposeConference(false);
  5500. this.eventEmitter.emit(XMPPEvents.KICKED);
  5501. }
  5502. }
  5503. };
  5504. ChatRoom.prototype.onMessage = function (msg, from) {
  5505. var nick =
  5506. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5507. .text() ||
  5508. Strophe.getResourceFromJid(from);
  5509. var txt = $(msg).find('>body').text();
  5510. var type = msg.getAttribute("type");
  5511. if (type == "error") {
  5512. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5513. $(msg).find('>text').text(), txt);
  5514. return true;
  5515. }
  5516. var subject = $(msg).find('>subject');
  5517. if (subject.length) {
  5518. var subjectText = subject.text();
  5519. if (subjectText || subjectText === "") {
  5520. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5521. logger.log("Subject is changed to " + subjectText);
  5522. }
  5523. }
  5524. // xep-0203 delay
  5525. var stamp = $(msg).find('>delay').attr('stamp');
  5526. if (!stamp) {
  5527. // or xep-0091 delay, UTC timestamp
  5528. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5529. if (stamp) {
  5530. // the format is CCYYMMDDThh:mm:ss
  5531. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5532. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5533. }
  5534. }
  5535. if (txt) {
  5536. logger.log('chat', nick, txt);
  5537. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5538. from, nick, txt, this.myroomjid, stamp);
  5539. }
  5540. };
  5541. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5542. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5543. logger.log('on password required', from);
  5544. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5545. } else if ($(pres).find(
  5546. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5547. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5548. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5549. // enter the room by replying with 'not-authorized'. This would
  5550. // result in reconnection from authorized domain.
  5551. // We're either missing Jicofo/Prosody config for anonymous
  5552. // domains or something is wrong.
  5553. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5554. } else {
  5555. logger.warn('onPresError ', pres);
  5556. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5557. }
  5558. } else {
  5559. logger.warn('onPresError ', pres);
  5560. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5561. }
  5562. };
  5563. ChatRoom.prototype.kick = function (jid) {
  5564. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5565. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5566. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5567. .c('reason').t('You have been kicked.').up().up().up();
  5568. this.connection.sendIQ(
  5569. kickIQ,
  5570. function (result) {
  5571. logger.log('Kick participant with jid: ', jid, result);
  5572. },
  5573. function (error) {
  5574. logger.log('Kick participant error: ', error);
  5575. });
  5576. };
  5577. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5578. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5579. var ob = this;
  5580. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5581. function (res) {
  5582. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5583. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5584. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5585. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5586. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5587. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5588. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5589. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5590. ob.connection.sendIQ(formsubmit,
  5591. onSuccess,
  5592. onError);
  5593. } else {
  5594. onNotSupported();
  5595. }
  5596. }, onError);
  5597. };
  5598. ChatRoom.prototype.addToPresence = function (key, values) {
  5599. values.tagName = key;
  5600. this.presMap["nodes"].push(values);
  5601. };
  5602. ChatRoom.prototype.removeFromPresence = function (key) {
  5603. for(var i = 0; i < this.presMap.nodes.length; i++)
  5604. {
  5605. if(key === this.presMap.nodes[i].tagName)
  5606. this.presMap.nodes.splice(i, 1);
  5607. }
  5608. };
  5609. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5610. this.presHandlers[name] = handler;
  5611. };
  5612. ChatRoom.prototype.removePresenceListener = function (name) {
  5613. delete this.presHandlers[name];
  5614. };
  5615. ChatRoom.prototype.isModerator = function () {
  5616. return this.role === 'moderator';
  5617. };
  5618. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5619. if (this.members[peerJid]) {
  5620. return this.members[peerJid].role;
  5621. }
  5622. return null;
  5623. };
  5624. ChatRoom.prototype.setJingleSession = function(session){
  5625. this.session = session;
  5626. this.session.room = this;
  5627. };
  5628. ChatRoom.prototype.removeStream = function (stream, callback) {
  5629. if(!this.session)
  5630. return;
  5631. this.session.removeStream(stream, callback);
  5632. };
  5633. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5634. if(this.session) {
  5635. // FIXME: will block switchInProgress on true value in case of exception
  5636. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5637. } else {
  5638. // We are done immediately
  5639. logger.warn("No conference handler or conference not started yet");
  5640. callback();
  5641. }
  5642. };
  5643. ChatRoom.prototype.addStream = function (stream, callback) {
  5644. if(this.session) {
  5645. // FIXME: will block switchInProgress on true value in case of exception
  5646. this.session.addStream(stream, callback);
  5647. } else {
  5648. // We are done immediately
  5649. logger.warn("No conference handler or conference not started yet");
  5650. callback();
  5651. }
  5652. };
  5653. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5654. var self = this;
  5655. var localCallback = function (mute) {
  5656. self.sendVideoInfoPresence(mute);
  5657. if(callback)
  5658. callback(mute);
  5659. };
  5660. if(this.session)
  5661. {
  5662. this.session.setVideoMute(
  5663. mute, localCallback, options);
  5664. }
  5665. else {
  5666. localCallback(mute);
  5667. }
  5668. };
  5669. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5670. //This will be for remote streams only
  5671. // if (this.forceMuted && !mute) {
  5672. // logger.info("Asking focus for unmute");
  5673. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5674. // // FIXME: wait for result before resetting muted status
  5675. // this.forceMuted = false;
  5676. // }
  5677. return this.sendAudioInfoPresence(mute, callback);
  5678. };
  5679. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5680. this.removeFromPresence("audiomuted");
  5681. this.addToPresence("audiomuted",
  5682. {attributes:
  5683. {"audions": "http://jitsi.org/jitmeet/audio"},
  5684. value: mute.toString()});
  5685. };
  5686. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5687. this.addAudioInfoToPresence(mute);
  5688. if(this.connection) {
  5689. this.sendPresence();
  5690. }
  5691. if(callback)
  5692. callback();
  5693. };
  5694. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5695. this.removeFromPresence("videomuted");
  5696. this.addToPresence("videomuted",
  5697. {attributes:
  5698. {"videons": "http://jitsi.org/jitmeet/video"},
  5699. value: mute.toString()});
  5700. };
  5701. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5702. this.addVideoInfoToPresence(mute);
  5703. if(!this.connection)
  5704. return;
  5705. this.sendPresence();
  5706. };
  5707. ChatRoom.prototype.addListener = function(type, listener) {
  5708. this.eventEmitter.on(type, listener);
  5709. };
  5710. ChatRoom.prototype.removeListener = function (type, listener) {
  5711. this.eventEmitter.removeListener(type, listener);
  5712. };
  5713. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5714. if(this.lastPresences[data.peerjid])
  5715. {
  5716. var pres = this.lastPresences[data.peerjid];
  5717. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5718. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5719. data.videomuted = ((videomuted.length > 0
  5720. && videomuted[0]
  5721. && videomuted[0]["value"] === "true")? true : false);
  5722. data.audiomuted = ((audiomuted.length > 0
  5723. && audiomuted[0]
  5724. && audiomuted[0]["value"] === "true")? true : false);
  5725. }
  5726. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5727. };
  5728. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5729. if (!this.session)
  5730. return null;
  5731. return this.session.getSsrcOwner(ssrc);
  5732. };
  5733. /**
  5734. * Returns true if the recording is supproted and false if not.
  5735. */
  5736. ChatRoom.prototype.isRecordingSupported = function () {
  5737. if(this.recording)
  5738. return this.recording.isSupported();
  5739. return false;
  5740. };
  5741. /**
  5742. * Returns null if the recording is not supported, "on" if the recording started
  5743. * and "off" if the recording is not started.
  5744. */
  5745. ChatRoom.prototype.getRecordingState = function () {
  5746. if(this.recording)
  5747. return this.recording.getState();
  5748. return "off";
  5749. }
  5750. /**
  5751. * Returns the url of the recorded video.
  5752. */
  5753. ChatRoom.prototype.getRecordingURL = function () {
  5754. if(this.recording)
  5755. return this.recording.getURL();
  5756. return null;
  5757. }
  5758. /**
  5759. * Starts/stops the recording
  5760. * @param token token for authentication
  5761. */
  5762. ChatRoom.prototype.toggleRecording = function (token) {
  5763. if(this.recording)
  5764. return this.recording.toggleRecording(token);
  5765. return new Promise(function(resolve, reject){
  5766. reject(new Error("The conference is not created yet!"))});
  5767. }
  5768. /**
  5769. * Dials a number.
  5770. * @param number the number
  5771. */
  5772. ChatRoom.prototype.dial = function (number) {
  5773. return this.connection.rayo.dial(number, "fromnumber",
  5774. Strophe.getNodeFromJid(this.myroomjid), this.password,
  5775. this.focusMucJid);
  5776. }
  5777. /**
  5778. * Hangup an existing call
  5779. */
  5780. ChatRoom.prototype.hangup = function () {
  5781. return this.connection.rayo.hangup();
  5782. }
  5783. /**
  5784. * Returns the phone number for joining the conference.
  5785. */
  5786. ChatRoom.prototype.getPhoneNumber = function () {
  5787. return this.phoneNumber;
  5788. }
  5789. /**
  5790. * Returns the pin for joining the conference with phone.
  5791. */
  5792. ChatRoom.prototype.getPhonePin = function () {
  5793. return this.phonePin;
  5794. }
  5795. module.exports = ChatRoom;
  5796. }).call(this,"/modules/xmpp/ChatRoom.js")
  5797. },{"../../service/xmpp/XMPPEvents":91,"./moderator":34,"./recording":35,"events":44,"jitsi-meet-logger":48}],27:[function(require,module,exports){
  5798. (function (__filename){
  5799. /*
  5800. * JingleSession provides an API to manage a single Jingle session. We will
  5801. * have different implementations depending on the underlying interface used
  5802. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5803. */
  5804. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5805. function JingleSession(me, sid, connection, service, eventEmitter) {
  5806. /**
  5807. * Our JID.
  5808. */
  5809. this.me = me;
  5810. /**
  5811. * The Jingle session identifier.
  5812. */
  5813. this.sid = sid;
  5814. /**
  5815. * The XMPP connection.
  5816. */
  5817. this.connection = connection;
  5818. /**
  5819. * The XMPP service.
  5820. */
  5821. this.service = service;
  5822. /**
  5823. * The event emitter.
  5824. */
  5825. this.eventEmitter = eventEmitter;
  5826. /**
  5827. * Whether to use dripping or not. Dripping is sending trickle candidates
  5828. * not one-by-one.
  5829. * Note: currently we do not support 'false'.
  5830. */
  5831. this.usedrip = true;
  5832. /**
  5833. * When dripping is used, stores ICE candidates which are to be sent.
  5834. */
  5835. this.drip_container = [];
  5836. // Media constraints. Is this WebRTC only?
  5837. this.media_constraints = null;
  5838. // ICE servers config (RTCConfiguration?).
  5839. this.ice_config = {};
  5840. // The chat room instance associated with the session.
  5841. this.room = null;
  5842. }
  5843. /**
  5844. * Prepares this object to initiate a session.
  5845. * @param peerjid the JID of the remote peer.
  5846. * @param isInitiator whether we will be the Jingle initiator.
  5847. * @param media_constraints
  5848. * @param ice_config
  5849. */
  5850. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5851. media_constraints, ice_config) {
  5852. this.media_constraints = media_constraints;
  5853. this.ice_config = ice_config;
  5854. if (this.state !== null) {
  5855. logger.error('attempt to initiate on session ' + this.sid +
  5856. 'in state ' + this.state);
  5857. return;
  5858. }
  5859. this.state = 'pending';
  5860. this.initiator = isInitiator ? this.me : peerjid;
  5861. this.responder = !isInitiator ? this.me : peerjid;
  5862. this.peerjid = peerjid;
  5863. this.doInitialize();
  5864. };
  5865. /**
  5866. * Finishes initialization.
  5867. */
  5868. JingleSession.prototype.doInitialize = function() {};
  5869. /**
  5870. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5871. * Note: currently only used on transport-info
  5872. */
  5873. JingleSession.prototype.addIceCandidates = function(contents) {};
  5874. /**
  5875. * Handles an 'add-source' event.
  5876. *
  5877. * @param contents an array of Jingle 'content' elements.
  5878. */
  5879. JingleSession.prototype.addSources = function(contents) {};
  5880. /**
  5881. * Handles a 'remove-source' event.
  5882. *
  5883. * @param contents an array of Jingle 'content' elements.
  5884. */
  5885. JingleSession.prototype.removeSources = function(contents) {};
  5886. /**
  5887. * Terminates this Jingle session (stops sending media and closes the streams?)
  5888. */
  5889. JingleSession.prototype.terminate = function() {};
  5890. /**
  5891. * Sends a Jingle session-terminate message to the peer and terminates the
  5892. * session.
  5893. * @param reason
  5894. * @param text
  5895. */
  5896. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5897. /**
  5898. * Handles an offer from the remote peer (prepares to accept a session).
  5899. * @param jingle the 'jingle' XML element.
  5900. */
  5901. JingleSession.prototype.setOffer = function(jingle) {};
  5902. /**
  5903. * Handles an answer from the remote peer (prepares to accept a session).
  5904. * @param jingle the 'jingle' XML element.
  5905. */
  5906. JingleSession.prototype.setAnswer = function(jingle) {};
  5907. module.exports = JingleSession;
  5908. }).call(this,"/modules/xmpp/JingleSession.js")
  5909. },{"jitsi-meet-logger":48}],28:[function(require,module,exports){
  5910. (function (__filename){
  5911. /* jshint -W117 */
  5912. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5913. var JingleSession = require("./JingleSession");
  5914. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5915. var SDPDiffer = require("./SDPDiffer");
  5916. var SDPUtil = require("./SDPUtil");
  5917. var SDP = require("./SDP");
  5918. var async = require("async");
  5919. var transform = require("sdp-transform");
  5920. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5921. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5922. var SSRCReplacement = require("./LocalSSRCReplacement");
  5923. var RTC = require("../RTC/RTC");
  5924. // Jingle stuff
  5925. function JingleSessionPC(me, sid, connection, service) {
  5926. JingleSession.call(this, me, sid, connection, service);
  5927. this.initiator = null;
  5928. this.responder = null;
  5929. this.peerjid = null;
  5930. this.state = null;
  5931. this.localSDP = null;
  5932. this.remoteSDP = null;
  5933. this.relayedStreams = [];
  5934. this.usetrickle = true;
  5935. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5936. this.hadstuncandidate = false;
  5937. this.hadturncandidate = false;
  5938. this.lasticecandidate = false;
  5939. this.statsinterval = null;
  5940. this.reason = null;
  5941. this.addssrc = [];
  5942. this.removessrc = [];
  5943. this.pendingop = null;
  5944. this.switchstreams = false;
  5945. this.addingStreams = false;
  5946. this.wait = true;
  5947. /**
  5948. * A map that stores SSRCs of local streams
  5949. * @type {{}} maps media type('audio' or 'video') to SSRC number
  5950. */
  5951. this.localStreamsSSRC = {};
  5952. this.ssrcOwners = {};
  5953. this.ssrcVideoTypes = {};
  5954. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  5955. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  5956. /**
  5957. * The indicator which determines whether the (local) video has been muted
  5958. * in response to a user command in contrast to an automatic decision made
  5959. * by the application logic.
  5960. */
  5961. this.videoMuteByUser = false;
  5962. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5963. // We start with the queue paused. We resume it when the signaling state is
  5964. // stable and the ice connection state is connected.
  5965. this.modifySourcesQueue.pause();
  5966. }
  5967. //XXX this is badly broken...
  5968. JingleSessionPC.prototype = JingleSession.prototype;
  5969. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5970. JingleSessionPC.prototype.setOffer = function(offer) {
  5971. this.setRemoteDescription(offer, 'offer');
  5972. };
  5973. JingleSessionPC.prototype.setAnswer = function(answer) {
  5974. this.setRemoteDescription(answer, 'answer');
  5975. };
  5976. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5977. var signalingState = this.peerconnection.signalingState;
  5978. var iceConnectionState = this.peerconnection.iceConnectionState;
  5979. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5980. this.modifySourcesQueue.resume();
  5981. } else {
  5982. this.modifySourcesQueue.pause();
  5983. }
  5984. };
  5985. JingleSessionPC.prototype.doInitialize = function () {
  5986. var self = this;
  5987. this.hadstuncandidate = false;
  5988. this.hadturncandidate = false;
  5989. this.lasticecandidate = false;
  5990. // True if reconnect is in progress
  5991. this.isreconnect = false;
  5992. // Set to true if the connection was ever stable
  5993. this.wasstable = false;
  5994. this.peerconnection = new TraceablePeerConnection(
  5995. this.connection.jingle.ice_config,
  5996. RTC.getPCConstraints(),
  5997. this);
  5998. this.peerconnection.onicecandidate = function (event) {
  5999. var protocol;
  6000. if (event && event.candidate) {
  6001. protocol = (typeof event.candidate.protocol === 'string')
  6002. ? event.candidate.protocol.toLowerCase() : '';
  6003. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6004. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6005. return;
  6006. }
  6007. }
  6008. self.sendIceCandidate(event.candidate);
  6009. };
  6010. this.peerconnection.onaddstream = function (event) {
  6011. if (event.stream.id !== 'default') {
  6012. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  6013. self.remoteStreamAdded(event);
  6014. } else {
  6015. // This is a recvonly stream. Clients that implement Unified Plan,
  6016. // such as Firefox use recvonly "streams/channels/tracks" for
  6017. // receiving remote stream/tracks, as opposed to Plan B where there
  6018. // are only 3 channels: audio, video and data.
  6019. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  6020. }
  6021. };
  6022. this.peerconnection.onremovestream = function (event) {
  6023. // Remove the stream from remoteStreams
  6024. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  6025. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  6026. };
  6027. this.peerconnection.onsignalingstatechange = function (event) {
  6028. if (!(self && self.peerconnection)) return;
  6029. if (self.peerconnection.signalingState === 'stable') {
  6030. self.wasstable = true;
  6031. }
  6032. self.updateModifySourcesQueue();
  6033. };
  6034. /**
  6035. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6036. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6037. * RTCPeerConnection.iceConnectionState changes.
  6038. *
  6039. * @param event the event containing information about the change
  6040. */
  6041. this.peerconnection.oniceconnectionstatechange = function (event) {
  6042. if (!(self && self.peerconnection)) return;
  6043. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6044. ":\t", window.performance.now());
  6045. self.updateModifySourcesQueue();
  6046. switch (self.peerconnection.iceConnectionState) {
  6047. case 'connected':
  6048. // Informs interested parties that the connection has been restored.
  6049. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6050. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6051. self.isreconnect = false;
  6052. break;
  6053. case 'disconnected':
  6054. self.isreconnect = true;
  6055. // Informs interested parties that the connection has been interrupted.
  6056. if (self.wasstable)
  6057. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6058. break;
  6059. case 'failed':
  6060. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6061. break;
  6062. }
  6063. onIceConnectionStateChange(self.sid, self);
  6064. };
  6065. this.peerconnection.onnegotiationneeded = function (event) {
  6066. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6067. };
  6068. this.relayedStreams.forEach(function(stream) {
  6069. self.peerconnection.addStream(stream);
  6070. });
  6071. };
  6072. function onIceConnectionStateChange(sid, session) {
  6073. switch (session.peerconnection.iceConnectionState) {
  6074. case 'checking':
  6075. session.timeChecking = (new Date()).getTime();
  6076. session.firstconnect = true;
  6077. break;
  6078. case 'completed': // on caller side
  6079. case 'connected':
  6080. if (session.firstconnect) {
  6081. session.firstconnect = false;
  6082. var metadata = {};
  6083. metadata.setupTime
  6084. = (new Date()).getTime() - session.timeChecking;
  6085. session.peerconnection.getStats(function (res) {
  6086. if(res && res.result) {
  6087. res.result().forEach(function (report) {
  6088. if (report.type == 'googCandidatePair' &&
  6089. report.stat('googActiveConnection') == 'true') {
  6090. metadata.localCandidateType
  6091. = report.stat('googLocalCandidateType');
  6092. metadata.remoteCandidateType
  6093. = report.stat('googRemoteCandidateType');
  6094. // log pair as well so we can get nice pie
  6095. // charts
  6096. metadata.candidatePair
  6097. = report.stat('googLocalCandidateType') +
  6098. ';' +
  6099. report.stat('googRemoteCandidateType');
  6100. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6101. {
  6102. metadata.ipv6 = true;
  6103. }
  6104. }
  6105. });
  6106. }
  6107. });
  6108. }
  6109. break;
  6110. }
  6111. }
  6112. JingleSessionPC.prototype.accept = function () {
  6113. this.state = 'active';
  6114. var pranswer = this.peerconnection.localDescription;
  6115. if (!pranswer || pranswer.type != 'pranswer') {
  6116. return;
  6117. }
  6118. logger.log('going from pranswer to answer');
  6119. if (this.usetrickle) {
  6120. // remove candidates already sent from session-accept
  6121. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6122. for (var i = 0; i < lines.length; i++) {
  6123. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6124. }
  6125. }
  6126. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6127. // FIXME: change any inactive to sendrecv or whatever they were originally
  6128. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6129. }
  6130. var prsdp = new SDP(pranswer.sdp);
  6131. if (self.webrtcIceTcpDisable) {
  6132. prsdp.removeTcpCandidates = true;
  6133. }
  6134. if (self.webrtcIceUdpDisable) {
  6135. prsdp.removeUdpCandidates = true;
  6136. }
  6137. var accept = $iq({to: this.peerjid,
  6138. type: 'set'})
  6139. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6140. action: 'session-accept',
  6141. initiator: this.initiator,
  6142. responder: this.responder,
  6143. sid: this.sid });
  6144. // FIXME why do we generate session-accept in 3 different places ?
  6145. prsdp.toJingle(
  6146. accept,
  6147. this.initiator == this.me ? 'initiator' : 'responder');
  6148. var sdp = this.peerconnection.localDescription.sdp;
  6149. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6150. // FIXME: change any inactive to sendrecv or whatever they were originally
  6151. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6152. }
  6153. var self = this;
  6154. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6155. function () {
  6156. //logger.log('setLocalDescription success');
  6157. self.setLocalDescription();
  6158. SSRCReplacement.processSessionInit(accept);
  6159. self.connection.sendIQ(accept,
  6160. function () {
  6161. var ack = {};
  6162. ack.source = 'answer';
  6163. $(document).trigger('ack.jingle', [self.sid, ack]);
  6164. },
  6165. function (stanza) {
  6166. var error = ($(stanza).find('error').length) ? {
  6167. code: $(stanza).find('error').attr('code'),
  6168. reason: $(stanza).find('error :first')[0].tagName
  6169. }:{};
  6170. error.source = 'answer';
  6171. JingleSessionPC.onJingleError(self.sid, error);
  6172. },
  6173. 10000);
  6174. },
  6175. function (e) {
  6176. logger.error('setLocalDescription failed', e);
  6177. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6178. }
  6179. );
  6180. };
  6181. JingleSessionPC.prototype.terminate = function (reason) {
  6182. this.state = 'ended';
  6183. this.reason = reason;
  6184. this.peerconnection.close();
  6185. if (this.statsinterval !== null) {
  6186. window.clearInterval(this.statsinterval);
  6187. this.statsinterval = null;
  6188. }
  6189. };
  6190. JingleSessionPC.prototype.active = function () {
  6191. return this.state == 'active';
  6192. };
  6193. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6194. var self = this;
  6195. if (candidate && !this.lasticecandidate) {
  6196. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6197. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6198. if (!(ice && jcand)) {
  6199. logger.error('failed to get ice && jcand');
  6200. return;
  6201. }
  6202. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6203. if (jcand.type === 'srflx') {
  6204. this.hadstuncandidate = true;
  6205. } else if (jcand.type === 'relay') {
  6206. this.hadturncandidate = true;
  6207. }
  6208. if (this.usetrickle) {
  6209. if (this.usedrip) {
  6210. if (this.drip_container.length === 0) {
  6211. // start 20ms callout
  6212. window.setTimeout(function () {
  6213. if (self.drip_container.length === 0) return;
  6214. self.sendIceCandidates(self.drip_container);
  6215. self.drip_container = [];
  6216. }, 20);
  6217. }
  6218. this.drip_container.push(candidate);
  6219. return;
  6220. } else {
  6221. self.sendIceCandidate([candidate]);
  6222. }
  6223. }
  6224. } else {
  6225. //logger.log('sendIceCandidate: last candidate.');
  6226. if (!this.usetrickle) {
  6227. //logger.log('should send full offer now...');
  6228. //FIXME why do we generate session-accept in 3 different places ?
  6229. var init = $iq({to: this.peerjid,
  6230. type: 'set'})
  6231. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6232. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6233. initiator: this.initiator,
  6234. sid: this.sid});
  6235. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6236. if (self.webrtcIceTcpDisable) {
  6237. this.localSDP.removeTcpCandidates = true;
  6238. }
  6239. if (self.webrtcIceUdpDisable) {
  6240. this.localSDP.removeUdpCandidates = true;
  6241. }
  6242. var sendJingle = function (ssrc) {
  6243. if(!ssrc)
  6244. ssrc = {};
  6245. self.localSDP.toJingle(
  6246. init,
  6247. self.initiator == self.me ? 'initiator' : 'responder',
  6248. ssrc);
  6249. SSRCReplacement.processSessionInit(init);
  6250. self.connection.sendIQ(init,
  6251. function () {
  6252. //logger.log('session initiate ack');
  6253. var ack = {};
  6254. ack.source = 'offer';
  6255. $(document).trigger('ack.jingle', [self.sid, ack]);
  6256. },
  6257. function (stanza) {
  6258. self.state = 'error';
  6259. self.peerconnection.close();
  6260. var error = ($(stanza).find('error').length) ? {
  6261. code: $(stanza).find('error').attr('code'),
  6262. reason: $(stanza).find('error :first')[0].tagName,
  6263. }:{};
  6264. error.source = 'offer';
  6265. JingleSessionPC.onJingleError(self.sid, error);
  6266. },
  6267. 10000);
  6268. };
  6269. sendJingle();
  6270. }
  6271. this.lasticecandidate = true;
  6272. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6273. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6274. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6275. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6276. }
  6277. }
  6278. };
  6279. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6280. logger.log('sendIceCandidates', candidates);
  6281. var cand = $iq({to: this.peerjid, type: 'set'})
  6282. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6283. action: 'transport-info',
  6284. initiator: this.initiator,
  6285. sid: this.sid});
  6286. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6287. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6288. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6289. if (cands.length > 0) {
  6290. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6291. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6292. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6293. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6294. }).c('transport', ice);
  6295. for (var i = 0; i < cands.length; i++) {
  6296. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6297. }
  6298. // add fingerprint
  6299. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6300. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6301. tmp.required = true;
  6302. cand.c(
  6303. 'fingerprint',
  6304. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6305. .t(tmp.fingerprint);
  6306. delete tmp.fingerprint;
  6307. cand.attrs(tmp);
  6308. cand.up();
  6309. }
  6310. cand.up(); // transport
  6311. cand.up(); // content
  6312. }
  6313. }
  6314. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6315. //logger.log('was this the last candidate', this.lasticecandidate);
  6316. this.connection.sendIQ(cand,
  6317. function () {
  6318. var ack = {};
  6319. ack.source = 'transportinfo';
  6320. $(document).trigger('ack.jingle', [this.sid, ack]);
  6321. },
  6322. function (stanza) {
  6323. var error = ($(stanza).find('error').length) ? {
  6324. code: $(stanza).find('error').attr('code'),
  6325. reason: $(stanza).find('error :first')[0].tagName,
  6326. }:{};
  6327. error.source = 'transportinfo';
  6328. JingleSessionPC.onJingleError(this.sid, error);
  6329. },
  6330. 10000);
  6331. };
  6332. JingleSessionPC.prototype.sendOffer = function () {
  6333. //logger.log('sendOffer...');
  6334. var self = this;
  6335. this.peerconnection.createOffer(function (sdp) {
  6336. self.createdOffer(sdp);
  6337. },
  6338. function (e) {
  6339. logger.error('createOffer failed', e);
  6340. },
  6341. this.media_constraints
  6342. );
  6343. };
  6344. // FIXME createdOffer is never used in jitsi-meet
  6345. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6346. //logger.log('createdOffer', sdp);
  6347. var self = this;
  6348. this.localSDP = new SDP(sdp.sdp);
  6349. //this.localSDP.mangle();
  6350. var sendJingle = function () {
  6351. var init = $iq({to: this.peerjid,
  6352. type: 'set'})
  6353. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6354. action: 'session-initiate',
  6355. initiator: this.initiator,
  6356. sid: this.sid});
  6357. self.localSDP.toJingle(
  6358. init,
  6359. this.initiator == this.me ? 'initiator' : 'responder');
  6360. SSRCReplacement.processSessionInit(init);
  6361. self.connection.sendIQ(init,
  6362. function () {
  6363. var ack = {};
  6364. ack.source = 'offer';
  6365. $(document).trigger('ack.jingle', [self.sid, ack]);
  6366. },
  6367. function (stanza) {
  6368. self.state = 'error';
  6369. self.peerconnection.close();
  6370. var error = ($(stanza).find('error').length) ? {
  6371. code: $(stanza).find('error').attr('code'),
  6372. reason: $(stanza).find('error :first')[0].tagName,
  6373. }:{};
  6374. error.source = 'offer';
  6375. JingleSessionPC.onJingleError(self.sid, error);
  6376. },
  6377. 10000);
  6378. }
  6379. sdp.sdp = this.localSDP.raw;
  6380. this.peerconnection.setLocalDescription(sdp,
  6381. function () {
  6382. if(self.usetrickle)
  6383. {
  6384. sendJingle();
  6385. }
  6386. self.setLocalDescription();
  6387. //logger.log('setLocalDescription success');
  6388. },
  6389. function (e) {
  6390. logger.error('setLocalDescription failed', e);
  6391. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6392. }
  6393. );
  6394. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6395. for (var i = 0; i < cands.length; i++) {
  6396. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6397. if (cand.type == 'srflx') {
  6398. this.hadstuncandidate = true;
  6399. } else if (cand.type == 'relay') {
  6400. this.hadturncandidate = true;
  6401. }
  6402. }
  6403. };
  6404. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6405. var self = this;
  6406. $(contents).each(function (idx, content) {
  6407. var name = $(content).attr('name');
  6408. var mediaType = this.getAttribute('name');
  6409. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6410. ssrcs.each(function () {
  6411. var ssrc = this.getAttribute('ssrc');
  6412. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6413. function () {
  6414. var owner = this.getAttribute('owner');
  6415. self.ssrcOwners[ssrc] = owner;
  6416. }
  6417. );
  6418. });
  6419. });
  6420. };
  6421. /**
  6422. * Returns the SSRC of local audio stream.
  6423. * @param mediaType 'audio' or 'video' media type
  6424. * @returns {*} the SSRC number of local audio or video stream.
  6425. */
  6426. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6427. return this.localStreamsSSRC[mediaType];
  6428. };
  6429. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6430. return this.ssrcOwners[ssrc];
  6431. };
  6432. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6433. //logger.log('setting remote description... ', desctype);
  6434. this.remoteSDP = new SDP('');
  6435. if (self.webrtcIceTcpDisable) {
  6436. this.remoteSDP.removeTcpCandidates = true;
  6437. }
  6438. if (self.webrtcIceUdpDisable) {
  6439. this.remoteSDP.removeUdpCandidates = true;
  6440. }
  6441. this.remoteSDP.fromJingle(elem);
  6442. this.readSsrcInfo($(elem).find(">content"));
  6443. if (this.peerconnection.remoteDescription) {
  6444. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6445. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6446. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6447. for (var i = 0; i < pranswer.media.length; i++) {
  6448. // make sure we have ice ufrag and pwd
  6449. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6450. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6451. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6452. } else {
  6453. logger.warn('no ice ufrag?');
  6454. }
  6455. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6456. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6457. } else {
  6458. logger.warn('no ice pwd?');
  6459. }
  6460. }
  6461. // copy over candidates
  6462. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6463. for (var j = 0; j < lines.length; j++) {
  6464. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6465. }
  6466. }
  6467. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6468. }
  6469. }
  6470. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6471. this.peerconnection.setRemoteDescription(remotedesc,
  6472. function () {
  6473. //logger.log('setRemoteDescription success');
  6474. },
  6475. function (e) {
  6476. logger.error('setRemoteDescription error', e);
  6477. JingleSessionPC.onJingleFatalError(self, e);
  6478. }
  6479. );
  6480. };
  6481. /**
  6482. * Adds remote ICE candidates to this Jingle session.
  6483. * @param elem An array of Jingle "content" elements?
  6484. */
  6485. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6486. var self = this;
  6487. if (this.peerconnection.signalingState == 'closed') {
  6488. return;
  6489. }
  6490. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6491. logger.log('trickle ice candidate arriving before session accept...');
  6492. // create a PRANSWER for setRemoteDescription
  6493. if (!this.remoteSDP) {
  6494. var cobbled = 'v=0\r\n' +
  6495. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6496. 's=-\r\n' +
  6497. 't=0 0\r\n';
  6498. // first, take some things from the local description
  6499. for (var i = 0; i < this.localSDP.media.length; i++) {
  6500. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6501. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6502. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6503. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6504. }
  6505. cobbled += 'a=inactive\r\n';
  6506. }
  6507. this.remoteSDP = new SDP(cobbled);
  6508. }
  6509. // then add things like ice and dtls from remote candidate
  6510. elem.each(function () {
  6511. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6512. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6513. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6514. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6515. var tmp = $(this).find('transport');
  6516. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6517. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6518. tmp = $(this).find('transport>fingerprint');
  6519. if (tmp.length) {
  6520. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6521. } else {
  6522. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6523. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6524. }
  6525. break;
  6526. }
  6527. }
  6528. }
  6529. });
  6530. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6531. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6532. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6533. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6534. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6535. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6536. }).length == this.remoteSDP.media.length;
  6537. if (iscomplete) {
  6538. logger.log('setting pranswer');
  6539. try {
  6540. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6541. function() {
  6542. },
  6543. function(e) {
  6544. logger.log('setRemoteDescription pranswer failed', e.toString());
  6545. });
  6546. } catch (e) {
  6547. logger.error('setting pranswer failed', e);
  6548. }
  6549. } else {
  6550. //logger.log('not yet setting pranswer');
  6551. }
  6552. }
  6553. // operate on each content element
  6554. elem.each(function () {
  6555. // would love to deactivate this, but firefox still requires it
  6556. var idx = -1;
  6557. var i;
  6558. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6559. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6560. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6561. idx = i;
  6562. break;
  6563. }
  6564. }
  6565. if (idx == -1) { // fall back to localdescription
  6566. for (i = 0; i < self.localSDP.media.length; i++) {
  6567. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6568. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6569. idx = i;
  6570. break;
  6571. }
  6572. }
  6573. }
  6574. var name = $(this).attr('name');
  6575. // TODO: check ice-pwd and ice-ufrag?
  6576. $(this).find('transport>candidate').each(function () {
  6577. var line, candidate;
  6578. var protocol = this.getAttribute('protocol');
  6579. protocol =
  6580. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6581. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6582. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6583. return;
  6584. }
  6585. line = SDPUtil.candidateFromJingle(this);
  6586. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6587. sdpMid: name,
  6588. candidate: line});
  6589. try {
  6590. self.peerconnection.addIceCandidate(candidate);
  6591. } catch (e) {
  6592. logger.error('addIceCandidate failed', e.toString(), line);
  6593. }
  6594. });
  6595. });
  6596. };
  6597. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6598. //logger.log('createAnswer', provisional);
  6599. var self = this;
  6600. this.peerconnection.createAnswer(
  6601. function (sdp) {
  6602. self.createdAnswer(sdp, provisional);
  6603. },
  6604. function (e) {
  6605. logger.error('createAnswer failed', e);
  6606. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6607. },
  6608. this.media_constraints
  6609. );
  6610. };
  6611. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6612. //logger.log('createAnswer callback');
  6613. var self = this;
  6614. this.localSDP = new SDP(sdp.sdp);
  6615. //this.localSDP.mangle();
  6616. this.usepranswer = provisional === true;
  6617. if (this.usetrickle) {
  6618. if (this.usepranswer) {
  6619. sdp.type = 'pranswer';
  6620. for (var i = 0; i < this.localSDP.media.length; i++) {
  6621. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6622. }
  6623. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6624. }
  6625. }
  6626. var self = this;
  6627. var sendJingle = function (ssrcs) {
  6628. // FIXME why do we generate session-accept in 3 different places ?
  6629. var accept = $iq({to: self.peerjid,
  6630. type: 'set'})
  6631. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6632. action: 'session-accept',
  6633. initiator: self.initiator,
  6634. responder: self.responder,
  6635. sid: self.sid });
  6636. if (self.webrtcIceTcpDisable) {
  6637. self.localSDP.removeTcpCandidates = true;
  6638. }
  6639. if (self.webrtcIceUdpDisable) {
  6640. self.localSDP.removeUdpCandidates = true;
  6641. }
  6642. self.localSDP.toJingle(
  6643. accept,
  6644. self.initiator == self.me ? 'initiator' : 'responder',
  6645. ssrcs);
  6646. SSRCReplacement.processSessionInit(accept);
  6647. self.connection.sendIQ(accept,
  6648. function () {
  6649. var ack = {};
  6650. ack.source = 'answer';
  6651. $(document).trigger('ack.jingle', [self.sid, ack]);
  6652. },
  6653. function (stanza) {
  6654. var error = ($(stanza).find('error').length) ? {
  6655. code: $(stanza).find('error').attr('code'),
  6656. reason: $(stanza).find('error :first')[0].tagName,
  6657. }:{};
  6658. error.source = 'answer';
  6659. JingleSessionPC.onJingleError(self.sid, error);
  6660. },
  6661. 10000);
  6662. }
  6663. sdp.sdp = this.localSDP.raw;
  6664. this.peerconnection.setLocalDescription(sdp,
  6665. function () {
  6666. //logger.log('setLocalDescription success');
  6667. if (self.usetrickle && !self.usepranswer) {
  6668. sendJingle();
  6669. }
  6670. self.setLocalDescription();
  6671. },
  6672. function (e) {
  6673. logger.error('setLocalDescription failed', e);
  6674. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6675. }
  6676. );
  6677. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6678. for (var j = 0; j < cands.length; j++) {
  6679. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6680. if (cand.type == 'srflx') {
  6681. this.hadstuncandidate = true;
  6682. } else if (cand.type == 'relay') {
  6683. this.hadturncandidate = true;
  6684. }
  6685. }
  6686. };
  6687. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6688. var self = this,
  6689. term = $iq({to: this.peerjid,
  6690. type: 'set'})
  6691. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6692. action: 'session-terminate',
  6693. initiator: this.initiator,
  6694. sid: this.sid})
  6695. .c('reason')
  6696. .c(reason || 'success');
  6697. if (text) {
  6698. term.up().c('text').t(text);
  6699. }
  6700. this.connection.sendIQ(term,
  6701. function () {
  6702. self.peerconnection.close();
  6703. self.peerconnection = null;
  6704. self.terminate();
  6705. var ack = {};
  6706. ack.source = 'terminate';
  6707. $(document).trigger('ack.jingle', [self.sid, ack]);
  6708. },
  6709. function (stanza) {
  6710. var error = ($(stanza).find('error').length) ? {
  6711. code: $(stanza).find('error').attr('code'),
  6712. reason: $(stanza).find('error :first')[0].tagName,
  6713. }:{};
  6714. $(document).trigger('ack.jingle', [self.sid, error]);
  6715. },
  6716. 10000);
  6717. if (this.statsinterval !== null) {
  6718. window.clearInterval(this.statsinterval);
  6719. this.statsinterval = null;
  6720. }
  6721. };
  6722. /**
  6723. * Handles a Jingle source-add message for this Jingle session.
  6724. * @param elem An array of Jingle "content" elements.
  6725. */
  6726. JingleSessionPC.prototype.addSource = function (elem) {
  6727. var self = this;
  6728. // FIXME: dirty waiting
  6729. if (!this.peerconnection.localDescription)
  6730. {
  6731. logger.warn("addSource - localDescription not ready yet")
  6732. setTimeout(function()
  6733. {
  6734. self.addSource(elem);
  6735. },
  6736. 200
  6737. );
  6738. return;
  6739. }
  6740. logger.log('addssrc', new Date().getTime());
  6741. logger.log('ice', this.peerconnection.iceConnectionState);
  6742. this.readSsrcInfo(elem);
  6743. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6744. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6745. $(elem).each(function (idx, content) {
  6746. var name = $(content).attr('name');
  6747. var lines = '';
  6748. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6749. var semantics = this.getAttribute('semantics');
  6750. var ssrcs = $(this).find('>source').map(function () {
  6751. return this.getAttribute('ssrc');
  6752. }).get();
  6753. if (ssrcs.length) {
  6754. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6755. }
  6756. });
  6757. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6758. tmp.each(function () {
  6759. var ssrc = $(this).attr('ssrc');
  6760. if(mySdp.containsSSRC(ssrc)){
  6761. /**
  6762. * This happens when multiple participants change their streams at the same time and
  6763. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6764. * addssrc are scheduled for update IQ. See
  6765. */
  6766. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6767. return;
  6768. }
  6769. if (sdp.containsSSRC(ssrc)) {
  6770. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6771. return;
  6772. }
  6773. $(this).find('>parameter').each(function () {
  6774. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6775. if ($(this).attr('value') && $(this).attr('value').length)
  6776. lines += ':' + $(this).attr('value');
  6777. lines += '\r\n';
  6778. });
  6779. });
  6780. sdp.media.forEach(function(media, idx) {
  6781. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6782. return;
  6783. sdp.media[idx] += lines;
  6784. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6785. self.addssrc[idx] += lines;
  6786. });
  6787. sdp.raw = sdp.session + sdp.media.join('');
  6788. });
  6789. this.modifySourcesQueue.push(function() {
  6790. // When a source is added and if this is FF, a new channel is allocated
  6791. // for receiving the added source. We need to diffuse the SSRC of this
  6792. // new recvonly channel to the rest of the peers.
  6793. logger.log('modify sources done');
  6794. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6795. logger.log("SDPs", mySdp, newSdp);
  6796. self.notifyMySSRCUpdate(mySdp, newSdp);
  6797. });
  6798. };
  6799. /**
  6800. * Handles a Jingle source-remove message for this Jingle session.
  6801. * @param elem An array of Jingle "content" elements.
  6802. */
  6803. JingleSessionPC.prototype.removeSource = function (elem) {
  6804. var self = this;
  6805. // FIXME: dirty waiting
  6806. if (!this.peerconnection.localDescription) {
  6807. logger.warn("removeSource - localDescription not ready yet");
  6808. setTimeout(function() {
  6809. self.removeSource(elem);
  6810. },
  6811. 200
  6812. );
  6813. return;
  6814. }
  6815. logger.log('removessrc', new Date().getTime());
  6816. logger.log('ice', this.peerconnection.iceConnectionState);
  6817. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6818. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6819. $(elem).each(function (idx, content) {
  6820. var name = $(content).attr('name');
  6821. var lines = '';
  6822. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6823. var semantics = this.getAttribute('semantics');
  6824. var ssrcs = $(this).find('>source').map(function () {
  6825. return this.getAttribute('ssrc');
  6826. }).get();
  6827. if (ssrcs.length) {
  6828. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6829. }
  6830. });
  6831. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6832. tmp.each(function () {
  6833. var ssrc = $(this).attr('ssrc');
  6834. // This should never happen, but can be useful for bug detection
  6835. if(mySdp.containsSSRC(ssrc)){
  6836. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6837. return;
  6838. }
  6839. $(this).find('>parameter').each(function () {
  6840. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6841. if ($(this).attr('value') && $(this).attr('value').length)
  6842. lines += ':' + $(this).attr('value');
  6843. lines += '\r\n';
  6844. });
  6845. });
  6846. sdp.media.forEach(function(media, idx) {
  6847. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6848. return;
  6849. sdp.media[idx] += lines;
  6850. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6851. self.removessrc[idx] += lines;
  6852. });
  6853. sdp.raw = sdp.session + sdp.media.join('');
  6854. });
  6855. this.modifySourcesQueue.push(function() {
  6856. // When a source is removed and if this is FF, the recvonly channel that
  6857. // receives the remote stream is deactivated . We need to diffuse the
  6858. // recvonly SSRC removal to the rest of the peers.
  6859. logger.log('modify sources done');
  6860. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6861. logger.log("SDPs", mySdp, newSdp);
  6862. self.notifyMySSRCUpdate(mySdp, newSdp);
  6863. });
  6864. };
  6865. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6866. var self = this;
  6867. if (this.peerconnection.signalingState == 'closed') return;
  6868. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6869. || this.switchstreams || this.addingStreams)){
  6870. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6871. this.setLocalDescription();
  6872. if(successCallback){
  6873. successCallback();
  6874. }
  6875. queueCallback();
  6876. return;
  6877. }
  6878. // Reset switch streams flags
  6879. this.switchstreams = false;
  6880. this.addingStreams = false;
  6881. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6882. // add sources
  6883. this.addssrc.forEach(function(lines, idx) {
  6884. sdp.media[idx] += lines;
  6885. });
  6886. this.addssrc = [];
  6887. // remove sources
  6888. this.removessrc.forEach(function(lines, idx) {
  6889. lines = lines.split('\r\n');
  6890. lines.pop(); // remove empty last element;
  6891. lines.forEach(function(line) {
  6892. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6893. });
  6894. });
  6895. this.removessrc = [];
  6896. sdp.raw = sdp.session + sdp.media.join('');
  6897. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6898. function() {
  6899. if(self.signalingState == 'closed') {
  6900. logger.error("createAnswer attempt on closed state");
  6901. queueCallback("createAnswer attempt on closed state");
  6902. return;
  6903. }
  6904. self.peerconnection.createAnswer(
  6905. function(modifiedAnswer) {
  6906. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6907. if (self.pendingop !== null) {
  6908. var sdp = new SDP(modifiedAnswer.sdp);
  6909. if (sdp.media.length > 1) {
  6910. switch(self.pendingop) {
  6911. case 'mute':
  6912. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6913. break;
  6914. case 'unmute':
  6915. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6916. break;
  6917. }
  6918. sdp.raw = sdp.session + sdp.media.join('');
  6919. modifiedAnswer.sdp = sdp.raw;
  6920. }
  6921. self.pendingop = null;
  6922. }
  6923. // FIXME: pushing down an answer while ice connection state
  6924. // is still checking is bad...
  6925. //logger.log(self.peerconnection.iceConnectionState);
  6926. // trying to work around another chrome bug
  6927. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6928. self.peerconnection.setLocalDescription(modifiedAnswer,
  6929. function() {
  6930. //logger.log('modified setLocalDescription ok');
  6931. self.setLocalDescription();
  6932. if(successCallback){
  6933. successCallback();
  6934. }
  6935. queueCallback();
  6936. },
  6937. function(error) {
  6938. logger.error('modified setLocalDescription failed', error);
  6939. queueCallback(error);
  6940. }
  6941. );
  6942. },
  6943. function(error) {
  6944. logger.error('modified answer failed', error);
  6945. queueCallback(error);
  6946. }
  6947. );
  6948. },
  6949. function(error) {
  6950. logger.error('modify failed', error);
  6951. queueCallback(error);
  6952. }
  6953. );
  6954. };
  6955. /**
  6956. * Switches video streams.
  6957. * @param newStream new stream that will be used as video of this session.
  6958. * @param oldStream old video stream of this session.
  6959. * @param successCallback callback executed after successful stream switch.
  6960. * @param isAudio whether the streams are audio (if true) or video (if false).
  6961. */
  6962. JingleSessionPC.prototype.switchStreams =
  6963. function (newStream, oldStream, successCallback, isAudio) {
  6964. var self = this;
  6965. var sender, newTrack;
  6966. var senderKind = isAudio ? 'audio' : 'video';
  6967. // Remember SDP to figure out added/removed SSRCs
  6968. var oldSdp = null;
  6969. if (self.peerconnection) {
  6970. if (self.peerconnection.localDescription) {
  6971. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6972. }
  6973. if (RTCBrowserType.getBrowserType() ===
  6974. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  6975. // On Firefox we don't replace MediaStreams as this messes up the
  6976. // m-lines (which can't be removed in Plan Unified) and brings a lot
  6977. // of complications. Instead, we use the RTPSender and replace just
  6978. // the track.
  6979. // Find the right sender (for audio or video)
  6980. self.peerconnection.peerconnection.getSenders().some(function (s) {
  6981. if (s.track && s.track.kind === senderKind) {
  6982. sender = s;
  6983. return true;
  6984. }
  6985. });
  6986. if (sender) {
  6987. // We assume that our streams have a single track, either audio
  6988. // or video.
  6989. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  6990. newStream.getVideoTracks()[0];
  6991. sender.replaceTrack(newTrack)
  6992. .then(function() {
  6993. console.log("Replaced a track, isAudio=" + isAudio);
  6994. })
  6995. .catch(function(err) {
  6996. console.log("Failed to replace a track: " + err);
  6997. });
  6998. } else {
  6999. console.log("Cannot switch tracks: no RTPSender.");
  7000. }
  7001. } else {
  7002. self.peerconnection.removeStream(oldStream, true);
  7003. if (newStream) {
  7004. self.peerconnection.addStream(newStream);
  7005. }
  7006. }
  7007. }
  7008. // Conference is not active
  7009. if (!oldSdp) {
  7010. successCallback();
  7011. return;
  7012. }
  7013. self.switchstreams = true;
  7014. self.modifySourcesQueue.push(function() {
  7015. logger.log('modify sources done');
  7016. successCallback();
  7017. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7018. logger.log("SDPs", oldSdp, newSdp);
  7019. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7020. });
  7021. };
  7022. /**
  7023. * Adds streams.
  7024. * @param stream new stream that will be added.
  7025. * @param success_callback callback executed after successful stream addition.
  7026. */
  7027. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7028. var self = this;
  7029. // Remember SDP to figure out added/removed SSRCs
  7030. var oldSdp = null;
  7031. if(this.peerconnection) {
  7032. if(this.peerconnection.localDescription) {
  7033. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7034. }
  7035. if(stream)
  7036. this.peerconnection.addStream(stream);
  7037. }
  7038. // Conference is not active
  7039. if(!oldSdp || !this.peerconnection) {
  7040. callback();
  7041. return;
  7042. }
  7043. this.addingStreams = true;
  7044. this.modifySourcesQueue.push(function() {
  7045. logger.log('modify sources done');
  7046. callback();
  7047. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7048. logger.log("SDPs", oldSdp, newSdp);
  7049. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7050. });
  7051. }
  7052. /**
  7053. * Remove streams.
  7054. * @param stream stream that will be removed.
  7055. * @param success_callback callback executed after successful stream addition.
  7056. */
  7057. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7058. var self = this;
  7059. // Remember SDP to figure out added/removed SSRCs
  7060. var oldSdp = null;
  7061. if(this.peerconnection) {
  7062. if(this.peerconnection.localDescription) {
  7063. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7064. }
  7065. if(stream)
  7066. this.peerconnection.removeStream(stream);
  7067. }
  7068. // Conference is not active
  7069. if(!oldSdp || !this.peerconnection) {
  7070. callback();
  7071. return;
  7072. }
  7073. this.addingStreams = true;
  7074. this.modifySourcesQueue.push(function() {
  7075. logger.log('modify sources done');
  7076. callback();
  7077. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7078. logger.log("SDPs", oldSdp, newSdp);
  7079. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7080. });
  7081. }
  7082. /**
  7083. * Figures out added/removed ssrcs and send update IQs.
  7084. * @param old_sdp SDP object for old description.
  7085. * @param new_sdp SDP object for new description.
  7086. */
  7087. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7088. if (!(this.peerconnection.signalingState == 'stable' &&
  7089. this.peerconnection.iceConnectionState == 'connected')){
  7090. logger.log("Too early to send updates");
  7091. return;
  7092. }
  7093. // send source-remove IQ.
  7094. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7095. var remove = $iq({to: this.peerjid, type: 'set'})
  7096. .c('jingle', {
  7097. xmlns: 'urn:xmpp:jingle:1',
  7098. action: 'source-remove',
  7099. initiator: this.initiator,
  7100. sid: this.sid
  7101. }
  7102. );
  7103. var removed = sdpDiffer.toJingle(remove);
  7104. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7105. // it in the current form
  7106. if (removed)
  7107. remove = SSRCReplacement.processSourceRemove(remove);
  7108. if (removed && remove) {
  7109. logger.info("Sending source-remove", remove);
  7110. this.connection.sendIQ(remove,
  7111. function (res) {
  7112. logger.info('got remove result', res);
  7113. },
  7114. function (err) {
  7115. logger.error('got remove error', err);
  7116. }
  7117. );
  7118. } else {
  7119. logger.log('removal not necessary');
  7120. }
  7121. // send source-add IQ.
  7122. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7123. var add = $iq({to: this.peerjid, type: 'set'})
  7124. .c('jingle', {
  7125. xmlns: 'urn:xmpp:jingle:1',
  7126. action: 'source-add',
  7127. initiator: this.initiator,
  7128. sid: this.sid
  7129. }
  7130. );
  7131. var added = sdpDiffer.toJingle(add);
  7132. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7133. // it in the current form
  7134. if (added)
  7135. add = SSRCReplacement.processSourceAdd(add);
  7136. if (added && add) {
  7137. logger.info("Sending source-add", add);
  7138. this.connection.sendIQ(add,
  7139. function (res) {
  7140. logger.info('got add result', res);
  7141. },
  7142. function (err) {
  7143. logger.error('got add error', err);
  7144. }
  7145. );
  7146. } else {
  7147. logger.log('addition not necessary');
  7148. }
  7149. };
  7150. /**
  7151. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7152. *
  7153. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7154. * tracks; otherwise, <tt>false</tt>
  7155. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7156. * tracks have been enabled/disabled. The function may, optionally, return
  7157. * another function which is to be invoked after the whole mute/unmute operation
  7158. * has completed successfully.
  7159. * @param options an object which specifies optional arguments such as the
  7160. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7161. * specifies whether the method was initiated in response to a user command (in
  7162. * contrast to an automatic decision made by the application logic)
  7163. */
  7164. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7165. var byUser;
  7166. if (options) {
  7167. byUser = options.byUser;
  7168. if (typeof byUser === 'undefined') {
  7169. byUser = true;
  7170. }
  7171. } else {
  7172. byUser = true;
  7173. }
  7174. // The user's command to mute the (local) video takes precedence over any
  7175. // automatic decision made by the application logic.
  7176. if (byUser) {
  7177. this.videoMuteByUser = mute;
  7178. } else if (this.videoMuteByUser) {
  7179. return;
  7180. }
  7181. this.hardMuteVideo(mute);
  7182. var self = this;
  7183. var oldSdp = null;
  7184. if(self.peerconnection) {
  7185. if(self.peerconnection.localDescription) {
  7186. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7187. }
  7188. }
  7189. this.modifySourcesQueue.push(function() {
  7190. logger.log('modify sources done');
  7191. callback(mute);
  7192. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7193. logger.log("SDPs", oldSdp, newSdp);
  7194. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7195. });
  7196. };
  7197. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7198. this.pendingop = muted ? 'mute' : 'unmute';
  7199. };
  7200. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7201. var info = $iq({to: this.peerjid,
  7202. type: 'set'})
  7203. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7204. action: 'session-info',
  7205. initiator: this.initiator,
  7206. sid: this.sid });
  7207. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7208. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7209. if (content) {
  7210. info.attrs({'name': content});
  7211. }
  7212. this.connection.send(info);
  7213. };
  7214. JingleSessionPC.prototype.sendRinging = function () {
  7215. var info = $iq({to: this.peerjid,
  7216. type: 'set'})
  7217. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7218. action: 'session-info',
  7219. initiator: this.initiator,
  7220. sid: this.sid });
  7221. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7222. this.connection.send(info);
  7223. };
  7224. JingleSessionPC.prototype.getStats = function (interval) {
  7225. var self = this;
  7226. var recv = {audio: 0, video: 0};
  7227. var lost = {audio: 0, video: 0};
  7228. var lastrecv = {audio: 0, video: 0};
  7229. var lastlost = {audio: 0, video: 0};
  7230. var loss = {audio: 0, video: 0};
  7231. var delta = {audio: 0, video: 0};
  7232. this.statsinterval = window.setInterval(function () {
  7233. if (self && self.peerconnection && self.peerconnection.getStats) {
  7234. self.peerconnection.getStats(function (stats) {
  7235. var results = stats.result();
  7236. // TODO: there are so much statistics you can get from this..
  7237. for (var i = 0; i < results.length; ++i) {
  7238. if (results[i].type == 'ssrc') {
  7239. var packetsrecv = results[i].stat('packetsReceived');
  7240. var packetslost = results[i].stat('packetsLost');
  7241. if (packetsrecv && packetslost) {
  7242. packetsrecv = parseInt(packetsrecv, 10);
  7243. packetslost = parseInt(packetslost, 10);
  7244. if (results[i].stat('googFrameRateReceived')) {
  7245. lastlost.video = lost.video;
  7246. lastrecv.video = recv.video;
  7247. recv.video = packetsrecv;
  7248. lost.video = packetslost;
  7249. } else {
  7250. lastlost.audio = lost.audio;
  7251. lastrecv.audio = recv.audio;
  7252. recv.audio = packetsrecv;
  7253. lost.audio = packetslost;
  7254. }
  7255. }
  7256. }
  7257. }
  7258. delta.audio = recv.audio - lastrecv.audio;
  7259. delta.video = recv.video - lastrecv.video;
  7260. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7261. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7262. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7263. });
  7264. }
  7265. }, interval || 3000);
  7266. return this.statsinterval;
  7267. };
  7268. JingleSessionPC.onJingleError = function (session, error)
  7269. {
  7270. logger.error("Jingle error", error);
  7271. }
  7272. JingleSessionPC.onJingleFatalError = function (session, error)
  7273. {
  7274. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7275. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7276. }
  7277. JingleSessionPC.prototype.setLocalDescription = function () {
  7278. var self = this;
  7279. var newssrcs = [];
  7280. if(!this.peerconnection.localDescription)
  7281. return;
  7282. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7283. var i;
  7284. session.media.forEach(function (media) {
  7285. if (media.ssrcs && media.ssrcs.length > 0) {
  7286. // TODO(gp) maybe exclude FID streams?
  7287. media.ssrcs.forEach(function (ssrc) {
  7288. if (ssrc.attribute !== 'cname') {
  7289. return;
  7290. }
  7291. newssrcs.push({
  7292. 'ssrc': ssrc.id,
  7293. 'type': media.type
  7294. });
  7295. // FIXME allows for only one SSRC per media type
  7296. self.localStreamsSSRC[media.type] = ssrc.id;
  7297. });
  7298. }
  7299. });
  7300. logger.log('new ssrcs', newssrcs);
  7301. // Bind us as local SSRCs owner
  7302. if (newssrcs.length > 0) {
  7303. for (i = 0; i < newssrcs.length; i++) {
  7304. var ssrc = newssrcs[i].ssrc;
  7305. var myJid = self.connection.emuc.myroomjid;
  7306. self.ssrcOwners[ssrc] = myJid;
  7307. }
  7308. }
  7309. }
  7310. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7311. JingleSessionPC.prototype.sendKeyframe = function () {
  7312. var pc = this.peerconnection;
  7313. logger.log('sendkeyframe', pc.iceConnectionState);
  7314. if (pc.iceConnectionState !== 'connected') return; // safe...
  7315. var self = this;
  7316. pc.setRemoteDescription(
  7317. pc.remoteDescription,
  7318. function () {
  7319. pc.createAnswer(
  7320. function (modifiedAnswer) {
  7321. pc.setLocalDescription(
  7322. modifiedAnswer,
  7323. function () {
  7324. // noop
  7325. },
  7326. function (error) {
  7327. logger.log('triggerKeyframe setLocalDescription failed', error);
  7328. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7329. }
  7330. );
  7331. },
  7332. function (error) {
  7333. logger.log('triggerKeyframe createAnswer failed', error);
  7334. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7335. }
  7336. );
  7337. },
  7338. function (error) {
  7339. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7340. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7341. }
  7342. );
  7343. }
  7344. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7345. var self = this;
  7346. var thessrc;
  7347. var streamId = RTC.getStreamID(data.stream);
  7348. // look up an associated JID for a stream id
  7349. if (!streamId) {
  7350. logger.error("No stream ID for", data.stream);
  7351. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7352. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7353. var ssrclines = this.peerconnection.remoteDescription?
  7354. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7355. ssrclines = ssrclines.filter(function (line) {
  7356. // NOTE(gp) previously we filtered on the mslabel, but that property
  7357. // is not always present.
  7358. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7359. if (RTCBrowserType.isTemasysPluginUsed()) {
  7360. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7361. } else {
  7362. return ((line.indexOf('msid:' + streamId) !== -1));
  7363. }
  7364. });
  7365. if (ssrclines.length) {
  7366. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7367. if (!self.ssrcOwners[thessrc]) {
  7368. logger.error("No SSRC owner known for: " + thessrc);
  7369. return;
  7370. }
  7371. data.peerjid = self.ssrcOwners[thessrc];
  7372. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7373. } else {
  7374. logger.error("No SSRC lines for ", streamId);
  7375. }
  7376. }
  7377. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7378. var isVideo = data.stream.getVideoTracks().length > 0;
  7379. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7380. if (isVideo &&
  7381. data.peerjid && this.peerjid === data.peerjid &&
  7382. data.stream.getVideoTracks().length === 0 &&
  7383. RTC.localVideo.getTracks().length > 0) {
  7384. window.setTimeout(function () {
  7385. self.sendKeyframe();
  7386. }, 3000);
  7387. }
  7388. }
  7389. module.exports = JingleSessionPC;
  7390. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7391. },{"../../service/xmpp/XMPPEvents":91,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":43,"jitsi-meet-logger":48,"sdp-transform":80}],29:[function(require,module,exports){
  7392. (function (__filename){
  7393. /* global $ */
  7394. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7395. /*
  7396. Here we do modifications of local video SSRCs. There are 2 situations we have
  7397. to handle:
  7398. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7399. have no local camera and it is not generated automatically, but SSRC=1 is
  7400. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7401. and we won't be able to request video key frames correctly.
  7402. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7403. in future. It turned out that Chrome may keep on using the SSRC of removed
  7404. video stream in RTCP even though a new one has been created. So we just
  7405. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7406. notifications are blocked once first video SSRC is advertised to the focus.
  7407. What this hack does:
  7408. 1. Stores the SSRC of the first video stream created by
  7409. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7410. b) watching for 'source-add' for new video stream if it has not been
  7411. created in step a)
  7412. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7413. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7414. returned to the other parts of the application.
  7415. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7416. blocks those notifications. This makes Jicofo and all participants think
  7417. that it exists all the time even if the video stream has been removed or
  7418. replaced locally. Thanks to that there is no additional signaling activity
  7419. on video mute or when switching to the desktop stream.
  7420. */
  7421. var SDP = require('./SDP');
  7422. var RandomUtil = require('../util/RandomUtil');
  7423. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7424. /**
  7425. * The hack is enabled on all browsers except FF by default
  7426. * FIXME finish the hack once removeStream method is implemented in FF
  7427. * @type {boolean}
  7428. */
  7429. var isEnabled = !RTCBrowserType.isFirefox();
  7430. /**
  7431. * Stored SSRC of local video stream.
  7432. */
  7433. var localVideoSSRC;
  7434. /**
  7435. * SSRC, msid, mslabel, label used for recvonly video stream when we have no local camera.
  7436. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7437. * instead of 1.
  7438. */
  7439. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7440. /**
  7441. * cname for <tt>localRecvOnlySSRC</tt>
  7442. */
  7443. var localRecvOnlyCName;
  7444. /**
  7445. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7446. * from given Jingle IQ.
  7447. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7448. * @param actionName display name of the action which will be printed in log
  7449. * messages.
  7450. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7451. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7452. * other SSRCs left to be signaled after removing it.
  7453. */
  7454. var filterOutSource = function (modifyIq, actionName) {
  7455. var modifyIqTree = $(modifyIq.tree());
  7456. if (!localVideoSSRC)
  7457. return modifyIqTree[0];
  7458. var videoSSRC = modifyIqTree.find(
  7459. '>jingle>content[name="video"]' +
  7460. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7461. if (!videoSSRC.length) {
  7462. return modifyIqTree[0];
  7463. }
  7464. logger.info(
  7465. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7466. videoSSRC.remove();
  7467. // Check if any sources still left to be added/removed
  7468. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7469. return modifyIqTree[0];
  7470. } else {
  7471. return null;
  7472. }
  7473. };
  7474. /**
  7475. * Scans given Jingle IQ for video SSRC and stores it.
  7476. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7477. */
  7478. var storeLocalVideoSSRC = function (jingleIq) {
  7479. var videoSSRCs =
  7480. $(jingleIq.tree())
  7481. .find('>jingle>content[name="video"]>description>source');
  7482. videoSSRCs.each(function (idx, ssrcElem) {
  7483. if (localVideoSSRC)
  7484. return;
  7485. // We consider SSRC real only if it has msid attribute
  7486. // recvonly streams in FF do not have it as well as local SSRCs
  7487. // we generate for recvonly streams in Chrome
  7488. var ssrSel = $(ssrcElem);
  7489. var msid = ssrSel.find('>parameter[name="msid"]');
  7490. if (msid.length) {
  7491. var ssrcVal = ssrSel.attr('ssrc');
  7492. if (ssrcVal) {
  7493. localVideoSSRC = ssrcVal;
  7494. logger.info('Stored local video SSRC' +
  7495. ' for future re-use: ' + localVideoSSRC);
  7496. }
  7497. }
  7498. });
  7499. };
  7500. /**
  7501. * Generates new label/mslabel attribute
  7502. * @returns {string} label/mslabel attribute
  7503. */
  7504. function generateLabel() {
  7505. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7506. "-" + RandomUtil.randomHexString(4) + "-" +
  7507. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  7508. }
  7509. /**
  7510. * Generates new SSRC, CNAME, mslabel, label and msid for local video recvonly stream.
  7511. * FIXME what about eventual SSRC collision ?
  7512. */
  7513. function generateRecvonlySSRC() {
  7514. localRecvOnlySSRC =
  7515. Math.random().toString(10).substring(2, 11);
  7516. localRecvOnlyCName =
  7517. Math.random().toString(36).substring(2);
  7518. localRecvOnlyMSLabel = generateLabel();
  7519. localRecvOnlyLabel = generateLabel();
  7520. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  7521. logger.info(
  7522. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7523. ", cname: " + localRecvOnlyCName);
  7524. }
  7525. var LocalSSRCReplacement = {
  7526. /**
  7527. * Method must be called before 'session-initiate' or 'session-invite' is
  7528. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7529. *
  7530. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7531. * which will be scanned for local video SSRC.
  7532. */
  7533. processSessionInit: function (sessionInit) {
  7534. if (!isEnabled)
  7535. return;
  7536. if (localVideoSSRC) {
  7537. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7538. return;
  7539. }
  7540. storeLocalVideoSSRC(sessionInit);
  7541. },
  7542. /**
  7543. * If we have local video SSRC stored searched given
  7544. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7545. * with the stored one.
  7546. * @param localDescription local description object that will have local
  7547. * video SSRC replaced with the stored one
  7548. * @returns modified <tt>localDescription</tt> object.
  7549. */
  7550. mungeLocalVideoSSRC: function (localDescription) {
  7551. if (!isEnabled)
  7552. return localDescription;
  7553. if (!localDescription) {
  7554. logger.warn("localDescription is null or undefined");
  7555. return localDescription;
  7556. }
  7557. // IF we have local video SSRC stored make sure it is replaced
  7558. // with old SSRC
  7559. if (localVideoSSRC) {
  7560. var newSdp = new SDP(localDescription.sdp);
  7561. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7562. !newSdp.containsSSRC(localVideoSSRC)) {
  7563. // Get new video SSRC
  7564. var map = newSdp.getMediaSsrcMap();
  7565. var videoPart = map[1];
  7566. var videoSSRCs = videoPart.ssrcs;
  7567. var newSSRC = Object.keys(videoSSRCs)[0];
  7568. logger.info(
  7569. "Replacing new video SSRC: " + newSSRC +
  7570. " with " + localVideoSSRC);
  7571. localDescription.sdp =
  7572. newSdp.raw.replace(
  7573. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7574. 'a=ssrc:' + localVideoSSRC);
  7575. }
  7576. } else {
  7577. // Make sure we have any SSRC for recvonly video stream
  7578. var sdp = new SDP(localDescription.sdp);
  7579. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7580. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7581. if (!localRecvOnlySSRC) {
  7582. generateRecvonlySSRC();
  7583. }
  7584. localVideoSSRC = localRecvOnlySSRC;
  7585. logger.info('No SSRC in video recvonly stream' +
  7586. ' - adding SSRC: ' + localRecvOnlySSRC);
  7587. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7588. ' cname:' + localRecvOnlyCName + '\r\n' +
  7589. 'a=ssrc:' + localRecvOnlySSRC +
  7590. ' msid:' + localRecvOnlyMSID + '\r\n' +
  7591. 'a=ssrc:' + localRecvOnlySSRC +
  7592. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  7593. 'a=ssrc:' + localRecvOnlySSRC +
  7594. ' label:' + localRecvOnlyLabel + '\r\n';
  7595. localDescription.sdp = sdp.session + sdp.media.join('');
  7596. }
  7597. }
  7598. return localDescription;
  7599. },
  7600. /**
  7601. * Method must be called before 'source-add' notification is sent. In case
  7602. * we have local video SSRC advertised already it will be removed from the
  7603. * notification. If no other SSRCs are described by given IQ null will be
  7604. * returned which means that there is no point in sending the notification.
  7605. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7606. * @returns modified 'source-add' IQ which can be sent to the focus or
  7607. * <tt>null</tt> if no notification shall be sent. It is no longer
  7608. * a Strophe IQ Builder instance, but DOM element tree.
  7609. */
  7610. processSourceAdd: function (sourceAdd) {
  7611. if (!isEnabled)
  7612. return sourceAdd;
  7613. if (!localVideoSSRC) {
  7614. // Store local SSRC if available
  7615. storeLocalVideoSSRC(sourceAdd);
  7616. return sourceAdd;
  7617. } else {
  7618. return filterOutSource(sourceAdd, 'source-add');
  7619. }
  7620. },
  7621. /**
  7622. * Method must be called before 'source-remove' notification is sent.
  7623. * Removes local video SSRC from the notification. If there are no other
  7624. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7625. * means that there is no point in sending the notification.
  7626. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7627. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7628. * <tt>null</tt> if no notification shall be sent. It is no longer
  7629. * a Strophe IQ Builder instance, but DOM element tree.
  7630. */
  7631. processSourceRemove: function (sourceRemove) {
  7632. if (!isEnabled)
  7633. return sourceRemove;
  7634. return filterOutSource(sourceRemove, 'source-remove');
  7635. },
  7636. /**
  7637. * Turns the hack on or off
  7638. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7639. * to disable it
  7640. */
  7641. setEnabled: function (enabled) {
  7642. isEnabled = enabled;
  7643. }
  7644. };
  7645. module.exports = LocalSSRCReplacement;
  7646. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7647. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":48}],30:[function(require,module,exports){
  7648. (function (__filename){
  7649. /* jshint -W117 */
  7650. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7651. var SDPUtil = require("./SDPUtil");
  7652. // SDP STUFF
  7653. function SDP(sdp) {
  7654. /**
  7655. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7656. * @type {boolean}
  7657. */
  7658. this.removeTcpCandidates = false;
  7659. /**
  7660. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7661. * @type {boolean}
  7662. */
  7663. this.removeUdpCandidates = false;
  7664. this.media = sdp.split('\r\nm=');
  7665. for (var i = 1; i < this.media.length; i++) {
  7666. this.media[i] = 'm=' + this.media[i];
  7667. if (i != this.media.length - 1) {
  7668. this.media[i] += '\r\n';
  7669. }
  7670. }
  7671. this.session = this.media.shift() + '\r\n';
  7672. this.raw = this.session + this.media.join('');
  7673. }
  7674. /**
  7675. * Returns map of MediaChannel mapped per channel idx.
  7676. */
  7677. SDP.prototype.getMediaSsrcMap = function() {
  7678. var self = this;
  7679. var media_ssrcs = {};
  7680. var tmp;
  7681. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7682. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7683. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7684. var media = {
  7685. mediaindex: mediaindex,
  7686. mid: mid,
  7687. ssrcs: {},
  7688. ssrcGroups: []
  7689. };
  7690. media_ssrcs[mediaindex] = media;
  7691. tmp.forEach(function (line) {
  7692. var linessrc = line.substring(7).split(' ')[0];
  7693. // allocate new ChannelSsrc
  7694. if(!media.ssrcs[linessrc]) {
  7695. media.ssrcs[linessrc] = {
  7696. ssrc: linessrc,
  7697. lines: []
  7698. };
  7699. }
  7700. media.ssrcs[linessrc].lines.push(line);
  7701. });
  7702. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7703. tmp.forEach(function(line){
  7704. var idx = line.indexOf(' ');
  7705. var semantics = line.substr(0, idx).substr(13);
  7706. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7707. if (ssrcs.length) {
  7708. media.ssrcGroups.push({
  7709. semantics: semantics,
  7710. ssrcs: ssrcs
  7711. });
  7712. }
  7713. });
  7714. }
  7715. return media_ssrcs;
  7716. };
  7717. /**
  7718. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7719. * @param ssrc the ssrc to check.
  7720. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7721. */
  7722. SDP.prototype.containsSSRC = function(ssrc) {
  7723. var medias = this.getMediaSsrcMap();
  7724. Object.keys(medias).forEach(function(mediaindex){
  7725. var media = medias[mediaindex];
  7726. //logger.log("Check", channel, ssrc);
  7727. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  7728. return true;
  7729. }
  7730. });
  7731. return false;
  7732. };
  7733. // remove iSAC and CN from SDP
  7734. SDP.prototype.mangle = function () {
  7735. var i, j, mline, lines, rtpmap, newdesc;
  7736. for (i = 0; i < this.media.length; i++) {
  7737. lines = this.media[i].split('\r\n');
  7738. lines.pop(); // remove empty last element
  7739. mline = SDPUtil.parse_mline(lines.shift());
  7740. if (mline.media != 'audio')
  7741. continue;
  7742. newdesc = '';
  7743. mline.fmt.length = 0;
  7744. for (j = 0; j < lines.length; j++) {
  7745. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7746. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7747. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7748. continue;
  7749. mline.fmt.push(rtpmap.id);
  7750. newdesc += lines[j] + '\r\n';
  7751. } else {
  7752. newdesc += lines[j] + '\r\n';
  7753. }
  7754. }
  7755. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7756. this.media[i] += newdesc;
  7757. }
  7758. this.raw = this.session + this.media.join('');
  7759. };
  7760. // remove lines matching prefix from session section
  7761. SDP.prototype.removeSessionLines = function(prefix) {
  7762. var self = this;
  7763. var lines = SDPUtil.find_lines(this.session, prefix);
  7764. lines.forEach(function(line) {
  7765. self.session = self.session.replace(line + '\r\n', '');
  7766. });
  7767. this.raw = this.session + this.media.join('');
  7768. return lines;
  7769. }
  7770. // remove lines matching prefix from a media section specified by mediaindex
  7771. // TODO: non-numeric mediaindex could match mid
  7772. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7773. var self = this;
  7774. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7775. lines.forEach(function(line) {
  7776. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7777. });
  7778. this.raw = this.session + this.media.join('');
  7779. return lines;
  7780. }
  7781. // add content's to a jingle element
  7782. SDP.prototype.toJingle = function (elem, thecreator) {
  7783. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7784. var self = this;
  7785. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7786. // new bundle plan
  7787. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7788. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7789. for (i = 0; i < lines.length; i++) {
  7790. tmp = lines[i].split(' ');
  7791. var semantics = tmp.shift().substr(8);
  7792. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7793. for (j = 0; j < tmp.length; j++) {
  7794. elem.c('content', {name: tmp[j]}).up();
  7795. }
  7796. elem.up();
  7797. }
  7798. }
  7799. for (i = 0; i < this.media.length; i++) {
  7800. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7801. if (!(mline.media === 'audio' ||
  7802. mline.media === 'video' ||
  7803. mline.media === 'application'))
  7804. {
  7805. continue;
  7806. }
  7807. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7808. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7809. } else {
  7810. ssrc = false;
  7811. }
  7812. elem.c('content', {creator: thecreator, name: mline.media});
  7813. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7814. // prefer identifier from a=mid if present
  7815. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7816. elem.attrs({ name: mid });
  7817. }
  7818. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  7819. elem.c('description',
  7820. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7821. media: mline.media });
  7822. if (ssrc) {
  7823. elem.attrs({ssrc: ssrc});
  7824. }
  7825. for (j = 0; j < mline.fmt.length; j++) {
  7826. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7827. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7828. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7829. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7830. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7831. for (k = 0; k < tmp.length; k++) {
  7832. elem.c('parameter', tmp[k]).up();
  7833. }
  7834. }
  7835. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7836. elem.up();
  7837. }
  7838. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7839. elem.c('encryption', {required: 1});
  7840. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7841. crypto.forEach(function(line) {
  7842. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7843. });
  7844. elem.up(); // end of encryption
  7845. }
  7846. if (ssrc) {
  7847. // new style mapping
  7848. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7849. // FIXME: group by ssrc and support multiple different ssrcs
  7850. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7851. if(ssrclines.length > 0) {
  7852. ssrclines.forEach(function (line) {
  7853. var idx = line.indexOf(' ');
  7854. var linessrc = line.substr(0, idx).substr(7);
  7855. if (linessrc != ssrc) {
  7856. elem.up();
  7857. ssrc = linessrc;
  7858. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7859. }
  7860. var kv = line.substr(idx + 1);
  7861. elem.c('parameter');
  7862. if (kv.indexOf(':') == -1) {
  7863. elem.attrs({ name: kv });
  7864. } else {
  7865. var k = kv.split(':', 2)[0];
  7866. elem.attrs({ name: k });
  7867. var v = kv.split(':', 2)[1];
  7868. v = SDPUtil.filter_special_chars(v);
  7869. elem.attrs({ value: v });
  7870. }
  7871. elem.up();
  7872. });
  7873. } else {
  7874. elem.up();
  7875. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7876. elem.c('parameter');
  7877. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7878. elem.up();
  7879. var msid = null;
  7880. if(mline.media == "audio")
  7881. {
  7882. msid = APP.RTC.localAudio.getId();
  7883. }
  7884. else
  7885. {
  7886. msid = APP.RTC.localVideo.getId();
  7887. }
  7888. if(msid != null)
  7889. {
  7890. msid = SDPUtil.filter_special_chars(msid);
  7891. elem.c('parameter');
  7892. elem.attrs({name: "msid", value:msid});
  7893. elem.up();
  7894. elem.c('parameter');
  7895. elem.attrs({name: "mslabel", value:msid});
  7896. elem.up();
  7897. elem.c('parameter');
  7898. elem.attrs({name: "label", value:msid});
  7899. elem.up();
  7900. }
  7901. }
  7902. elem.up();
  7903. // XEP-0339 handle ssrc-group attributes
  7904. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7905. ssrc_group_lines.forEach(function(line) {
  7906. var idx = line.indexOf(' ');
  7907. var semantics = line.substr(0, idx).substr(13);
  7908. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7909. if (ssrcs.length) {
  7910. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7911. ssrcs.forEach(function(ssrc) {
  7912. elem.c('source', { ssrc: ssrc })
  7913. .up();
  7914. });
  7915. elem.up();
  7916. }
  7917. });
  7918. }
  7919. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7920. elem.c('rtcp-mux').up();
  7921. }
  7922. // XEP-0293 -- map a=rtcp-fb:*
  7923. this.rtcpFbToJingle(i, elem, '*');
  7924. // XEP-0294
  7925. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7926. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7927. for (j = 0; j < lines.length; j++) {
  7928. tmp = SDPUtil.parse_extmap(lines[j]);
  7929. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7930. uri: tmp.uri,
  7931. id: tmp.value });
  7932. if (tmp.hasOwnProperty('direction')) {
  7933. switch (tmp.direction) {
  7934. case 'sendonly':
  7935. elem.attrs({senders: 'responder'});
  7936. break;
  7937. case 'recvonly':
  7938. elem.attrs({senders: 'initiator'});
  7939. break;
  7940. case 'sendrecv':
  7941. elem.attrs({senders: 'both'});
  7942. break;
  7943. case 'inactive':
  7944. elem.attrs({senders: 'none'});
  7945. break;
  7946. }
  7947. }
  7948. // TODO: handle params
  7949. elem.up();
  7950. }
  7951. }
  7952. elem.up(); // end of description
  7953. }
  7954. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7955. this.transportToJingle(i, elem);
  7956. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7957. elem.attrs({senders: 'both'});
  7958. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7959. elem.attrs({senders: 'initiator'});
  7960. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7961. elem.attrs({senders: 'responder'});
  7962. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7963. elem.attrs({senders: 'none'});
  7964. }
  7965. if (mline.port == '0') {
  7966. // estos hack to reject an m-line
  7967. elem.attrs({senders: 'rejected'});
  7968. }
  7969. elem.up(); // end of content
  7970. }
  7971. elem.up();
  7972. return elem;
  7973. };
  7974. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  7975. var tmp, sctpmap, sctpAttrs, fingerprints;
  7976. var self = this;
  7977. elem.c('transport');
  7978. // XEP-0343 DTLS/SCTP
  7979. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7980. {
  7981. sctpmap = SDPUtil.find_line(
  7982. this.media[mediaindex], 'a=sctpmap:', self.session);
  7983. if (sctpmap)
  7984. {
  7985. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7986. elem.c('sctpmap',
  7987. {
  7988. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7989. number: sctpAttrs[0], /* SCTP port */
  7990. protocol: sctpAttrs[1] /* protocol */
  7991. });
  7992. // Optional stream count attribute
  7993. if (sctpAttrs.length > 2)
  7994. elem.attrs({ streams: sctpAttrs[2]});
  7995. elem.up();
  7996. }
  7997. }
  7998. // XEP-0320
  7999. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  8000. fingerprints.forEach(function(line) {
  8001. tmp = SDPUtil.parse_fingerprint(line);
  8002. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  8003. elem.c('fingerprint').t(tmp.fingerprint);
  8004. delete tmp.fingerprint;
  8005. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  8006. if (line) {
  8007. tmp.setup = line.substr(8);
  8008. }
  8009. elem.attrs(tmp);
  8010. elem.up(); // end of fingerprint
  8011. });
  8012. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  8013. if (tmp) {
  8014. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  8015. elem.attrs(tmp);
  8016. // XEP-0176
  8017. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  8018. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  8019. lines.forEach(function (line) {
  8020. var candidate = SDPUtil.candidateToJingle(line);
  8021. var protocol = (candidate &&
  8022. typeof candidate.protocol === 'string')
  8023. ? candidate.protocol.toLowerCase() : '';
  8024. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8025. (self.removeUdpCandidates && protocol === 'udp')) {
  8026. return;
  8027. }
  8028. elem.c('candidate', candidate).up();
  8029. });
  8030. }
  8031. }
  8032. elem.up(); // end of transport
  8033. }
  8034. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  8035. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  8036. lines.forEach(function (line) {
  8037. var tmp = SDPUtil.parse_rtcpfb(line);
  8038. if (tmp.type == 'trr-int') {
  8039. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  8040. elem.up();
  8041. } else {
  8042. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  8043. if (tmp.params.length > 0) {
  8044. elem.attrs({'subtype': tmp.params[0]});
  8045. }
  8046. elem.up();
  8047. }
  8048. });
  8049. };
  8050. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8051. var media = '';
  8052. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8053. if (tmp.length) {
  8054. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8055. if (tmp.attr('value')) {
  8056. media += tmp.attr('value');
  8057. } else {
  8058. media += '0';
  8059. }
  8060. media += '\r\n';
  8061. }
  8062. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8063. tmp.each(function () {
  8064. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8065. if ($(this).attr('subtype')) {
  8066. media += ' ' + $(this).attr('subtype');
  8067. }
  8068. media += '\r\n';
  8069. });
  8070. return media;
  8071. };
  8072. // construct an SDP from a jingle stanza
  8073. SDP.prototype.fromJingle = function (jingle) {
  8074. var self = this;
  8075. this.raw = 'v=0\r\n' +
  8076. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8077. 's=-\r\n' +
  8078. 't=0 0\r\n';
  8079. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8080. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8081. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8082. var contents = $(group).find('>content').map(function (idx, content) {
  8083. return content.getAttribute('name');
  8084. }).get();
  8085. if (contents.length > 0) {
  8086. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8087. }
  8088. });
  8089. }
  8090. this.session = this.raw;
  8091. jingle.find('>content').each(function () {
  8092. var m = self.jingle2media($(this));
  8093. self.media.push(m);
  8094. });
  8095. // reconstruct msid-semantic -- apparently not necessary
  8096. /*
  8097. var msid = SDPUtil.parse_ssrc(this.raw);
  8098. if (msid.hasOwnProperty('mslabel')) {
  8099. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8100. }
  8101. */
  8102. this.raw = this.session + this.media.join('');
  8103. };
  8104. // translate a jingle content element into an an SDP media part
  8105. SDP.prototype.jingle2media = function (content) {
  8106. var media = '',
  8107. desc = content.find('description'),
  8108. ssrc = desc.attr('ssrc'),
  8109. self = this,
  8110. tmp;
  8111. var sctp = content.find(
  8112. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8113. tmp = { media: desc.attr('media') };
  8114. tmp.port = '1';
  8115. if (content.attr('senders') == 'rejected') {
  8116. // estos hack to reject an m-line.
  8117. tmp.port = '0';
  8118. }
  8119. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8120. if (sctp.length)
  8121. tmp.proto = 'DTLS/SCTP';
  8122. else
  8123. tmp.proto = 'RTP/SAVPF';
  8124. } else {
  8125. tmp.proto = 'RTP/AVPF';
  8126. }
  8127. if (!sctp.length) {
  8128. tmp.fmt = desc.find('payload-type').map(
  8129. function () { return this.getAttribute('id'); }).get();
  8130. media += SDPUtil.build_mline(tmp) + '\r\n';
  8131. } else {
  8132. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8133. media += 'a=sctpmap:' + sctp.attr('number') +
  8134. ' ' + sctp.attr('protocol');
  8135. var streamCount = sctp.attr('streams');
  8136. if (streamCount)
  8137. media += ' ' + streamCount + '\r\n';
  8138. else
  8139. media += '\r\n';
  8140. }
  8141. media += 'c=IN IP4 0.0.0.0\r\n';
  8142. if (!sctp.length)
  8143. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8144. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8145. if (tmp.length) {
  8146. if (tmp.attr('ufrag')) {
  8147. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8148. }
  8149. if (tmp.attr('pwd')) {
  8150. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8151. }
  8152. tmp.find('>fingerprint').each(function () {
  8153. // FIXME: check namespace at some point
  8154. media += 'a=fingerprint:' + this.getAttribute('hash');
  8155. media += ' ' + $(this).text();
  8156. media += '\r\n';
  8157. if (this.getAttribute('setup')) {
  8158. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8159. }
  8160. });
  8161. }
  8162. switch (content.attr('senders')) {
  8163. case 'initiator':
  8164. media += 'a=sendonly\r\n';
  8165. break;
  8166. case 'responder':
  8167. media += 'a=recvonly\r\n';
  8168. break;
  8169. case 'none':
  8170. media += 'a=inactive\r\n';
  8171. break;
  8172. case 'both':
  8173. media += 'a=sendrecv\r\n';
  8174. break;
  8175. }
  8176. media += 'a=mid:' + content.attr('name') + '\r\n';
  8177. // <description><rtcp-mux/></description>
  8178. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8179. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8180. if (desc.find('rtcp-mux').length) {
  8181. media += 'a=rtcp-mux\r\n';
  8182. }
  8183. if (desc.find('encryption').length) {
  8184. desc.find('encryption>crypto').each(function () {
  8185. media += 'a=crypto:' + this.getAttribute('tag');
  8186. media += ' ' + this.getAttribute('crypto-suite');
  8187. media += ' ' + this.getAttribute('key-params');
  8188. if (this.getAttribute('session-params')) {
  8189. media += ' ' + this.getAttribute('session-params');
  8190. }
  8191. media += '\r\n';
  8192. });
  8193. }
  8194. desc.find('payload-type').each(function () {
  8195. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8196. if ($(this).find('>parameter').length) {
  8197. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8198. media += $(this).find('parameter').map(function () {
  8199. return (this.getAttribute('name')
  8200. ? (this.getAttribute('name') + '=') : '') +
  8201. this.getAttribute('value');
  8202. }).get().join('; ');
  8203. media += '\r\n';
  8204. }
  8205. // xep-0293
  8206. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8207. });
  8208. // xep-0293
  8209. media += self.rtcpFbFromJingle(desc, '*');
  8210. // xep-0294
  8211. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8212. tmp.each(function () {
  8213. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8214. });
  8215. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8216. var protocol = this.getAttribute('protocol');
  8217. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8218. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8219. (self.removeUdpCandidates && protocol === 'udp')) {
  8220. return;
  8221. }
  8222. media += SDPUtil.candidateFromJingle(this);
  8223. });
  8224. // XEP-0339 handle ssrc-group attributes
  8225. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8226. var semantics = this.getAttribute('semantics');
  8227. var ssrcs = $(this).find('>source').map(function() {
  8228. return this.getAttribute('ssrc');
  8229. }).get();
  8230. if (ssrcs.length) {
  8231. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8232. }
  8233. });
  8234. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8235. tmp.each(function () {
  8236. var ssrc = this.getAttribute('ssrc');
  8237. $(this).find('>parameter').each(function () {
  8238. var name = this.getAttribute('name');
  8239. var value = this.getAttribute('value');
  8240. value = SDPUtil.filter_special_chars(value);
  8241. media += 'a=ssrc:' + ssrc + ' ' + name;
  8242. if (value && value.length)
  8243. media += ':' + value;
  8244. media += '\r\n';
  8245. });
  8246. });
  8247. return media;
  8248. };
  8249. module.exports = SDP;
  8250. }).call(this,"/modules/xmpp/SDP.js")
  8251. },{"./SDPUtil":32,"jitsi-meet-logger":48}],31:[function(require,module,exports){
  8252. var SDPUtil = require("./SDPUtil");
  8253. function SDPDiffer(mySDP, otherSDP)
  8254. {
  8255. this.mySDP = mySDP;
  8256. this.otherSDP = otherSDP;
  8257. }
  8258. /**
  8259. * Returns map of MediaChannel that contains media contained in
  8260. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8261. */
  8262. SDPDiffer.prototype.getNewMedia = function() {
  8263. // this could be useful in Array.prototype.
  8264. function arrayEquals(array) {
  8265. // if the other array is a falsy value, return
  8266. if (!array)
  8267. return false;
  8268. // compare lengths - can save a lot of time
  8269. if (this.length != array.length)
  8270. return false;
  8271. for (var i = 0, l=this.length; i < l; i++) {
  8272. // Check if we have nested arrays
  8273. if (this[i] instanceof Array && array[i] instanceof Array) {
  8274. // recurse into the nested arrays
  8275. if (!this[i].equals(array[i]))
  8276. return false;
  8277. }
  8278. else if (this[i] != array[i]) {
  8279. // Warning - two different object instances will never be
  8280. // equal: {x:20} != {x:20}
  8281. return false;
  8282. }
  8283. }
  8284. return true;
  8285. }
  8286. var myMedias = this.mySDP.getMediaSsrcMap();
  8287. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8288. var newMedia = {};
  8289. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8290. var myMedia = myMedias[othersMediaIdx];
  8291. var othersMedia = othersMedias[othersMediaIdx];
  8292. if(!myMedia && othersMedia) {
  8293. // Add whole channel
  8294. newMedia[othersMediaIdx] = othersMedia;
  8295. return;
  8296. }
  8297. // Look for new ssrcs across the channel
  8298. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8299. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8300. // Allocate channel if we've found ssrc that doesn't exist in
  8301. // our channel
  8302. if(!newMedia[othersMediaIdx]){
  8303. newMedia[othersMediaIdx] = {
  8304. mediaindex: othersMedia.mediaindex,
  8305. mid: othersMedia.mid,
  8306. ssrcs: {},
  8307. ssrcGroups: []
  8308. };
  8309. }
  8310. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8311. }
  8312. });
  8313. // Look for new ssrc groups across the channels
  8314. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8315. // try to match the other ssrc-group with an ssrc-group of ours
  8316. var matched = false;
  8317. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8318. var mySsrcGroup = myMedia.ssrcGroups[i];
  8319. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8320. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8321. [mySsrcGroup.ssrcs])) {
  8322. matched = true;
  8323. break;
  8324. }
  8325. }
  8326. if (!matched) {
  8327. // Allocate channel if we've found an ssrc-group that doesn't
  8328. // exist in our channel
  8329. if(!newMedia[othersMediaIdx]){
  8330. newMedia[othersMediaIdx] = {
  8331. mediaindex: othersMedia.mediaindex,
  8332. mid: othersMedia.mid,
  8333. ssrcs: {},
  8334. ssrcGroups: []
  8335. };
  8336. }
  8337. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8338. }
  8339. });
  8340. });
  8341. return newMedia;
  8342. };
  8343. /**
  8344. * TODO: document!
  8345. */
  8346. SDPDiffer.prototype.toJingle = function(modify) {
  8347. var sdpMediaSsrcs = this.getNewMedia();
  8348. var modified = false;
  8349. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8350. modified = true;
  8351. var media = sdpMediaSsrcs[mediaindex];
  8352. modify.c('content', {name: media.mid});
  8353. modify.c('description',
  8354. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8355. // FIXME: not completely sure this operates on blocks and / or handles
  8356. // different ssrcs correctly
  8357. // generate sources from lines
  8358. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8359. var mediaSsrc = media.ssrcs[ssrcNum];
  8360. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8361. modify.attrs({ssrc: mediaSsrc.ssrc});
  8362. // iterate over ssrc lines
  8363. mediaSsrc.lines.forEach(function (line) {
  8364. var idx = line.indexOf(' ');
  8365. var kv = line.substr(idx + 1);
  8366. modify.c('parameter');
  8367. if (kv.indexOf(':') == -1) {
  8368. modify.attrs({ name: kv });
  8369. } else {
  8370. var nv = kv.split(':', 2);
  8371. var name = nv[0];
  8372. var value = SDPUtil.filter_special_chars(nv[1]);
  8373. modify.attrs({ name: name });
  8374. modify.attrs({ value: value });
  8375. }
  8376. modify.up(); // end of parameter
  8377. });
  8378. modify.up(); // end of source
  8379. });
  8380. // generate source groups from lines
  8381. media.ssrcGroups.forEach(function(ssrcGroup) {
  8382. if (ssrcGroup.ssrcs.length) {
  8383. modify.c('ssrc-group', {
  8384. semantics: ssrcGroup.semantics,
  8385. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8386. });
  8387. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8388. modify.c('source', { ssrc: ssrc })
  8389. .up(); // end of source
  8390. });
  8391. modify.up(); // end of ssrc-group
  8392. }
  8393. });
  8394. modify.up(); // end of description
  8395. modify.up(); // end of content
  8396. });
  8397. return modified;
  8398. };
  8399. module.exports = SDPDiffer;
  8400. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8401. (function (__filename){
  8402. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8403. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8404. SDPUtil = {
  8405. filter_special_chars: function (text) {
  8406. return text.replace(/[\\\/\{,\}\+]/g, "");
  8407. },
  8408. iceparams: function (mediadesc, sessiondesc) {
  8409. var data = null;
  8410. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8411. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8412. data = {
  8413. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8414. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8415. };
  8416. }
  8417. return data;
  8418. },
  8419. parse_iceufrag: function (line) {
  8420. return line.substring(12);
  8421. },
  8422. build_iceufrag: function (frag) {
  8423. return 'a=ice-ufrag:' + frag;
  8424. },
  8425. parse_icepwd: function (line) {
  8426. return line.substring(10);
  8427. },
  8428. build_icepwd: function (pwd) {
  8429. return 'a=ice-pwd:' + pwd;
  8430. },
  8431. parse_mid: function (line) {
  8432. return line.substring(6);
  8433. },
  8434. parse_mline: function (line) {
  8435. var parts = line.substring(2).split(' '),
  8436. data = {};
  8437. data.media = parts.shift();
  8438. data.port = parts.shift();
  8439. data.proto = parts.shift();
  8440. if (parts[parts.length - 1] === '') { // trailing whitespace
  8441. parts.pop();
  8442. }
  8443. data.fmt = parts;
  8444. return data;
  8445. },
  8446. build_mline: function (mline) {
  8447. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8448. },
  8449. parse_rtpmap: function (line) {
  8450. var parts = line.substring(9).split(' '),
  8451. data = {};
  8452. data.id = parts.shift();
  8453. parts = parts[0].split('/');
  8454. data.name = parts.shift();
  8455. data.clockrate = parts.shift();
  8456. data.channels = parts.length ? parts.shift() : '1';
  8457. return data;
  8458. },
  8459. /**
  8460. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8461. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8462. * @returns [SCTP port number, protocol, streams]
  8463. */
  8464. parse_sctpmap: function (line)
  8465. {
  8466. var parts = line.substring(10).split(' ');
  8467. var sctpPort = parts[0];
  8468. var protocol = parts[1];
  8469. // Stream count is optional
  8470. var streamCount = parts.length > 2 ? parts[2] : null;
  8471. return [sctpPort, protocol, streamCount];// SCTP port
  8472. },
  8473. build_rtpmap: function (el) {
  8474. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8475. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8476. line += '/' + el.getAttribute('channels');
  8477. }
  8478. return line;
  8479. },
  8480. parse_crypto: function (line) {
  8481. var parts = line.substring(9).split(' '),
  8482. data = {};
  8483. data.tag = parts.shift();
  8484. data['crypto-suite'] = parts.shift();
  8485. data['key-params'] = parts.shift();
  8486. if (parts.length) {
  8487. data['session-params'] = parts.join(' ');
  8488. }
  8489. return data;
  8490. },
  8491. parse_fingerprint: function (line) { // RFC 4572
  8492. var parts = line.substring(14).split(' '),
  8493. data = {};
  8494. data.hash = parts.shift();
  8495. data.fingerprint = parts.shift();
  8496. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8497. return data;
  8498. },
  8499. parse_fmtp: function (line) {
  8500. var parts = line.split(' '),
  8501. i, key, value,
  8502. data = [];
  8503. parts.shift();
  8504. parts = parts.join(' ').split(';');
  8505. for (i = 0; i < parts.length; i++) {
  8506. key = parts[i].split('=')[0];
  8507. while (key.length && key[0] == ' ') {
  8508. key = key.substring(1);
  8509. }
  8510. value = parts[i].split('=')[1];
  8511. if (key && value) {
  8512. data.push({name: key, value: value});
  8513. } else if (key) {
  8514. // rfc 4733 (DTMF) style stuff
  8515. data.push({name: '', value: key});
  8516. }
  8517. }
  8518. return data;
  8519. },
  8520. parse_icecandidate: function (line) {
  8521. var candidate = {},
  8522. elems = line.split(' ');
  8523. candidate.foundation = elems[0].substring(12);
  8524. candidate.component = elems[1];
  8525. candidate.protocol = elems[2].toLowerCase();
  8526. candidate.priority = elems[3];
  8527. candidate.ip = elems[4];
  8528. candidate.port = elems[5];
  8529. // elems[6] => "typ"
  8530. candidate.type = elems[7];
  8531. candidate.generation = 0; // default value, may be overwritten below
  8532. for (var i = 8; i < elems.length; i += 2) {
  8533. switch (elems[i]) {
  8534. case 'raddr':
  8535. candidate['rel-addr'] = elems[i + 1];
  8536. break;
  8537. case 'rport':
  8538. candidate['rel-port'] = elems[i + 1];
  8539. break;
  8540. case 'generation':
  8541. candidate.generation = elems[i + 1];
  8542. break;
  8543. case 'tcptype':
  8544. candidate.tcptype = elems[i + 1];
  8545. break;
  8546. default: // TODO
  8547. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8548. }
  8549. }
  8550. candidate.network = '1';
  8551. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8552. return candidate;
  8553. },
  8554. build_icecandidate: function (cand) {
  8555. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8556. line += ' ';
  8557. switch (cand.type) {
  8558. case 'srflx':
  8559. case 'prflx':
  8560. case 'relay':
  8561. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8562. line += 'raddr';
  8563. line += ' ';
  8564. line += cand['rel-addr'];
  8565. line += ' ';
  8566. line += 'rport';
  8567. line += ' ';
  8568. line += cand['rel-port'];
  8569. line += ' ';
  8570. }
  8571. break;
  8572. }
  8573. if (cand.hasOwnAttribute('tcptype')) {
  8574. line += 'tcptype';
  8575. line += ' ';
  8576. line += cand.tcptype;
  8577. line += ' ';
  8578. }
  8579. line += 'generation';
  8580. line += ' ';
  8581. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8582. return line;
  8583. },
  8584. parse_ssrc: function (desc) {
  8585. // proprietary mapping of a=ssrc lines
  8586. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8587. // and parse according to that
  8588. var lines = desc.split('\r\n'),
  8589. data = {};
  8590. for (var i = 0; i < lines.length; i++) {
  8591. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8592. var idx = lines[i].indexOf(' ');
  8593. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8594. }
  8595. }
  8596. return data;
  8597. },
  8598. parse_rtcpfb: function (line) {
  8599. var parts = line.substr(10).split(' ');
  8600. var data = {};
  8601. data.pt = parts.shift();
  8602. data.type = parts.shift();
  8603. data.params = parts;
  8604. return data;
  8605. },
  8606. parse_extmap: function (line) {
  8607. var parts = line.substr(9).split(' ');
  8608. var data = {};
  8609. data.value = parts.shift();
  8610. if (data.value.indexOf('/') != -1) {
  8611. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8612. data.value = data.value.substr(0, data.value.indexOf('/'));
  8613. } else {
  8614. data.direction = 'both';
  8615. }
  8616. data.uri = parts.shift();
  8617. data.params = parts;
  8618. return data;
  8619. },
  8620. find_line: function (haystack, needle, sessionpart) {
  8621. var lines = haystack.split('\r\n');
  8622. for (var i = 0; i < lines.length; i++) {
  8623. if (lines[i].substring(0, needle.length) == needle) {
  8624. return lines[i];
  8625. }
  8626. }
  8627. if (!sessionpart) {
  8628. return false;
  8629. }
  8630. // search session part
  8631. lines = sessionpart.split('\r\n');
  8632. for (var j = 0; j < lines.length; j++) {
  8633. if (lines[j].substring(0, needle.length) == needle) {
  8634. return lines[j];
  8635. }
  8636. }
  8637. return false;
  8638. },
  8639. find_lines: function (haystack, needle, sessionpart) {
  8640. var lines = haystack.split('\r\n'),
  8641. needles = [];
  8642. for (var i = 0; i < lines.length; i++) {
  8643. if (lines[i].substring(0, needle.length) == needle)
  8644. needles.push(lines[i]);
  8645. }
  8646. if (needles.length || !sessionpart) {
  8647. return needles;
  8648. }
  8649. // search session part
  8650. lines = sessionpart.split('\r\n');
  8651. for (var j = 0; j < lines.length; j++) {
  8652. if (lines[j].substring(0, needle.length) == needle) {
  8653. needles.push(lines[j]);
  8654. }
  8655. }
  8656. return needles;
  8657. },
  8658. candidateToJingle: function (line) {
  8659. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8660. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8661. if (line.indexOf('candidate:') === 0) {
  8662. line = 'a=' + line;
  8663. } else if (line.substring(0, 12) != 'a=candidate:') {
  8664. logger.log('parseCandidate called with a line that is not a candidate line');
  8665. logger.log(line);
  8666. return null;
  8667. }
  8668. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8669. line = line.substring(0, line.length - 2);
  8670. var candidate = {},
  8671. elems = line.split(' '),
  8672. i;
  8673. if (elems[6] != 'typ') {
  8674. logger.log('did not find typ in the right place');
  8675. logger.log(line);
  8676. return null;
  8677. }
  8678. candidate.foundation = elems[0].substring(12);
  8679. candidate.component = elems[1];
  8680. candidate.protocol = elems[2].toLowerCase();
  8681. candidate.priority = elems[3];
  8682. candidate.ip = elems[4];
  8683. candidate.port = elems[5];
  8684. // elems[6] => "typ"
  8685. candidate.type = elems[7];
  8686. candidate.generation = '0'; // default, may be overwritten below
  8687. for (i = 8; i < elems.length; i += 2) {
  8688. switch (elems[i]) {
  8689. case 'raddr':
  8690. candidate['rel-addr'] = elems[i + 1];
  8691. break;
  8692. case 'rport':
  8693. candidate['rel-port'] = elems[i + 1];
  8694. break;
  8695. case 'generation':
  8696. candidate.generation = elems[i + 1];
  8697. break;
  8698. case 'tcptype':
  8699. candidate.tcptype = elems[i + 1];
  8700. break;
  8701. default: // TODO
  8702. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8703. }
  8704. }
  8705. candidate.network = '1';
  8706. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8707. return candidate;
  8708. },
  8709. candidateFromJingle: function (cand) {
  8710. var line = 'a=candidate:';
  8711. line += cand.getAttribute('foundation');
  8712. line += ' ';
  8713. line += cand.getAttribute('component');
  8714. line += ' ';
  8715. var protocol = cand.getAttribute('protocol');
  8716. // use tcp candidates for FF
  8717. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8718. protocol = 'tcp';
  8719. }
  8720. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  8721. line += ' ';
  8722. line += cand.getAttribute('priority');
  8723. line += ' ';
  8724. line += cand.getAttribute('ip');
  8725. line += ' ';
  8726. line += cand.getAttribute('port');
  8727. line += ' ';
  8728. line += 'typ';
  8729. line += ' ' + cand.getAttribute('type');
  8730. line += ' ';
  8731. switch (cand.getAttribute('type')) {
  8732. case 'srflx':
  8733. case 'prflx':
  8734. case 'relay':
  8735. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8736. line += 'raddr';
  8737. line += ' ';
  8738. line += cand.getAttribute('rel-addr');
  8739. line += ' ';
  8740. line += 'rport';
  8741. line += ' ';
  8742. line += cand.getAttribute('rel-port');
  8743. line += ' ';
  8744. }
  8745. break;
  8746. }
  8747. if (protocol.toLowerCase() == 'tcp') {
  8748. line += 'tcptype';
  8749. line += ' ';
  8750. line += cand.getAttribute('tcptype');
  8751. line += ' ';
  8752. }
  8753. line += 'generation';
  8754. line += ' ';
  8755. line += cand.getAttribute('generation') || '0';
  8756. return line + '\r\n';
  8757. }
  8758. };
  8759. module.exports = SDPUtil;
  8760. }).call(this,"/modules/xmpp/SDPUtil.js")
  8761. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],33:[function(require,module,exports){
  8762. (function (__filename){
  8763. /* global $ */
  8764. var RTC = require('../RTC/RTC');
  8765. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8766. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8767. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8768. var SSRCReplacement = require("./LocalSSRCReplacement");
  8769. function TraceablePeerConnection(ice_config, constraints, session) {
  8770. var self = this;
  8771. this.session = session;
  8772. var RTCPeerConnectionType = null;
  8773. if (RTCBrowserType.isFirefox()) {
  8774. RTCPeerConnectionType = mozRTCPeerConnection;
  8775. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8776. RTCPeerConnectionType = RTCPeerConnection;
  8777. } else {
  8778. RTCPeerConnectionType = webkitRTCPeerConnection;
  8779. }
  8780. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8781. this.updateLog = [];
  8782. this.stats = {};
  8783. this.statsinterval = null;
  8784. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8785. var Interop = require('sdp-interop').Interop;
  8786. this.interop = new Interop();
  8787. var Simulcast = require('sdp-simulcast');
  8788. this.simulcast = new Simulcast({numOfLayers: 2, explodeRemoteSimulcast: false});
  8789. // override as desired
  8790. this.trace = function (what, info) {
  8791. /*logger.warn('WTRACE', what, info);
  8792. if (info && RTCBrowserType.isIExplorer()) {
  8793. if (info.length > 1024) {
  8794. logger.warn('WTRACE', what, info.substr(1024));
  8795. }
  8796. if (info.length > 2048) {
  8797. logger.warn('WTRACE', what, info.substr(2048));
  8798. }
  8799. }*/
  8800. self.updateLog.push({
  8801. time: new Date(),
  8802. type: what,
  8803. value: info || ""
  8804. });
  8805. };
  8806. this.onicecandidate = null;
  8807. this.peerconnection.onicecandidate = function (event) {
  8808. // FIXME: this causes stack overflow with Temasys Plugin
  8809. if (!RTCBrowserType.isTemasysPluginUsed())
  8810. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8811. if (self.onicecandidate !== null) {
  8812. self.onicecandidate(event);
  8813. }
  8814. };
  8815. this.onaddstream = null;
  8816. this.peerconnection.onaddstream = function (event) {
  8817. self.trace('onaddstream', event.stream.id);
  8818. if (self.onaddstream !== null) {
  8819. self.onaddstream(event);
  8820. }
  8821. };
  8822. this.onremovestream = null;
  8823. this.peerconnection.onremovestream = function (event) {
  8824. self.trace('onremovestream', event.stream.id);
  8825. if (self.onremovestream !== null) {
  8826. self.onremovestream(event);
  8827. }
  8828. };
  8829. this.onsignalingstatechange = null;
  8830. this.peerconnection.onsignalingstatechange = function (event) {
  8831. self.trace('onsignalingstatechange', self.signalingState);
  8832. if (self.onsignalingstatechange !== null) {
  8833. self.onsignalingstatechange(event);
  8834. }
  8835. };
  8836. this.oniceconnectionstatechange = null;
  8837. this.peerconnection.oniceconnectionstatechange = function (event) {
  8838. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8839. if (self.oniceconnectionstatechange !== null) {
  8840. self.oniceconnectionstatechange(event);
  8841. }
  8842. };
  8843. this.onnegotiationneeded = null;
  8844. this.peerconnection.onnegotiationneeded = function (event) {
  8845. self.trace('onnegotiationneeded');
  8846. if (self.onnegotiationneeded !== null) {
  8847. self.onnegotiationneeded(event);
  8848. }
  8849. };
  8850. self.ondatachannel = null;
  8851. this.peerconnection.ondatachannel = function (event) {
  8852. self.trace('ondatachannel', event);
  8853. if (self.ondatachannel !== null) {
  8854. self.ondatachannel(event);
  8855. }
  8856. };
  8857. // XXX: do all non-firefox browsers which we support also support this?
  8858. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8859. this.statsinterval = window.setInterval(function() {
  8860. self.peerconnection.getStats(function(stats) {
  8861. var results = stats.result();
  8862. var now = new Date();
  8863. for (var i = 0; i < results.length; ++i) {
  8864. results[i].names().forEach(function (name) {
  8865. var id = results[i].id + '-' + name;
  8866. if (!self.stats[id]) {
  8867. self.stats[id] = {
  8868. startTime: now,
  8869. endTime: now,
  8870. values: [],
  8871. times: []
  8872. };
  8873. }
  8874. self.stats[id].values.push(results[i].stat(name));
  8875. self.stats[id].times.push(now.getTime());
  8876. if (self.stats[id].values.length > self.maxstats) {
  8877. self.stats[id].values.shift();
  8878. self.stats[id].times.shift();
  8879. }
  8880. self.stats[id].endTime = now;
  8881. });
  8882. }
  8883. });
  8884. }, 1000);
  8885. }
  8886. }
  8887. /**
  8888. * Returns a string representation of a SessionDescription object.
  8889. */
  8890. var dumpSDP = function(description) {
  8891. if (typeof description === 'undefined' || description == null) {
  8892. return '';
  8893. }
  8894. return 'type: ' + description.type + '\r\n' + description.sdp;
  8895. };
  8896. /**
  8897. * Takes a SessionDescription object and returns a "normalized" version.
  8898. * Currently it only takes care of ordering the a=ssrc lines.
  8899. */
  8900. var normalizePlanB = function(desc) {
  8901. if (typeof desc !== 'object' || desc === null ||
  8902. typeof desc.sdp !== 'string') {
  8903. logger.warn('An empty description was passed as an argument.');
  8904. return desc;
  8905. }
  8906. var transform = require('sdp-transform');
  8907. var session = transform.parse(desc.sdp);
  8908. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8909. Array.isArray(session.media)) {
  8910. session.media.forEach(function (mLine) {
  8911. // Chrome appears to be picky about the order in which a=ssrc lines
  8912. // are listed in an m-line when rtx is enabled (and thus there are
  8913. // a=ssrc-group lines with FID semantics). Specifically if we have
  8914. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8915. // the "a=ssrc:S1" lines, SRD fails.
  8916. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8917. // first.
  8918. var firstSsrcs = [];
  8919. var newSsrcLines = [];
  8920. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8921. mLine.ssrcGroups.forEach(function (group) {
  8922. if (typeof group.semantics !== 'undefined' &&
  8923. group.semantics === 'FID') {
  8924. if (typeof group.ssrcs !== 'undefined') {
  8925. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8926. }
  8927. }
  8928. });
  8929. }
  8930. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8931. var i;
  8932. for (i = 0; i<mLine.ssrcs.length; i++){
  8933. if (typeof mLine.ssrcs[i] === 'object'
  8934. && typeof mLine.ssrcs[i].id !== 'undefined'
  8935. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  8936. newSsrcLines.push(mLine.ssrcs[i]);
  8937. delete mLine.ssrcs[i];
  8938. }
  8939. }
  8940. for (i = 0; i<mLine.ssrcs.length; i++){
  8941. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8942. newSsrcLines.push(mLine.ssrcs[i]);
  8943. }
  8944. }
  8945. mLine.ssrcs = newSsrcLines;
  8946. }
  8947. });
  8948. }
  8949. var resStr = transform.write(session);
  8950. return new RTCSessionDescription({
  8951. type: desc.type,
  8952. sdp: resStr
  8953. });
  8954. };
  8955. var getters = {
  8956. signalingState: function () {
  8957. return this.peerconnection.signalingState;
  8958. },
  8959. iceConnectionState: function () {
  8960. return this.peerconnection.iceConnectionState;
  8961. },
  8962. localDescription: function() {
  8963. var desc = this.peerconnection.localDescription;
  8964. // FIXME this should probably be after the Unified Plan -> Plan B
  8965. // transformation.
  8966. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8967. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8968. // if we're running on FF, transform to Plan B first.
  8969. if (RTCBrowserType.usesUnifiedPlan()) {
  8970. desc = this.interop.toPlanB(desc);
  8971. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8972. }
  8973. return desc;
  8974. },
  8975. remoteDescription: function() {
  8976. var desc = this.peerconnection.remoteDescription;
  8977. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8978. // if we're running on FF, transform to Plan B first.
  8979. if (RTCBrowserType.usesUnifiedPlan()) {
  8980. desc = this.interop.toPlanB(desc);
  8981. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8982. }
  8983. return desc;
  8984. }
  8985. };
  8986. Object.keys(getters).forEach(function (prop) {
  8987. Object.defineProperty(
  8988. TraceablePeerConnection.prototype,
  8989. prop, {
  8990. get: getters[prop]
  8991. }
  8992. );
  8993. });
  8994. TraceablePeerConnection.prototype.addStream = function (stream) {
  8995. this.trace('addStream', stream.id);
  8996. try
  8997. {
  8998. this.peerconnection.addStream(stream);
  8999. }
  9000. catch (e)
  9001. {
  9002. logger.error(e);
  9003. }
  9004. };
  9005. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  9006. this.trace('removeStream', stream.id);
  9007. if(stopStreams) {
  9008. RTC.stopMediaStream(stream);
  9009. }
  9010. try {
  9011. // FF doesn't support this yet.
  9012. if (this.peerconnection.removeStream)
  9013. this.peerconnection.removeStream(stream);
  9014. } catch (e) {
  9015. logger.error(e);
  9016. }
  9017. };
  9018. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  9019. this.trace('createDataChannel', label, opts);
  9020. return this.peerconnection.createDataChannel(label, opts);
  9021. };
  9022. TraceablePeerConnection.prototype.setLocalDescription
  9023. = function (description, successCallback, failureCallback) {
  9024. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  9025. // if we're running on FF, transform to Plan A first.
  9026. if (RTCBrowserType.usesUnifiedPlan()) {
  9027. description = this.interop.toUnifiedPlan(description);
  9028. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  9029. }
  9030. var self = this;
  9031. this.peerconnection.setLocalDescription(description,
  9032. function () {
  9033. self.trace('setLocalDescriptionOnSuccess');
  9034. successCallback();
  9035. },
  9036. function (err) {
  9037. self.trace('setLocalDescriptionOnFailure', err);
  9038. failureCallback(err);
  9039. }
  9040. );
  9041. /*
  9042. if (this.statsinterval === null && this.maxstats > 0) {
  9043. // start gathering stats
  9044. }
  9045. */
  9046. };
  9047. TraceablePeerConnection.prototype.setRemoteDescription
  9048. = function (description, successCallback, failureCallback) {
  9049. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9050. // TODO the focus should squeze or explode the remote simulcast
  9051. description = this.simulcast.mungeRemoteDescription(description);
  9052. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9053. // if we're running on FF, transform to Plan A first.
  9054. if (RTCBrowserType.usesUnifiedPlan()) {
  9055. description = this.interop.toUnifiedPlan(description);
  9056. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9057. }
  9058. if (RTCBrowserType.usesPlanB()) {
  9059. description = normalizePlanB(description);
  9060. }
  9061. var self = this;
  9062. this.peerconnection.setRemoteDescription(description,
  9063. function () {
  9064. self.trace('setRemoteDescriptionOnSuccess');
  9065. successCallback();
  9066. },
  9067. function (err) {
  9068. self.trace('setRemoteDescriptionOnFailure', err);
  9069. failureCallback(err);
  9070. }
  9071. );
  9072. /*
  9073. if (this.statsinterval === null && this.maxstats > 0) {
  9074. // start gathering stats
  9075. }
  9076. */
  9077. };
  9078. TraceablePeerConnection.prototype.close = function () {
  9079. this.trace('stop');
  9080. if (this.statsinterval !== null) {
  9081. window.clearInterval(this.statsinterval);
  9082. this.statsinterval = null;
  9083. }
  9084. this.peerconnection.close();
  9085. };
  9086. TraceablePeerConnection.prototype.createOffer
  9087. = function (successCallback, failureCallback, constraints) {
  9088. var self = this;
  9089. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9090. this.peerconnection.createOffer(
  9091. function (offer) {
  9092. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9093. // NOTE this is not tested because in meet the focus generates the
  9094. // offer.
  9095. // if we're running on FF, transform to Plan B first.
  9096. if (RTCBrowserType.usesUnifiedPlan()) {
  9097. offer = self.interop.toPlanB(offer);
  9098. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9099. }
  9100. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9101. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9102. offer = self.simulcast.mungeLocalDescription(offer);
  9103. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9104. }
  9105. successCallback(offer);
  9106. },
  9107. function(err) {
  9108. self.trace('createOfferOnFailure', err);
  9109. failureCallback(err);
  9110. },
  9111. constraints
  9112. );
  9113. };
  9114. TraceablePeerConnection.prototype.createAnswer
  9115. = function (successCallback, failureCallback, constraints) {
  9116. var self = this;
  9117. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9118. this.peerconnection.createAnswer(
  9119. function (answer) {
  9120. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9121. // if we're running on FF, transform to Plan A first.
  9122. if (RTCBrowserType.usesUnifiedPlan()) {
  9123. answer = self.interop.toPlanB(answer);
  9124. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9125. }
  9126. // munge local video SSRC
  9127. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9128. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9129. answer = self.simulcast.mungeLocalDescription(answer);
  9130. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9131. }
  9132. successCallback(answer);
  9133. },
  9134. function(err) {
  9135. self.trace('createAnswerOnFailure', err);
  9136. failureCallback(err);
  9137. },
  9138. constraints
  9139. );
  9140. };
  9141. TraceablePeerConnection.prototype.addIceCandidate
  9142. = function (candidate, successCallback, failureCallback) {
  9143. //var self = this;
  9144. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9145. this.peerconnection.addIceCandidate(candidate);
  9146. /* maybe later
  9147. this.peerconnection.addIceCandidate(candidate,
  9148. function () {
  9149. self.trace('addIceCandidateOnSuccess');
  9150. successCallback();
  9151. },
  9152. function (err) {
  9153. self.trace('addIceCandidateOnFailure', err);
  9154. failureCallback(err);
  9155. }
  9156. );
  9157. */
  9158. };
  9159. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9160. // TODO: Is this the correct way to handle Opera, Temasys?
  9161. if (RTCBrowserType.isFirefox()) {
  9162. // ignore for now...
  9163. if(!errback)
  9164. errback = function () {};
  9165. this.peerconnection.getStats(null, callback, errback);
  9166. } else {
  9167. this.peerconnection.getStats(callback);
  9168. }
  9169. };
  9170. module.exports = TraceablePeerConnection;
  9171. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9172. },{"../../service/xmpp/XMPPEvents":91,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":48,"sdp-interop":66,"sdp-simulcast":73,"sdp-transform":80}],34:[function(require,module,exports){
  9173. (function (__filename){
  9174. /* global $, $iq, APP, config, messageHandler,
  9175. roomName, sessionTerminated, Strophe, Util */
  9176. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9177. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9178. var Settings = require("../settings/Settings");
  9179. var AuthenticationEvents
  9180. = require("../../service/authentication/AuthenticationEvents");
  9181. function createExpBackoffTimer(step) {
  9182. var count = 1;
  9183. return function (reset) {
  9184. // Reset call
  9185. if (reset) {
  9186. count = 1;
  9187. return;
  9188. }
  9189. // Calculate next timeout
  9190. var timeout = Math.pow(2, count - 1);
  9191. count += 1;
  9192. return timeout * step;
  9193. };
  9194. }
  9195. function Moderator(roomName, xmpp, emitter) {
  9196. this.roomName = roomName;
  9197. this.xmppService = xmpp;
  9198. this.getNextTimeout = createExpBackoffTimer(1000);
  9199. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9200. // External authentication stuff
  9201. this.externalAuthEnabled = false;
  9202. this.settings = new Settings(roomName);
  9203. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9204. // it will be enabled automatically if focus detects the component through
  9205. // service discovery.
  9206. this.sipGatewayEnabled =
  9207. this.xmppService.options.hosts.call_control !== undefined;
  9208. this.eventEmitter = emitter;
  9209. this.connection = this.xmppService.connection;
  9210. this.focusUserJid;
  9211. //FIXME:
  9212. // Message listener that talks to POPUP window
  9213. function listener(event) {
  9214. if (event.data && event.data.sessionId) {
  9215. if (event.origin !== window.location.origin) {
  9216. logger.warn("Ignoring sessionId from different origin: " +
  9217. event.origin);
  9218. return;
  9219. }
  9220. localStorage.setItem('sessionId', event.data.sessionId);
  9221. // After popup is closed we will authenticate
  9222. }
  9223. }
  9224. // Register
  9225. if (window.addEventListener) {
  9226. window.addEventListener("message", listener, false);
  9227. } else {
  9228. window.attachEvent("onmessage", listener);
  9229. }
  9230. }
  9231. Moderator.prototype.isExternalAuthEnabled = function () {
  9232. return this.externalAuthEnabled;
  9233. };
  9234. Moderator.prototype.isSipGatewayEnabled = function () {
  9235. return this.sipGatewayEnabled;
  9236. };
  9237. Moderator.prototype.onMucMemberLeft = function (jid) {
  9238. logger.info("Someone left is it focus ? " + jid);
  9239. var resource = Strophe.getResourceFromJid(jid);
  9240. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9241. logger.info(
  9242. "Focus has left the room - leaving conference");
  9243. //hangUp();
  9244. // We'd rather reload to have everything re-initialized
  9245. //FIXME: show some message before reload
  9246. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9247. }
  9248. };
  9249. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9250. if (!this.focusUserJid) {
  9251. this.focusUserJid = focusJid;
  9252. logger.info("Focus jid set to: " + this.focusUserJid);
  9253. }
  9254. };
  9255. Moderator.prototype.getFocusUserJid = function () {
  9256. return this.focusUserJid;
  9257. };
  9258. Moderator.prototype.getFocusComponent = function () {
  9259. // Get focus component address
  9260. var focusComponent = this.xmppService.options.hosts.focus;
  9261. // If not specified use default: 'focus.domain'
  9262. if (!focusComponent) {
  9263. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9264. }
  9265. return focusComponent;
  9266. };
  9267. Moderator.prototype.createConferenceIq = function () {
  9268. // Generate create conference IQ
  9269. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9270. // Session Id used for authentication
  9271. var sessionId = localStorage.getItem('sessionId');
  9272. var machineUID = this.settings.getSettings().uid;
  9273. logger.info(
  9274. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9275. elem.c('conference', {
  9276. xmlns: 'http://jitsi.org/protocol/focus',
  9277. room: this.roomName,
  9278. 'machine-uid': machineUID
  9279. });
  9280. if (sessionId) {
  9281. elem.attrs({ 'session-id': sessionId});
  9282. }
  9283. if (this.xmppService.options.hosts.bridge !== undefined) {
  9284. elem.c(
  9285. 'property', {
  9286. name: 'bridge',
  9287. value: this.xmppService.options.hosts.bridge
  9288. }).up();
  9289. }
  9290. if (this.xmppService.options.enforcedBridge !== undefined) {
  9291. elem.c(
  9292. 'property', {
  9293. name: 'enforcedBridge',
  9294. value: this.xmppService.options.enforcedBridge
  9295. }).up();
  9296. }
  9297. // Tell the focus we have Jigasi configured
  9298. if (this.xmppService.options.hosts.call_control !== undefined) {
  9299. elem.c(
  9300. 'property', {
  9301. name: 'call_control',
  9302. value: this.xmppService.options.hosts.call_control
  9303. }).up();
  9304. }
  9305. if (this.xmppService.options.channelLastN !== undefined) {
  9306. elem.c(
  9307. 'property', {
  9308. name: 'channelLastN',
  9309. value: this.xmppService.options.channelLastN
  9310. }).up();
  9311. }
  9312. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9313. elem.c(
  9314. 'property', {
  9315. name: 'adaptiveLastN',
  9316. value: this.xmppService.options.adaptiveLastN
  9317. }).up();
  9318. }
  9319. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9320. elem.c(
  9321. 'property', {
  9322. name: 'adaptiveSimulcast',
  9323. value: this.xmppService.options.adaptiveSimulcast
  9324. }).up();
  9325. }
  9326. if (this.xmppService.options.openSctp !== undefined) {
  9327. elem.c(
  9328. 'property', {
  9329. name: 'openSctp',
  9330. value: this.xmppService.options.openSctp
  9331. }).up();
  9332. }
  9333. if (this.xmppService.options.startAudioMuted !== undefined)
  9334. {
  9335. elem.c(
  9336. 'property', {
  9337. name: 'startAudioMuted',
  9338. value: this.xmppService.options.startAudioMuted
  9339. }).up();
  9340. }
  9341. if (this.xmppService.options.startVideoMuted !== undefined)
  9342. {
  9343. elem.c(
  9344. 'property', {
  9345. name: 'startVideoMuted',
  9346. value: this.xmppService.options.startVideoMuted
  9347. }).up();
  9348. }
  9349. elem.c(
  9350. 'property', {
  9351. name: 'simulcastMode',
  9352. value: 'rewriting'
  9353. }).up();
  9354. elem.up();
  9355. return elem;
  9356. };
  9357. Moderator.prototype.parseSessionId = function (resultIq) {
  9358. var sessionId = $(resultIq).find('conference').attr('session-id');
  9359. if (sessionId) {
  9360. logger.info('Received sessionId: ' + sessionId);
  9361. localStorage.setItem('sessionId', sessionId);
  9362. }
  9363. };
  9364. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9365. this.setFocusUserJid(
  9366. $(resultIq).find('conference').attr('focusjid'));
  9367. var authenticationEnabled
  9368. = $(resultIq).find(
  9369. '>conference>property' +
  9370. '[name=\'authentication\'][value=\'true\']').length > 0;
  9371. logger.info("Authentication enabled: " + authenticationEnabled);
  9372. this.externalAuthEnabled = $(resultIq).find(
  9373. '>conference>property' +
  9374. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9375. console.info(
  9376. 'External authentication enabled: ' + this.externalAuthEnabled);
  9377. if (!this.externalAuthEnabled) {
  9378. // We expect to receive sessionId in 'internal' authentication mode
  9379. this.parseSessionId(resultIq);
  9380. }
  9381. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9382. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9383. authenticationEnabled, authIdentity);
  9384. // Check if focus has auto-detected Jigasi component(this will be also
  9385. // included if we have passed our host from the config)
  9386. if ($(resultIq).find(
  9387. '>conference>property' +
  9388. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9389. this.sipGatewayEnabled = true;
  9390. }
  9391. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9392. };
  9393. // FIXME = we need to show the fact that we're waiting for the focus
  9394. // to the user(or that focus is not available)
  9395. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9396. // Try to use focus user JID from the config
  9397. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9398. // Send create conference IQ
  9399. var iq = this.createConferenceIq();
  9400. var self = this;
  9401. this.connection.sendIQ(
  9402. iq,
  9403. function (result) {
  9404. // Setup config options
  9405. self.parseConfigOptions(result);
  9406. if ('true' === $(result).find('conference').attr('ready')) {
  9407. // Reset both timers
  9408. self.getNextTimeout(true);
  9409. self.getNextErrorTimeout(true);
  9410. // Exec callback
  9411. callback();
  9412. } else {
  9413. var waitMs = self.getNextTimeout();
  9414. logger.info("Waiting for the focus... " + waitMs);
  9415. // Reset error timeout
  9416. self.getNextErrorTimeout(true);
  9417. window.setTimeout(
  9418. function () {
  9419. self.allocateConferenceFocus(callback);
  9420. }, waitMs);
  9421. }
  9422. },
  9423. function (error) {
  9424. // Invalid session ? remove and try again
  9425. // without session ID to get a new one
  9426. var invalidSession
  9427. = $(error).find('>error>session-invalid').length;
  9428. if (invalidSession) {
  9429. logger.info("Session expired! - removing");
  9430. localStorage.removeItem("sessionId");
  9431. }
  9432. if ($(error).find('>error>graceful-shutdown').length) {
  9433. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9434. return;
  9435. }
  9436. // Check for error returned by the reservation system
  9437. var reservationErr = $(error).find('>error>reservation-error');
  9438. if (reservationErr.length) {
  9439. // Trigger error event
  9440. var errorCode = reservationErr.attr('error-code');
  9441. var errorMsg;
  9442. if ($(error).find('>error>text')) {
  9443. errorMsg = $(error).find('>error>text').text();
  9444. }
  9445. self.eventEmitter.emit(
  9446. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9447. return;
  9448. }
  9449. // Not authorized to create new room
  9450. if ($(error).find('>error>not-authorized').length) {
  9451. logger.warn("Unauthorized to start the conference", error);
  9452. var toDomain
  9453. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9454. if (toDomain !==
  9455. this.xmppService.options.hosts.anonymousdomain) {
  9456. //FIXME: "is external" should come either from
  9457. // the focus or config.js
  9458. self.externalAuthEnabled = true;
  9459. }
  9460. self.eventEmitter.emit(
  9461. XMPPEvents.AUTHENTICATION_REQUIRED,
  9462. function () {
  9463. self.allocateConferenceFocus(
  9464. callback);
  9465. });
  9466. return;
  9467. }
  9468. var waitMs = self.getNextErrorTimeout();
  9469. logger.error("Focus error, retry after " + waitMs, error);
  9470. // Show message
  9471. var focusComponent = self.getFocusComponent();
  9472. var retrySec = waitMs / 1000;
  9473. //FIXME: message is duplicated ?
  9474. // Do not show in case of session invalid
  9475. // which means just a retry
  9476. if (!invalidSession) {
  9477. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9478. focusComponent, retrySec);
  9479. }
  9480. // Reset response timeout
  9481. self.getNextTimeout(true);
  9482. window.setTimeout(
  9483. function () {
  9484. self.allocateConferenceFocus(callback);
  9485. }, waitMs);
  9486. }
  9487. );
  9488. };
  9489. Moderator.prototype.getLoginUrl = function (urlCallback) {
  9490. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9491. iq.c('login-url', {
  9492. xmlns: 'http://jitsi.org/protocol/focus',
  9493. room: this.roomName,
  9494. 'machine-uid': this.settings.getSettings().uid
  9495. });
  9496. this.connection.sendIQ(
  9497. iq,
  9498. function (result) {
  9499. var url = $(result).find('login-url').attr('url');
  9500. url = url = decodeURIComponent(url);
  9501. if (url) {
  9502. logger.info("Got auth url: " + url);
  9503. urlCallback(url);
  9504. } else {
  9505. logger.error(
  9506. "Failed to get auth url from the focus", result);
  9507. }
  9508. },
  9509. function (error) {
  9510. logger.error("Get auth url error", error);
  9511. }
  9512. );
  9513. };
  9514. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  9515. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9516. iq.c('login-url', {
  9517. xmlns: 'http://jitsi.org/protocol/focus',
  9518. room: this.roomName,
  9519. 'machine-uid': this.settings.getSettings().uid,
  9520. popup: true
  9521. });
  9522. this.connection.sendIQ(
  9523. iq,
  9524. function (result) {
  9525. var url = $(result).find('login-url').attr('url');
  9526. url = url = decodeURIComponent(url);
  9527. if (url) {
  9528. logger.info("Got POPUP auth url: " + url);
  9529. urlCallback(url);
  9530. } else {
  9531. logger.error(
  9532. "Failed to get POPUP auth url from the focus", result);
  9533. }
  9534. },
  9535. function (error) {
  9536. logger.error('Get POPUP auth url error', error);
  9537. }
  9538. );
  9539. };
  9540. Moderator.prototype.logout = function (callback) {
  9541. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9542. var sessionId = localStorage.getItem('sessionId');
  9543. if (!sessionId) {
  9544. callback();
  9545. return;
  9546. }
  9547. iq.c('logout', {
  9548. xmlns: 'http://jitsi.org/protocol/focus',
  9549. 'session-id': sessionId
  9550. });
  9551. this.connection.sendIQ(
  9552. iq,
  9553. function (result) {
  9554. var logoutUrl = $(result).find('logout').attr('logout-url');
  9555. if (logoutUrl) {
  9556. logoutUrl = decodeURIComponent(logoutUrl);
  9557. }
  9558. logger.info("Log out OK, url: " + logoutUrl, result);
  9559. localStorage.removeItem('sessionId');
  9560. callback(logoutUrl);
  9561. },
  9562. function (error) {
  9563. logger.error("Logout error", error);
  9564. }
  9565. );
  9566. };
  9567. module.exports = Moderator;
  9568. }).call(this,"/modules/xmpp/moderator.js")
  9569. },{"../../service/authentication/AuthenticationEvents":87,"../../service/xmpp/XMPPEvents":91,"../settings/Settings":21,"jitsi-meet-logger":48}],35:[function(require,module,exports){
  9570. (function (__filename){
  9571. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  9572. Toolbar, Util, Promise */
  9573. var XMPPEvents = require("../../service/XMPP/XMPPEvents");
  9574. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9575. function Recording(ee, connection, focusMucJid) {
  9576. this.eventEmitter = ee;
  9577. this.connection = connection;
  9578. this.state = "off";
  9579. this.focusMucJid = focusMucJid;
  9580. this.url = null;
  9581. this._isSupported = false;
  9582. }
  9583. Recording.prototype.handleJibriPresence = function (jibri) {
  9584. var attributes = jibri.attributes;
  9585. if(!attributes)
  9586. return;
  9587. this._isSupported =
  9588. (attributes.status && attributes.status !== "undefined");
  9589. if(this._isSupported) {
  9590. this.url = attributes.url || null;
  9591. this.state = attributes.status || "off";
  9592. }
  9593. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  9594. };
  9595. Recording.prototype.setRecording = function (state, streamId, callback,
  9596. errCallback){
  9597. if (state == this.state){
  9598. return;
  9599. }
  9600. // FIXME jibri does not accept IQ without 'url' attribute set ?
  9601. var iq = $iq({to: this.focusMucJid, type: 'set'})
  9602. .c('jibri', {
  9603. xmlns: 'http://jitsi.org/protocol/jibri',
  9604. action: (state === 'on') ? 'start' : 'stop',
  9605. streamid: streamId
  9606. }).up();
  9607. logger.log('Set jibri recording: '+state, iq);
  9608. this.connection.sendIQ(
  9609. iq,
  9610. function (result) {
  9611. callback($(result).find('jibri').attr('state'),
  9612. $(result).find('jibri').attr('url'));
  9613. },
  9614. function (error) {
  9615. logger.log('Failed to start recording, error: ', error);
  9616. errCallback(error);
  9617. });
  9618. };
  9619. Recording.prototype.toggleRecording = function (token) {
  9620. var self = this;
  9621. return new Promise(function(resolve, reject) {
  9622. if (!token) {
  9623. reject(new Error("No token passed!"));
  9624. logger.error("No token passed!");
  9625. return;
  9626. }
  9627. if(self.state === "on") {
  9628. reject(new Error("Recording is already started!"));
  9629. logger.error("Recording is already started!");
  9630. return;
  9631. }
  9632. var oldState = self.state;
  9633. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  9634. self.setRecording(newState,
  9635. token,
  9636. function (state, url) {
  9637. logger.log("New recording state: ", state);
  9638. if (state && state !== oldState) {
  9639. self.state = state;
  9640. self.url = url;
  9641. resolve();
  9642. } else {
  9643. reject(new Error("State not changed!"));
  9644. }
  9645. },
  9646. function (error) {
  9647. reject(error);
  9648. }
  9649. );
  9650. });
  9651. };
  9652. /**
  9653. * Returns true if the recording is supproted and false if not.
  9654. */
  9655. Recording.prototype.isSupported = function () {
  9656. return this._isSupported;
  9657. };
  9658. /**
  9659. * Returns null if the recording is not supported, "on" if the recording started
  9660. * and "off" if the recording is not started.
  9661. */
  9662. Recording.prototype.getState = function () {
  9663. return this.state;
  9664. };
  9665. /**
  9666. * Returns the url of the recorded video.
  9667. */
  9668. Recording.prototype.getURL = function () {
  9669. return this.url;
  9670. };
  9671. module.exports = Recording;
  9672. }).call(this,"/modules/xmpp/recording.js")
  9673. },{"../../service/XMPP/XMPPEvents":86,"jitsi-meet-logger":48}],36:[function(require,module,exports){
  9674. (function (__filename){
  9675. /* jshint -W117 */
  9676. /* a simple MUC connection plugin
  9677. * can only handle a single MUC room
  9678. */
  9679. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9680. var ChatRoom = require("./ChatRoom");
  9681. module.exports = function(XMPP) {
  9682. Strophe.addConnectionPlugin('emuc', {
  9683. connection: null,
  9684. rooms: {},//map with the rooms
  9685. init: function (conn) {
  9686. this.connection = conn;
  9687. // add handlers (just once)
  9688. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9689. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9690. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9691. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9692. },
  9693. createRoom: function (jid, password, options) {
  9694. var roomJid = Strophe.getBareJidFromJid(jid);
  9695. if (this.rooms[roomJid]) {
  9696. logger.error("You are already in the room!");
  9697. return;
  9698. }
  9699. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9700. return this.rooms[roomJid];
  9701. },
  9702. doLeave: function (jid) {
  9703. this.rooms[jid].doLeave();
  9704. delete this.rooms[jid];
  9705. },
  9706. onPresence: function (pres) {
  9707. var from = pres.getAttribute('from');
  9708. // What is this for? A workaround for something?
  9709. if (pres.getAttribute('type')) {
  9710. return true;
  9711. }
  9712. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9713. if(!room)
  9714. return;
  9715. // Parse status.
  9716. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9717. room.createNonAnonymousRoom();
  9718. }
  9719. room.onPresence(pres);
  9720. return true;
  9721. },
  9722. onPresenceUnavailable: function (pres) {
  9723. var from = pres.getAttribute('from');
  9724. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9725. if(!room)
  9726. return;
  9727. room.onPresenceUnavailable(pres, from);
  9728. return true;
  9729. },
  9730. onPresenceError: function (pres) {
  9731. var from = pres.getAttribute('from');
  9732. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9733. if(!room)
  9734. return;
  9735. room.onPresenceError(pres, from);
  9736. return true;
  9737. },
  9738. onMessage: function (msg) {
  9739. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9740. var from = msg.getAttribute('from');
  9741. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9742. if(!room)
  9743. return;
  9744. room.onMessage(msg, from);
  9745. return true;
  9746. },
  9747. setJingleSession: function (from, session) {
  9748. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9749. if(!room)
  9750. return;
  9751. room.setJingleSession(session);
  9752. }
  9753. });
  9754. };
  9755. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9756. },{"./ChatRoom":26,"jitsi-meet-logger":48}],37:[function(require,module,exports){
  9757. (function (__filename){
  9758. /* jshint -W117 */
  9759. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9760. var JingleSession = require("./JingleSessionPC");
  9761. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9762. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9763. module.exports = function(XMPP, eventEmitter) {
  9764. Strophe.addConnectionPlugin('jingle', {
  9765. connection: null,
  9766. sessions: {},
  9767. jid2session: {},
  9768. ice_config: {iceServers: []},
  9769. media_constraints: {
  9770. mandatory: {
  9771. 'OfferToReceiveAudio': true,
  9772. 'OfferToReceiveVideo': true
  9773. }
  9774. // MozDontOfferDataChannel: true when this is firefox
  9775. },
  9776. init: function (conn) {
  9777. this.connection = conn;
  9778. if (this.connection.disco) {
  9779. // http://xmpp.org/extensions/xep-0167.html#support
  9780. // http://xmpp.org/extensions/xep-0176.html#support
  9781. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9782. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9783. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9784. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9785. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9786. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9787. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9788. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9789. || RTCBrowserType.isTemasysPluginUsed()) {
  9790. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9791. }
  9792. // this is dealt with by SDP O/A so we don't need to announce this
  9793. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9794. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9795. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9796. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9797. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9798. }
  9799. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9800. },
  9801. onJingle: function (iq) {
  9802. var sid = $(iq).find('jingle').attr('sid');
  9803. var action = $(iq).find('jingle').attr('action');
  9804. var fromJid = iq.getAttribute('from');
  9805. // send ack first
  9806. var ack = $iq({type: 'result',
  9807. to: fromJid,
  9808. id: iq.getAttribute('id')
  9809. });
  9810. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9811. var sess = this.sessions[sid];
  9812. if ('session-initiate' != action) {
  9813. if (sess === null) {
  9814. ack.type = 'error';
  9815. ack.c('error', {type: 'cancel'})
  9816. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9817. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9818. this.connection.send(ack);
  9819. return true;
  9820. }
  9821. // local jid is not checked
  9822. if (fromJid != sess.peerjid) {
  9823. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9824. ack.type = 'error';
  9825. ack.c('error', {type: 'cancel'})
  9826. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9827. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9828. this.connection.send(ack);
  9829. return true;
  9830. }
  9831. } else if (sess !== undefined) {
  9832. // existing session with same session id
  9833. // this might be out-of-order if the sess.peerjid is the same as from
  9834. ack.type = 'error';
  9835. ack.c('error', {type: 'cancel'})
  9836. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9837. logger.warn('duplicate session id', sid);
  9838. this.connection.send(ack);
  9839. return true;
  9840. }
  9841. // FIXME: check for a defined action
  9842. this.connection.send(ack);
  9843. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9844. switch (action) {
  9845. case 'session-initiate':
  9846. console.log("(TIME) received session-initiate:\t",
  9847. window.performance.now());
  9848. var startMuted = $(iq).find('jingle>startmuted');
  9849. if (startMuted && startMuted.length > 0) {
  9850. var audioMuted = startMuted.attr("audio");
  9851. var videoMuted = startMuted.attr("video");
  9852. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9853. audioMuted === "true", videoMuted === "true");
  9854. }
  9855. sess = new JingleSession(
  9856. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9857. this.connection, XMPP);
  9858. // configure session
  9859. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9860. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9861. sess.media_constraints = this.media_constraints;
  9862. sess.ice_config = this.ice_config;
  9863. sess.initialize(fromJid, false);
  9864. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9865. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9866. sess.setOffer($(iq).find('>jingle'));
  9867. this.sessions[sess.sid] = sess;
  9868. this.jid2session[sess.peerjid] = sess;
  9869. // the callback should either
  9870. // .sendAnswer and .accept
  9871. // or .sendTerminate -- not necessarily synchronous
  9872. sess.sendAnswer();
  9873. sess.accept();
  9874. break;
  9875. case 'session-accept':
  9876. sess.setAnswer($(iq).find('>jingle'));
  9877. sess.accept();
  9878. break;
  9879. case 'session-terminate':
  9880. // If this is not the focus sending the terminate, we have
  9881. // nothing more to do here.
  9882. if (Object.keys(this.sessions).length < 1
  9883. || !(this.sessions[Object.keys(this.sessions)[0]]
  9884. instanceof JingleSession))
  9885. {
  9886. break;
  9887. }
  9888. logger.log('terminating...', sess.sid);
  9889. sess.terminate();
  9890. this.terminate(sess.sid);
  9891. if ($(iq).find('>jingle>reason').length) {
  9892. $(document).trigger('callterminated.jingle', [
  9893. sess.sid,
  9894. sess.peerjid,
  9895. $(iq).find('>jingle>reason>:first')[0].tagName,
  9896. $(iq).find('>jingle>reason>text').text()
  9897. ]);
  9898. } else {
  9899. $(document).trigger('callterminated.jingle',
  9900. [sess.sid, sess.peerjid]);
  9901. }
  9902. break;
  9903. case 'transport-info':
  9904. sess.addIceCandidate($(iq).find('>jingle>content'));
  9905. break;
  9906. case 'session-info':
  9907. var affected;
  9908. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9909. $(document).trigger('ringing.jingle', [sess.sid]);
  9910. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9911. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9912. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9913. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9914. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9915. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9916. }
  9917. break;
  9918. case 'addsource': // FIXME: proprietary, un-jingleish
  9919. case 'source-add': // FIXME: proprietary
  9920. sess.addSource($(iq).find('>jingle>content'));
  9921. break;
  9922. case 'removesource': // FIXME: proprietary, un-jingleish
  9923. case 'source-remove': // FIXME: proprietary
  9924. sess.removeSource($(iq).find('>jingle>content'));
  9925. break;
  9926. default:
  9927. logger.warn('jingle action not implemented', action);
  9928. break;
  9929. }
  9930. return true;
  9931. },
  9932. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9933. if (sid === null || sid === undefined) {
  9934. for (sid in this.sessions) {
  9935. if (this.sessions[sid].state != 'ended') {
  9936. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9937. this.sessions[sid].terminate();
  9938. }
  9939. delete this.jid2session[this.sessions[sid].peerjid];
  9940. delete this.sessions[sid];
  9941. }
  9942. } else if (this.sessions.hasOwnProperty(sid)) {
  9943. if (this.sessions[sid].state != 'ended') {
  9944. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9945. this.sessions[sid].terminate();
  9946. }
  9947. delete this.jid2session[this.sessions[sid].peerjid];
  9948. delete this.sessions[sid];
  9949. }
  9950. },
  9951. getStunAndTurnCredentials: function () {
  9952. // get stun and turn configuration from server via xep-0215
  9953. // uses time-limited credentials as described in
  9954. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9955. //
  9956. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9957. // for a prosody module which implements this
  9958. //
  9959. // currently, this doesn't work with updateIce and therefore credentials with a long
  9960. // validity have to be fetched before creating the peerconnection
  9961. // TODO: implement refresh via updateIce as described in
  9962. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9963. var self = this;
  9964. this.connection.sendIQ(
  9965. $iq({type: 'get', to: this.connection.domain})
  9966. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9967. function (res) {
  9968. var iceservers = [];
  9969. $(res).find('>services>service').each(function (idx, el) {
  9970. el = $(el);
  9971. var dict = {};
  9972. var type = el.attr('type');
  9973. switch (type) {
  9974. case 'stun':
  9975. dict.url = 'stun:' + el.attr('host');
  9976. if (el.attr('port')) {
  9977. dict.url += ':' + el.attr('port');
  9978. }
  9979. iceservers.push(dict);
  9980. break;
  9981. case 'turn':
  9982. case 'turns':
  9983. dict.url = type + ':';
  9984. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  9985. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  9986. dict.url += el.attr('username') + '@';
  9987. } else {
  9988. dict.username = el.attr('username'); // only works in M28
  9989. }
  9990. }
  9991. dict.url += el.attr('host');
  9992. if (el.attr('port') && el.attr('port') != '3478') {
  9993. dict.url += ':' + el.attr('port');
  9994. }
  9995. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9996. dict.url += '?transport=' + el.attr('transport');
  9997. }
  9998. if (el.attr('password')) {
  9999. dict.credential = el.attr('password');
  10000. }
  10001. iceservers.push(dict);
  10002. break;
  10003. }
  10004. });
  10005. self.ice_config.iceServers = iceservers;
  10006. },
  10007. function (err) {
  10008. logger.warn('getting turn credentials failed', err);
  10009. logger.warn('is mod_turncredentials or similar installed?');
  10010. }
  10011. );
  10012. // implement push?
  10013. },
  10014. /**
  10015. * Returns the data saved in 'updateLog' in a format to be logged.
  10016. */
  10017. getLog: function () {
  10018. var data = {};
  10019. var self = this;
  10020. Object.keys(this.sessions).forEach(function (sid) {
  10021. var session = self.sessions[sid];
  10022. if (session.peerconnection && session.peerconnection.updateLog) {
  10023. // FIXME: should probably be a .dump call
  10024. data["jingle_" + session.sid] = {
  10025. updateLog: session.peerconnection.updateLog,
  10026. stats: session.peerconnection.stats,
  10027. url: window.location.href
  10028. };
  10029. }
  10030. });
  10031. return data;
  10032. }
  10033. });
  10034. };
  10035. }).call(this,"/modules/xmpp/strophe.jingle.js")
  10036. },{"../../service/xmpp/XMPPEvents":91,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":48}],38:[function(require,module,exports){
  10037. /* global Strophe */
  10038. module.exports = function () {
  10039. Strophe.addConnectionPlugin('logger', {
  10040. // logs raw stanzas and makes them available for download as JSON
  10041. connection: null,
  10042. log: [],
  10043. init: function (conn) {
  10044. this.connection = conn;
  10045. this.connection.rawInput = this.log_incoming.bind(this);
  10046. this.connection.rawOutput = this.log_outgoing.bind(this);
  10047. },
  10048. log_incoming: function (stanza) {
  10049. this.log.push([new Date().getTime(), 'incoming', stanza]);
  10050. },
  10051. log_outgoing: function (stanza) {
  10052. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  10053. }
  10054. });
  10055. };
  10056. },{}],39:[function(require,module,exports){
  10057. (function (__filename){
  10058. /* global $, $iq, Strophe */
  10059. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10060. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10061. /**
  10062. * Ping every 20 sec
  10063. */
  10064. var PING_INTERVAL = 20000;
  10065. /**
  10066. * Ping timeout error after 15 sec of waiting.
  10067. */
  10068. var PING_TIMEOUT = 15000;
  10069. /**
  10070. * Will close the connection after 3 consecutive ping errors.
  10071. */
  10072. var PING_THRESHOLD = 3;
  10073. /**
  10074. * XEP-0199 ping plugin.
  10075. *
  10076. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  10077. */
  10078. module.exports = function (XMPP, eventEmitter) {
  10079. Strophe.addConnectionPlugin('ping', {
  10080. connection: null,
  10081. failedPings: 0,
  10082. /**
  10083. * Initializes the plugin. Method called by Strophe.
  10084. * @param connection Strophe connection instance.
  10085. */
  10086. init: function (connection) {
  10087. this.connection = connection;
  10088. Strophe.addNamespace('PING', "urn:xmpp:ping");
  10089. },
  10090. /**
  10091. * Sends "ping" to given <tt>jid</tt>
  10092. * @param jid the JID to which ping request will be sent.
  10093. * @param success callback called on success.
  10094. * @param error callback called on error.
  10095. * @param timeout ms how long are we going to wait for the response. On
  10096. * timeout <tt>error<//t> callback is called with undefined error
  10097. * argument.
  10098. */
  10099. ping: function (jid, success, error, timeout) {
  10100. var iq = $iq({type: 'get', to: jid});
  10101. iq.c('ping', {xmlns: Strophe.NS.PING});
  10102. this.connection.sendIQ(iq, success, error, timeout);
  10103. },
  10104. /**
  10105. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  10106. * @param jid the JID to be checked for ping support.
  10107. * @param callback function with boolean argument which will be
  10108. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  10109. */
  10110. hasPingSupport: function (jid, callback) {
  10111. this.connection.disco.info(
  10112. jid, null,
  10113. function (result) {
  10114. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  10115. callback(ping.length > 0);
  10116. },
  10117. function (error) {
  10118. logger.error("Ping feature discovery error", error);
  10119. callback(false);
  10120. }
  10121. );
  10122. },
  10123. /**
  10124. * Starts to send ping in given interval to specified remote JID.
  10125. * This plugin supports only one such task and <tt>stopInterval</tt>
  10126. * must be called before starting a new one.
  10127. * @param remoteJid remote JID to which ping requests will be sent to.
  10128. * @param interval task interval in ms.
  10129. */
  10130. startInterval: function (remoteJid, interval) {
  10131. if (this.intervalId) {
  10132. logger.error("Ping task scheduled already");
  10133. return;
  10134. }
  10135. if (!interval)
  10136. interval = PING_INTERVAL;
  10137. var self = this;
  10138. this.intervalId = window.setInterval(function () {
  10139. self.ping(remoteJid,
  10140. function (result) {
  10141. // Ping OK
  10142. self.failedPings = 0;
  10143. },
  10144. function (error) {
  10145. self.failedPings += 1;
  10146. logger.error(
  10147. "Ping " + (error ? "error" : "timeout"), error);
  10148. if (self.failedPings >= PING_THRESHOLD) {
  10149. self.connection.disconnect();
  10150. }
  10151. }, PING_TIMEOUT);
  10152. }, interval);
  10153. logger.info("XMPP pings will be sent every " + interval + " ms");
  10154. },
  10155. /**
  10156. * Stops current "ping" interval task.
  10157. */
  10158. stopInterval: function () {
  10159. if (this.intervalId) {
  10160. window.clearInterval(this.intervalId);
  10161. this.intervalId = null;
  10162. this.failedPings = 0;
  10163. logger.info("Ping interval cleared");
  10164. }
  10165. }
  10166. });
  10167. };
  10168. }).call(this,"/modules/xmpp/strophe.ping.js")
  10169. },{"../../service/xmpp/XMPPEvents":91,"jitsi-meet-logger":48}],40:[function(require,module,exports){
  10170. (function (__filename){
  10171. /* jshint -W117 */
  10172. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10173. module.exports = function() {
  10174. Strophe.addConnectionPlugin('rayo',
  10175. {
  10176. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10177. connection: null,
  10178. init: function (conn) {
  10179. this.connection = conn;
  10180. if (this.connection.disco) {
  10181. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10182. }
  10183. this.connection.addHandler(
  10184. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  10185. null, null);
  10186. },
  10187. onRayo: function (iq) {
  10188. logger.info("Rayo IQ", iq);
  10189. },
  10190. dial: function (to, from, roomName, roomPass, focusMucJid) {
  10191. var self = this;
  10192. return new Promise(function (resolve, reject) {
  10193. if(self.call_resource) {
  10194. reject(new Error("There is already started call!"));
  10195. return;
  10196. }
  10197. if(!focusMucJid) {
  10198. reject(new Error("Internal error!"));
  10199. return;
  10200. }
  10201. var req = $iq(
  10202. {
  10203. type: 'set',
  10204. to: focusMucJid
  10205. }
  10206. );
  10207. req.c('dial',
  10208. {
  10209. xmlns: self.RAYO_XMLNS,
  10210. to: to,
  10211. from: from
  10212. });
  10213. req.c('header',
  10214. {
  10215. name: 'JvbRoomName',
  10216. value: roomName
  10217. }).up();
  10218. if (roomPass !== null && roomPass.length) {
  10219. req.c('header',
  10220. {
  10221. name: 'JvbRoomPassword',
  10222. value: roomPass
  10223. }).up();
  10224. }
  10225. self.connection.sendIQ(
  10226. req,
  10227. function (result) {
  10228. logger.info('Dial result ', result);
  10229. var resource = $(result).find('ref').attr('uri');
  10230. self.call_resource = resource.substr('xmpp:'.length);
  10231. logger.info(
  10232. "Received call resource: " + self.call_resource);
  10233. resolve();
  10234. },
  10235. function (error) {
  10236. logger.info('Dial error ', error);
  10237. reject(error);
  10238. }
  10239. );
  10240. });
  10241. },
  10242. hangup: function () {
  10243. var self = this;
  10244. return new Promise(function (resolve, reject) {
  10245. if (!self.call_resource) {
  10246. reject(new Error("No call in progress"));
  10247. logger.warn("No call in progress");
  10248. return;
  10249. }
  10250. var req = $iq(
  10251. {
  10252. type: 'set',
  10253. to: self.call_resource
  10254. }
  10255. );
  10256. req.c('hangup',
  10257. {
  10258. xmlns: self.RAYO_XMLNS
  10259. });
  10260. self.connection.sendIQ(
  10261. req,
  10262. function (result) {
  10263. logger.info('Hangup result ', result);
  10264. self.call_resource = null;
  10265. resolve();
  10266. },
  10267. function (error) {
  10268. logger.info('Hangup error ', error);
  10269. self.call_resource = null;
  10270. reject(new Error('Hangup error '));
  10271. }
  10272. );
  10273. });
  10274. }
  10275. }
  10276. );
  10277. };
  10278. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10279. },{"jitsi-meet-logger":48}],41:[function(require,module,exports){
  10280. (function (__filename){
  10281. /* global Strophe */
  10282. /**
  10283. * Strophe logger implementation. Logs from level WARN and above.
  10284. */
  10285. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10286. module.exports = function () {
  10287. Strophe.log = function (level, msg) {
  10288. switch (level) {
  10289. case Strophe.LogLevel.WARN:
  10290. logger.warn("Strophe: " + msg);
  10291. break;
  10292. case Strophe.LogLevel.ERROR:
  10293. case Strophe.LogLevel.FATAL:
  10294. logger.error("Strophe: " + msg);
  10295. break;
  10296. }
  10297. };
  10298. Strophe.getStatusString = function (status) {
  10299. switch (status) {
  10300. case Strophe.Status.ERROR:
  10301. return "ERROR";
  10302. case Strophe.Status.CONNECTING:
  10303. return "CONNECTING";
  10304. case Strophe.Status.CONNFAIL:
  10305. return "CONNFAIL";
  10306. case Strophe.Status.AUTHENTICATING:
  10307. return "AUTHENTICATING";
  10308. case Strophe.Status.AUTHFAIL:
  10309. return "AUTHFAIL";
  10310. case Strophe.Status.CONNECTED:
  10311. return "CONNECTED";
  10312. case Strophe.Status.DISCONNECTED:
  10313. return "DISCONNECTED";
  10314. case Strophe.Status.DISCONNECTING:
  10315. return "DISCONNECTING";
  10316. case Strophe.Status.ATTACHED:
  10317. return "ATTACHED";
  10318. default:
  10319. return "unknown";
  10320. }
  10321. };
  10322. };
  10323. }).call(this,"/modules/xmpp/strophe.util.js")
  10324. },{"jitsi-meet-logger":48}],42:[function(require,module,exports){
  10325. (function (__filename){
  10326. /* global $, APP, config, Strophe*/
  10327. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10328. var EventEmitter = require("events");
  10329. var Pako = require("pako");
  10330. var RTCEvents = require("../../service/RTC/RTCEvents");
  10331. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10332. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10333. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10334. var RTC = require("../RTC/RTC");
  10335. var authenticatedUser = false;
  10336. function createConnection(bosh) {
  10337. bosh = bosh || '/http-bind';
  10338. return new Strophe.Connection(bosh);
  10339. };
  10340. //!!!!!!!!!! FIXME: ...
  10341. function initStrophePlugins(XMPP)
  10342. {
  10343. require("./strophe.emuc")(XMPP);
  10344. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10345. // require("./strophe.moderate")(XMPP, eventEmitter);
  10346. require("./strophe.util")();
  10347. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10348. require("./strophe.rayo")();
  10349. require("./strophe.logger")();
  10350. }
  10351. //!!!!!!!!!! FIXME: ...
  10352. ///**
  10353. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10354. // * video type in MUC presence.
  10355. // * @param localStream new or modified <tt>LocalStream</tt>.
  10356. // */
  10357. //function broadcastLocalVideoType(localStream) {
  10358. // if (localStream.videoType)
  10359. // XMPP.addToPresence('videoType', localStream.videoType);
  10360. //}
  10361. //
  10362. //function registerListeners() {
  10363. // RTC.addStreamListener(
  10364. // broadcastLocalVideoType,
  10365. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10366. // );
  10367. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10368. // XMPP.addToPresence("devices", devices);
  10369. // });
  10370. //}
  10371. function XMPP(options) {
  10372. this.eventEmitter = new EventEmitter();
  10373. this.connection = null;
  10374. this.disconnectInProgress = false;
  10375. this.forceMuted = false;
  10376. this.options = options;
  10377. initStrophePlugins(this);
  10378. // registerListeners();
  10379. this.connection = createConnection(options.bosh);
  10380. }
  10381. XMPP.prototype.getConnection = function(){ return connection; };
  10382. XMPP.prototype._connect = function (jid, password) {
  10383. var self = this;
  10384. // connection.connect() starts the connection process.
  10385. //
  10386. // As the connection process proceeds, the user supplied callback will
  10387. // be triggered multiple times with status updates. The callback should
  10388. // take two arguments - the status code and the error condition.
  10389. //
  10390. // The status code will be one of the values in the Strophe.Status
  10391. // constants. The error condition will be one of the conditions defined
  10392. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10393. //
  10394. // The Parameters wait, hold and route are optional and only relevant
  10395. // for BOSH connections. Please see XEP 124 for a more detailed
  10396. // explanation of the optional parameters.
  10397. //
  10398. // Connection status constants for use by the connection handler
  10399. // callback.
  10400. //
  10401. // Status.ERROR - An error has occurred (websockets specific)
  10402. // Status.CONNECTING - The connection is currently being made
  10403. // Status.CONNFAIL - The connection attempt failed
  10404. // Status.AUTHENTICATING - The connection is authenticating
  10405. // Status.AUTHFAIL - The authentication attempt failed
  10406. // Status.CONNECTED - The connection has succeeded
  10407. // Status.DISCONNECTED - The connection has been terminated
  10408. // Status.DISCONNECTING - The connection is currently being terminated
  10409. // Status.ATTACHED - The connection has been attached
  10410. var anonymousConnectionFailed = false;
  10411. var connectionFailed = false;
  10412. var lastErrorMsg;
  10413. this.connection.connect(jid, password, function (status, msg) {
  10414. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10415. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10416. if (status === Strophe.Status.CONNECTED) {
  10417. if (self.options.useStunTurn) {
  10418. self.connection.jingle.getStunAndTurnCredentials();
  10419. }
  10420. logger.info("My Jabber ID: " + self.connection.jid);
  10421. // Schedule ping ?
  10422. var pingJid = self.connection.domain;
  10423. self.connection.ping.hasPingSupport(
  10424. pingJid,
  10425. function (hasPing) {
  10426. if (hasPing)
  10427. self.connection.ping.startInterval(pingJid);
  10428. else
  10429. logger.warn("Ping NOT supported by " + pingJid);
  10430. }
  10431. );
  10432. if (password)
  10433. authenticatedUser = true;
  10434. if (self.connection && self.connection.connected &&
  10435. Strophe.getResourceFromJid(self.connection.jid)) {
  10436. // .connected is true while connecting?
  10437. // self.connection.send($pres());
  10438. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10439. Strophe.getResourceFromJid(self.connection.jid));
  10440. }
  10441. } else if (status === Strophe.Status.CONNFAIL) {
  10442. if (msg === 'x-strophe-bad-non-anon-jid') {
  10443. anonymousConnectionFailed = true;
  10444. }
  10445. else
  10446. {
  10447. connectionFailed = true;
  10448. }
  10449. lastErrorMsg = msg;
  10450. } else if (status === Strophe.Status.DISCONNECTED) {
  10451. // Stop ping interval
  10452. self.connection.ping.stopInterval();
  10453. self.disconnectInProgress = false;
  10454. if (anonymousConnectionFailed) {
  10455. // prompt user for username and password
  10456. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10457. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10458. } else if(connectionFailed) {
  10459. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10460. JitsiConnectionErrors.OTHER_ERROR,
  10461. msg ? msg : lastErrorMsg);
  10462. } else {
  10463. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10464. msg ? msg : lastErrorMsg);
  10465. }
  10466. } else if (status === Strophe.Status.AUTHFAIL) {
  10467. // wrong password or username, prompt user
  10468. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10469. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10470. }
  10471. });
  10472. }
  10473. XMPP.prototype.connect = function (jid, password) {
  10474. if(!jid) {
  10475. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10476. // Force authenticated domain if room is appended with '?login=true'
  10477. if (this.options.hosts.anonymousdomain &&
  10478. window.location.search.indexOf("login=true") !== -1) {
  10479. configDomain = this.options.hosts.domain;
  10480. }
  10481. jid = configDomain || window.location.hostname;
  10482. }
  10483. return this._connect(jid, password);
  10484. };
  10485. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  10486. var roomjid = roomName + '@' + this.options.hosts.muc;
  10487. if (useNicks) {
  10488. if (nick) {
  10489. roomjid += '/' + nick;
  10490. } else {
  10491. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10492. }
  10493. } else {
  10494. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10495. if(!authenticatedUser)
  10496. tmpJid = tmpJid.substr(0, 8);
  10497. roomjid += '/' + tmpJid;
  10498. }
  10499. return this.connection.emuc.createRoom(roomjid, null, options);
  10500. }
  10501. XMPP.prototype.addListener = function(type, listener) {
  10502. this.eventEmitter.on(type, listener);
  10503. };
  10504. XMPP.prototype.removeListener = function (type, listener) {
  10505. this.eventEmitter.removeListener(type, listener);
  10506. };
  10507. //FIXME: this should work with the room
  10508. XMPP.prototype.leaveRoom = function (jid) {
  10509. var handler = this.connection.jingle.jid2session[jid];
  10510. if (handler && handler.peerconnection) {
  10511. // FIXME: probably removing streams is not required and close() should
  10512. // be enough
  10513. if (RTC.localAudio) {
  10514. handler.peerconnection.removeStream(
  10515. RTC.localAudio.getOriginalStream(), true);
  10516. }
  10517. if (RTC.localVideo) {
  10518. handler.peerconnection.removeStream(
  10519. RTC.localVideo.getOriginalStream(), true);
  10520. }
  10521. handler.peerconnection.close();
  10522. }
  10523. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10524. this.connection.emuc.doLeave(jid);
  10525. };
  10526. /**
  10527. * Sends 'data' as a log message to the focus. Returns true iff a message
  10528. * was sent.
  10529. * @param data
  10530. * @returns {boolean} true iff a message was sent.
  10531. */
  10532. XMPP.prototype.sendLogs = function (data) {
  10533. if(!this.connection.emuc.focusMucJid)
  10534. return false;
  10535. var deflate = true;
  10536. var content = JSON.stringify(data);
  10537. if (deflate) {
  10538. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10539. }
  10540. content = Base64.encode(content);
  10541. // XEP-0337-ish
  10542. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10543. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10544. id: 'PeerConnectionStats'});
  10545. message.c('message').t(content).up();
  10546. if (deflate) {
  10547. message.c('tag', {name: "deflated", value: "true"}).up();
  10548. }
  10549. message.up();
  10550. this.connection.send(message);
  10551. return true;
  10552. };
  10553. // Gets the logs from strophe.jingle.
  10554. XMPP.prototype.getJingleLog = function () {
  10555. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10556. };
  10557. // Gets the logs from strophe.
  10558. XMPP.prototype.getXmppLog = function () {
  10559. return this.connection.logger ? this.connection.logger.log : null;
  10560. };
  10561. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10562. this.connection.rayo.dial(to, from, roomName,roomPass);
  10563. };
  10564. XMPP.prototype.setMute = function (jid, mute) {
  10565. this.connection.moderate.setMute(jid, mute);
  10566. };
  10567. XMPP.prototype.eject = function (jid) {
  10568. this.connection.moderate.eject(jid);
  10569. };
  10570. XMPP.prototype.getSessions = function () {
  10571. return this.connection.jingle.sessions;
  10572. };
  10573. XMPP.prototype.disconnect = function () {
  10574. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10575. {
  10576. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10577. return;
  10578. }
  10579. this.disconnectInProgress = true;
  10580. this.connection.disconnect();
  10581. };
  10582. /**
  10583. * Gets the SSRC of local media stream.
  10584. * @param mediaType the media type that tells whether we want to get
  10585. * the SSRC of local audio or video stream.
  10586. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  10587. * not available.
  10588. */
  10589. XMPP.prototype.getLocalSSRC = function (mediaType) {
  10590. if (this.connection.jingle.activecall &&
  10591. this.connection.jingle.activecall.peerconnection) {
  10592. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  10593. } else {
  10594. return null;
  10595. }
  10596. };
  10597. module.exports = XMPP;
  10598. }).call(this,"/modules/xmpp/xmpp.js")
  10599. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":84,"../../service/xmpp/XMPPEvents":91,"../RTC/RTC":16,"./strophe.emuc":36,"./strophe.jingle":37,"./strophe.logger":38,"./strophe.ping":39,"./strophe.rayo":40,"./strophe.util":41,"events":44,"jitsi-meet-logger":48,"pako":49}],43:[function(require,module,exports){
  10600. (function (process){
  10601. /*!
  10602. * async
  10603. * https://github.com/caolan/async
  10604. *
  10605. * Copyright 2010-2014 Caolan McMahon
  10606. * Released under the MIT license
  10607. */
  10608. /*jshint onevar: false, indent:4 */
  10609. /*global setImmediate: false, setTimeout: false, console: false */
  10610. (function () {
  10611. var async = {};
  10612. // global on the server, window in the browser
  10613. var root, previous_async;
  10614. root = this;
  10615. if (root != null) {
  10616. previous_async = root.async;
  10617. }
  10618. async.noConflict = function () {
  10619. root.async = previous_async;
  10620. return async;
  10621. };
  10622. function only_once(fn) {
  10623. var called = false;
  10624. return function() {
  10625. if (called) throw new Error("Callback was already called.");
  10626. called = true;
  10627. fn.apply(root, arguments);
  10628. }
  10629. }
  10630. //// cross-browser compatiblity functions ////
  10631. var _toString = Object.prototype.toString;
  10632. var _isArray = Array.isArray || function (obj) {
  10633. return _toString.call(obj) === '[object Array]';
  10634. };
  10635. var _each = function (arr, iterator) {
  10636. if (arr.forEach) {
  10637. return arr.forEach(iterator);
  10638. }
  10639. for (var i = 0; i < arr.length; i += 1) {
  10640. iterator(arr[i], i, arr);
  10641. }
  10642. };
  10643. var _map = function (arr, iterator) {
  10644. if (arr.map) {
  10645. return arr.map(iterator);
  10646. }
  10647. var results = [];
  10648. _each(arr, function (x, i, a) {
  10649. results.push(iterator(x, i, a));
  10650. });
  10651. return results;
  10652. };
  10653. var _reduce = function (arr, iterator, memo) {
  10654. if (arr.reduce) {
  10655. return arr.reduce(iterator, memo);
  10656. }
  10657. _each(arr, function (x, i, a) {
  10658. memo = iterator(memo, x, i, a);
  10659. });
  10660. return memo;
  10661. };
  10662. var _keys = function (obj) {
  10663. if (Object.keys) {
  10664. return Object.keys(obj);
  10665. }
  10666. var keys = [];
  10667. for (var k in obj) {
  10668. if (obj.hasOwnProperty(k)) {
  10669. keys.push(k);
  10670. }
  10671. }
  10672. return keys;
  10673. };
  10674. //// exported async module functions ////
  10675. //// nextTick implementation with browser-compatible fallback ////
  10676. if (typeof process === 'undefined' || !(process.nextTick)) {
  10677. if (typeof setImmediate === 'function') {
  10678. async.nextTick = function (fn) {
  10679. // not a direct alias for IE10 compatibility
  10680. setImmediate(fn);
  10681. };
  10682. async.setImmediate = async.nextTick;
  10683. }
  10684. else {
  10685. async.nextTick = function (fn) {
  10686. setTimeout(fn, 0);
  10687. };
  10688. async.setImmediate = async.nextTick;
  10689. }
  10690. }
  10691. else {
  10692. async.nextTick = process.nextTick;
  10693. if (typeof setImmediate !== 'undefined') {
  10694. async.setImmediate = function (fn) {
  10695. // not a direct alias for IE10 compatibility
  10696. setImmediate(fn);
  10697. };
  10698. }
  10699. else {
  10700. async.setImmediate = async.nextTick;
  10701. }
  10702. }
  10703. async.each = function (arr, iterator, callback) {
  10704. callback = callback || function () {};
  10705. if (!arr.length) {
  10706. return callback();
  10707. }
  10708. var completed = 0;
  10709. _each(arr, function (x) {
  10710. iterator(x, only_once(done) );
  10711. });
  10712. function done(err) {
  10713. if (err) {
  10714. callback(err);
  10715. callback = function () {};
  10716. }
  10717. else {
  10718. completed += 1;
  10719. if (completed >= arr.length) {
  10720. callback();
  10721. }
  10722. }
  10723. }
  10724. };
  10725. async.forEach = async.each;
  10726. async.eachSeries = function (arr, iterator, callback) {
  10727. callback = callback || function () {};
  10728. if (!arr.length) {
  10729. return callback();
  10730. }
  10731. var completed = 0;
  10732. var iterate = function () {
  10733. iterator(arr[completed], function (err) {
  10734. if (err) {
  10735. callback(err);
  10736. callback = function () {};
  10737. }
  10738. else {
  10739. completed += 1;
  10740. if (completed >= arr.length) {
  10741. callback();
  10742. }
  10743. else {
  10744. iterate();
  10745. }
  10746. }
  10747. });
  10748. };
  10749. iterate();
  10750. };
  10751. async.forEachSeries = async.eachSeries;
  10752. async.eachLimit = function (arr, limit, iterator, callback) {
  10753. var fn = _eachLimit(limit);
  10754. fn.apply(null, [arr, iterator, callback]);
  10755. };
  10756. async.forEachLimit = async.eachLimit;
  10757. var _eachLimit = function (limit) {
  10758. return function (arr, iterator, callback) {
  10759. callback = callback || function () {};
  10760. if (!arr.length || limit <= 0) {
  10761. return callback();
  10762. }
  10763. var completed = 0;
  10764. var started = 0;
  10765. var running = 0;
  10766. (function replenish () {
  10767. if (completed >= arr.length) {
  10768. return callback();
  10769. }
  10770. while (running < limit && started < arr.length) {
  10771. started += 1;
  10772. running += 1;
  10773. iterator(arr[started - 1], function (err) {
  10774. if (err) {
  10775. callback(err);
  10776. callback = function () {};
  10777. }
  10778. else {
  10779. completed += 1;
  10780. running -= 1;
  10781. if (completed >= arr.length) {
  10782. callback();
  10783. }
  10784. else {
  10785. replenish();
  10786. }
  10787. }
  10788. });
  10789. }
  10790. })();
  10791. };
  10792. };
  10793. var doParallel = function (fn) {
  10794. return function () {
  10795. var args = Array.prototype.slice.call(arguments);
  10796. return fn.apply(null, [async.each].concat(args));
  10797. };
  10798. };
  10799. var doParallelLimit = function(limit, fn) {
  10800. return function () {
  10801. var args = Array.prototype.slice.call(arguments);
  10802. return fn.apply(null, [_eachLimit(limit)].concat(args));
  10803. };
  10804. };
  10805. var doSeries = function (fn) {
  10806. return function () {
  10807. var args = Array.prototype.slice.call(arguments);
  10808. return fn.apply(null, [async.eachSeries].concat(args));
  10809. };
  10810. };
  10811. var _asyncMap = function (eachfn, arr, iterator, callback) {
  10812. arr = _map(arr, function (x, i) {
  10813. return {index: i, value: x};
  10814. });
  10815. if (!callback) {
  10816. eachfn(arr, function (x, callback) {
  10817. iterator(x.value, function (err) {
  10818. callback(err);
  10819. });
  10820. });
  10821. } else {
  10822. var results = [];
  10823. eachfn(arr, function (x, callback) {
  10824. iterator(x.value, function (err, v) {
  10825. results[x.index] = v;
  10826. callback(err);
  10827. });
  10828. }, function (err) {
  10829. callback(err, results);
  10830. });
  10831. }
  10832. };
  10833. async.map = doParallel(_asyncMap);
  10834. async.mapSeries = doSeries(_asyncMap);
  10835. async.mapLimit = function (arr, limit, iterator, callback) {
  10836. return _mapLimit(limit)(arr, iterator, callback);
  10837. };
  10838. var _mapLimit = function(limit) {
  10839. return doParallelLimit(limit, _asyncMap);
  10840. };
  10841. // reduce only has a series version, as doing reduce in parallel won't
  10842. // work in many situations.
  10843. async.reduce = function (arr, memo, iterator, callback) {
  10844. async.eachSeries(arr, function (x, callback) {
  10845. iterator(memo, x, function (err, v) {
  10846. memo = v;
  10847. callback(err);
  10848. });
  10849. }, function (err) {
  10850. callback(err, memo);
  10851. });
  10852. };
  10853. // inject alias
  10854. async.inject = async.reduce;
  10855. // foldl alias
  10856. async.foldl = async.reduce;
  10857. async.reduceRight = function (arr, memo, iterator, callback) {
  10858. var reversed = _map(arr, function (x) {
  10859. return x;
  10860. }).reverse();
  10861. async.reduce(reversed, memo, iterator, callback);
  10862. };
  10863. // foldr alias
  10864. async.foldr = async.reduceRight;
  10865. var _filter = function (eachfn, arr, iterator, callback) {
  10866. var results = [];
  10867. arr = _map(arr, function (x, i) {
  10868. return {index: i, value: x};
  10869. });
  10870. eachfn(arr, function (x, callback) {
  10871. iterator(x.value, function (v) {
  10872. if (v) {
  10873. results.push(x);
  10874. }
  10875. callback();
  10876. });
  10877. }, function (err) {
  10878. callback(_map(results.sort(function (a, b) {
  10879. return a.index - b.index;
  10880. }), function (x) {
  10881. return x.value;
  10882. }));
  10883. });
  10884. };
  10885. async.filter = doParallel(_filter);
  10886. async.filterSeries = doSeries(_filter);
  10887. // select alias
  10888. async.select = async.filter;
  10889. async.selectSeries = async.filterSeries;
  10890. var _reject = function (eachfn, arr, iterator, callback) {
  10891. var results = [];
  10892. arr = _map(arr, function (x, i) {
  10893. return {index: i, value: x};
  10894. });
  10895. eachfn(arr, function (x, callback) {
  10896. iterator(x.value, function (v) {
  10897. if (!v) {
  10898. results.push(x);
  10899. }
  10900. callback();
  10901. });
  10902. }, function (err) {
  10903. callback(_map(results.sort(function (a, b) {
  10904. return a.index - b.index;
  10905. }), function (x) {
  10906. return x.value;
  10907. }));
  10908. });
  10909. };
  10910. async.reject = doParallel(_reject);
  10911. async.rejectSeries = doSeries(_reject);
  10912. var _detect = function (eachfn, arr, iterator, main_callback) {
  10913. eachfn(arr, function (x, callback) {
  10914. iterator(x, function (result) {
  10915. if (result) {
  10916. main_callback(x);
  10917. main_callback = function () {};
  10918. }
  10919. else {
  10920. callback();
  10921. }
  10922. });
  10923. }, function (err) {
  10924. main_callback();
  10925. });
  10926. };
  10927. async.detect = doParallel(_detect);
  10928. async.detectSeries = doSeries(_detect);
  10929. async.some = function (arr, iterator, main_callback) {
  10930. async.each(arr, function (x, callback) {
  10931. iterator(x, function (v) {
  10932. if (v) {
  10933. main_callback(true);
  10934. main_callback = function () {};
  10935. }
  10936. callback();
  10937. });
  10938. }, function (err) {
  10939. main_callback(false);
  10940. });
  10941. };
  10942. // any alias
  10943. async.any = async.some;
  10944. async.every = function (arr, iterator, main_callback) {
  10945. async.each(arr, function (x, callback) {
  10946. iterator(x, function (v) {
  10947. if (!v) {
  10948. main_callback(false);
  10949. main_callback = function () {};
  10950. }
  10951. callback();
  10952. });
  10953. }, function (err) {
  10954. main_callback(true);
  10955. });
  10956. };
  10957. // all alias
  10958. async.all = async.every;
  10959. async.sortBy = function (arr, iterator, callback) {
  10960. async.map(arr, function (x, callback) {
  10961. iterator(x, function (err, criteria) {
  10962. if (err) {
  10963. callback(err);
  10964. }
  10965. else {
  10966. callback(null, {value: x, criteria: criteria});
  10967. }
  10968. });
  10969. }, function (err, results) {
  10970. if (err) {
  10971. return callback(err);
  10972. }
  10973. else {
  10974. var fn = function (left, right) {
  10975. var a = left.criteria, b = right.criteria;
  10976. return a < b ? -1 : a > b ? 1 : 0;
  10977. };
  10978. callback(null, _map(results.sort(fn), function (x) {
  10979. return x.value;
  10980. }));
  10981. }
  10982. });
  10983. };
  10984. async.auto = function (tasks, callback) {
  10985. callback = callback || function () {};
  10986. var keys = _keys(tasks);
  10987. var remainingTasks = keys.length
  10988. if (!remainingTasks) {
  10989. return callback();
  10990. }
  10991. var results = {};
  10992. var listeners = [];
  10993. var addListener = function (fn) {
  10994. listeners.unshift(fn);
  10995. };
  10996. var removeListener = function (fn) {
  10997. for (var i = 0; i < listeners.length; i += 1) {
  10998. if (listeners[i] === fn) {
  10999. listeners.splice(i, 1);
  11000. return;
  11001. }
  11002. }
  11003. };
  11004. var taskComplete = function () {
  11005. remainingTasks--
  11006. _each(listeners.slice(0), function (fn) {
  11007. fn();
  11008. });
  11009. };
  11010. addListener(function () {
  11011. if (!remainingTasks) {
  11012. var theCallback = callback;
  11013. // prevent final callback from calling itself if it errors
  11014. callback = function () {};
  11015. theCallback(null, results);
  11016. }
  11017. });
  11018. _each(keys, function (k) {
  11019. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  11020. var taskCallback = function (err) {
  11021. var args = Array.prototype.slice.call(arguments, 1);
  11022. if (args.length <= 1) {
  11023. args = args[0];
  11024. }
  11025. if (err) {
  11026. var safeResults = {};
  11027. _each(_keys(results), function(rkey) {
  11028. safeResults[rkey] = results[rkey];
  11029. });
  11030. safeResults[k] = args;
  11031. callback(err, safeResults);
  11032. // stop subsequent errors hitting callback multiple times
  11033. callback = function () {};
  11034. }
  11035. else {
  11036. results[k] = args;
  11037. async.setImmediate(taskComplete);
  11038. }
  11039. };
  11040. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  11041. var ready = function () {
  11042. return _reduce(requires, function (a, x) {
  11043. return (a && results.hasOwnProperty(x));
  11044. }, true) && !results.hasOwnProperty(k);
  11045. };
  11046. if (ready()) {
  11047. task[task.length - 1](taskCallback, results);
  11048. }
  11049. else {
  11050. var listener = function () {
  11051. if (ready()) {
  11052. removeListener(listener);
  11053. task[task.length - 1](taskCallback, results);
  11054. }
  11055. };
  11056. addListener(listener);
  11057. }
  11058. });
  11059. };
  11060. async.retry = function(times, task, callback) {
  11061. var DEFAULT_TIMES = 5;
  11062. var attempts = [];
  11063. // Use defaults if times not passed
  11064. if (typeof times === 'function') {
  11065. callback = task;
  11066. task = times;
  11067. times = DEFAULT_TIMES;
  11068. }
  11069. // Make sure times is a number
  11070. times = parseInt(times, 10) || DEFAULT_TIMES;
  11071. var wrappedTask = function(wrappedCallback, wrappedResults) {
  11072. var retryAttempt = function(task, finalAttempt) {
  11073. return function(seriesCallback) {
  11074. task(function(err, result){
  11075. seriesCallback(!err || finalAttempt, {err: err, result: result});
  11076. }, wrappedResults);
  11077. };
  11078. };
  11079. while (times) {
  11080. attempts.push(retryAttempt(task, !(times-=1)));
  11081. }
  11082. async.series(attempts, function(done, data){
  11083. data = data[data.length - 1];
  11084. (wrappedCallback || callback)(data.err, data.result);
  11085. });
  11086. }
  11087. // If a callback is passed, run this as a controll flow
  11088. return callback ? wrappedTask() : wrappedTask
  11089. };
  11090. async.waterfall = function (tasks, callback) {
  11091. callback = callback || function () {};
  11092. if (!_isArray(tasks)) {
  11093. var err = new Error('First argument to waterfall must be an array of functions');
  11094. return callback(err);
  11095. }
  11096. if (!tasks.length) {
  11097. return callback();
  11098. }
  11099. var wrapIterator = function (iterator) {
  11100. return function (err) {
  11101. if (err) {
  11102. callback.apply(null, arguments);
  11103. callback = function () {};
  11104. }
  11105. else {
  11106. var args = Array.prototype.slice.call(arguments, 1);
  11107. var next = iterator.next();
  11108. if (next) {
  11109. args.push(wrapIterator(next));
  11110. }
  11111. else {
  11112. args.push(callback);
  11113. }
  11114. async.setImmediate(function () {
  11115. iterator.apply(null, args);
  11116. });
  11117. }
  11118. };
  11119. };
  11120. wrapIterator(async.iterator(tasks))();
  11121. };
  11122. var _parallel = function(eachfn, tasks, callback) {
  11123. callback = callback || function () {};
  11124. if (_isArray(tasks)) {
  11125. eachfn.map(tasks, function (fn, callback) {
  11126. if (fn) {
  11127. fn(function (err) {
  11128. var args = Array.prototype.slice.call(arguments, 1);
  11129. if (args.length <= 1) {
  11130. args = args[0];
  11131. }
  11132. callback.call(null, err, args);
  11133. });
  11134. }
  11135. }, callback);
  11136. }
  11137. else {
  11138. var results = {};
  11139. eachfn.each(_keys(tasks), function (k, callback) {
  11140. tasks[k](function (err) {
  11141. var args = Array.prototype.slice.call(arguments, 1);
  11142. if (args.length <= 1) {
  11143. args = args[0];
  11144. }
  11145. results[k] = args;
  11146. callback(err);
  11147. });
  11148. }, function (err) {
  11149. callback(err, results);
  11150. });
  11151. }
  11152. };
  11153. async.parallel = function (tasks, callback) {
  11154. _parallel({ map: async.map, each: async.each }, tasks, callback);
  11155. };
  11156. async.parallelLimit = function(tasks, limit, callback) {
  11157. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  11158. };
  11159. async.series = function (tasks, callback) {
  11160. callback = callback || function () {};
  11161. if (_isArray(tasks)) {
  11162. async.mapSeries(tasks, function (fn, callback) {
  11163. if (fn) {
  11164. fn(function (err) {
  11165. var args = Array.prototype.slice.call(arguments, 1);
  11166. if (args.length <= 1) {
  11167. args = args[0];
  11168. }
  11169. callback.call(null, err, args);
  11170. });
  11171. }
  11172. }, callback);
  11173. }
  11174. else {
  11175. var results = {};
  11176. async.eachSeries(_keys(tasks), function (k, callback) {
  11177. tasks[k](function (err) {
  11178. var args = Array.prototype.slice.call(arguments, 1);
  11179. if (args.length <= 1) {
  11180. args = args[0];
  11181. }
  11182. results[k] = args;
  11183. callback(err);
  11184. });
  11185. }, function (err) {
  11186. callback(err, results);
  11187. });
  11188. }
  11189. };
  11190. async.iterator = function (tasks) {
  11191. var makeCallback = function (index) {
  11192. var fn = function () {
  11193. if (tasks.length) {
  11194. tasks[index].apply(null, arguments);
  11195. }
  11196. return fn.next();
  11197. };
  11198. fn.next = function () {
  11199. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11200. };
  11201. return fn;
  11202. };
  11203. return makeCallback(0);
  11204. };
  11205. async.apply = function (fn) {
  11206. var args = Array.prototype.slice.call(arguments, 1);
  11207. return function () {
  11208. return fn.apply(
  11209. null, args.concat(Array.prototype.slice.call(arguments))
  11210. );
  11211. };
  11212. };
  11213. var _concat = function (eachfn, arr, fn, callback) {
  11214. var r = [];
  11215. eachfn(arr, function (x, cb) {
  11216. fn(x, function (err, y) {
  11217. r = r.concat(y || []);
  11218. cb(err);
  11219. });
  11220. }, function (err) {
  11221. callback(err, r);
  11222. });
  11223. };
  11224. async.concat = doParallel(_concat);
  11225. async.concatSeries = doSeries(_concat);
  11226. async.whilst = function (test, iterator, callback) {
  11227. if (test()) {
  11228. iterator(function (err) {
  11229. if (err) {
  11230. return callback(err);
  11231. }
  11232. async.whilst(test, iterator, callback);
  11233. });
  11234. }
  11235. else {
  11236. callback();
  11237. }
  11238. };
  11239. async.doWhilst = function (iterator, test, callback) {
  11240. iterator(function (err) {
  11241. if (err) {
  11242. return callback(err);
  11243. }
  11244. var args = Array.prototype.slice.call(arguments, 1);
  11245. if (test.apply(null, args)) {
  11246. async.doWhilst(iterator, test, callback);
  11247. }
  11248. else {
  11249. callback();
  11250. }
  11251. });
  11252. };
  11253. async.until = function (test, iterator, callback) {
  11254. if (!test()) {
  11255. iterator(function (err) {
  11256. if (err) {
  11257. return callback(err);
  11258. }
  11259. async.until(test, iterator, callback);
  11260. });
  11261. }
  11262. else {
  11263. callback();
  11264. }
  11265. };
  11266. async.doUntil = function (iterator, test, callback) {
  11267. iterator(function (err) {
  11268. if (err) {
  11269. return callback(err);
  11270. }
  11271. var args = Array.prototype.slice.call(arguments, 1);
  11272. if (!test.apply(null, args)) {
  11273. async.doUntil(iterator, test, callback);
  11274. }
  11275. else {
  11276. callback();
  11277. }
  11278. });
  11279. };
  11280. async.queue = function (worker, concurrency) {
  11281. if (concurrency === undefined) {
  11282. concurrency = 1;
  11283. }
  11284. function _insert(q, data, pos, callback) {
  11285. if (!q.started){
  11286. q.started = true;
  11287. }
  11288. if (!_isArray(data)) {
  11289. data = [data];
  11290. }
  11291. if(data.length == 0) {
  11292. // call drain immediately if there are no tasks
  11293. return async.setImmediate(function() {
  11294. if (q.drain) {
  11295. q.drain();
  11296. }
  11297. });
  11298. }
  11299. _each(data, function(task) {
  11300. var item = {
  11301. data: task,
  11302. callback: typeof callback === 'function' ? callback : null
  11303. };
  11304. if (pos) {
  11305. q.tasks.unshift(item);
  11306. } else {
  11307. q.tasks.push(item);
  11308. }
  11309. if (q.saturated && q.tasks.length === q.concurrency) {
  11310. q.saturated();
  11311. }
  11312. async.setImmediate(q.process);
  11313. });
  11314. }
  11315. var workers = 0;
  11316. var q = {
  11317. tasks: [],
  11318. concurrency: concurrency,
  11319. saturated: null,
  11320. empty: null,
  11321. drain: null,
  11322. started: false,
  11323. paused: false,
  11324. push: function (data, callback) {
  11325. _insert(q, data, false, callback);
  11326. },
  11327. kill: function () {
  11328. q.drain = null;
  11329. q.tasks = [];
  11330. },
  11331. unshift: function (data, callback) {
  11332. _insert(q, data, true, callback);
  11333. },
  11334. process: function () {
  11335. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11336. var task = q.tasks.shift();
  11337. if (q.empty && q.tasks.length === 0) {
  11338. q.empty();
  11339. }
  11340. workers += 1;
  11341. var next = function () {
  11342. workers -= 1;
  11343. if (task.callback) {
  11344. task.callback.apply(task, arguments);
  11345. }
  11346. if (q.drain && q.tasks.length + workers === 0) {
  11347. q.drain();
  11348. }
  11349. q.process();
  11350. };
  11351. var cb = only_once(next);
  11352. worker(task.data, cb);
  11353. }
  11354. },
  11355. length: function () {
  11356. return q.tasks.length;
  11357. },
  11358. running: function () {
  11359. return workers;
  11360. },
  11361. idle: function() {
  11362. return q.tasks.length + workers === 0;
  11363. },
  11364. pause: function () {
  11365. if (q.paused === true) { return; }
  11366. q.paused = true;
  11367. q.process();
  11368. },
  11369. resume: function () {
  11370. if (q.paused === false) { return; }
  11371. q.paused = false;
  11372. q.process();
  11373. }
  11374. };
  11375. return q;
  11376. };
  11377. async.priorityQueue = function (worker, concurrency) {
  11378. function _compareTasks(a, b){
  11379. return a.priority - b.priority;
  11380. };
  11381. function _binarySearch(sequence, item, compare) {
  11382. var beg = -1,
  11383. end = sequence.length - 1;
  11384. while (beg < end) {
  11385. var mid = beg + ((end - beg + 1) >>> 1);
  11386. if (compare(item, sequence[mid]) >= 0) {
  11387. beg = mid;
  11388. } else {
  11389. end = mid - 1;
  11390. }
  11391. }
  11392. return beg;
  11393. }
  11394. function _insert(q, data, priority, callback) {
  11395. if (!q.started){
  11396. q.started = true;
  11397. }
  11398. if (!_isArray(data)) {
  11399. data = [data];
  11400. }
  11401. if(data.length == 0) {
  11402. // call drain immediately if there are no tasks
  11403. return async.setImmediate(function() {
  11404. if (q.drain) {
  11405. q.drain();
  11406. }
  11407. });
  11408. }
  11409. _each(data, function(task) {
  11410. var item = {
  11411. data: task,
  11412. priority: priority,
  11413. callback: typeof callback === 'function' ? callback : null
  11414. };
  11415. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11416. if (q.saturated && q.tasks.length === q.concurrency) {
  11417. q.saturated();
  11418. }
  11419. async.setImmediate(q.process);
  11420. });
  11421. }
  11422. // Start with a normal queue
  11423. var q = async.queue(worker, concurrency);
  11424. // Override push to accept second parameter representing priority
  11425. q.push = function (data, priority, callback) {
  11426. _insert(q, data, priority, callback);
  11427. };
  11428. // Remove unshift function
  11429. delete q.unshift;
  11430. return q;
  11431. };
  11432. async.cargo = function (worker, payload) {
  11433. var working = false,
  11434. tasks = [];
  11435. var cargo = {
  11436. tasks: tasks,
  11437. payload: payload,
  11438. saturated: null,
  11439. empty: null,
  11440. drain: null,
  11441. drained: true,
  11442. push: function (data, callback) {
  11443. if (!_isArray(data)) {
  11444. data = [data];
  11445. }
  11446. _each(data, function(task) {
  11447. tasks.push({
  11448. data: task,
  11449. callback: typeof callback === 'function' ? callback : null
  11450. });
  11451. cargo.drained = false;
  11452. if (cargo.saturated && tasks.length === payload) {
  11453. cargo.saturated();
  11454. }
  11455. });
  11456. async.setImmediate(cargo.process);
  11457. },
  11458. process: function process() {
  11459. if (working) return;
  11460. if (tasks.length === 0) {
  11461. if(cargo.drain && !cargo.drained) cargo.drain();
  11462. cargo.drained = true;
  11463. return;
  11464. }
  11465. var ts = typeof payload === 'number'
  11466. ? tasks.splice(0, payload)
  11467. : tasks.splice(0, tasks.length);
  11468. var ds = _map(ts, function (task) {
  11469. return task.data;
  11470. });
  11471. if(cargo.empty) cargo.empty();
  11472. working = true;
  11473. worker(ds, function () {
  11474. working = false;
  11475. var args = arguments;
  11476. _each(ts, function (data) {
  11477. if (data.callback) {
  11478. data.callback.apply(null, args);
  11479. }
  11480. });
  11481. process();
  11482. });
  11483. },
  11484. length: function () {
  11485. return tasks.length;
  11486. },
  11487. running: function () {
  11488. return working;
  11489. }
  11490. };
  11491. return cargo;
  11492. };
  11493. var _console_fn = function (name) {
  11494. return function (fn) {
  11495. var args = Array.prototype.slice.call(arguments, 1);
  11496. fn.apply(null, args.concat([function (err) {
  11497. var args = Array.prototype.slice.call(arguments, 1);
  11498. if (typeof console !== 'undefined') {
  11499. if (err) {
  11500. if (console.error) {
  11501. console.error(err);
  11502. }
  11503. }
  11504. else if (console[name]) {
  11505. _each(args, function (x) {
  11506. console[name](x);
  11507. });
  11508. }
  11509. }
  11510. }]));
  11511. };
  11512. };
  11513. async.log = _console_fn('log');
  11514. async.dir = _console_fn('dir');
  11515. /*async.info = _console_fn('info');
  11516. async.warn = _console_fn('warn');
  11517. async.error = _console_fn('error');*/
  11518. async.memoize = function (fn, hasher) {
  11519. var memo = {};
  11520. var queues = {};
  11521. hasher = hasher || function (x) {
  11522. return x;
  11523. };
  11524. var memoized = function () {
  11525. var args = Array.prototype.slice.call(arguments);
  11526. var callback = args.pop();
  11527. var key = hasher.apply(null, args);
  11528. if (key in memo) {
  11529. async.nextTick(function () {
  11530. callback.apply(null, memo[key]);
  11531. });
  11532. }
  11533. else if (key in queues) {
  11534. queues[key].push(callback);
  11535. }
  11536. else {
  11537. queues[key] = [callback];
  11538. fn.apply(null, args.concat([function () {
  11539. memo[key] = arguments;
  11540. var q = queues[key];
  11541. delete queues[key];
  11542. for (var i = 0, l = q.length; i < l; i++) {
  11543. q[i].apply(null, arguments);
  11544. }
  11545. }]));
  11546. }
  11547. };
  11548. memoized.memo = memo;
  11549. memoized.unmemoized = fn;
  11550. return memoized;
  11551. };
  11552. async.unmemoize = function (fn) {
  11553. return function () {
  11554. return (fn.unmemoized || fn).apply(null, arguments);
  11555. };
  11556. };
  11557. async.times = function (count, iterator, callback) {
  11558. var counter = [];
  11559. for (var i = 0; i < count; i++) {
  11560. counter.push(i);
  11561. }
  11562. return async.map(counter, iterator, callback);
  11563. };
  11564. async.timesSeries = function (count, iterator, callback) {
  11565. var counter = [];
  11566. for (var i = 0; i < count; i++) {
  11567. counter.push(i);
  11568. }
  11569. return async.mapSeries(counter, iterator, callback);
  11570. };
  11571. async.seq = function (/* functions... */) {
  11572. var fns = arguments;
  11573. return function () {
  11574. var that = this;
  11575. var args = Array.prototype.slice.call(arguments);
  11576. var callback = args.pop();
  11577. async.reduce(fns, args, function (newargs, fn, cb) {
  11578. fn.apply(that, newargs.concat([function () {
  11579. var err = arguments[0];
  11580. var nextargs = Array.prototype.slice.call(arguments, 1);
  11581. cb(err, nextargs);
  11582. }]))
  11583. },
  11584. function (err, results) {
  11585. callback.apply(that, [err].concat(results));
  11586. });
  11587. };
  11588. };
  11589. async.compose = function (/* functions... */) {
  11590. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11591. };
  11592. var _applyEach = function (eachfn, fns /*args...*/) {
  11593. var go = function () {
  11594. var that = this;
  11595. var args = Array.prototype.slice.call(arguments);
  11596. var callback = args.pop();
  11597. return eachfn(fns, function (fn, cb) {
  11598. fn.apply(that, args.concat([cb]));
  11599. },
  11600. callback);
  11601. };
  11602. if (arguments.length > 2) {
  11603. var args = Array.prototype.slice.call(arguments, 2);
  11604. return go.apply(this, args);
  11605. }
  11606. else {
  11607. return go;
  11608. }
  11609. };
  11610. async.applyEach = doParallel(_applyEach);
  11611. async.applyEachSeries = doSeries(_applyEach);
  11612. async.forever = function (fn, callback) {
  11613. function next(err) {
  11614. if (err) {
  11615. if (callback) {
  11616. return callback(err);
  11617. }
  11618. throw err;
  11619. }
  11620. fn(next);
  11621. }
  11622. next();
  11623. };
  11624. // Node.js
  11625. if (typeof module !== 'undefined' && module.exports) {
  11626. module.exports = async;
  11627. }
  11628. // AMD / RequireJS
  11629. else if (typeof define !== 'undefined' && define.amd) {
  11630. define([], function () {
  11631. return async;
  11632. });
  11633. }
  11634. // included directly via <script> tag
  11635. else {
  11636. root.async = async;
  11637. }
  11638. }());
  11639. }).call(this,require('_process'))
  11640. },{"_process":45}],44:[function(require,module,exports){
  11641. // Copyright Joyent, Inc. and other Node contributors.
  11642. //
  11643. // Permission is hereby granted, free of charge, to any person obtaining a
  11644. // copy of this software and associated documentation files (the
  11645. // "Software"), to deal in the Software without restriction, including
  11646. // without limitation the rights to use, copy, modify, merge, publish,
  11647. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11648. // persons to whom the Software is furnished to do so, subject to the
  11649. // following conditions:
  11650. //
  11651. // The above copyright notice and this permission notice shall be included
  11652. // in all copies or substantial portions of the Software.
  11653. //
  11654. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11655. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11656. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11657. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11658. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11659. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11660. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11661. function EventEmitter() {
  11662. this._events = this._events || {};
  11663. this._maxListeners = this._maxListeners || undefined;
  11664. }
  11665. module.exports = EventEmitter;
  11666. // Backwards-compat with node 0.10.x
  11667. EventEmitter.EventEmitter = EventEmitter;
  11668. EventEmitter.prototype._events = undefined;
  11669. EventEmitter.prototype._maxListeners = undefined;
  11670. // By default EventEmitters will print a warning if more than 10 listeners are
  11671. // added to it. This is a useful default which helps finding memory leaks.
  11672. EventEmitter.defaultMaxListeners = 10;
  11673. // Obviously not all Emitters should be limited to 10. This function allows
  11674. // that to be increased. Set to zero for unlimited.
  11675. EventEmitter.prototype.setMaxListeners = function(n) {
  11676. if (!isNumber(n) || n < 0 || isNaN(n))
  11677. throw TypeError('n must be a positive number');
  11678. this._maxListeners = n;
  11679. return this;
  11680. };
  11681. EventEmitter.prototype.emit = function(type) {
  11682. var er, handler, len, args, i, listeners;
  11683. if (!this._events)
  11684. this._events = {};
  11685. // If there is no 'error' event listener then throw.
  11686. if (type === 'error') {
  11687. if (!this._events.error ||
  11688. (isObject(this._events.error) && !this._events.error.length)) {
  11689. er = arguments[1];
  11690. if (er instanceof Error) {
  11691. throw er; // Unhandled 'error' event
  11692. }
  11693. throw TypeError('Uncaught, unspecified "error" event.');
  11694. }
  11695. }
  11696. handler = this._events[type];
  11697. if (isUndefined(handler))
  11698. return false;
  11699. if (isFunction(handler)) {
  11700. switch (arguments.length) {
  11701. // fast cases
  11702. case 1:
  11703. handler.call(this);
  11704. break;
  11705. case 2:
  11706. handler.call(this, arguments[1]);
  11707. break;
  11708. case 3:
  11709. handler.call(this, arguments[1], arguments[2]);
  11710. break;
  11711. // slower
  11712. default:
  11713. len = arguments.length;
  11714. args = new Array(len - 1);
  11715. for (i = 1; i < len; i++)
  11716. args[i - 1] = arguments[i];
  11717. handler.apply(this, args);
  11718. }
  11719. } else if (isObject(handler)) {
  11720. len = arguments.length;
  11721. args = new Array(len - 1);
  11722. for (i = 1; i < len; i++)
  11723. args[i - 1] = arguments[i];
  11724. listeners = handler.slice();
  11725. len = listeners.length;
  11726. for (i = 0; i < len; i++)
  11727. listeners[i].apply(this, args);
  11728. }
  11729. return true;
  11730. };
  11731. EventEmitter.prototype.addListener = function(type, listener) {
  11732. var m;
  11733. if (!isFunction(listener))
  11734. throw TypeError('listener must be a function');
  11735. if (!this._events)
  11736. this._events = {};
  11737. // To avoid recursion in the case that type === "newListener"! Before
  11738. // adding it to the listeners, first emit "newListener".
  11739. if (this._events.newListener)
  11740. this.emit('newListener', type,
  11741. isFunction(listener.listener) ?
  11742. listener.listener : listener);
  11743. if (!this._events[type])
  11744. // Optimize the case of one listener. Don't need the extra array object.
  11745. this._events[type] = listener;
  11746. else if (isObject(this._events[type]))
  11747. // If we've already got an array, just append.
  11748. this._events[type].push(listener);
  11749. else
  11750. // Adding the second element, need to change to array.
  11751. this._events[type] = [this._events[type], listener];
  11752. // Check for listener leak
  11753. if (isObject(this._events[type]) && !this._events[type].warned) {
  11754. var m;
  11755. if (!isUndefined(this._maxListeners)) {
  11756. m = this._maxListeners;
  11757. } else {
  11758. m = EventEmitter.defaultMaxListeners;
  11759. }
  11760. if (m && m > 0 && this._events[type].length > m) {
  11761. this._events[type].warned = true;
  11762. console.error('(node) warning: possible EventEmitter memory ' +
  11763. 'leak detected. %d listeners added. ' +
  11764. 'Use emitter.setMaxListeners() to increase limit.',
  11765. this._events[type].length);
  11766. if (typeof console.trace === 'function') {
  11767. // not supported in IE 10
  11768. console.trace();
  11769. }
  11770. }
  11771. }
  11772. return this;
  11773. };
  11774. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11775. EventEmitter.prototype.once = function(type, listener) {
  11776. if (!isFunction(listener))
  11777. throw TypeError('listener must be a function');
  11778. var fired = false;
  11779. function g() {
  11780. this.removeListener(type, g);
  11781. if (!fired) {
  11782. fired = true;
  11783. listener.apply(this, arguments);
  11784. }
  11785. }
  11786. g.listener = listener;
  11787. this.on(type, g);
  11788. return this;
  11789. };
  11790. // emits a 'removeListener' event iff the listener was removed
  11791. EventEmitter.prototype.removeListener = function(type, listener) {
  11792. var list, position, length, i;
  11793. if (!isFunction(listener))
  11794. throw TypeError('listener must be a function');
  11795. if (!this._events || !this._events[type])
  11796. return this;
  11797. list = this._events[type];
  11798. length = list.length;
  11799. position = -1;
  11800. if (list === listener ||
  11801. (isFunction(list.listener) && list.listener === listener)) {
  11802. delete this._events[type];
  11803. if (this._events.removeListener)
  11804. this.emit('removeListener', type, listener);
  11805. } else if (isObject(list)) {
  11806. for (i = length; i-- > 0;) {
  11807. if (list[i] === listener ||
  11808. (list[i].listener && list[i].listener === listener)) {
  11809. position = i;
  11810. break;
  11811. }
  11812. }
  11813. if (position < 0)
  11814. return this;
  11815. if (list.length === 1) {
  11816. list.length = 0;
  11817. delete this._events[type];
  11818. } else {
  11819. list.splice(position, 1);
  11820. }
  11821. if (this._events.removeListener)
  11822. this.emit('removeListener', type, listener);
  11823. }
  11824. return this;
  11825. };
  11826. EventEmitter.prototype.removeAllListeners = function(type) {
  11827. var key, listeners;
  11828. if (!this._events)
  11829. return this;
  11830. // not listening for removeListener, no need to emit
  11831. if (!this._events.removeListener) {
  11832. if (arguments.length === 0)
  11833. this._events = {};
  11834. else if (this._events[type])
  11835. delete this._events[type];
  11836. return this;
  11837. }
  11838. // emit removeListener for all listeners on all events
  11839. if (arguments.length === 0) {
  11840. for (key in this._events) {
  11841. if (key === 'removeListener') continue;
  11842. this.removeAllListeners(key);
  11843. }
  11844. this.removeAllListeners('removeListener');
  11845. this._events = {};
  11846. return this;
  11847. }
  11848. listeners = this._events[type];
  11849. if (isFunction(listeners)) {
  11850. this.removeListener(type, listeners);
  11851. } else {
  11852. // LIFO order
  11853. while (listeners.length)
  11854. this.removeListener(type, listeners[listeners.length - 1]);
  11855. }
  11856. delete this._events[type];
  11857. return this;
  11858. };
  11859. EventEmitter.prototype.listeners = function(type) {
  11860. var ret;
  11861. if (!this._events || !this._events[type])
  11862. ret = [];
  11863. else if (isFunction(this._events[type]))
  11864. ret = [this._events[type]];
  11865. else
  11866. ret = this._events[type].slice();
  11867. return ret;
  11868. };
  11869. EventEmitter.listenerCount = function(emitter, type) {
  11870. var ret;
  11871. if (!emitter._events || !emitter._events[type])
  11872. ret = 0;
  11873. else if (isFunction(emitter._events[type]))
  11874. ret = 1;
  11875. else
  11876. ret = emitter._events[type].length;
  11877. return ret;
  11878. };
  11879. function isFunction(arg) {
  11880. return typeof arg === 'function';
  11881. }
  11882. function isNumber(arg) {
  11883. return typeof arg === 'number';
  11884. }
  11885. function isObject(arg) {
  11886. return typeof arg === 'object' && arg !== null;
  11887. }
  11888. function isUndefined(arg) {
  11889. return arg === void 0;
  11890. }
  11891. },{}],45:[function(require,module,exports){
  11892. // shim for using process in browser
  11893. var process = module.exports = {};
  11894. var queue = [];
  11895. var draining = false;
  11896. var currentQueue;
  11897. var queueIndex = -1;
  11898. function cleanUpNextTick() {
  11899. draining = false;
  11900. if (currentQueue.length) {
  11901. queue = currentQueue.concat(queue);
  11902. } else {
  11903. queueIndex = -1;
  11904. }
  11905. if (queue.length) {
  11906. drainQueue();
  11907. }
  11908. }
  11909. function drainQueue() {
  11910. if (draining) {
  11911. return;
  11912. }
  11913. var timeout = setTimeout(cleanUpNextTick);
  11914. draining = true;
  11915. var len = queue.length;
  11916. while(len) {
  11917. currentQueue = queue;
  11918. queue = [];
  11919. while (++queueIndex < len) {
  11920. if (currentQueue) {
  11921. currentQueue[queueIndex].run();
  11922. }
  11923. }
  11924. queueIndex = -1;
  11925. len = queue.length;
  11926. }
  11927. currentQueue = null;
  11928. draining = false;
  11929. clearTimeout(timeout);
  11930. }
  11931. process.nextTick = function (fun) {
  11932. var args = new Array(arguments.length - 1);
  11933. if (arguments.length > 1) {
  11934. for (var i = 1; i < arguments.length; i++) {
  11935. args[i - 1] = arguments[i];
  11936. }
  11937. }
  11938. queue.push(new Item(fun, args));
  11939. if (queue.length === 1 && !draining) {
  11940. setTimeout(drainQueue, 0);
  11941. }
  11942. };
  11943. // v8 likes predictible objects
  11944. function Item(fun, array) {
  11945. this.fun = fun;
  11946. this.array = array;
  11947. }
  11948. Item.prototype.run = function () {
  11949. this.fun.apply(null, this.array);
  11950. };
  11951. process.title = 'browser';
  11952. process.browser = true;
  11953. process.env = {};
  11954. process.argv = [];
  11955. process.version = ''; // empty string to avoid regexp issues
  11956. process.versions = {};
  11957. function noop() {}
  11958. process.on = noop;
  11959. process.addListener = noop;
  11960. process.once = noop;
  11961. process.off = noop;
  11962. process.removeListener = noop;
  11963. process.removeAllListeners = noop;
  11964. process.emit = noop;
  11965. process.binding = function (name) {
  11966. throw new Error('process.binding is not supported');
  11967. };
  11968. process.cwd = function () { return '/' };
  11969. process.chdir = function (dir) {
  11970. throw new Error('process.chdir is not supported');
  11971. };
  11972. process.umask = function() { return 0; };
  11973. },{}],46:[function(require,module,exports){
  11974. (function (process,global){
  11975. /*!
  11976. * @overview es6-promise - a tiny implementation of Promises/A+.
  11977. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11978. * @license Licensed under MIT license
  11979. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  11980. * @version 3.0.2
  11981. */
  11982. (function() {
  11983. "use strict";
  11984. function lib$es6$promise$utils$$objectOrFunction(x) {
  11985. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  11986. }
  11987. function lib$es6$promise$utils$$isFunction(x) {
  11988. return typeof x === 'function';
  11989. }
  11990. function lib$es6$promise$utils$$isMaybeThenable(x) {
  11991. return typeof x === 'object' && x !== null;
  11992. }
  11993. var lib$es6$promise$utils$$_isArray;
  11994. if (!Array.isArray) {
  11995. lib$es6$promise$utils$$_isArray = function (x) {
  11996. return Object.prototype.toString.call(x) === '[object Array]';
  11997. };
  11998. } else {
  11999. lib$es6$promise$utils$$_isArray = Array.isArray;
  12000. }
  12001. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  12002. var lib$es6$promise$asap$$len = 0;
  12003. var lib$es6$promise$asap$$toString = {}.toString;
  12004. var lib$es6$promise$asap$$vertxNext;
  12005. var lib$es6$promise$asap$$customSchedulerFn;
  12006. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  12007. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  12008. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  12009. lib$es6$promise$asap$$len += 2;
  12010. if (lib$es6$promise$asap$$len === 2) {
  12011. // If len is 2, that means that we need to schedule an async flush.
  12012. // If additional callbacks are queued before the queue is flushed, they
  12013. // will be processed by this flush that we are scheduling.
  12014. if (lib$es6$promise$asap$$customSchedulerFn) {
  12015. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  12016. } else {
  12017. lib$es6$promise$asap$$scheduleFlush();
  12018. }
  12019. }
  12020. }
  12021. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  12022. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  12023. }
  12024. function lib$es6$promise$asap$$setAsap(asapFn) {
  12025. lib$es6$promise$asap$$asap = asapFn;
  12026. }
  12027. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  12028. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  12029. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  12030. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  12031. // test for web worker but not in IE10
  12032. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  12033. typeof importScripts !== 'undefined' &&
  12034. typeof MessageChannel !== 'undefined';
  12035. // node
  12036. function lib$es6$promise$asap$$useNextTick() {
  12037. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  12038. // see https://github.com/cujojs/when/issues/410 for details
  12039. return function() {
  12040. process.nextTick(lib$es6$promise$asap$$flush);
  12041. };
  12042. }
  12043. // vertx
  12044. function lib$es6$promise$asap$$useVertxTimer() {
  12045. return function() {
  12046. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  12047. };
  12048. }
  12049. function lib$es6$promise$asap$$useMutationObserver() {
  12050. var iterations = 0;
  12051. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  12052. var node = document.createTextNode('');
  12053. observer.observe(node, { characterData: true });
  12054. return function() {
  12055. node.data = (iterations = ++iterations % 2);
  12056. };
  12057. }
  12058. // web worker
  12059. function lib$es6$promise$asap$$useMessageChannel() {
  12060. var channel = new MessageChannel();
  12061. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  12062. return function () {
  12063. channel.port2.postMessage(0);
  12064. };
  12065. }
  12066. function lib$es6$promise$asap$$useSetTimeout() {
  12067. return function() {
  12068. setTimeout(lib$es6$promise$asap$$flush, 1);
  12069. };
  12070. }
  12071. var lib$es6$promise$asap$$queue = new Array(1000);
  12072. function lib$es6$promise$asap$$flush() {
  12073. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  12074. var callback = lib$es6$promise$asap$$queue[i];
  12075. var arg = lib$es6$promise$asap$$queue[i+1];
  12076. callback(arg);
  12077. lib$es6$promise$asap$$queue[i] = undefined;
  12078. lib$es6$promise$asap$$queue[i+1] = undefined;
  12079. }
  12080. lib$es6$promise$asap$$len = 0;
  12081. }
  12082. function lib$es6$promise$asap$$attemptVertx() {
  12083. try {
  12084. var r = require;
  12085. var vertx = r('vertx');
  12086. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  12087. return lib$es6$promise$asap$$useVertxTimer();
  12088. } catch(e) {
  12089. return lib$es6$promise$asap$$useSetTimeout();
  12090. }
  12091. }
  12092. var lib$es6$promise$asap$$scheduleFlush;
  12093. // Decide what async method to use to triggering processing of queued callbacks:
  12094. if (lib$es6$promise$asap$$isNode) {
  12095. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  12096. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  12097. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  12098. } else if (lib$es6$promise$asap$$isWorker) {
  12099. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  12100. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  12101. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  12102. } else {
  12103. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  12104. }
  12105. function lib$es6$promise$$internal$$noop() {}
  12106. var lib$es6$promise$$internal$$PENDING = void 0;
  12107. var lib$es6$promise$$internal$$FULFILLED = 1;
  12108. var lib$es6$promise$$internal$$REJECTED = 2;
  12109. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12110. function lib$es6$promise$$internal$$selfFulfillment() {
  12111. return new TypeError("You cannot resolve a promise with itself");
  12112. }
  12113. function lib$es6$promise$$internal$$cannotReturnOwn() {
  12114. return new TypeError('A promises callback cannot return that same promise.');
  12115. }
  12116. function lib$es6$promise$$internal$$getThen(promise) {
  12117. try {
  12118. return promise.then;
  12119. } catch(error) {
  12120. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  12121. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  12122. }
  12123. }
  12124. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  12125. try {
  12126. then.call(value, fulfillmentHandler, rejectionHandler);
  12127. } catch(e) {
  12128. return e;
  12129. }
  12130. }
  12131. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  12132. lib$es6$promise$asap$$asap(function(promise) {
  12133. var sealed = false;
  12134. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  12135. if (sealed) { return; }
  12136. sealed = true;
  12137. if (thenable !== value) {
  12138. lib$es6$promise$$internal$$resolve(promise, value);
  12139. } else {
  12140. lib$es6$promise$$internal$$fulfill(promise, value);
  12141. }
  12142. }, function(reason) {
  12143. if (sealed) { return; }
  12144. sealed = true;
  12145. lib$es6$promise$$internal$$reject(promise, reason);
  12146. }, 'Settle: ' + (promise._label || ' unknown promise'));
  12147. if (!sealed && error) {
  12148. sealed = true;
  12149. lib$es6$promise$$internal$$reject(promise, error);
  12150. }
  12151. }, promise);
  12152. }
  12153. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  12154. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  12155. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  12156. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  12157. lib$es6$promise$$internal$$reject(promise, thenable._result);
  12158. } else {
  12159. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  12160. lib$es6$promise$$internal$$resolve(promise, value);
  12161. }, function(reason) {
  12162. lib$es6$promise$$internal$$reject(promise, reason);
  12163. });
  12164. }
  12165. }
  12166. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12167. if (maybeThenable.constructor === promise.constructor) {
  12168. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12169. } else {
  12170. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12171. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12172. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12173. } else if (then === undefined) {
  12174. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12175. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12176. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12177. } else {
  12178. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12179. }
  12180. }
  12181. }
  12182. function lib$es6$promise$$internal$$resolve(promise, value) {
  12183. if (promise === value) {
  12184. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12185. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12186. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12187. } else {
  12188. lib$es6$promise$$internal$$fulfill(promise, value);
  12189. }
  12190. }
  12191. function lib$es6$promise$$internal$$publishRejection(promise) {
  12192. if (promise._onerror) {
  12193. promise._onerror(promise._result);
  12194. }
  12195. lib$es6$promise$$internal$$publish(promise);
  12196. }
  12197. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12198. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12199. promise._result = value;
  12200. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12201. if (promise._subscribers.length !== 0) {
  12202. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12203. }
  12204. }
  12205. function lib$es6$promise$$internal$$reject(promise, reason) {
  12206. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12207. promise._state = lib$es6$promise$$internal$$REJECTED;
  12208. promise._result = reason;
  12209. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12210. }
  12211. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12212. var subscribers = parent._subscribers;
  12213. var length = subscribers.length;
  12214. parent._onerror = null;
  12215. subscribers[length] = child;
  12216. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12217. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12218. if (length === 0 && parent._state) {
  12219. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12220. }
  12221. }
  12222. function lib$es6$promise$$internal$$publish(promise) {
  12223. var subscribers = promise._subscribers;
  12224. var settled = promise._state;
  12225. if (subscribers.length === 0) { return; }
  12226. var child, callback, detail = promise._result;
  12227. for (var i = 0; i < subscribers.length; i += 3) {
  12228. child = subscribers[i];
  12229. callback = subscribers[i + settled];
  12230. if (child) {
  12231. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12232. } else {
  12233. callback(detail);
  12234. }
  12235. }
  12236. promise._subscribers.length = 0;
  12237. }
  12238. function lib$es6$promise$$internal$$ErrorObject() {
  12239. this.error = null;
  12240. }
  12241. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12242. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12243. try {
  12244. return callback(detail);
  12245. } catch(e) {
  12246. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12247. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12248. }
  12249. }
  12250. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12251. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12252. value, error, succeeded, failed;
  12253. if (hasCallback) {
  12254. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12255. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12256. failed = true;
  12257. error = value.error;
  12258. value = null;
  12259. } else {
  12260. succeeded = true;
  12261. }
  12262. if (promise === value) {
  12263. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12264. return;
  12265. }
  12266. } else {
  12267. value = detail;
  12268. succeeded = true;
  12269. }
  12270. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12271. // noop
  12272. } else if (hasCallback && succeeded) {
  12273. lib$es6$promise$$internal$$resolve(promise, value);
  12274. } else if (failed) {
  12275. lib$es6$promise$$internal$$reject(promise, error);
  12276. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12277. lib$es6$promise$$internal$$fulfill(promise, value);
  12278. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12279. lib$es6$promise$$internal$$reject(promise, value);
  12280. }
  12281. }
  12282. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12283. try {
  12284. resolver(function resolvePromise(value){
  12285. lib$es6$promise$$internal$$resolve(promise, value);
  12286. }, function rejectPromise(reason) {
  12287. lib$es6$promise$$internal$$reject(promise, reason);
  12288. });
  12289. } catch(e) {
  12290. lib$es6$promise$$internal$$reject(promise, e);
  12291. }
  12292. }
  12293. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12294. var enumerator = this;
  12295. enumerator._instanceConstructor = Constructor;
  12296. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12297. if (enumerator._validateInput(input)) {
  12298. enumerator._input = input;
  12299. enumerator.length = input.length;
  12300. enumerator._remaining = input.length;
  12301. enumerator._init();
  12302. if (enumerator.length === 0) {
  12303. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12304. } else {
  12305. enumerator.length = enumerator.length || 0;
  12306. enumerator._enumerate();
  12307. if (enumerator._remaining === 0) {
  12308. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12309. }
  12310. }
  12311. } else {
  12312. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12313. }
  12314. }
  12315. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12316. return lib$es6$promise$utils$$isArray(input);
  12317. };
  12318. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12319. return new Error('Array Methods must be provided an Array');
  12320. };
  12321. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12322. this._result = new Array(this.length);
  12323. };
  12324. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12325. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12326. var enumerator = this;
  12327. var length = enumerator.length;
  12328. var promise = enumerator.promise;
  12329. var input = enumerator._input;
  12330. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12331. enumerator._eachEntry(input[i], i);
  12332. }
  12333. };
  12334. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12335. var enumerator = this;
  12336. var c = enumerator._instanceConstructor;
  12337. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12338. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12339. entry._onerror = null;
  12340. enumerator._settledAt(entry._state, i, entry._result);
  12341. } else {
  12342. enumerator._willSettleAt(c.resolve(entry), i);
  12343. }
  12344. } else {
  12345. enumerator._remaining--;
  12346. enumerator._result[i] = entry;
  12347. }
  12348. };
  12349. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12350. var enumerator = this;
  12351. var promise = enumerator.promise;
  12352. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12353. enumerator._remaining--;
  12354. if (state === lib$es6$promise$$internal$$REJECTED) {
  12355. lib$es6$promise$$internal$$reject(promise, value);
  12356. } else {
  12357. enumerator._result[i] = value;
  12358. }
  12359. }
  12360. if (enumerator._remaining === 0) {
  12361. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12362. }
  12363. };
  12364. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12365. var enumerator = this;
  12366. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12367. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12368. }, function(reason) {
  12369. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12370. });
  12371. };
  12372. function lib$es6$promise$promise$all$$all(entries) {
  12373. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12374. }
  12375. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12376. function lib$es6$promise$promise$race$$race(entries) {
  12377. /*jshint validthis:true */
  12378. var Constructor = this;
  12379. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12380. if (!lib$es6$promise$utils$$isArray(entries)) {
  12381. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12382. return promise;
  12383. }
  12384. var length = entries.length;
  12385. function onFulfillment(value) {
  12386. lib$es6$promise$$internal$$resolve(promise, value);
  12387. }
  12388. function onRejection(reason) {
  12389. lib$es6$promise$$internal$$reject(promise, reason);
  12390. }
  12391. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12392. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12393. }
  12394. return promise;
  12395. }
  12396. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12397. function lib$es6$promise$promise$resolve$$resolve(object) {
  12398. /*jshint validthis:true */
  12399. var Constructor = this;
  12400. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12401. return object;
  12402. }
  12403. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12404. lib$es6$promise$$internal$$resolve(promise, object);
  12405. return promise;
  12406. }
  12407. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12408. function lib$es6$promise$promise$reject$$reject(reason) {
  12409. /*jshint validthis:true */
  12410. var Constructor = this;
  12411. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12412. lib$es6$promise$$internal$$reject(promise, reason);
  12413. return promise;
  12414. }
  12415. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12416. var lib$es6$promise$promise$$counter = 0;
  12417. function lib$es6$promise$promise$$needsResolver() {
  12418. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12419. }
  12420. function lib$es6$promise$promise$$needsNew() {
  12421. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12422. }
  12423. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12424. /**
  12425. Promise objects represent the eventual result of an asynchronous operation. The
  12426. primary way of interacting with a promise is through its `then` method, which
  12427. registers callbacks to receive either a promise's eventual value or the reason
  12428. why the promise cannot be fulfilled.
  12429. Terminology
  12430. -----------
  12431. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12432. - `thenable` is an object or function that defines a `then` method.
  12433. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12434. - `exception` is a value that is thrown using the throw statement.
  12435. - `reason` is a value that indicates why a promise was rejected.
  12436. - `settled` the final resting state of a promise, fulfilled or rejected.
  12437. A promise can be in one of three states: pending, fulfilled, or rejected.
  12438. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12439. state. Promises that are rejected have a rejection reason and are in the
  12440. rejected state. A fulfillment value is never a thenable.
  12441. Promises can also be said to *resolve* a value. If this value is also a
  12442. promise, then the original promise's settled state will match the value's
  12443. settled state. So a promise that *resolves* a promise that rejects will
  12444. itself reject, and a promise that *resolves* a promise that fulfills will
  12445. itself fulfill.
  12446. Basic Usage:
  12447. ------------
  12448. ```js
  12449. var promise = new Promise(function(resolve, reject) {
  12450. // on success
  12451. resolve(value);
  12452. // on failure
  12453. reject(reason);
  12454. });
  12455. promise.then(function(value) {
  12456. // on fulfillment
  12457. }, function(reason) {
  12458. // on rejection
  12459. });
  12460. ```
  12461. Advanced Usage:
  12462. ---------------
  12463. Promises shine when abstracting away asynchronous interactions such as
  12464. `XMLHttpRequest`s.
  12465. ```js
  12466. function getJSON(url) {
  12467. return new Promise(function(resolve, reject){
  12468. var xhr = new XMLHttpRequest();
  12469. xhr.open('GET', url);
  12470. xhr.onreadystatechange = handler;
  12471. xhr.responseType = 'json';
  12472. xhr.setRequestHeader('Accept', 'application/json');
  12473. xhr.send();
  12474. function handler() {
  12475. if (this.readyState === this.DONE) {
  12476. if (this.status === 200) {
  12477. resolve(this.response);
  12478. } else {
  12479. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12480. }
  12481. }
  12482. };
  12483. });
  12484. }
  12485. getJSON('/posts.json').then(function(json) {
  12486. // on fulfillment
  12487. }, function(reason) {
  12488. // on rejection
  12489. });
  12490. ```
  12491. Unlike callbacks, promises are great composable primitives.
  12492. ```js
  12493. Promise.all([
  12494. getJSON('/posts'),
  12495. getJSON('/comments')
  12496. ]).then(function(values){
  12497. values[0] // => postsJSON
  12498. values[1] // => commentsJSON
  12499. return values;
  12500. });
  12501. ```
  12502. @class Promise
  12503. @param {function} resolver
  12504. Useful for tooling.
  12505. @constructor
  12506. */
  12507. function lib$es6$promise$promise$$Promise(resolver) {
  12508. this._id = lib$es6$promise$promise$$counter++;
  12509. this._state = undefined;
  12510. this._result = undefined;
  12511. this._subscribers = [];
  12512. if (lib$es6$promise$$internal$$noop !== resolver) {
  12513. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12514. lib$es6$promise$promise$$needsResolver();
  12515. }
  12516. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12517. lib$es6$promise$promise$$needsNew();
  12518. }
  12519. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12520. }
  12521. }
  12522. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12523. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12524. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12525. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12526. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12527. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12528. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12529. lib$es6$promise$promise$$Promise.prototype = {
  12530. constructor: lib$es6$promise$promise$$Promise,
  12531. /**
  12532. The primary way of interacting with a promise is through its `then` method,
  12533. which registers callbacks to receive either a promise's eventual value or the
  12534. reason why the promise cannot be fulfilled.
  12535. ```js
  12536. findUser().then(function(user){
  12537. // user is available
  12538. }, function(reason){
  12539. // user is unavailable, and you are given the reason why
  12540. });
  12541. ```
  12542. Chaining
  12543. --------
  12544. The return value of `then` is itself a promise. This second, 'downstream'
  12545. promise is resolved with the return value of the first promise's fulfillment
  12546. or rejection handler, or rejected if the handler throws an exception.
  12547. ```js
  12548. findUser().then(function (user) {
  12549. return user.name;
  12550. }, function (reason) {
  12551. return 'default name';
  12552. }).then(function (userName) {
  12553. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12554. // will be `'default name'`
  12555. });
  12556. findUser().then(function (user) {
  12557. throw new Error('Found user, but still unhappy');
  12558. }, function (reason) {
  12559. throw new Error('`findUser` rejected and we're unhappy');
  12560. }).then(function (value) {
  12561. // never reached
  12562. }, function (reason) {
  12563. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12564. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12565. });
  12566. ```
  12567. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12568. ```js
  12569. findUser().then(function (user) {
  12570. throw new PedagogicalException('Upstream error');
  12571. }).then(function (value) {
  12572. // never reached
  12573. }).then(function (value) {
  12574. // never reached
  12575. }, function (reason) {
  12576. // The `PedgagocialException` is propagated all the way down to here
  12577. });
  12578. ```
  12579. Assimilation
  12580. ------------
  12581. Sometimes the value you want to propagate to a downstream promise can only be
  12582. retrieved asynchronously. This can be achieved by returning a promise in the
  12583. fulfillment or rejection handler. The downstream promise will then be pending
  12584. until the returned promise is settled. This is called *assimilation*.
  12585. ```js
  12586. findUser().then(function (user) {
  12587. return findCommentsByAuthor(user);
  12588. }).then(function (comments) {
  12589. // The user's comments are now available
  12590. });
  12591. ```
  12592. If the assimliated promise rejects, then the downstream promise will also reject.
  12593. ```js
  12594. findUser().then(function (user) {
  12595. return findCommentsByAuthor(user);
  12596. }).then(function (comments) {
  12597. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12598. }, function (reason) {
  12599. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12600. });
  12601. ```
  12602. Simple Example
  12603. --------------
  12604. Synchronous Example
  12605. ```javascript
  12606. var result;
  12607. try {
  12608. result = findResult();
  12609. // success
  12610. } catch(reason) {
  12611. // failure
  12612. }
  12613. ```
  12614. Errback Example
  12615. ```js
  12616. findResult(function(result, err){
  12617. if (err) {
  12618. // failure
  12619. } else {
  12620. // success
  12621. }
  12622. });
  12623. ```
  12624. Promise Example;
  12625. ```javascript
  12626. findResult().then(function(result){
  12627. // success
  12628. }, function(reason){
  12629. // failure
  12630. });
  12631. ```
  12632. Advanced Example
  12633. --------------
  12634. Synchronous Example
  12635. ```javascript
  12636. var author, books;
  12637. try {
  12638. author = findAuthor();
  12639. books = findBooksByAuthor(author);
  12640. // success
  12641. } catch(reason) {
  12642. // failure
  12643. }
  12644. ```
  12645. Errback Example
  12646. ```js
  12647. function foundBooks(books) {
  12648. }
  12649. function failure(reason) {
  12650. }
  12651. findAuthor(function(author, err){
  12652. if (err) {
  12653. failure(err);
  12654. // failure
  12655. } else {
  12656. try {
  12657. findBoooksByAuthor(author, function(books, err) {
  12658. if (err) {
  12659. failure(err);
  12660. } else {
  12661. try {
  12662. foundBooks(books);
  12663. } catch(reason) {
  12664. failure(reason);
  12665. }
  12666. }
  12667. });
  12668. } catch(error) {
  12669. failure(err);
  12670. }
  12671. // success
  12672. }
  12673. });
  12674. ```
  12675. Promise Example;
  12676. ```javascript
  12677. findAuthor().
  12678. then(findBooksByAuthor).
  12679. then(function(books){
  12680. // found books
  12681. }).catch(function(reason){
  12682. // something went wrong
  12683. });
  12684. ```
  12685. @method then
  12686. @param {Function} onFulfilled
  12687. @param {Function} onRejected
  12688. Useful for tooling.
  12689. @return {Promise}
  12690. */
  12691. then: function(onFulfillment, onRejection) {
  12692. var parent = this;
  12693. var state = parent._state;
  12694. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12695. return this;
  12696. }
  12697. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12698. var result = parent._result;
  12699. if (state) {
  12700. var callback = arguments[state - 1];
  12701. lib$es6$promise$asap$$asap(function(){
  12702. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12703. });
  12704. } else {
  12705. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12706. }
  12707. return child;
  12708. },
  12709. /**
  12710. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12711. as the catch block of a try/catch statement.
  12712. ```js
  12713. function findAuthor(){
  12714. throw new Error('couldn't find that author');
  12715. }
  12716. // synchronous
  12717. try {
  12718. findAuthor();
  12719. } catch(reason) {
  12720. // something went wrong
  12721. }
  12722. // async with promises
  12723. findAuthor().catch(function(reason){
  12724. // something went wrong
  12725. });
  12726. ```
  12727. @method catch
  12728. @param {Function} onRejection
  12729. Useful for tooling.
  12730. @return {Promise}
  12731. */
  12732. 'catch': function(onRejection) {
  12733. return this.then(null, onRejection);
  12734. }
  12735. };
  12736. function lib$es6$promise$polyfill$$polyfill() {
  12737. var local;
  12738. if (typeof global !== 'undefined') {
  12739. local = global;
  12740. } else if (typeof self !== 'undefined') {
  12741. local = self;
  12742. } else {
  12743. try {
  12744. local = Function('return this')();
  12745. } catch (e) {
  12746. throw new Error('polyfill failed because global object is unavailable in this environment');
  12747. }
  12748. }
  12749. var P = local.Promise;
  12750. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12751. return;
  12752. }
  12753. local.Promise = lib$es6$promise$promise$$default;
  12754. }
  12755. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12756. var lib$es6$promise$umd$$ES6Promise = {
  12757. 'Promise': lib$es6$promise$promise$$default,
  12758. 'polyfill': lib$es6$promise$polyfill$$default
  12759. };
  12760. /* global define:true module:true window: true */
  12761. if (typeof define === 'function' && define['amd']) {
  12762. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12763. } else if (typeof module !== 'undefined' && module['exports']) {
  12764. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12765. } else if (typeof this !== 'undefined') {
  12766. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12767. }
  12768. lib$es6$promise$polyfill$$default();
  12769. }).call(this);
  12770. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12771. },{"_process":45}],47:[function(require,module,exports){
  12772. /* Copyright @ 2015 Atlassian Pty Ltd
  12773. *
  12774. * Licensed under the Apache License, Version 2.0 (the "License");
  12775. * you may not use this file except in compliance with the License.
  12776. * You may obtain a copy of the License at
  12777. *
  12778. * http://www.apache.org/licenses/LICENSE-2.0
  12779. *
  12780. * Unless required by applicable law or agreed to in writing, software
  12781. * distributed under the License is distributed on an "AS IS" BASIS,
  12782. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12783. * See the License for the specific language governing permissions and
  12784. * limitations under the License.
  12785. */
  12786. /**
  12787. * Ordered log levels.
  12788. */
  12789. var levels = {
  12790. "trace": 0,
  12791. "debug": 1,
  12792. "info": 2,
  12793. "log": 3,
  12794. "warn": 4,
  12795. "error": 5
  12796. };
  12797. /**
  12798. * Parses Error's object stack trace and extracts information about the last
  12799. * caller before the log method was called.
  12800. * @returns JS object with info about the caller - method name, file location,
  12801. * line and column.
  12802. */
  12803. function getCallerInfo() {
  12804. var callerInfo = {
  12805. methodName: "",
  12806. fileLocation: "",
  12807. line: null,
  12808. column: null
  12809. };
  12810. //gets the part of the stack without the logger wrappers
  12811. var error = new Error();
  12812. var stack = error.stack? error.stack.split("\n") : [];
  12813. if(!stack || stack.length < 1) {
  12814. return callerInfo;
  12815. }
  12816. var m = null;
  12817. if(stack[3]) {
  12818. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  12819. }
  12820. if(!m || m.length <= 4) {
  12821. //Firefox && Safari
  12822. if(stack[2].indexOf("log@") === 0){
  12823. //Safari
  12824. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  12825. } else {
  12826. //Firefox
  12827. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  12828. }
  12829. return callerInfo;
  12830. }
  12831. callerInfo.methodName = m[1];
  12832. callerInfo.fileLocation = m[2];
  12833. callerInfo.line = m[3];
  12834. callerInfo.column = m[4];
  12835. return callerInfo;
  12836. }
  12837. /**
  12838. * Logs messages using the transports and level from the logger.
  12839. * @param logger a logger instance.
  12840. * @param level the log level of the message. See the levels variable.
  12841. * @param arguments array with arguments that will be logged.
  12842. */
  12843. function log() {
  12844. var logger = arguments[0], level = arguments[1],
  12845. args = Array.prototype.slice.call(arguments, 2);
  12846. if(levels[level] <= logger.level) {
  12847. return;
  12848. }
  12849. var callerInfo = getCallerInfo();
  12850. for(var i = 0; i < logger.transports.length; i++) {
  12851. var t = logger.transports[i];
  12852. var l = t[level];
  12853. if(l && typeof(l) === "function") {
  12854. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12855. .apply(t, args);
  12856. }
  12857. }
  12858. }
  12859. /**
  12860. *
  12861. * Constructs new logger object.
  12862. * @param level the logging level for the new logger
  12863. * @param id optional identifier for the logger instance.
  12864. * @param transports optional list of handlers(objects) for the logs.
  12865. * The handlers must support - log, warn, error, debug, info, trace.
  12866. * @param format optional (NOT implemented) string.
  12867. */
  12868. function Logger(level, id, transports, format) {
  12869. this.id = id;
  12870. this.format = format;
  12871. if(!this.transports) {
  12872. this.transports = [];
  12873. this.transports.push(Logger.consoleTransport);
  12874. }
  12875. this.level = levels[level];
  12876. var methods = Object.keys(levels);
  12877. for(var i = 0; i < methods.length; i++){
  12878. this[methods[i]] =
  12879. log.bind(null, this, methods[i]);
  12880. }
  12881. }
  12882. /**
  12883. * Sets the log level for the logger.
  12884. * @param level the new log level.
  12885. */
  12886. Logger.prototype.setLevel = function (level) {
  12887. this.level = levels[level];
  12888. };
  12889. module.exports = Logger;
  12890. /**
  12891. * The default transport - console
  12892. */
  12893. Logger.consoleTransport = console;
  12894. /**
  12895. * Enum for the supported log levels.
  12896. */
  12897. Logger.levels = {
  12898. TRACE: "trace",
  12899. DEBUG: "debug",
  12900. INFO: "info",
  12901. LOG: "log",
  12902. WARN: "warn",
  12903. ERROR: "error"
  12904. };
  12905. },{}],48:[function(require,module,exports){
  12906. /* Copyright @ 2015 Atlassian Pty Ltd
  12907. *
  12908. * Licensed under the Apache License, Version 2.0 (the "License");
  12909. * you may not use this file except in compliance with the License.
  12910. * You may obtain a copy of the License at
  12911. *
  12912. * http://www.apache.org/licenses/LICENSE-2.0
  12913. *
  12914. * Unless required by applicable law or agreed to in writing, software
  12915. * distributed under the License is distributed on an "AS IS" BASIS,
  12916. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12917. * See the License for the specific language governing permissions and
  12918. * limitations under the License.
  12919. */
  12920. var Logger = require("./Logger");
  12921. /**
  12922. * Map with the created loggers with ID.
  12923. */
  12924. var idLoggers = {};
  12925. /**
  12926. * Array with the loggers without id.
  12927. */
  12928. var loggers = [];
  12929. /**
  12930. * Log level for the lbrary.
  12931. */
  12932. var curLevel = Logger.levels.TRACE;
  12933. module.exports = {
  12934. /**
  12935. * Creates new logger.
  12936. * @arguments the same as Logger constructor
  12937. */
  12938. getLogger: function(id, transports, format) {
  12939. var logger = new Logger(curLevel, id, transports, format);
  12940. if(id) {
  12941. idLoggers[id] = idLoggers[id] || [];
  12942. idLoggers[id].push(logger);
  12943. } else {
  12944. loggers.push(logger);
  12945. }
  12946. return logger;
  12947. },
  12948. /**
  12949. * Changes the log level for the existing loggers by id.
  12950. * @param level the new log level.
  12951. * @param id if specified the level will be changed only for loggers with the
  12952. * same id. Otherwise the operation will affect all loggers that don't
  12953. * have id.
  12954. */
  12955. setLogLevelById: function(level, id) {
  12956. var l = id? (idLoggers[id] || []) : loggers;
  12957. for(var i = 0; i < l.length; i++) {
  12958. l[i].setLevel(level);
  12959. }
  12960. },
  12961. /**
  12962. * Changes the log level for all existing loggers.
  12963. * @param level the new log level.
  12964. */
  12965. setLogLevel: function (level) {
  12966. curLevel = level;
  12967. var i = 0;
  12968. for(; i < loggers.length; i++) {
  12969. loggers[i].setLevel(level);
  12970. }
  12971. for(var id in idLoggers) {
  12972. var l = idLoggers[id] || [];
  12973. for(i = 0; i < l.length; i++) {
  12974. l[i].setLevel(level);
  12975. }
  12976. }
  12977. },
  12978. /**
  12979. * The supported log levels.
  12980. */
  12981. levels: Logger.levels
  12982. };
  12983. },{"./Logger":47}],49:[function(require,module,exports){
  12984. // Top level file is just a mixin of submodules & constants
  12985. 'use strict';
  12986. var assign = require('./lib/utils/common').assign;
  12987. var deflate = require('./lib/deflate');
  12988. var inflate = require('./lib/inflate');
  12989. var constants = require('./lib/zlib/constants');
  12990. var pako = {};
  12991. assign(pako, deflate, inflate, constants);
  12992. module.exports = pako;
  12993. },{"./lib/deflate":50,"./lib/inflate":51,"./lib/utils/common":52,"./lib/zlib/constants":55}],50:[function(require,module,exports){
  12994. 'use strict';
  12995. var zlib_deflate = require('./zlib/deflate.js');
  12996. var utils = require('./utils/common');
  12997. var strings = require('./utils/strings');
  12998. var msg = require('./zlib/messages');
  12999. var zstream = require('./zlib/zstream');
  13000. var toString = Object.prototype.toString;
  13001. /* Public constants ==========================================================*/
  13002. /* ===========================================================================*/
  13003. var Z_NO_FLUSH = 0;
  13004. var Z_FINISH = 4;
  13005. var Z_OK = 0;
  13006. var Z_STREAM_END = 1;
  13007. var Z_SYNC_FLUSH = 2;
  13008. var Z_DEFAULT_COMPRESSION = -1;
  13009. var Z_DEFAULT_STRATEGY = 0;
  13010. var Z_DEFLATED = 8;
  13011. /* ===========================================================================*/
  13012. /**
  13013. * class Deflate
  13014. *
  13015. * Generic JS-style wrapper for zlib calls. If you don't need
  13016. * streaming behaviour - use more simple functions: [[deflate]],
  13017. * [[deflateRaw]] and [[gzip]].
  13018. **/
  13019. /* internal
  13020. * Deflate.chunks -> Array
  13021. *
  13022. * Chunks of output data, if [[Deflate#onData]] not overriden.
  13023. **/
  13024. /**
  13025. * Deflate.result -> Uint8Array|Array
  13026. *
  13027. * Compressed result, generated by default [[Deflate#onData]]
  13028. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  13029. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  13030. * push a chunk with explicit flush (call [[Deflate#push]] with
  13031. * `Z_SYNC_FLUSH` param).
  13032. **/
  13033. /**
  13034. * Deflate.err -> Number
  13035. *
  13036. * Error code after deflate finished. 0 (Z_OK) on success.
  13037. * You will not need it in real life, because deflate errors
  13038. * are possible only on wrong options or bad `onData` / `onEnd`
  13039. * custom handlers.
  13040. **/
  13041. /**
  13042. * Deflate.msg -> String
  13043. *
  13044. * Error message, if [[Deflate.err]] != 0
  13045. **/
  13046. /**
  13047. * new Deflate(options)
  13048. * - options (Object): zlib deflate options.
  13049. *
  13050. * Creates new deflator instance with specified params. Throws exception
  13051. * on bad params. Supported options:
  13052. *
  13053. * - `level`
  13054. * - `windowBits`
  13055. * - `memLevel`
  13056. * - `strategy`
  13057. *
  13058. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13059. * for more information on these.
  13060. *
  13061. * Additional options, for internal needs:
  13062. *
  13063. * - `chunkSize` - size of generated data chunks (16K by default)
  13064. * - `raw` (Boolean) - do raw deflate
  13065. * - `gzip` (Boolean) - create gzip wrapper
  13066. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13067. * (each char code [0..255])
  13068. * - `header` (Object) - custom header for gzip
  13069. * - `text` (Boolean) - true if compressed data believed to be text
  13070. * - `time` (Number) - modification time, unix timestamp
  13071. * - `os` (Number) - operation system code
  13072. * - `extra` (Array) - array of bytes with extra data (max 65536)
  13073. * - `name` (String) - file name (binary string)
  13074. * - `comment` (String) - comment (binary string)
  13075. * - `hcrc` (Boolean) - true if header crc should be added
  13076. *
  13077. * ##### Example:
  13078. *
  13079. * ```javascript
  13080. * var pako = require('pako')
  13081. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13082. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13083. *
  13084. * var deflate = new pako.Deflate({ level: 3});
  13085. *
  13086. * deflate.push(chunk1, false);
  13087. * deflate.push(chunk2, true); // true -> last chunk
  13088. *
  13089. * if (deflate.err) { throw new Error(deflate.err); }
  13090. *
  13091. * console.log(deflate.result);
  13092. * ```
  13093. **/
  13094. var Deflate = function(options) {
  13095. this.options = utils.assign({
  13096. level: Z_DEFAULT_COMPRESSION,
  13097. method: Z_DEFLATED,
  13098. chunkSize: 16384,
  13099. windowBits: 15,
  13100. memLevel: 8,
  13101. strategy: Z_DEFAULT_STRATEGY,
  13102. to: ''
  13103. }, options || {});
  13104. var opt = this.options;
  13105. if (opt.raw && (opt.windowBits > 0)) {
  13106. opt.windowBits = -opt.windowBits;
  13107. }
  13108. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  13109. opt.windowBits += 16;
  13110. }
  13111. this.err = 0; // error code, if happens (0 = Z_OK)
  13112. this.msg = ''; // error message
  13113. this.ended = false; // used to avoid multiple onEnd() calls
  13114. this.chunks = []; // chunks of compressed data
  13115. this.strm = new zstream();
  13116. this.strm.avail_out = 0;
  13117. var status = zlib_deflate.deflateInit2(
  13118. this.strm,
  13119. opt.level,
  13120. opt.method,
  13121. opt.windowBits,
  13122. opt.memLevel,
  13123. opt.strategy
  13124. );
  13125. if (status !== Z_OK) {
  13126. throw new Error(msg[status]);
  13127. }
  13128. if (opt.header) {
  13129. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  13130. }
  13131. };
  13132. /**
  13133. * Deflate#push(data[, mode]) -> Boolean
  13134. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  13135. * converted to utf8 byte sequence.
  13136. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13137. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13138. *
  13139. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  13140. * new compressed chunks. Returns `true` on success. The last data block must have
  13141. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13142. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13143. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  13144. *
  13145. * On fail call [[Deflate#onEnd]] with error code and return false.
  13146. *
  13147. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13148. * array format is detected automatically). Also, don't skip last param and always
  13149. * use the same type in your code (boolean or number). That will improve JS speed.
  13150. *
  13151. * For regular `Array`-s make sure all elements are [0..255].
  13152. *
  13153. * ##### Example
  13154. *
  13155. * ```javascript
  13156. * push(chunk, false); // push one of data chunks
  13157. * ...
  13158. * push(chunk, true); // push last chunk
  13159. * ```
  13160. **/
  13161. Deflate.prototype.push = function(data, mode) {
  13162. var strm = this.strm;
  13163. var chunkSize = this.options.chunkSize;
  13164. var status, _mode;
  13165. if (this.ended) { return false; }
  13166. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13167. // Convert data if needed
  13168. if (typeof data === 'string') {
  13169. // If we need to compress text, change encoding to utf8.
  13170. strm.input = strings.string2buf(data);
  13171. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13172. strm.input = new Uint8Array(data);
  13173. } else {
  13174. strm.input = data;
  13175. }
  13176. strm.next_in = 0;
  13177. strm.avail_in = strm.input.length;
  13178. do {
  13179. if (strm.avail_out === 0) {
  13180. strm.output = new utils.Buf8(chunkSize);
  13181. strm.next_out = 0;
  13182. strm.avail_out = chunkSize;
  13183. }
  13184. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13185. if (status !== Z_STREAM_END && status !== Z_OK) {
  13186. this.onEnd(status);
  13187. this.ended = true;
  13188. return false;
  13189. }
  13190. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13191. if (this.options.to === 'string') {
  13192. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13193. } else {
  13194. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13195. }
  13196. }
  13197. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13198. // Finalize on the last chunk.
  13199. if (_mode === Z_FINISH) {
  13200. status = zlib_deflate.deflateEnd(this.strm);
  13201. this.onEnd(status);
  13202. this.ended = true;
  13203. return status === Z_OK;
  13204. }
  13205. // callback interim results if Z_SYNC_FLUSH.
  13206. if (_mode === Z_SYNC_FLUSH) {
  13207. this.onEnd(Z_OK);
  13208. strm.avail_out = 0;
  13209. return true;
  13210. }
  13211. return true;
  13212. };
  13213. /**
  13214. * Deflate#onData(chunk) -> Void
  13215. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13216. * on js engine support. When string output requested, each chunk
  13217. * will be string.
  13218. *
  13219. * By default, stores data blocks in `chunks[]` property and glue
  13220. * those in `onEnd`. Override this handler, if you need another behaviour.
  13221. **/
  13222. Deflate.prototype.onData = function(chunk) {
  13223. this.chunks.push(chunk);
  13224. };
  13225. /**
  13226. * Deflate#onEnd(status) -> Void
  13227. * - status (Number): deflate status. 0 (Z_OK) on success,
  13228. * other if not.
  13229. *
  13230. * Called once after you tell deflate that the input stream is
  13231. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13232. * or if an error happened. By default - join collected chunks,
  13233. * free memory and fill `results` / `err` properties.
  13234. **/
  13235. Deflate.prototype.onEnd = function(status) {
  13236. // On success - join
  13237. if (status === Z_OK) {
  13238. if (this.options.to === 'string') {
  13239. this.result = this.chunks.join('');
  13240. } else {
  13241. this.result = utils.flattenChunks(this.chunks);
  13242. }
  13243. }
  13244. this.chunks = [];
  13245. this.err = status;
  13246. this.msg = this.strm.msg;
  13247. };
  13248. /**
  13249. * deflate(data[, options]) -> Uint8Array|Array|String
  13250. * - data (Uint8Array|Array|String): input data to compress.
  13251. * - options (Object): zlib deflate options.
  13252. *
  13253. * Compress `data` with deflate alrorythm and `options`.
  13254. *
  13255. * Supported options are:
  13256. *
  13257. * - level
  13258. * - windowBits
  13259. * - memLevel
  13260. * - strategy
  13261. *
  13262. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13263. * for more information on these.
  13264. *
  13265. * Sugar (options):
  13266. *
  13267. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13268. * negative windowBits implicitly.
  13269. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13270. * (each char code [0..255])
  13271. *
  13272. * ##### Example:
  13273. *
  13274. * ```javascript
  13275. * var pako = require('pako')
  13276. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13277. *
  13278. * console.log(pako.deflate(data));
  13279. * ```
  13280. **/
  13281. function deflate(input, options) {
  13282. var deflator = new Deflate(options);
  13283. deflator.push(input, true);
  13284. // That will never happens, if you don't cheat with options :)
  13285. if (deflator.err) { throw deflator.msg; }
  13286. return deflator.result;
  13287. }
  13288. /**
  13289. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13290. * - data (Uint8Array|Array|String): input data to compress.
  13291. * - options (Object): zlib deflate options.
  13292. *
  13293. * The same as [[deflate]], but creates raw data, without wrapper
  13294. * (header and adler32 crc).
  13295. **/
  13296. function deflateRaw(input, options) {
  13297. options = options || {};
  13298. options.raw = true;
  13299. return deflate(input, options);
  13300. }
  13301. /**
  13302. * gzip(data[, options]) -> Uint8Array|Array|String
  13303. * - data (Uint8Array|Array|String): input data to compress.
  13304. * - options (Object): zlib deflate options.
  13305. *
  13306. * The same as [[deflate]], but create gzip wrapper instead of
  13307. * deflate one.
  13308. **/
  13309. function gzip(input, options) {
  13310. options = options || {};
  13311. options.gzip = true;
  13312. return deflate(input, options);
  13313. }
  13314. exports.Deflate = Deflate;
  13315. exports.deflate = deflate;
  13316. exports.deflateRaw = deflateRaw;
  13317. exports.gzip = gzip;
  13318. },{"./utils/common":52,"./utils/strings":53,"./zlib/deflate.js":57,"./zlib/messages":62,"./zlib/zstream":64}],51:[function(require,module,exports){
  13319. 'use strict';
  13320. var zlib_inflate = require('./zlib/inflate.js');
  13321. var utils = require('./utils/common');
  13322. var strings = require('./utils/strings');
  13323. var c = require('./zlib/constants');
  13324. var msg = require('./zlib/messages');
  13325. var zstream = require('./zlib/zstream');
  13326. var gzheader = require('./zlib/gzheader');
  13327. var toString = Object.prototype.toString;
  13328. /**
  13329. * class Inflate
  13330. *
  13331. * Generic JS-style wrapper for zlib calls. If you don't need
  13332. * streaming behaviour - use more simple functions: [[inflate]]
  13333. * and [[inflateRaw]].
  13334. **/
  13335. /* internal
  13336. * inflate.chunks -> Array
  13337. *
  13338. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13339. **/
  13340. /**
  13341. * Inflate.result -> Uint8Array|Array|String
  13342. *
  13343. * Uncompressed result, generated by default [[Inflate#onData]]
  13344. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13345. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13346. * push a chunk with explicit flush (call [[Inflate#push]] with
  13347. * `Z_SYNC_FLUSH` param).
  13348. **/
  13349. /**
  13350. * Inflate.err -> Number
  13351. *
  13352. * Error code after inflate finished. 0 (Z_OK) on success.
  13353. * Should be checked if broken data possible.
  13354. **/
  13355. /**
  13356. * Inflate.msg -> String
  13357. *
  13358. * Error message, if [[Inflate.err]] != 0
  13359. **/
  13360. /**
  13361. * new Inflate(options)
  13362. * - options (Object): zlib inflate options.
  13363. *
  13364. * Creates new inflator instance with specified params. Throws exception
  13365. * on bad params. Supported options:
  13366. *
  13367. * - `windowBits`
  13368. *
  13369. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13370. * for more information on these.
  13371. *
  13372. * Additional options, for internal needs:
  13373. *
  13374. * - `chunkSize` - size of generated data chunks (16K by default)
  13375. * - `raw` (Boolean) - do raw inflate
  13376. * - `to` (String) - if equal to 'string', then result will be converted
  13377. * from utf8 to utf16 (javascript) string. When string output requested,
  13378. * chunk length can differ from `chunkSize`, depending on content.
  13379. *
  13380. * By default, when no options set, autodetect deflate/gzip data format via
  13381. * wrapper header.
  13382. *
  13383. * ##### Example:
  13384. *
  13385. * ```javascript
  13386. * var pako = require('pako')
  13387. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13388. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13389. *
  13390. * var inflate = new pako.Inflate({ level: 3});
  13391. *
  13392. * inflate.push(chunk1, false);
  13393. * inflate.push(chunk2, true); // true -> last chunk
  13394. *
  13395. * if (inflate.err) { throw new Error(inflate.err); }
  13396. *
  13397. * console.log(inflate.result);
  13398. * ```
  13399. **/
  13400. var Inflate = function(options) {
  13401. this.options = utils.assign({
  13402. chunkSize: 16384,
  13403. windowBits: 0,
  13404. to: ''
  13405. }, options || {});
  13406. var opt = this.options;
  13407. // Force window size for `raw` data, if not set directly,
  13408. // because we have no header for autodetect.
  13409. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13410. opt.windowBits = -opt.windowBits;
  13411. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13412. }
  13413. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13414. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13415. !(options && options.windowBits)) {
  13416. opt.windowBits += 32;
  13417. }
  13418. // Gzip header has no info about windows size, we can do autodetect only
  13419. // for deflate. So, if window size not set, force it to max when gzip possible
  13420. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13421. // bit 3 (16) -> gzipped data
  13422. // bit 4 (32) -> autodetect gzip/deflate
  13423. if ((opt.windowBits & 15) === 0) {
  13424. opt.windowBits |= 15;
  13425. }
  13426. }
  13427. this.err = 0; // error code, if happens (0 = Z_OK)
  13428. this.msg = ''; // error message
  13429. this.ended = false; // used to avoid multiple onEnd() calls
  13430. this.chunks = []; // chunks of compressed data
  13431. this.strm = new zstream();
  13432. this.strm.avail_out = 0;
  13433. var status = zlib_inflate.inflateInit2(
  13434. this.strm,
  13435. opt.windowBits
  13436. );
  13437. if (status !== c.Z_OK) {
  13438. throw new Error(msg[status]);
  13439. }
  13440. this.header = new gzheader();
  13441. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13442. };
  13443. /**
  13444. * Inflate#push(data[, mode]) -> Boolean
  13445. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13446. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13447. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13448. *
  13449. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13450. * new output chunks. Returns `true` on success. The last data block must have
  13451. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13452. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13453. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13454. *
  13455. * On fail call [[Inflate#onEnd]] with error code and return false.
  13456. *
  13457. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13458. * format is detected automatically). Also, don't skip last param and always
  13459. * use the same type in your code (boolean or number). That will improve JS speed.
  13460. *
  13461. * For regular `Array`-s make sure all elements are [0..255].
  13462. *
  13463. * ##### Example
  13464. *
  13465. * ```javascript
  13466. * push(chunk, false); // push one of data chunks
  13467. * ...
  13468. * push(chunk, true); // push last chunk
  13469. * ```
  13470. **/
  13471. Inflate.prototype.push = function(data, mode) {
  13472. var strm = this.strm;
  13473. var chunkSize = this.options.chunkSize;
  13474. var status, _mode;
  13475. var next_out_utf8, tail, utf8str;
  13476. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13477. // when we check that all output data was flushed.
  13478. var allowBufError = false;
  13479. if (this.ended) { return false; }
  13480. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13481. // Convert data if needed
  13482. if (typeof data === 'string') {
  13483. // Only binary strings can be decompressed on practice
  13484. strm.input = strings.binstring2buf(data);
  13485. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13486. strm.input = new Uint8Array(data);
  13487. } else {
  13488. strm.input = data;
  13489. }
  13490. strm.next_in = 0;
  13491. strm.avail_in = strm.input.length;
  13492. do {
  13493. if (strm.avail_out === 0) {
  13494. strm.output = new utils.Buf8(chunkSize);
  13495. strm.next_out = 0;
  13496. strm.avail_out = chunkSize;
  13497. }
  13498. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13499. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13500. status = c.Z_OK;
  13501. allowBufError = false;
  13502. }
  13503. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13504. this.onEnd(status);
  13505. this.ended = true;
  13506. return false;
  13507. }
  13508. if (strm.next_out) {
  13509. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13510. if (this.options.to === 'string') {
  13511. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13512. tail = strm.next_out - next_out_utf8;
  13513. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13514. // move tail
  13515. strm.next_out = tail;
  13516. strm.avail_out = chunkSize - tail;
  13517. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13518. this.onData(utf8str);
  13519. } else {
  13520. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13521. }
  13522. }
  13523. }
  13524. // When no more input data, we should check that internal inflate buffers
  13525. // are flushed. The only way to do it when avail_out = 0 - run one more
  13526. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13527. // Here we set flag to process this error properly.
  13528. //
  13529. // NOTE. Deflate does not return error in this case and does not needs such
  13530. // logic.
  13531. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13532. allowBufError = true;
  13533. }
  13534. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13535. if (status === c.Z_STREAM_END) {
  13536. _mode = c.Z_FINISH;
  13537. }
  13538. // Finalize on the last chunk.
  13539. if (_mode === c.Z_FINISH) {
  13540. status = zlib_inflate.inflateEnd(this.strm);
  13541. this.onEnd(status);
  13542. this.ended = true;
  13543. return status === c.Z_OK;
  13544. }
  13545. // callback interim results if Z_SYNC_FLUSH.
  13546. if (_mode === c.Z_SYNC_FLUSH) {
  13547. this.onEnd(c.Z_OK);
  13548. strm.avail_out = 0;
  13549. return true;
  13550. }
  13551. return true;
  13552. };
  13553. /**
  13554. * Inflate#onData(chunk) -> Void
  13555. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13556. * on js engine support. When string output requested, each chunk
  13557. * will be string.
  13558. *
  13559. * By default, stores data blocks in `chunks[]` property and glue
  13560. * those in `onEnd`. Override this handler, if you need another behaviour.
  13561. **/
  13562. Inflate.prototype.onData = function(chunk) {
  13563. this.chunks.push(chunk);
  13564. };
  13565. /**
  13566. * Inflate#onEnd(status) -> Void
  13567. * - status (Number): inflate status. 0 (Z_OK) on success,
  13568. * other if not.
  13569. *
  13570. * Called either after you tell inflate that the input stream is
  13571. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13572. * or if an error happened. By default - join collected chunks,
  13573. * free memory and fill `results` / `err` properties.
  13574. **/
  13575. Inflate.prototype.onEnd = function(status) {
  13576. // On success - join
  13577. if (status === c.Z_OK) {
  13578. if (this.options.to === 'string') {
  13579. // Glue & convert here, until we teach pako to send
  13580. // utf8 alligned strings to onData
  13581. this.result = this.chunks.join('');
  13582. } else {
  13583. this.result = utils.flattenChunks(this.chunks);
  13584. }
  13585. }
  13586. this.chunks = [];
  13587. this.err = status;
  13588. this.msg = this.strm.msg;
  13589. };
  13590. /**
  13591. * inflate(data[, options]) -> Uint8Array|Array|String
  13592. * - data (Uint8Array|Array|String): input data to decompress.
  13593. * - options (Object): zlib inflate options.
  13594. *
  13595. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13596. * format via wrapper header by default. That's why we don't provide
  13597. * separate `ungzip` method.
  13598. *
  13599. * Supported options are:
  13600. *
  13601. * - windowBits
  13602. *
  13603. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13604. * for more information.
  13605. *
  13606. * Sugar (options):
  13607. *
  13608. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13609. * negative windowBits implicitly.
  13610. * - `to` (String) - if equal to 'string', then result will be converted
  13611. * from utf8 to utf16 (javascript) string. When string output requested,
  13612. * chunk length can differ from `chunkSize`, depending on content.
  13613. *
  13614. *
  13615. * ##### Example:
  13616. *
  13617. * ```javascript
  13618. * var pako = require('pako')
  13619. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13620. * , output;
  13621. *
  13622. * try {
  13623. * output = pako.inflate(input);
  13624. * } catch (err)
  13625. * console.log(err);
  13626. * }
  13627. * ```
  13628. **/
  13629. function inflate(input, options) {
  13630. var inflator = new Inflate(options);
  13631. inflator.push(input, true);
  13632. // That will never happens, if you don't cheat with options :)
  13633. if (inflator.err) { throw inflator.msg; }
  13634. return inflator.result;
  13635. }
  13636. /**
  13637. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13638. * - data (Uint8Array|Array|String): input data to decompress.
  13639. * - options (Object): zlib inflate options.
  13640. *
  13641. * The same as [[inflate]], but creates raw data, without wrapper
  13642. * (header and adler32 crc).
  13643. **/
  13644. function inflateRaw(input, options) {
  13645. options = options || {};
  13646. options.raw = true;
  13647. return inflate(input, options);
  13648. }
  13649. /**
  13650. * ungzip(data[, options]) -> Uint8Array|Array|String
  13651. * - data (Uint8Array|Array|String): input data to decompress.
  13652. * - options (Object): zlib inflate options.
  13653. *
  13654. * Just shortcut to [[inflate]], because it autodetects format
  13655. * by header.content. Done for convenience.
  13656. **/
  13657. exports.Inflate = Inflate;
  13658. exports.inflate = inflate;
  13659. exports.inflateRaw = inflateRaw;
  13660. exports.ungzip = inflate;
  13661. },{"./utils/common":52,"./utils/strings":53,"./zlib/constants":55,"./zlib/gzheader":58,"./zlib/inflate.js":60,"./zlib/messages":62,"./zlib/zstream":64}],52:[function(require,module,exports){
  13662. 'use strict';
  13663. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13664. (typeof Uint16Array !== 'undefined') &&
  13665. (typeof Int32Array !== 'undefined');
  13666. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13667. var sources = Array.prototype.slice.call(arguments, 1);
  13668. while (sources.length) {
  13669. var source = sources.shift();
  13670. if (!source) { continue; }
  13671. if (typeof source !== 'object') {
  13672. throw new TypeError(source + 'must be non-object');
  13673. }
  13674. for (var p in source) {
  13675. if (source.hasOwnProperty(p)) {
  13676. obj[p] = source[p];
  13677. }
  13678. }
  13679. }
  13680. return obj;
  13681. };
  13682. // reduce buffer size, avoiding mem copy
  13683. exports.shrinkBuf = function (buf, size) {
  13684. if (buf.length === size) { return buf; }
  13685. if (buf.subarray) { return buf.subarray(0, size); }
  13686. buf.length = size;
  13687. return buf;
  13688. };
  13689. var fnTyped = {
  13690. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13691. if (src.subarray && dest.subarray) {
  13692. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13693. return;
  13694. }
  13695. // Fallback to ordinary array
  13696. for (var i=0; i<len; i++) {
  13697. dest[dest_offs + i] = src[src_offs + i];
  13698. }
  13699. },
  13700. // Join array of chunks to single array.
  13701. flattenChunks: function(chunks) {
  13702. var i, l, len, pos, chunk, result;
  13703. // calculate data length
  13704. len = 0;
  13705. for (i=0, l=chunks.length; i<l; i++) {
  13706. len += chunks[i].length;
  13707. }
  13708. // join chunks
  13709. result = new Uint8Array(len);
  13710. pos = 0;
  13711. for (i=0, l=chunks.length; i<l; i++) {
  13712. chunk = chunks[i];
  13713. result.set(chunk, pos);
  13714. pos += chunk.length;
  13715. }
  13716. return result;
  13717. }
  13718. };
  13719. var fnUntyped = {
  13720. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13721. for (var i=0; i<len; i++) {
  13722. dest[dest_offs + i] = src[src_offs + i];
  13723. }
  13724. },
  13725. // Join array of chunks to single array.
  13726. flattenChunks: function(chunks) {
  13727. return [].concat.apply([], chunks);
  13728. }
  13729. };
  13730. // Enable/Disable typed arrays use, for testing
  13731. //
  13732. exports.setTyped = function (on) {
  13733. if (on) {
  13734. exports.Buf8 = Uint8Array;
  13735. exports.Buf16 = Uint16Array;
  13736. exports.Buf32 = Int32Array;
  13737. exports.assign(exports, fnTyped);
  13738. } else {
  13739. exports.Buf8 = Array;
  13740. exports.Buf16 = Array;
  13741. exports.Buf32 = Array;
  13742. exports.assign(exports, fnUntyped);
  13743. }
  13744. };
  13745. exports.setTyped(TYPED_OK);
  13746. },{}],53:[function(require,module,exports){
  13747. // String encode/decode helpers
  13748. 'use strict';
  13749. var utils = require('./common');
  13750. // Quick check if we can use fast array to bin string conversion
  13751. //
  13752. // - apply(Array) can fail on Android 2.2
  13753. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13754. //
  13755. var STR_APPLY_OK = true;
  13756. var STR_APPLY_UIA_OK = true;
  13757. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13758. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13759. // Table with utf8 lengths (calculated by first byte of sequence)
  13760. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13761. // because max possible codepoint is 0x10ffff
  13762. var _utf8len = new utils.Buf8(256);
  13763. for (var q=0; q<256; q++) {
  13764. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13765. }
  13766. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13767. // convert string to array (typed, when possible)
  13768. exports.string2buf = function (str) {
  13769. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13770. // count binary size
  13771. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13772. c = str.charCodeAt(m_pos);
  13773. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13774. c2 = str.charCodeAt(m_pos+1);
  13775. if ((c2 & 0xfc00) === 0xdc00) {
  13776. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13777. m_pos++;
  13778. }
  13779. }
  13780. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13781. }
  13782. // allocate buffer
  13783. buf = new utils.Buf8(buf_len);
  13784. // convert
  13785. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13786. c = str.charCodeAt(m_pos);
  13787. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13788. c2 = str.charCodeAt(m_pos+1);
  13789. if ((c2 & 0xfc00) === 0xdc00) {
  13790. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13791. m_pos++;
  13792. }
  13793. }
  13794. if (c < 0x80) {
  13795. /* one byte */
  13796. buf[i++] = c;
  13797. } else if (c < 0x800) {
  13798. /* two bytes */
  13799. buf[i++] = 0xC0 | (c >>> 6);
  13800. buf[i++] = 0x80 | (c & 0x3f);
  13801. } else if (c < 0x10000) {
  13802. /* three bytes */
  13803. buf[i++] = 0xE0 | (c >>> 12);
  13804. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13805. buf[i++] = 0x80 | (c & 0x3f);
  13806. } else {
  13807. /* four bytes */
  13808. buf[i++] = 0xf0 | (c >>> 18);
  13809. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13810. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13811. buf[i++] = 0x80 | (c & 0x3f);
  13812. }
  13813. }
  13814. return buf;
  13815. };
  13816. // Helper (used in 2 places)
  13817. function buf2binstring(buf, len) {
  13818. // use fallback for big arrays to avoid stack overflow
  13819. if (len < 65537) {
  13820. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13821. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13822. }
  13823. }
  13824. var result = '';
  13825. for (var i=0; i < len; i++) {
  13826. result += String.fromCharCode(buf[i]);
  13827. }
  13828. return result;
  13829. }
  13830. // Convert byte array to binary string
  13831. exports.buf2binstring = function(buf) {
  13832. return buf2binstring(buf, buf.length);
  13833. };
  13834. // Convert binary string (typed, when possible)
  13835. exports.binstring2buf = function(str) {
  13836. var buf = new utils.Buf8(str.length);
  13837. for (var i=0, len=buf.length; i < len; i++) {
  13838. buf[i] = str.charCodeAt(i);
  13839. }
  13840. return buf;
  13841. };
  13842. // convert array to string
  13843. exports.buf2string = function (buf, max) {
  13844. var i, out, c, c_len;
  13845. var len = max || buf.length;
  13846. // Reserve max possible length (2 words per char)
  13847. // NB: by unknown reasons, Array is significantly faster for
  13848. // String.fromCharCode.apply than Uint16Array.
  13849. var utf16buf = new Array(len*2);
  13850. for (out=0, i=0; i<len;) {
  13851. c = buf[i++];
  13852. // quick process ascii
  13853. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13854. c_len = _utf8len[c];
  13855. // skip 5 & 6 byte codes
  13856. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13857. // apply mask on first byte
  13858. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13859. // join the rest
  13860. while (c_len > 1 && i < len) {
  13861. c = (c << 6) | (buf[i++] & 0x3f);
  13862. c_len--;
  13863. }
  13864. // terminated by end of string?
  13865. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13866. if (c < 0x10000) {
  13867. utf16buf[out++] = c;
  13868. } else {
  13869. c -= 0x10000;
  13870. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13871. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13872. }
  13873. }
  13874. return buf2binstring(utf16buf, out);
  13875. };
  13876. // Calculate max possible position in utf8 buffer,
  13877. // that will not break sequence. If that's not possible
  13878. // - (very small limits) return max size as is.
  13879. //
  13880. // buf[] - utf8 bytes array
  13881. // max - length limit (mandatory);
  13882. exports.utf8border = function(buf, max) {
  13883. var pos;
  13884. max = max || buf.length;
  13885. if (max > buf.length) { max = buf.length; }
  13886. // go back from last position, until start of sequence found
  13887. pos = max-1;
  13888. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13889. // Fuckup - very small and broken sequence,
  13890. // return max, because we should return something anyway.
  13891. if (pos < 0) { return max; }
  13892. // If we came to start of buffer - that means vuffer is too small,
  13893. // return max too.
  13894. if (pos === 0) { return max; }
  13895. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13896. };
  13897. },{"./common":52}],54:[function(require,module,exports){
  13898. 'use strict';
  13899. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13900. // It doesn't worth to make additional optimizationa as in original.
  13901. // Small size is preferable.
  13902. function adler32(adler, buf, len, pos) {
  13903. var s1 = (adler & 0xffff) |0,
  13904. s2 = ((adler >>> 16) & 0xffff) |0,
  13905. n = 0;
  13906. while (len !== 0) {
  13907. // Set limit ~ twice less than 5552, to keep
  13908. // s2 in 31-bits, because we force signed ints.
  13909. // in other case %= will fail.
  13910. n = len > 2000 ? 2000 : len;
  13911. len -= n;
  13912. do {
  13913. s1 = (s1 + buf[pos++]) |0;
  13914. s2 = (s2 + s1) |0;
  13915. } while (--n);
  13916. s1 %= 65521;
  13917. s2 %= 65521;
  13918. }
  13919. return (s1 | (s2 << 16)) |0;
  13920. }
  13921. module.exports = adler32;
  13922. },{}],55:[function(require,module,exports){
  13923. module.exports = {
  13924. /* Allowed flush values; see deflate() and inflate() below for details */
  13925. Z_NO_FLUSH: 0,
  13926. Z_PARTIAL_FLUSH: 1,
  13927. Z_SYNC_FLUSH: 2,
  13928. Z_FULL_FLUSH: 3,
  13929. Z_FINISH: 4,
  13930. Z_BLOCK: 5,
  13931. Z_TREES: 6,
  13932. /* Return codes for the compression/decompression functions. Negative values
  13933. * are errors, positive values are used for special but normal events.
  13934. */
  13935. Z_OK: 0,
  13936. Z_STREAM_END: 1,
  13937. Z_NEED_DICT: 2,
  13938. Z_ERRNO: -1,
  13939. Z_STREAM_ERROR: -2,
  13940. Z_DATA_ERROR: -3,
  13941. //Z_MEM_ERROR: -4,
  13942. Z_BUF_ERROR: -5,
  13943. //Z_VERSION_ERROR: -6,
  13944. /* compression levels */
  13945. Z_NO_COMPRESSION: 0,
  13946. Z_BEST_SPEED: 1,
  13947. Z_BEST_COMPRESSION: 9,
  13948. Z_DEFAULT_COMPRESSION: -1,
  13949. Z_FILTERED: 1,
  13950. Z_HUFFMAN_ONLY: 2,
  13951. Z_RLE: 3,
  13952. Z_FIXED: 4,
  13953. Z_DEFAULT_STRATEGY: 0,
  13954. /* Possible values of the data_type field (though see inflate()) */
  13955. Z_BINARY: 0,
  13956. Z_TEXT: 1,
  13957. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13958. Z_UNKNOWN: 2,
  13959. /* The deflate compression method */
  13960. Z_DEFLATED: 8
  13961. //Z_NULL: null // Use -1 or null inline, depending on var type
  13962. };
  13963. },{}],56:[function(require,module,exports){
  13964. 'use strict';
  13965. // Note: we can't get significant speed boost here.
  13966. // So write code to minimize size - no pregenerated tables
  13967. // and array tools dependencies.
  13968. // Use ordinary array, since untyped makes no boost here
  13969. function makeTable() {
  13970. var c, table = [];
  13971. for (var n =0; n < 256; n++) {
  13972. c = n;
  13973. for (var k =0; k < 8; k++) {
  13974. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13975. }
  13976. table[n] = c;
  13977. }
  13978. return table;
  13979. }
  13980. // Create table on load. Just 255 signed longs. Not a problem.
  13981. var crcTable = makeTable();
  13982. function crc32(crc, buf, len, pos) {
  13983. var t = crcTable,
  13984. end = pos + len;
  13985. crc = crc ^ (-1);
  13986. for (var i = pos; i < end; i++) {
  13987. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13988. }
  13989. return (crc ^ (-1)); // >>> 0;
  13990. }
  13991. module.exports = crc32;
  13992. },{}],57:[function(require,module,exports){
  13993. 'use strict';
  13994. var utils = require('../utils/common');
  13995. var trees = require('./trees');
  13996. var adler32 = require('./adler32');
  13997. var crc32 = require('./crc32');
  13998. var msg = require('./messages');
  13999. /* Public constants ==========================================================*/
  14000. /* ===========================================================================*/
  14001. /* Allowed flush values; see deflate() and inflate() below for details */
  14002. var Z_NO_FLUSH = 0;
  14003. var Z_PARTIAL_FLUSH = 1;
  14004. //var Z_SYNC_FLUSH = 2;
  14005. var Z_FULL_FLUSH = 3;
  14006. var Z_FINISH = 4;
  14007. var Z_BLOCK = 5;
  14008. //var Z_TREES = 6;
  14009. /* Return codes for the compression/decompression functions. Negative values
  14010. * are errors, positive values are used for special but normal events.
  14011. */
  14012. var Z_OK = 0;
  14013. var Z_STREAM_END = 1;
  14014. //var Z_NEED_DICT = 2;
  14015. //var Z_ERRNO = -1;
  14016. var Z_STREAM_ERROR = -2;
  14017. var Z_DATA_ERROR = -3;
  14018. //var Z_MEM_ERROR = -4;
  14019. var Z_BUF_ERROR = -5;
  14020. //var Z_VERSION_ERROR = -6;
  14021. /* compression levels */
  14022. //var Z_NO_COMPRESSION = 0;
  14023. //var Z_BEST_SPEED = 1;
  14024. //var Z_BEST_COMPRESSION = 9;
  14025. var Z_DEFAULT_COMPRESSION = -1;
  14026. var Z_FILTERED = 1;
  14027. var Z_HUFFMAN_ONLY = 2;
  14028. var Z_RLE = 3;
  14029. var Z_FIXED = 4;
  14030. var Z_DEFAULT_STRATEGY = 0;
  14031. /* Possible values of the data_type field (though see inflate()) */
  14032. //var Z_BINARY = 0;
  14033. //var Z_TEXT = 1;
  14034. //var Z_ASCII = 1; // = Z_TEXT
  14035. var Z_UNKNOWN = 2;
  14036. /* The deflate compression method */
  14037. var Z_DEFLATED = 8;
  14038. /*============================================================================*/
  14039. var MAX_MEM_LEVEL = 9;
  14040. /* Maximum value for memLevel in deflateInit2 */
  14041. var MAX_WBITS = 15;
  14042. /* 32K LZ77 window */
  14043. var DEF_MEM_LEVEL = 8;
  14044. var LENGTH_CODES = 29;
  14045. /* number of length codes, not counting the special END_BLOCK code */
  14046. var LITERALS = 256;
  14047. /* number of literal bytes 0..255 */
  14048. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14049. /* number of Literal or Length codes, including the END_BLOCK code */
  14050. var D_CODES = 30;
  14051. /* number of distance codes */
  14052. var BL_CODES = 19;
  14053. /* number of codes used to transfer the bit lengths */
  14054. var HEAP_SIZE = 2*L_CODES + 1;
  14055. /* maximum heap size */
  14056. var MAX_BITS = 15;
  14057. /* All codes must not exceed MAX_BITS bits */
  14058. var MIN_MATCH = 3;
  14059. var MAX_MATCH = 258;
  14060. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  14061. var PRESET_DICT = 0x20;
  14062. var INIT_STATE = 42;
  14063. var EXTRA_STATE = 69;
  14064. var NAME_STATE = 73;
  14065. var COMMENT_STATE = 91;
  14066. var HCRC_STATE = 103;
  14067. var BUSY_STATE = 113;
  14068. var FINISH_STATE = 666;
  14069. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  14070. var BS_BLOCK_DONE = 2; /* block flush performed */
  14071. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  14072. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  14073. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  14074. function err(strm, errorCode) {
  14075. strm.msg = msg[errorCode];
  14076. return errorCode;
  14077. }
  14078. function rank(f) {
  14079. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  14080. }
  14081. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14082. /* =========================================================================
  14083. * Flush as much pending output as possible. All deflate() output goes
  14084. * through this function so some applications may wish to modify it
  14085. * to avoid allocating a large strm->output buffer and copying into it.
  14086. * (See also read_buf()).
  14087. */
  14088. function flush_pending(strm) {
  14089. var s = strm.state;
  14090. //_tr_flush_bits(s);
  14091. var len = s.pending;
  14092. if (len > strm.avail_out) {
  14093. len = strm.avail_out;
  14094. }
  14095. if (len === 0) { return; }
  14096. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  14097. strm.next_out += len;
  14098. s.pending_out += len;
  14099. strm.total_out += len;
  14100. strm.avail_out -= len;
  14101. s.pending -= len;
  14102. if (s.pending === 0) {
  14103. s.pending_out = 0;
  14104. }
  14105. }
  14106. function flush_block_only (s, last) {
  14107. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  14108. s.block_start = s.strstart;
  14109. flush_pending(s.strm);
  14110. }
  14111. function put_byte(s, b) {
  14112. s.pending_buf[s.pending++] = b;
  14113. }
  14114. /* =========================================================================
  14115. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  14116. * IN assertion: the stream state is correct and there is enough room in
  14117. * pending_buf.
  14118. */
  14119. function putShortMSB(s, b) {
  14120. // put_byte(s, (Byte)(b >> 8));
  14121. // put_byte(s, (Byte)(b & 0xff));
  14122. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  14123. s.pending_buf[s.pending++] = b & 0xff;
  14124. }
  14125. /* ===========================================================================
  14126. * Read a new buffer from the current input stream, update the adler32
  14127. * and total number of bytes read. All deflate() input goes through
  14128. * this function so some applications may wish to modify it to avoid
  14129. * allocating a large strm->input buffer and copying from it.
  14130. * (See also flush_pending()).
  14131. */
  14132. function read_buf(strm, buf, start, size) {
  14133. var len = strm.avail_in;
  14134. if (len > size) { len = size; }
  14135. if (len === 0) { return 0; }
  14136. strm.avail_in -= len;
  14137. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  14138. if (strm.state.wrap === 1) {
  14139. strm.adler = adler32(strm.adler, buf, len, start);
  14140. }
  14141. else if (strm.state.wrap === 2) {
  14142. strm.adler = crc32(strm.adler, buf, len, start);
  14143. }
  14144. strm.next_in += len;
  14145. strm.total_in += len;
  14146. return len;
  14147. }
  14148. /* ===========================================================================
  14149. * Set match_start to the longest match starting at the given string and
  14150. * return its length. Matches shorter or equal to prev_length are discarded,
  14151. * in which case the result is equal to prev_length and match_start is
  14152. * garbage.
  14153. * IN assertions: cur_match is the head of the hash chain for the current
  14154. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  14155. * OUT assertion: the match length is not greater than s->lookahead.
  14156. */
  14157. function longest_match(s, cur_match) {
  14158. var chain_length = s.max_chain_length; /* max hash chain length */
  14159. var scan = s.strstart; /* current string */
  14160. var match; /* matched string */
  14161. var len; /* length of current match */
  14162. var best_len = s.prev_length; /* best match length so far */
  14163. var nice_match = s.nice_match; /* stop if match long enough */
  14164. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14165. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14166. var _win = s.window; // shortcut
  14167. var wmask = s.w_mask;
  14168. var prev = s.prev;
  14169. /* Stop when cur_match becomes <= limit. To simplify the code,
  14170. * we prevent matches with the string of window index 0.
  14171. */
  14172. var strend = s.strstart + MAX_MATCH;
  14173. var scan_end1 = _win[scan + best_len - 1];
  14174. var scan_end = _win[scan + best_len];
  14175. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14176. * It is easy to get rid of this optimization if necessary.
  14177. */
  14178. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14179. /* Do not waste too much time if we already have a good match: */
  14180. if (s.prev_length >= s.good_match) {
  14181. chain_length >>= 2;
  14182. }
  14183. /* Do not look for matches beyond the end of the input. This is necessary
  14184. * to make deflate deterministic.
  14185. */
  14186. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14187. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14188. do {
  14189. // Assert(cur_match < s->strstart, "no future");
  14190. match = cur_match;
  14191. /* Skip to next match if the match length cannot increase
  14192. * or if the match length is less than 2. Note that the checks below
  14193. * for insufficient lookahead only occur occasionally for performance
  14194. * reasons. Therefore uninitialized memory will be accessed, and
  14195. * conditional jumps will be made that depend on those values.
  14196. * However the length of the match is limited to the lookahead, so
  14197. * the output of deflate is not affected by the uninitialized values.
  14198. */
  14199. if (_win[match + best_len] !== scan_end ||
  14200. _win[match + best_len - 1] !== scan_end1 ||
  14201. _win[match] !== _win[scan] ||
  14202. _win[++match] !== _win[scan + 1]) {
  14203. continue;
  14204. }
  14205. /* The check at best_len-1 can be removed because it will be made
  14206. * again later. (This heuristic is not always a win.)
  14207. * It is not necessary to compare scan[2] and match[2] since they
  14208. * are always equal when the other bytes match, given that
  14209. * the hash keys are equal and that HASH_BITS >= 8.
  14210. */
  14211. scan += 2;
  14212. match++;
  14213. // Assert(*scan == *match, "match[2]?");
  14214. /* We check for insufficient lookahead only every 8th comparison;
  14215. * the 256th check will be made at strstart+258.
  14216. */
  14217. do {
  14218. /*jshint noempty:false*/
  14219. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14220. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14221. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14222. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14223. scan < strend);
  14224. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14225. len = MAX_MATCH - (strend - scan);
  14226. scan = strend - MAX_MATCH;
  14227. if (len > best_len) {
  14228. s.match_start = cur_match;
  14229. best_len = len;
  14230. if (len >= nice_match) {
  14231. break;
  14232. }
  14233. scan_end1 = _win[scan + best_len - 1];
  14234. scan_end = _win[scan + best_len];
  14235. }
  14236. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14237. if (best_len <= s.lookahead) {
  14238. return best_len;
  14239. }
  14240. return s.lookahead;
  14241. }
  14242. /* ===========================================================================
  14243. * Fill the window when the lookahead becomes insufficient.
  14244. * Updates strstart and lookahead.
  14245. *
  14246. * IN assertion: lookahead < MIN_LOOKAHEAD
  14247. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14248. * At least one byte has been read, or avail_in == 0; reads are
  14249. * performed for at least two bytes (required for the zip translate_eol
  14250. * option -- not supported here).
  14251. */
  14252. function fill_window(s) {
  14253. var _w_size = s.w_size;
  14254. var p, n, m, more, str;
  14255. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14256. do {
  14257. more = s.window_size - s.lookahead - s.strstart;
  14258. // JS ints have 32 bit, block below not needed
  14259. /* Deal with !@#$% 64K limit: */
  14260. //if (sizeof(int) <= 2) {
  14261. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14262. // more = wsize;
  14263. //
  14264. // } else if (more == (unsigned)(-1)) {
  14265. // /* Very unlikely, but possible on 16 bit machine if
  14266. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14267. // */
  14268. // more--;
  14269. // }
  14270. //}
  14271. /* If the window is almost full and there is insufficient lookahead,
  14272. * move the upper half to the lower one to make room in the upper half.
  14273. */
  14274. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14275. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14276. s.match_start -= _w_size;
  14277. s.strstart -= _w_size;
  14278. /* we now have strstart >= MAX_DIST */
  14279. s.block_start -= _w_size;
  14280. /* Slide the hash table (could be avoided with 32 bit values
  14281. at the expense of memory usage). We slide even when level == 0
  14282. to keep the hash table consistent if we switch back to level > 0
  14283. later. (Using level 0 permanently is not an optimal usage of
  14284. zlib, so we don't care about this pathological case.)
  14285. */
  14286. n = s.hash_size;
  14287. p = n;
  14288. do {
  14289. m = s.head[--p];
  14290. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14291. } while (--n);
  14292. n = _w_size;
  14293. p = n;
  14294. do {
  14295. m = s.prev[--p];
  14296. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14297. /* If n is not on any hash chain, prev[n] is garbage but
  14298. * its value will never be used.
  14299. */
  14300. } while (--n);
  14301. more += _w_size;
  14302. }
  14303. if (s.strm.avail_in === 0) {
  14304. break;
  14305. }
  14306. /* If there was no sliding:
  14307. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14308. * more == window_size - lookahead - strstart
  14309. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14310. * => more >= window_size - 2*WSIZE + 2
  14311. * In the BIG_MEM or MMAP case (not yet supported),
  14312. * window_size == input_size + MIN_LOOKAHEAD &&
  14313. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14314. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14315. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14316. */
  14317. //Assert(more >= 2, "more < 2");
  14318. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14319. s.lookahead += n;
  14320. /* Initialize the hash value now that we have some input: */
  14321. if (s.lookahead + s.insert >= MIN_MATCH) {
  14322. str = s.strstart - s.insert;
  14323. s.ins_h = s.window[str];
  14324. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14325. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14326. //#if MIN_MATCH != 3
  14327. // Call update_hash() MIN_MATCH-3 more times
  14328. //#endif
  14329. while (s.insert) {
  14330. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14331. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14332. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14333. s.head[s.ins_h] = str;
  14334. str++;
  14335. s.insert--;
  14336. if (s.lookahead + s.insert < MIN_MATCH) {
  14337. break;
  14338. }
  14339. }
  14340. }
  14341. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14342. * but this is not important since only literal bytes will be emitted.
  14343. */
  14344. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14345. /* If the WIN_INIT bytes after the end of the current data have never been
  14346. * written, then zero those bytes in order to avoid memory check reports of
  14347. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14348. * the longest match routines. Update the high water mark for the next
  14349. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14350. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14351. */
  14352. // if (s.high_water < s.window_size) {
  14353. // var curr = s.strstart + s.lookahead;
  14354. // var init = 0;
  14355. //
  14356. // if (s.high_water < curr) {
  14357. // /* Previous high water mark below current data -- zero WIN_INIT
  14358. // * bytes or up to end of window, whichever is less.
  14359. // */
  14360. // init = s.window_size - curr;
  14361. // if (init > WIN_INIT)
  14362. // init = WIN_INIT;
  14363. // zmemzero(s->window + curr, (unsigned)init);
  14364. // s->high_water = curr + init;
  14365. // }
  14366. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14367. // /* High water mark at or above current data, but below current data
  14368. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14369. // * to end of window, whichever is less.
  14370. // */
  14371. // init = (ulg)curr + WIN_INIT - s->high_water;
  14372. // if (init > s->window_size - s->high_water)
  14373. // init = s->window_size - s->high_water;
  14374. // zmemzero(s->window + s->high_water, (unsigned)init);
  14375. // s->high_water += init;
  14376. // }
  14377. // }
  14378. //
  14379. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14380. // "not enough room for search");
  14381. }
  14382. /* ===========================================================================
  14383. * Copy without compression as much as possible from the input stream, return
  14384. * the current block state.
  14385. * This function does not insert new strings in the dictionary since
  14386. * uncompressible data is probably not useful. This function is used
  14387. * only for the level=0 compression option.
  14388. * NOTE: this function should be optimized to avoid extra copying from
  14389. * window to pending_buf.
  14390. */
  14391. function deflate_stored(s, flush) {
  14392. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14393. * to pending_buf_size, and each stored block has a 5 byte header:
  14394. */
  14395. var max_block_size = 0xffff;
  14396. if (max_block_size > s.pending_buf_size - 5) {
  14397. max_block_size = s.pending_buf_size - 5;
  14398. }
  14399. /* Copy as much as possible from input to output: */
  14400. for (;;) {
  14401. /* Fill the window as much as possible: */
  14402. if (s.lookahead <= 1) {
  14403. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14404. // s->block_start >= (long)s->w_size, "slide too late");
  14405. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14406. // s.block_start >= s.w_size)) {
  14407. // throw new Error("slide too late");
  14408. // }
  14409. fill_window(s);
  14410. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14411. return BS_NEED_MORE;
  14412. }
  14413. if (s.lookahead === 0) {
  14414. break;
  14415. }
  14416. /* flush the current block */
  14417. }
  14418. //Assert(s->block_start >= 0L, "block gone");
  14419. // if (s.block_start < 0) throw new Error("block gone");
  14420. s.strstart += s.lookahead;
  14421. s.lookahead = 0;
  14422. /* Emit a stored block if pending_buf will be full: */
  14423. var max_start = s.block_start + max_block_size;
  14424. if (s.strstart === 0 || s.strstart >= max_start) {
  14425. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14426. s.lookahead = s.strstart - max_start;
  14427. s.strstart = max_start;
  14428. /*** FLUSH_BLOCK(s, 0); ***/
  14429. flush_block_only(s, false);
  14430. if (s.strm.avail_out === 0) {
  14431. return BS_NEED_MORE;
  14432. }
  14433. /***/
  14434. }
  14435. /* Flush if we may have to slide, otherwise block_start may become
  14436. * negative and the data will be gone:
  14437. */
  14438. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14439. /*** FLUSH_BLOCK(s, 0); ***/
  14440. flush_block_only(s, false);
  14441. if (s.strm.avail_out === 0) {
  14442. return BS_NEED_MORE;
  14443. }
  14444. /***/
  14445. }
  14446. }
  14447. s.insert = 0;
  14448. if (flush === Z_FINISH) {
  14449. /*** FLUSH_BLOCK(s, 1); ***/
  14450. flush_block_only(s, true);
  14451. if (s.strm.avail_out === 0) {
  14452. return BS_FINISH_STARTED;
  14453. }
  14454. /***/
  14455. return BS_FINISH_DONE;
  14456. }
  14457. if (s.strstart > s.block_start) {
  14458. /*** FLUSH_BLOCK(s, 0); ***/
  14459. flush_block_only(s, false);
  14460. if (s.strm.avail_out === 0) {
  14461. return BS_NEED_MORE;
  14462. }
  14463. /***/
  14464. }
  14465. return BS_NEED_MORE;
  14466. }
  14467. /* ===========================================================================
  14468. * Compress as much as possible from the input stream, return the current
  14469. * block state.
  14470. * This function does not perform lazy evaluation of matches and inserts
  14471. * new strings in the dictionary only for unmatched strings or for short
  14472. * matches. It is used only for the fast compression options.
  14473. */
  14474. function deflate_fast(s, flush) {
  14475. var hash_head; /* head of the hash chain */
  14476. var bflush; /* set if current block must be flushed */
  14477. for (;;) {
  14478. /* Make sure that we always have enough lookahead, except
  14479. * at the end of the input file. We need MAX_MATCH bytes
  14480. * for the next match, plus MIN_MATCH bytes to insert the
  14481. * string following the next match.
  14482. */
  14483. if (s.lookahead < MIN_LOOKAHEAD) {
  14484. fill_window(s);
  14485. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14486. return BS_NEED_MORE;
  14487. }
  14488. if (s.lookahead === 0) {
  14489. break; /* flush the current block */
  14490. }
  14491. }
  14492. /* Insert the string window[strstart .. strstart+2] in the
  14493. * dictionary, and set hash_head to the head of the hash chain:
  14494. */
  14495. hash_head = 0/*NIL*/;
  14496. if (s.lookahead >= MIN_MATCH) {
  14497. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14498. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14499. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14500. s.head[s.ins_h] = s.strstart;
  14501. /***/
  14502. }
  14503. /* Find the longest match, discarding those <= prev_length.
  14504. * At this point we have always match_length < MIN_MATCH
  14505. */
  14506. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14507. /* To simplify the code, we prevent matches with the string
  14508. * of window index 0 (in particular we have to avoid a match
  14509. * of the string with itself at the start of the input file).
  14510. */
  14511. s.match_length = longest_match(s, hash_head);
  14512. /* longest_match() sets match_start */
  14513. }
  14514. if (s.match_length >= MIN_MATCH) {
  14515. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14516. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14517. s.match_length - MIN_MATCH, bflush); ***/
  14518. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14519. s.lookahead -= s.match_length;
  14520. /* Insert new strings in the hash table only if the match length
  14521. * is not too large. This saves time but degrades compression.
  14522. */
  14523. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14524. s.match_length--; /* string at strstart already in table */
  14525. do {
  14526. s.strstart++;
  14527. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14528. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14529. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14530. s.head[s.ins_h] = s.strstart;
  14531. /***/
  14532. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14533. * always MIN_MATCH bytes ahead.
  14534. */
  14535. } while (--s.match_length !== 0);
  14536. s.strstart++;
  14537. } else
  14538. {
  14539. s.strstart += s.match_length;
  14540. s.match_length = 0;
  14541. s.ins_h = s.window[s.strstart];
  14542. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14543. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14544. //#if MIN_MATCH != 3
  14545. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14546. //#endif
  14547. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14548. * matter since it will be recomputed at next deflate call.
  14549. */
  14550. }
  14551. } else {
  14552. /* No match, output a literal byte */
  14553. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14554. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14555. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14556. s.lookahead--;
  14557. s.strstart++;
  14558. }
  14559. if (bflush) {
  14560. /*** FLUSH_BLOCK(s, 0); ***/
  14561. flush_block_only(s, false);
  14562. if (s.strm.avail_out === 0) {
  14563. return BS_NEED_MORE;
  14564. }
  14565. /***/
  14566. }
  14567. }
  14568. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14569. if (flush === Z_FINISH) {
  14570. /*** FLUSH_BLOCK(s, 1); ***/
  14571. flush_block_only(s, true);
  14572. if (s.strm.avail_out === 0) {
  14573. return BS_FINISH_STARTED;
  14574. }
  14575. /***/
  14576. return BS_FINISH_DONE;
  14577. }
  14578. if (s.last_lit) {
  14579. /*** FLUSH_BLOCK(s, 0); ***/
  14580. flush_block_only(s, false);
  14581. if (s.strm.avail_out === 0) {
  14582. return BS_NEED_MORE;
  14583. }
  14584. /***/
  14585. }
  14586. return BS_BLOCK_DONE;
  14587. }
  14588. /* ===========================================================================
  14589. * Same as above, but achieves better compression. We use a lazy
  14590. * evaluation for matches: a match is finally adopted only if there is
  14591. * no better match at the next window position.
  14592. */
  14593. function deflate_slow(s, flush) {
  14594. var hash_head; /* head of hash chain */
  14595. var bflush; /* set if current block must be flushed */
  14596. var max_insert;
  14597. /* Process the input block. */
  14598. for (;;) {
  14599. /* Make sure that we always have enough lookahead, except
  14600. * at the end of the input file. We need MAX_MATCH bytes
  14601. * for the next match, plus MIN_MATCH bytes to insert the
  14602. * string following the next match.
  14603. */
  14604. if (s.lookahead < MIN_LOOKAHEAD) {
  14605. fill_window(s);
  14606. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14607. return BS_NEED_MORE;
  14608. }
  14609. if (s.lookahead === 0) { break; } /* flush the current block */
  14610. }
  14611. /* Insert the string window[strstart .. strstart+2] in the
  14612. * dictionary, and set hash_head to the head of the hash chain:
  14613. */
  14614. hash_head = 0/*NIL*/;
  14615. if (s.lookahead >= MIN_MATCH) {
  14616. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14617. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14618. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14619. s.head[s.ins_h] = s.strstart;
  14620. /***/
  14621. }
  14622. /* Find the longest match, discarding those <= prev_length.
  14623. */
  14624. s.prev_length = s.match_length;
  14625. s.prev_match = s.match_start;
  14626. s.match_length = MIN_MATCH-1;
  14627. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14628. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14629. /* To simplify the code, we prevent matches with the string
  14630. * of window index 0 (in particular we have to avoid a match
  14631. * of the string with itself at the start of the input file).
  14632. */
  14633. s.match_length = longest_match(s, hash_head);
  14634. /* longest_match() sets match_start */
  14635. if (s.match_length <= 5 &&
  14636. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14637. /* If prev_match is also MIN_MATCH, match_start is garbage
  14638. * but we will ignore the current match anyway.
  14639. */
  14640. s.match_length = MIN_MATCH-1;
  14641. }
  14642. }
  14643. /* If there was a match at the previous step and the current
  14644. * match is not better, output the previous match:
  14645. */
  14646. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14647. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14648. /* Do not insert strings in hash table beyond this. */
  14649. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14650. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14651. s.prev_length - MIN_MATCH, bflush);***/
  14652. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14653. /* Insert in hash table all strings up to the end of the match.
  14654. * strstart-1 and strstart are already inserted. If there is not
  14655. * enough lookahead, the last two strings are not inserted in
  14656. * the hash table.
  14657. */
  14658. s.lookahead -= s.prev_length-1;
  14659. s.prev_length -= 2;
  14660. do {
  14661. if (++s.strstart <= max_insert) {
  14662. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14663. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14664. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14665. s.head[s.ins_h] = s.strstart;
  14666. /***/
  14667. }
  14668. } while (--s.prev_length !== 0);
  14669. s.match_available = 0;
  14670. s.match_length = MIN_MATCH-1;
  14671. s.strstart++;
  14672. if (bflush) {
  14673. /*** FLUSH_BLOCK(s, 0); ***/
  14674. flush_block_only(s, false);
  14675. if (s.strm.avail_out === 0) {
  14676. return BS_NEED_MORE;
  14677. }
  14678. /***/
  14679. }
  14680. } else if (s.match_available) {
  14681. /* If there was no match at the previous position, output a
  14682. * single literal. If there was a match but the current match
  14683. * is longer, truncate the previous match to a single literal.
  14684. */
  14685. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14686. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14687. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14688. if (bflush) {
  14689. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14690. flush_block_only(s, false);
  14691. /***/
  14692. }
  14693. s.strstart++;
  14694. s.lookahead--;
  14695. if (s.strm.avail_out === 0) {
  14696. return BS_NEED_MORE;
  14697. }
  14698. } else {
  14699. /* There is no previous match to compare with, wait for
  14700. * the next step to decide.
  14701. */
  14702. s.match_available = 1;
  14703. s.strstart++;
  14704. s.lookahead--;
  14705. }
  14706. }
  14707. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14708. if (s.match_available) {
  14709. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14710. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14711. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14712. s.match_available = 0;
  14713. }
  14714. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14715. if (flush === Z_FINISH) {
  14716. /*** FLUSH_BLOCK(s, 1); ***/
  14717. flush_block_only(s, true);
  14718. if (s.strm.avail_out === 0) {
  14719. return BS_FINISH_STARTED;
  14720. }
  14721. /***/
  14722. return BS_FINISH_DONE;
  14723. }
  14724. if (s.last_lit) {
  14725. /*** FLUSH_BLOCK(s, 0); ***/
  14726. flush_block_only(s, false);
  14727. if (s.strm.avail_out === 0) {
  14728. return BS_NEED_MORE;
  14729. }
  14730. /***/
  14731. }
  14732. return BS_BLOCK_DONE;
  14733. }
  14734. /* ===========================================================================
  14735. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14736. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14737. * deflate switches away from Z_RLE.)
  14738. */
  14739. function deflate_rle(s, flush) {
  14740. var bflush; /* set if current block must be flushed */
  14741. var prev; /* byte at distance one to match */
  14742. var scan, strend; /* scan goes up to strend for length of run */
  14743. var _win = s.window;
  14744. for (;;) {
  14745. /* Make sure that we always have enough lookahead, except
  14746. * at the end of the input file. We need MAX_MATCH bytes
  14747. * for the longest run, plus one for the unrolled loop.
  14748. */
  14749. if (s.lookahead <= MAX_MATCH) {
  14750. fill_window(s);
  14751. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14752. return BS_NEED_MORE;
  14753. }
  14754. if (s.lookahead === 0) { break; } /* flush the current block */
  14755. }
  14756. /* See how many times the previous byte repeats */
  14757. s.match_length = 0;
  14758. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14759. scan = s.strstart - 1;
  14760. prev = _win[scan];
  14761. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14762. strend = s.strstart + MAX_MATCH;
  14763. do {
  14764. /*jshint noempty:false*/
  14765. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14766. prev === _win[++scan] && prev === _win[++scan] &&
  14767. prev === _win[++scan] && prev === _win[++scan] &&
  14768. prev === _win[++scan] && prev === _win[++scan] &&
  14769. scan < strend);
  14770. s.match_length = MAX_MATCH - (strend - scan);
  14771. if (s.match_length > s.lookahead) {
  14772. s.match_length = s.lookahead;
  14773. }
  14774. }
  14775. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14776. }
  14777. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14778. if (s.match_length >= MIN_MATCH) {
  14779. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14780. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14781. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14782. s.lookahead -= s.match_length;
  14783. s.strstart += s.match_length;
  14784. s.match_length = 0;
  14785. } else {
  14786. /* No match, output a literal byte */
  14787. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14788. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14789. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14790. s.lookahead--;
  14791. s.strstart++;
  14792. }
  14793. if (bflush) {
  14794. /*** FLUSH_BLOCK(s, 0); ***/
  14795. flush_block_only(s, false);
  14796. if (s.strm.avail_out === 0) {
  14797. return BS_NEED_MORE;
  14798. }
  14799. /***/
  14800. }
  14801. }
  14802. s.insert = 0;
  14803. if (flush === Z_FINISH) {
  14804. /*** FLUSH_BLOCK(s, 1); ***/
  14805. flush_block_only(s, true);
  14806. if (s.strm.avail_out === 0) {
  14807. return BS_FINISH_STARTED;
  14808. }
  14809. /***/
  14810. return BS_FINISH_DONE;
  14811. }
  14812. if (s.last_lit) {
  14813. /*** FLUSH_BLOCK(s, 0); ***/
  14814. flush_block_only(s, false);
  14815. if (s.strm.avail_out === 0) {
  14816. return BS_NEED_MORE;
  14817. }
  14818. /***/
  14819. }
  14820. return BS_BLOCK_DONE;
  14821. }
  14822. /* ===========================================================================
  14823. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14824. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14825. */
  14826. function deflate_huff(s, flush) {
  14827. var bflush; /* set if current block must be flushed */
  14828. for (;;) {
  14829. /* Make sure that we have a literal to write. */
  14830. if (s.lookahead === 0) {
  14831. fill_window(s);
  14832. if (s.lookahead === 0) {
  14833. if (flush === Z_NO_FLUSH) {
  14834. return BS_NEED_MORE;
  14835. }
  14836. break; /* flush the current block */
  14837. }
  14838. }
  14839. /* Output a literal byte */
  14840. s.match_length = 0;
  14841. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14842. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14843. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14844. s.lookahead--;
  14845. s.strstart++;
  14846. if (bflush) {
  14847. /*** FLUSH_BLOCK(s, 0); ***/
  14848. flush_block_only(s, false);
  14849. if (s.strm.avail_out === 0) {
  14850. return BS_NEED_MORE;
  14851. }
  14852. /***/
  14853. }
  14854. }
  14855. s.insert = 0;
  14856. if (flush === Z_FINISH) {
  14857. /*** FLUSH_BLOCK(s, 1); ***/
  14858. flush_block_only(s, true);
  14859. if (s.strm.avail_out === 0) {
  14860. return BS_FINISH_STARTED;
  14861. }
  14862. /***/
  14863. return BS_FINISH_DONE;
  14864. }
  14865. if (s.last_lit) {
  14866. /*** FLUSH_BLOCK(s, 0); ***/
  14867. flush_block_only(s, false);
  14868. if (s.strm.avail_out === 0) {
  14869. return BS_NEED_MORE;
  14870. }
  14871. /***/
  14872. }
  14873. return BS_BLOCK_DONE;
  14874. }
  14875. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14876. * the desired pack level (0..9). The values given below have been tuned to
  14877. * exclude worst case performance for pathological files. Better values may be
  14878. * found for specific files.
  14879. */
  14880. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14881. this.good_length = good_length;
  14882. this.max_lazy = max_lazy;
  14883. this.nice_length = nice_length;
  14884. this.max_chain = max_chain;
  14885. this.func = func;
  14886. };
  14887. var configuration_table;
  14888. configuration_table = [
  14889. /* good lazy nice chain */
  14890. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14891. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14892. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14893. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14894. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14895. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14896. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14897. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14898. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14899. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14900. ];
  14901. /* ===========================================================================
  14902. * Initialize the "longest match" routines for a new zlib stream
  14903. */
  14904. function lm_init(s) {
  14905. s.window_size = 2 * s.w_size;
  14906. /*** CLEAR_HASH(s); ***/
  14907. zero(s.head); // Fill with NIL (= 0);
  14908. /* Set the default configuration parameters:
  14909. */
  14910. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14911. s.good_match = configuration_table[s.level].good_length;
  14912. s.nice_match = configuration_table[s.level].nice_length;
  14913. s.max_chain_length = configuration_table[s.level].max_chain;
  14914. s.strstart = 0;
  14915. s.block_start = 0;
  14916. s.lookahead = 0;
  14917. s.insert = 0;
  14918. s.match_length = s.prev_length = MIN_MATCH - 1;
  14919. s.match_available = 0;
  14920. s.ins_h = 0;
  14921. }
  14922. function DeflateState() {
  14923. this.strm = null; /* pointer back to this zlib stream */
  14924. this.status = 0; /* as the name implies */
  14925. this.pending_buf = null; /* output still pending */
  14926. this.pending_buf_size = 0; /* size of pending_buf */
  14927. this.pending_out = 0; /* next pending byte to output to the stream */
  14928. this.pending = 0; /* nb of bytes in the pending buffer */
  14929. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14930. this.gzhead = null; /* gzip header information to write */
  14931. this.gzindex = 0; /* where in extra, name, or comment */
  14932. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14933. this.last_flush = -1; /* value of flush param for previous deflate call */
  14934. this.w_size = 0; /* LZ77 window size (32K by default) */
  14935. this.w_bits = 0; /* log2(w_size) (8..16) */
  14936. this.w_mask = 0; /* w_size - 1 */
  14937. this.window = null;
  14938. /* Sliding window. Input bytes are read into the second half of the window,
  14939. * and move to the first half later to keep a dictionary of at least wSize
  14940. * bytes. With this organization, matches are limited to a distance of
  14941. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14942. * performed with a length multiple of the block size.
  14943. */
  14944. this.window_size = 0;
  14945. /* Actual size of window: 2*wSize, except when the user input buffer
  14946. * is directly used as sliding window.
  14947. */
  14948. this.prev = null;
  14949. /* Link to older string with same hash index. To limit the size of this
  14950. * array to 64K, this link is maintained only for the last 32K strings.
  14951. * An index in this array is thus a window index modulo 32K.
  14952. */
  14953. this.head = null; /* Heads of the hash chains or NIL. */
  14954. this.ins_h = 0; /* hash index of string to be inserted */
  14955. this.hash_size = 0; /* number of elements in hash table */
  14956. this.hash_bits = 0; /* log2(hash_size) */
  14957. this.hash_mask = 0; /* hash_size-1 */
  14958. this.hash_shift = 0;
  14959. /* Number of bits by which ins_h must be shifted at each input
  14960. * step. It must be such that after MIN_MATCH steps, the oldest
  14961. * byte no longer takes part in the hash key, that is:
  14962. * hash_shift * MIN_MATCH >= hash_bits
  14963. */
  14964. this.block_start = 0;
  14965. /* Window position at the beginning of the current output block. Gets
  14966. * negative when the window is moved backwards.
  14967. */
  14968. this.match_length = 0; /* length of best match */
  14969. this.prev_match = 0; /* previous match */
  14970. this.match_available = 0; /* set if previous match exists */
  14971. this.strstart = 0; /* start of string to insert */
  14972. this.match_start = 0; /* start of matching string */
  14973. this.lookahead = 0; /* number of valid bytes ahead in window */
  14974. this.prev_length = 0;
  14975. /* Length of the best match at previous step. Matches not greater than this
  14976. * are discarded. This is used in the lazy match evaluation.
  14977. */
  14978. this.max_chain_length = 0;
  14979. /* To speed up deflation, hash chains are never searched beyond this
  14980. * length. A higher limit improves compression ratio but degrades the
  14981. * speed.
  14982. */
  14983. this.max_lazy_match = 0;
  14984. /* Attempt to find a better match only when the current match is strictly
  14985. * smaller than this value. This mechanism is used only for compression
  14986. * levels >= 4.
  14987. */
  14988. // That's alias to max_lazy_match, don't use directly
  14989. //this.max_insert_length = 0;
  14990. /* Insert new strings in the hash table only if the match length is not
  14991. * greater than this length. This saves time but degrades compression.
  14992. * max_insert_length is used only for compression levels <= 3.
  14993. */
  14994. this.level = 0; /* compression level (1..9) */
  14995. this.strategy = 0; /* favor or force Huffman coding*/
  14996. this.good_match = 0;
  14997. /* Use a faster search when the previous match is longer than this */
  14998. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14999. /* used by trees.c: */
  15000. /* Didn't use ct_data typedef below to suppress compiler warning */
  15001. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  15002. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  15003. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  15004. // Use flat array of DOUBLE size, with interleaved fata,
  15005. // because JS does not support effective
  15006. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  15007. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  15008. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  15009. zero(this.dyn_ltree);
  15010. zero(this.dyn_dtree);
  15011. zero(this.bl_tree);
  15012. this.l_desc = null; /* desc. for literal tree */
  15013. this.d_desc = null; /* desc. for distance tree */
  15014. this.bl_desc = null; /* desc. for bit length tree */
  15015. //ush bl_count[MAX_BITS+1];
  15016. this.bl_count = new utils.Buf16(MAX_BITS+1);
  15017. /* number of codes at each bit length for an optimal tree */
  15018. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  15019. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  15020. zero(this.heap);
  15021. this.heap_len = 0; /* number of elements in the heap */
  15022. this.heap_max = 0; /* element of largest frequency */
  15023. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15024. * The same heap array is used to build all trees.
  15025. */
  15026. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  15027. zero(this.depth);
  15028. /* Depth of each subtree used as tie breaker for trees of equal frequency
  15029. */
  15030. this.l_buf = 0; /* buffer index for literals or lengths */
  15031. this.lit_bufsize = 0;
  15032. /* Size of match buffer for literals/lengths. There are 4 reasons for
  15033. * limiting lit_bufsize to 64K:
  15034. * - frequencies can be kept in 16 bit counters
  15035. * - if compression is not successful for the first block, all input
  15036. * data is still in the window so we can still emit a stored block even
  15037. * when input comes from standard input. (This can also be done for
  15038. * all blocks if lit_bufsize is not greater than 32K.)
  15039. * - if compression is not successful for a file smaller than 64K, we can
  15040. * even emit a stored file instead of a stored block (saving 5 bytes).
  15041. * This is applicable only for zip (not gzip or zlib).
  15042. * - creating new Huffman trees less frequently may not provide fast
  15043. * adaptation to changes in the input data statistics. (Take for
  15044. * example a binary file with poorly compressible code followed by
  15045. * a highly compressible string table.) Smaller buffer sizes give
  15046. * fast adaptation but have of course the overhead of transmitting
  15047. * trees more frequently.
  15048. * - I can't count above 4
  15049. */
  15050. this.last_lit = 0; /* running index in l_buf */
  15051. this.d_buf = 0;
  15052. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  15053. * the same number of elements. To use different lengths, an extra flag
  15054. * array would be necessary.
  15055. */
  15056. this.opt_len = 0; /* bit length of current block with optimal trees */
  15057. this.static_len = 0; /* bit length of current block with static trees */
  15058. this.matches = 0; /* number of string matches in current block */
  15059. this.insert = 0; /* bytes at end of window left to insert */
  15060. this.bi_buf = 0;
  15061. /* Output buffer. bits are inserted starting at the bottom (least
  15062. * significant bits).
  15063. */
  15064. this.bi_valid = 0;
  15065. /* Number of valid bits in bi_buf. All bits above the last valid bit
  15066. * are always zero.
  15067. */
  15068. // Used for window memory init. We safely ignore it for JS. That makes
  15069. // sense only for pointers and memory check tools.
  15070. //this.high_water = 0;
  15071. /* High water mark offset in window for initialized bytes -- bytes above
  15072. * this are set to zero in order to avoid memory check warnings when
  15073. * longest match routines access bytes past the input. This is then
  15074. * updated to the new high water mark.
  15075. */
  15076. }
  15077. function deflateResetKeep(strm) {
  15078. var s;
  15079. if (!strm || !strm.state) {
  15080. return err(strm, Z_STREAM_ERROR);
  15081. }
  15082. strm.total_in = strm.total_out = 0;
  15083. strm.data_type = Z_UNKNOWN;
  15084. s = strm.state;
  15085. s.pending = 0;
  15086. s.pending_out = 0;
  15087. if (s.wrap < 0) {
  15088. s.wrap = -s.wrap;
  15089. /* was made negative by deflate(..., Z_FINISH); */
  15090. }
  15091. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  15092. strm.adler = (s.wrap === 2) ?
  15093. 0 // crc32(0, Z_NULL, 0)
  15094. :
  15095. 1; // adler32(0, Z_NULL, 0)
  15096. s.last_flush = Z_NO_FLUSH;
  15097. trees._tr_init(s);
  15098. return Z_OK;
  15099. }
  15100. function deflateReset(strm) {
  15101. var ret = deflateResetKeep(strm);
  15102. if (ret === Z_OK) {
  15103. lm_init(strm.state);
  15104. }
  15105. return ret;
  15106. }
  15107. function deflateSetHeader(strm, head) {
  15108. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15109. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  15110. strm.state.gzhead = head;
  15111. return Z_OK;
  15112. }
  15113. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  15114. if (!strm) { // === Z_NULL
  15115. return Z_STREAM_ERROR;
  15116. }
  15117. var wrap = 1;
  15118. if (level === Z_DEFAULT_COMPRESSION) {
  15119. level = 6;
  15120. }
  15121. if (windowBits < 0) { /* suppress zlib wrapper */
  15122. wrap = 0;
  15123. windowBits = -windowBits;
  15124. }
  15125. else if (windowBits > 15) {
  15126. wrap = 2; /* write gzip wrapper instead */
  15127. windowBits -= 16;
  15128. }
  15129. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  15130. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  15131. strategy < 0 || strategy > Z_FIXED) {
  15132. return err(strm, Z_STREAM_ERROR);
  15133. }
  15134. if (windowBits === 8) {
  15135. windowBits = 9;
  15136. }
  15137. /* until 256-byte window bug fixed */
  15138. var s = new DeflateState();
  15139. strm.state = s;
  15140. s.strm = strm;
  15141. s.wrap = wrap;
  15142. s.gzhead = null;
  15143. s.w_bits = windowBits;
  15144. s.w_size = 1 << s.w_bits;
  15145. s.w_mask = s.w_size - 1;
  15146. s.hash_bits = memLevel + 7;
  15147. s.hash_size = 1 << s.hash_bits;
  15148. s.hash_mask = s.hash_size - 1;
  15149. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15150. s.window = new utils.Buf8(s.w_size * 2);
  15151. s.head = new utils.Buf16(s.hash_size);
  15152. s.prev = new utils.Buf16(s.w_size);
  15153. // Don't need mem init magic for JS.
  15154. //s.high_water = 0; /* nothing written to s->window yet */
  15155. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  15156. s.pending_buf_size = s.lit_bufsize * 4;
  15157. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  15158. s.d_buf = s.lit_bufsize >> 1;
  15159. s.l_buf = (1 + 2) * s.lit_bufsize;
  15160. s.level = level;
  15161. s.strategy = strategy;
  15162. s.method = method;
  15163. return deflateReset(strm);
  15164. }
  15165. function deflateInit(strm, level) {
  15166. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15167. }
  15168. function deflate(strm, flush) {
  15169. var old_flush, s;
  15170. var beg, val; // for gzip header write only
  15171. if (!strm || !strm.state ||
  15172. flush > Z_BLOCK || flush < 0) {
  15173. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15174. }
  15175. s = strm.state;
  15176. if (!strm.output ||
  15177. (!strm.input && strm.avail_in !== 0) ||
  15178. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15179. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15180. }
  15181. s.strm = strm; /* just in case */
  15182. old_flush = s.last_flush;
  15183. s.last_flush = flush;
  15184. /* Write the header */
  15185. if (s.status === INIT_STATE) {
  15186. if (s.wrap === 2) { // GZIP header
  15187. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15188. put_byte(s, 31);
  15189. put_byte(s, 139);
  15190. put_byte(s, 8);
  15191. if (!s.gzhead) { // s->gzhead == Z_NULL
  15192. put_byte(s, 0);
  15193. put_byte(s, 0);
  15194. put_byte(s, 0);
  15195. put_byte(s, 0);
  15196. put_byte(s, 0);
  15197. put_byte(s, s.level === 9 ? 2 :
  15198. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15199. 4 : 0));
  15200. put_byte(s, OS_CODE);
  15201. s.status = BUSY_STATE;
  15202. }
  15203. else {
  15204. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15205. (s.gzhead.hcrc ? 2 : 0) +
  15206. (!s.gzhead.extra ? 0 : 4) +
  15207. (!s.gzhead.name ? 0 : 8) +
  15208. (!s.gzhead.comment ? 0 : 16)
  15209. );
  15210. put_byte(s, s.gzhead.time & 0xff);
  15211. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15212. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15213. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15214. put_byte(s, s.level === 9 ? 2 :
  15215. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15216. 4 : 0));
  15217. put_byte(s, s.gzhead.os & 0xff);
  15218. if (s.gzhead.extra && s.gzhead.extra.length) {
  15219. put_byte(s, s.gzhead.extra.length & 0xff);
  15220. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15221. }
  15222. if (s.gzhead.hcrc) {
  15223. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15224. }
  15225. s.gzindex = 0;
  15226. s.status = EXTRA_STATE;
  15227. }
  15228. }
  15229. else // DEFLATE header
  15230. {
  15231. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15232. var level_flags = -1;
  15233. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15234. level_flags = 0;
  15235. } else if (s.level < 6) {
  15236. level_flags = 1;
  15237. } else if (s.level === 6) {
  15238. level_flags = 2;
  15239. } else {
  15240. level_flags = 3;
  15241. }
  15242. header |= (level_flags << 6);
  15243. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15244. header += 31 - (header % 31);
  15245. s.status = BUSY_STATE;
  15246. putShortMSB(s, header);
  15247. /* Save the adler32 of the preset dictionary: */
  15248. if (s.strstart !== 0) {
  15249. putShortMSB(s, strm.adler >>> 16);
  15250. putShortMSB(s, strm.adler & 0xffff);
  15251. }
  15252. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15253. }
  15254. }
  15255. //#ifdef GZIP
  15256. if (s.status === EXTRA_STATE) {
  15257. if (s.gzhead.extra/* != Z_NULL*/) {
  15258. beg = s.pending; /* start of bytes to update crc */
  15259. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15260. if (s.pending === s.pending_buf_size) {
  15261. if (s.gzhead.hcrc && s.pending > beg) {
  15262. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15263. }
  15264. flush_pending(strm);
  15265. beg = s.pending;
  15266. if (s.pending === s.pending_buf_size) {
  15267. break;
  15268. }
  15269. }
  15270. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15271. s.gzindex++;
  15272. }
  15273. if (s.gzhead.hcrc && s.pending > beg) {
  15274. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15275. }
  15276. if (s.gzindex === s.gzhead.extra.length) {
  15277. s.gzindex = 0;
  15278. s.status = NAME_STATE;
  15279. }
  15280. }
  15281. else {
  15282. s.status = NAME_STATE;
  15283. }
  15284. }
  15285. if (s.status === NAME_STATE) {
  15286. if (s.gzhead.name/* != Z_NULL*/) {
  15287. beg = s.pending; /* start of bytes to update crc */
  15288. //int val;
  15289. do {
  15290. if (s.pending === s.pending_buf_size) {
  15291. if (s.gzhead.hcrc && s.pending > beg) {
  15292. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15293. }
  15294. flush_pending(strm);
  15295. beg = s.pending;
  15296. if (s.pending === s.pending_buf_size) {
  15297. val = 1;
  15298. break;
  15299. }
  15300. }
  15301. // JS specific: little magic to add zero terminator to end of string
  15302. if (s.gzindex < s.gzhead.name.length) {
  15303. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15304. } else {
  15305. val = 0;
  15306. }
  15307. put_byte(s, val);
  15308. } while (val !== 0);
  15309. if (s.gzhead.hcrc && s.pending > beg) {
  15310. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15311. }
  15312. if (val === 0) {
  15313. s.gzindex = 0;
  15314. s.status = COMMENT_STATE;
  15315. }
  15316. }
  15317. else {
  15318. s.status = COMMENT_STATE;
  15319. }
  15320. }
  15321. if (s.status === COMMENT_STATE) {
  15322. if (s.gzhead.comment/* != Z_NULL*/) {
  15323. beg = s.pending; /* start of bytes to update crc */
  15324. //int val;
  15325. do {
  15326. if (s.pending === s.pending_buf_size) {
  15327. if (s.gzhead.hcrc && s.pending > beg) {
  15328. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15329. }
  15330. flush_pending(strm);
  15331. beg = s.pending;
  15332. if (s.pending === s.pending_buf_size) {
  15333. val = 1;
  15334. break;
  15335. }
  15336. }
  15337. // JS specific: little magic to add zero terminator to end of string
  15338. if (s.gzindex < s.gzhead.comment.length) {
  15339. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15340. } else {
  15341. val = 0;
  15342. }
  15343. put_byte(s, val);
  15344. } while (val !== 0);
  15345. if (s.gzhead.hcrc && s.pending > beg) {
  15346. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15347. }
  15348. if (val === 0) {
  15349. s.status = HCRC_STATE;
  15350. }
  15351. }
  15352. else {
  15353. s.status = HCRC_STATE;
  15354. }
  15355. }
  15356. if (s.status === HCRC_STATE) {
  15357. if (s.gzhead.hcrc) {
  15358. if (s.pending + 2 > s.pending_buf_size) {
  15359. flush_pending(strm);
  15360. }
  15361. if (s.pending + 2 <= s.pending_buf_size) {
  15362. put_byte(s, strm.adler & 0xff);
  15363. put_byte(s, (strm.adler >> 8) & 0xff);
  15364. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15365. s.status = BUSY_STATE;
  15366. }
  15367. }
  15368. else {
  15369. s.status = BUSY_STATE;
  15370. }
  15371. }
  15372. //#endif
  15373. /* Flush as much pending output as possible */
  15374. if (s.pending !== 0) {
  15375. flush_pending(strm);
  15376. if (strm.avail_out === 0) {
  15377. /* Since avail_out is 0, deflate will be called again with
  15378. * more output space, but possibly with both pending and
  15379. * avail_in equal to zero. There won't be anything to do,
  15380. * but this is not an error situation so make sure we
  15381. * return OK instead of BUF_ERROR at next call of deflate:
  15382. */
  15383. s.last_flush = -1;
  15384. return Z_OK;
  15385. }
  15386. /* Make sure there is something to do and avoid duplicate consecutive
  15387. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15388. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15389. */
  15390. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15391. flush !== Z_FINISH) {
  15392. return err(strm, Z_BUF_ERROR);
  15393. }
  15394. /* User must not provide more input after the first FINISH: */
  15395. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15396. return err(strm, Z_BUF_ERROR);
  15397. }
  15398. /* Start a new block or continue the current one.
  15399. */
  15400. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15401. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15402. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15403. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15404. configuration_table[s.level].func(s, flush));
  15405. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15406. s.status = FINISH_STATE;
  15407. }
  15408. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15409. if (strm.avail_out === 0) {
  15410. s.last_flush = -1;
  15411. /* avoid BUF_ERROR next call, see above */
  15412. }
  15413. return Z_OK;
  15414. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15415. * of deflate should use the same flush parameter to make sure
  15416. * that the flush is complete. So we don't have to output an
  15417. * empty block here, this will be done at next call. This also
  15418. * ensures that for a very small output buffer, we emit at most
  15419. * one empty block.
  15420. */
  15421. }
  15422. if (bstate === BS_BLOCK_DONE) {
  15423. if (flush === Z_PARTIAL_FLUSH) {
  15424. trees._tr_align(s);
  15425. }
  15426. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15427. trees._tr_stored_block(s, 0, 0, false);
  15428. /* For a full flush, this empty block will be recognized
  15429. * as a special marker by inflate_sync().
  15430. */
  15431. if (flush === Z_FULL_FLUSH) {
  15432. /*** CLEAR_HASH(s); ***/ /* forget history */
  15433. zero(s.head); // Fill with NIL (= 0);
  15434. if (s.lookahead === 0) {
  15435. s.strstart = 0;
  15436. s.block_start = 0;
  15437. s.insert = 0;
  15438. }
  15439. }
  15440. }
  15441. flush_pending(strm);
  15442. if (strm.avail_out === 0) {
  15443. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15444. return Z_OK;
  15445. }
  15446. }
  15447. }
  15448. //Assert(strm->avail_out > 0, "bug2");
  15449. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15450. if (flush !== Z_FINISH) { return Z_OK; }
  15451. if (s.wrap <= 0) { return Z_STREAM_END; }
  15452. /* Write the trailer */
  15453. if (s.wrap === 2) {
  15454. put_byte(s, strm.adler & 0xff);
  15455. put_byte(s, (strm.adler >> 8) & 0xff);
  15456. put_byte(s, (strm.adler >> 16) & 0xff);
  15457. put_byte(s, (strm.adler >> 24) & 0xff);
  15458. put_byte(s, strm.total_in & 0xff);
  15459. put_byte(s, (strm.total_in >> 8) & 0xff);
  15460. put_byte(s, (strm.total_in >> 16) & 0xff);
  15461. put_byte(s, (strm.total_in >> 24) & 0xff);
  15462. }
  15463. else
  15464. {
  15465. putShortMSB(s, strm.adler >>> 16);
  15466. putShortMSB(s, strm.adler & 0xffff);
  15467. }
  15468. flush_pending(strm);
  15469. /* If avail_out is zero, the application will call deflate again
  15470. * to flush the rest.
  15471. */
  15472. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15473. /* write the trailer only once! */
  15474. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15475. }
  15476. function deflateEnd(strm) {
  15477. var status;
  15478. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15479. return Z_STREAM_ERROR;
  15480. }
  15481. status = strm.state.status;
  15482. if (status !== INIT_STATE &&
  15483. status !== EXTRA_STATE &&
  15484. status !== NAME_STATE &&
  15485. status !== COMMENT_STATE &&
  15486. status !== HCRC_STATE &&
  15487. status !== BUSY_STATE &&
  15488. status !== FINISH_STATE
  15489. ) {
  15490. return err(strm, Z_STREAM_ERROR);
  15491. }
  15492. strm.state = null;
  15493. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15494. }
  15495. /* =========================================================================
  15496. * Copy the source state to the destination state
  15497. */
  15498. //function deflateCopy(dest, source) {
  15499. //
  15500. //}
  15501. exports.deflateInit = deflateInit;
  15502. exports.deflateInit2 = deflateInit2;
  15503. exports.deflateReset = deflateReset;
  15504. exports.deflateResetKeep = deflateResetKeep;
  15505. exports.deflateSetHeader = deflateSetHeader;
  15506. exports.deflate = deflate;
  15507. exports.deflateEnd = deflateEnd;
  15508. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15509. /* Not implemented
  15510. exports.deflateBound = deflateBound;
  15511. exports.deflateCopy = deflateCopy;
  15512. exports.deflateSetDictionary = deflateSetDictionary;
  15513. exports.deflateParams = deflateParams;
  15514. exports.deflatePending = deflatePending;
  15515. exports.deflatePrime = deflatePrime;
  15516. exports.deflateTune = deflateTune;
  15517. */
  15518. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./messages":62,"./trees":63}],58:[function(require,module,exports){
  15519. 'use strict';
  15520. function GZheader() {
  15521. /* true if compressed data believed to be text */
  15522. this.text = 0;
  15523. /* modification time */
  15524. this.time = 0;
  15525. /* extra flags (not used when writing a gzip file) */
  15526. this.xflags = 0;
  15527. /* operating system */
  15528. this.os = 0;
  15529. /* pointer to extra field or Z_NULL if none */
  15530. this.extra = null;
  15531. /* extra field length (valid if extra != Z_NULL) */
  15532. this.extra_len = 0; // Actually, we don't need it in JS,
  15533. // but leave for few code modifications
  15534. //
  15535. // Setup limits is not necessary because in js we should not preallocate memory
  15536. // for inflate use constant limit in 65536 bytes
  15537. //
  15538. /* space at extra (only when reading header) */
  15539. // this.extra_max = 0;
  15540. /* pointer to zero-terminated file name or Z_NULL */
  15541. this.name = '';
  15542. /* space at name (only when reading header) */
  15543. // this.name_max = 0;
  15544. /* pointer to zero-terminated comment or Z_NULL */
  15545. this.comment = '';
  15546. /* space at comment (only when reading header) */
  15547. // this.comm_max = 0;
  15548. /* true if there was or will be a header crc */
  15549. this.hcrc = 0;
  15550. /* true when done reading gzip header (not used when writing a gzip file) */
  15551. this.done = false;
  15552. }
  15553. module.exports = GZheader;
  15554. },{}],59:[function(require,module,exports){
  15555. 'use strict';
  15556. // See state defs from inflate.js
  15557. var BAD = 30; /* got a data error -- remain here until reset */
  15558. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15559. /*
  15560. Decode literal, length, and distance codes and write out the resulting
  15561. literal and match bytes until either not enough input or output is
  15562. available, an end-of-block is encountered, or a data error is encountered.
  15563. When large enough input and output buffers are supplied to inflate(), for
  15564. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15565. inflate execution time is spent in this routine.
  15566. Entry assumptions:
  15567. state.mode === LEN
  15568. strm.avail_in >= 6
  15569. strm.avail_out >= 258
  15570. start >= strm.avail_out
  15571. state.bits < 8
  15572. On return, state.mode is one of:
  15573. LEN -- ran out of enough output space or enough available input
  15574. TYPE -- reached end of block code, inflate() to interpret next block
  15575. BAD -- error in block data
  15576. Notes:
  15577. - The maximum input bits used by a length/distance pair is 15 bits for the
  15578. length code, 5 bits for the length extra, 15 bits for the distance code,
  15579. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15580. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15581. checking for available input while decoding.
  15582. - The maximum bytes that a single length/distance pair can output is 258
  15583. bytes, which is the maximum length that can be coded. inflate_fast()
  15584. requires strm.avail_out >= 258 for each loop to avoid checking for
  15585. output space.
  15586. */
  15587. module.exports = function inflate_fast(strm, start) {
  15588. var state;
  15589. var _in; /* local strm.input */
  15590. var last; /* have enough input while in < last */
  15591. var _out; /* local strm.output */
  15592. var beg; /* inflate()'s initial strm.output */
  15593. var end; /* while out < end, enough space available */
  15594. //#ifdef INFLATE_STRICT
  15595. var dmax; /* maximum distance from zlib header */
  15596. //#endif
  15597. var wsize; /* window size or zero if not using window */
  15598. var whave; /* valid bytes in the window */
  15599. var wnext; /* window write index */
  15600. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15601. var s_window; /* allocated sliding window, if wsize != 0 */
  15602. var hold; /* local strm.hold */
  15603. var bits; /* local strm.bits */
  15604. var lcode; /* local strm.lencode */
  15605. var dcode; /* local strm.distcode */
  15606. var lmask; /* mask for first level of length codes */
  15607. var dmask; /* mask for first level of distance codes */
  15608. var here; /* retrieved table entry */
  15609. var op; /* code bits, operation, extra bits, or */
  15610. /* window position, window bytes to copy */
  15611. var len; /* match length, unused bytes */
  15612. var dist; /* match distance */
  15613. var from; /* where to copy match from */
  15614. var from_source;
  15615. var input, output; // JS specific, because we have no pointers
  15616. /* copy state to local variables */
  15617. state = strm.state;
  15618. //here = state.here;
  15619. _in = strm.next_in;
  15620. input = strm.input;
  15621. last = _in + (strm.avail_in - 5);
  15622. _out = strm.next_out;
  15623. output = strm.output;
  15624. beg = _out - (start - strm.avail_out);
  15625. end = _out + (strm.avail_out - 257);
  15626. //#ifdef INFLATE_STRICT
  15627. dmax = state.dmax;
  15628. //#endif
  15629. wsize = state.wsize;
  15630. whave = state.whave;
  15631. wnext = state.wnext;
  15632. s_window = state.window;
  15633. hold = state.hold;
  15634. bits = state.bits;
  15635. lcode = state.lencode;
  15636. dcode = state.distcode;
  15637. lmask = (1 << state.lenbits) - 1;
  15638. dmask = (1 << state.distbits) - 1;
  15639. /* decode literals and length/distances until end-of-block or not enough
  15640. input data or output space */
  15641. top:
  15642. do {
  15643. if (bits < 15) {
  15644. hold += input[_in++] << bits;
  15645. bits += 8;
  15646. hold += input[_in++] << bits;
  15647. bits += 8;
  15648. }
  15649. here = lcode[hold & lmask];
  15650. dolen:
  15651. for (;;) { // Goto emulation
  15652. op = here >>> 24/*here.bits*/;
  15653. hold >>>= op;
  15654. bits -= op;
  15655. op = (here >>> 16) & 0xff/*here.op*/;
  15656. if (op === 0) { /* literal */
  15657. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15658. // "inflate: literal '%c'\n" :
  15659. // "inflate: literal 0x%02x\n", here.val));
  15660. output[_out++] = here & 0xffff/*here.val*/;
  15661. }
  15662. else if (op & 16) { /* length base */
  15663. len = here & 0xffff/*here.val*/;
  15664. op &= 15; /* number of extra bits */
  15665. if (op) {
  15666. if (bits < op) {
  15667. hold += input[_in++] << bits;
  15668. bits += 8;
  15669. }
  15670. len += hold & ((1 << op) - 1);
  15671. hold >>>= op;
  15672. bits -= op;
  15673. }
  15674. //Tracevv((stderr, "inflate: length %u\n", len));
  15675. if (bits < 15) {
  15676. hold += input[_in++] << bits;
  15677. bits += 8;
  15678. hold += input[_in++] << bits;
  15679. bits += 8;
  15680. }
  15681. here = dcode[hold & dmask];
  15682. dodist:
  15683. for (;;) { // goto emulation
  15684. op = here >>> 24/*here.bits*/;
  15685. hold >>>= op;
  15686. bits -= op;
  15687. op = (here >>> 16) & 0xff/*here.op*/;
  15688. if (op & 16) { /* distance base */
  15689. dist = here & 0xffff/*here.val*/;
  15690. op &= 15; /* number of extra bits */
  15691. if (bits < op) {
  15692. hold += input[_in++] << bits;
  15693. bits += 8;
  15694. if (bits < op) {
  15695. hold += input[_in++] << bits;
  15696. bits += 8;
  15697. }
  15698. }
  15699. dist += hold & ((1 << op) - 1);
  15700. //#ifdef INFLATE_STRICT
  15701. if (dist > dmax) {
  15702. strm.msg = 'invalid distance too far back';
  15703. state.mode = BAD;
  15704. break top;
  15705. }
  15706. //#endif
  15707. hold >>>= op;
  15708. bits -= op;
  15709. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15710. op = _out - beg; /* max distance in output */
  15711. if (dist > op) { /* see if copy from window */
  15712. op = dist - op; /* distance back in window */
  15713. if (op > whave) {
  15714. if (state.sane) {
  15715. strm.msg = 'invalid distance too far back';
  15716. state.mode = BAD;
  15717. break top;
  15718. }
  15719. // (!) This block is disabled in zlib defailts,
  15720. // don't enable it for binary compatibility
  15721. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15722. // if (len <= op - whave) {
  15723. // do {
  15724. // output[_out++] = 0;
  15725. // } while (--len);
  15726. // continue top;
  15727. // }
  15728. // len -= op - whave;
  15729. // do {
  15730. // output[_out++] = 0;
  15731. // } while (--op > whave);
  15732. // if (op === 0) {
  15733. // from = _out - dist;
  15734. // do {
  15735. // output[_out++] = output[from++];
  15736. // } while (--len);
  15737. // continue top;
  15738. // }
  15739. //#endif
  15740. }
  15741. from = 0; // window index
  15742. from_source = s_window;
  15743. if (wnext === 0) { /* very common case */
  15744. from += wsize - op;
  15745. if (op < len) { /* some from window */
  15746. len -= op;
  15747. do {
  15748. output[_out++] = s_window[from++];
  15749. } while (--op);
  15750. from = _out - dist; /* rest from output */
  15751. from_source = output;
  15752. }
  15753. }
  15754. else if (wnext < op) { /* wrap around window */
  15755. from += wsize + wnext - op;
  15756. op -= wnext;
  15757. if (op < len) { /* some from end of window */
  15758. len -= op;
  15759. do {
  15760. output[_out++] = s_window[from++];
  15761. } while (--op);
  15762. from = 0;
  15763. if (wnext < len) { /* some from start of window */
  15764. op = wnext;
  15765. len -= op;
  15766. do {
  15767. output[_out++] = s_window[from++];
  15768. } while (--op);
  15769. from = _out - dist; /* rest from output */
  15770. from_source = output;
  15771. }
  15772. }
  15773. }
  15774. else { /* contiguous in window */
  15775. from += wnext - op;
  15776. if (op < len) { /* some from window */
  15777. len -= op;
  15778. do {
  15779. output[_out++] = s_window[from++];
  15780. } while (--op);
  15781. from = _out - dist; /* rest from output */
  15782. from_source = output;
  15783. }
  15784. }
  15785. while (len > 2) {
  15786. output[_out++] = from_source[from++];
  15787. output[_out++] = from_source[from++];
  15788. output[_out++] = from_source[from++];
  15789. len -= 3;
  15790. }
  15791. if (len) {
  15792. output[_out++] = from_source[from++];
  15793. if (len > 1) {
  15794. output[_out++] = from_source[from++];
  15795. }
  15796. }
  15797. }
  15798. else {
  15799. from = _out - dist; /* copy direct from output */
  15800. do { /* minimum length is three */
  15801. output[_out++] = output[from++];
  15802. output[_out++] = output[from++];
  15803. output[_out++] = output[from++];
  15804. len -= 3;
  15805. } while (len > 2);
  15806. if (len) {
  15807. output[_out++] = output[from++];
  15808. if (len > 1) {
  15809. output[_out++] = output[from++];
  15810. }
  15811. }
  15812. }
  15813. }
  15814. else if ((op & 64) === 0) { /* 2nd level distance code */
  15815. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15816. continue dodist;
  15817. }
  15818. else {
  15819. strm.msg = 'invalid distance code';
  15820. state.mode = BAD;
  15821. break top;
  15822. }
  15823. break; // need to emulate goto via "continue"
  15824. }
  15825. }
  15826. else if ((op & 64) === 0) { /* 2nd level length code */
  15827. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15828. continue dolen;
  15829. }
  15830. else if (op & 32) { /* end-of-block */
  15831. //Tracevv((stderr, "inflate: end of block\n"));
  15832. state.mode = TYPE;
  15833. break top;
  15834. }
  15835. else {
  15836. strm.msg = 'invalid literal/length code';
  15837. state.mode = BAD;
  15838. break top;
  15839. }
  15840. break; // need to emulate goto via "continue"
  15841. }
  15842. } while (_in < last && _out < end);
  15843. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15844. len = bits >> 3;
  15845. _in -= len;
  15846. bits -= len << 3;
  15847. hold &= (1 << bits) - 1;
  15848. /* update state and return */
  15849. strm.next_in = _in;
  15850. strm.next_out = _out;
  15851. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15852. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15853. state.hold = hold;
  15854. state.bits = bits;
  15855. return;
  15856. };
  15857. },{}],60:[function(require,module,exports){
  15858. 'use strict';
  15859. var utils = require('../utils/common');
  15860. var adler32 = require('./adler32');
  15861. var crc32 = require('./crc32');
  15862. var inflate_fast = require('./inffast');
  15863. var inflate_table = require('./inftrees');
  15864. var CODES = 0;
  15865. var LENS = 1;
  15866. var DISTS = 2;
  15867. /* Public constants ==========================================================*/
  15868. /* ===========================================================================*/
  15869. /* Allowed flush values; see deflate() and inflate() below for details */
  15870. //var Z_NO_FLUSH = 0;
  15871. //var Z_PARTIAL_FLUSH = 1;
  15872. //var Z_SYNC_FLUSH = 2;
  15873. //var Z_FULL_FLUSH = 3;
  15874. var Z_FINISH = 4;
  15875. var Z_BLOCK = 5;
  15876. var Z_TREES = 6;
  15877. /* Return codes for the compression/decompression functions. Negative values
  15878. * are errors, positive values are used for special but normal events.
  15879. */
  15880. var Z_OK = 0;
  15881. var Z_STREAM_END = 1;
  15882. var Z_NEED_DICT = 2;
  15883. //var Z_ERRNO = -1;
  15884. var Z_STREAM_ERROR = -2;
  15885. var Z_DATA_ERROR = -3;
  15886. var Z_MEM_ERROR = -4;
  15887. var Z_BUF_ERROR = -5;
  15888. //var Z_VERSION_ERROR = -6;
  15889. /* The deflate compression method */
  15890. var Z_DEFLATED = 8;
  15891. /* STATES ====================================================================*/
  15892. /* ===========================================================================*/
  15893. var HEAD = 1; /* i: waiting for magic header */
  15894. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15895. var TIME = 3; /* i: waiting for modification time (gzip) */
  15896. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15897. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15898. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15899. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15900. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15901. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15902. var DICTID = 10; /* i: waiting for dictionary check value */
  15903. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15904. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15905. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15906. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15907. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15908. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15909. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15910. var LENLENS = 18; /* i: waiting for code length code lengths */
  15911. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15912. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15913. var LEN = 21; /* i: waiting for length/lit/eob code */
  15914. var LENEXT = 22; /* i: waiting for length extra bits */
  15915. var DIST = 23; /* i: waiting for distance code */
  15916. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15917. var MATCH = 25; /* o: waiting for output space to copy string */
  15918. var LIT = 26; /* o: waiting for output space to write literal */
  15919. var CHECK = 27; /* i: waiting for 32-bit check value */
  15920. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15921. var DONE = 29; /* finished check, done -- remain here until reset */
  15922. var BAD = 30; /* got a data error -- remain here until reset */
  15923. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15924. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15925. /* ===========================================================================*/
  15926. var ENOUGH_LENS = 852;
  15927. var ENOUGH_DISTS = 592;
  15928. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15929. var MAX_WBITS = 15;
  15930. /* 32K LZ77 window */
  15931. var DEF_WBITS = MAX_WBITS;
  15932. function ZSWAP32(q) {
  15933. return (((q >>> 24) & 0xff) +
  15934. ((q >>> 8) & 0xff00) +
  15935. ((q & 0xff00) << 8) +
  15936. ((q & 0xff) << 24));
  15937. }
  15938. function InflateState() {
  15939. this.mode = 0; /* current inflate mode */
  15940. this.last = false; /* true if processing last block */
  15941. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15942. this.havedict = false; /* true if dictionary provided */
  15943. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15944. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15945. this.check = 0; /* protected copy of check value */
  15946. this.total = 0; /* protected copy of output count */
  15947. // TODO: may be {}
  15948. this.head = null; /* where to save gzip header information */
  15949. /* sliding window */
  15950. this.wbits = 0; /* log base 2 of requested window size */
  15951. this.wsize = 0; /* window size or zero if not using window */
  15952. this.whave = 0; /* valid bytes in the window */
  15953. this.wnext = 0; /* window write index */
  15954. this.window = null; /* allocated sliding window, if needed */
  15955. /* bit accumulator */
  15956. this.hold = 0; /* input bit accumulator */
  15957. this.bits = 0; /* number of bits in "in" */
  15958. /* for string and stored block copying */
  15959. this.length = 0; /* literal or length of data to copy */
  15960. this.offset = 0; /* distance back to copy string from */
  15961. /* for table and code decoding */
  15962. this.extra = 0; /* extra bits needed */
  15963. /* fixed and dynamic code tables */
  15964. this.lencode = null; /* starting table for length/literal codes */
  15965. this.distcode = null; /* starting table for distance codes */
  15966. this.lenbits = 0; /* index bits for lencode */
  15967. this.distbits = 0; /* index bits for distcode */
  15968. /* dynamic table building */
  15969. this.ncode = 0; /* number of code length code lengths */
  15970. this.nlen = 0; /* number of length code lengths */
  15971. this.ndist = 0; /* number of distance code lengths */
  15972. this.have = 0; /* number of code lengths in lens[] */
  15973. this.next = null; /* next available space in codes[] */
  15974. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15975. this.work = new utils.Buf16(288); /* work area for code table building */
  15976. /*
  15977. because we don't have pointers in js, we use lencode and distcode directly
  15978. as buffers so we don't need codes
  15979. */
  15980. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15981. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15982. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15983. this.sane = 0; /* if false, allow invalid distance too far */
  15984. this.back = 0; /* bits back of last unprocessed length/lit */
  15985. this.was = 0; /* initial length of match */
  15986. }
  15987. function inflateResetKeep(strm) {
  15988. var state;
  15989. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15990. state = strm.state;
  15991. strm.total_in = strm.total_out = state.total = 0;
  15992. strm.msg = ''; /*Z_NULL*/
  15993. if (state.wrap) { /* to support ill-conceived Java test suite */
  15994. strm.adler = state.wrap & 1;
  15995. }
  15996. state.mode = HEAD;
  15997. state.last = 0;
  15998. state.havedict = 0;
  15999. state.dmax = 32768;
  16000. state.head = null/*Z_NULL*/;
  16001. state.hold = 0;
  16002. state.bits = 0;
  16003. //state.lencode = state.distcode = state.next = state.codes;
  16004. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  16005. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  16006. state.sane = 1;
  16007. state.back = -1;
  16008. //Tracev((stderr, "inflate: reset\n"));
  16009. return Z_OK;
  16010. }
  16011. function inflateReset(strm) {
  16012. var state;
  16013. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16014. state = strm.state;
  16015. state.wsize = 0;
  16016. state.whave = 0;
  16017. state.wnext = 0;
  16018. return inflateResetKeep(strm);
  16019. }
  16020. function inflateReset2(strm, windowBits) {
  16021. var wrap;
  16022. var state;
  16023. /* get the state */
  16024. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16025. state = strm.state;
  16026. /* extract wrap request from windowBits parameter */
  16027. if (windowBits < 0) {
  16028. wrap = 0;
  16029. windowBits = -windowBits;
  16030. }
  16031. else {
  16032. wrap = (windowBits >> 4) + 1;
  16033. if (windowBits < 48) {
  16034. windowBits &= 15;
  16035. }
  16036. }
  16037. /* set number of window bits, free window if different */
  16038. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  16039. return Z_STREAM_ERROR;
  16040. }
  16041. if (state.window !== null && state.wbits !== windowBits) {
  16042. state.window = null;
  16043. }
  16044. /* update state and reset the rest of it */
  16045. state.wrap = wrap;
  16046. state.wbits = windowBits;
  16047. return inflateReset(strm);
  16048. }
  16049. function inflateInit2(strm, windowBits) {
  16050. var ret;
  16051. var state;
  16052. if (!strm) { return Z_STREAM_ERROR; }
  16053. //strm.msg = Z_NULL; /* in case we return an error */
  16054. state = new InflateState();
  16055. //if (state === Z_NULL) return Z_MEM_ERROR;
  16056. //Tracev((stderr, "inflate: allocated\n"));
  16057. strm.state = state;
  16058. state.window = null/*Z_NULL*/;
  16059. ret = inflateReset2(strm, windowBits);
  16060. if (ret !== Z_OK) {
  16061. strm.state = null/*Z_NULL*/;
  16062. }
  16063. return ret;
  16064. }
  16065. function inflateInit(strm) {
  16066. return inflateInit2(strm, DEF_WBITS);
  16067. }
  16068. /*
  16069. Return state with length and distance decoding tables and index sizes set to
  16070. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  16071. If BUILDFIXED is defined, then instead this routine builds the tables the
  16072. first time it's called, and returns those tables the first time and
  16073. thereafter. This reduces the size of the code by about 2K bytes, in
  16074. exchange for a little execution time. However, BUILDFIXED should not be
  16075. used for threaded applications, since the rewriting of the tables and virgin
  16076. may not be thread-safe.
  16077. */
  16078. var virgin = true;
  16079. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  16080. function fixedtables(state) {
  16081. /* build fixed huffman tables if first call (may not be thread safe) */
  16082. if (virgin) {
  16083. var sym;
  16084. lenfix = new utils.Buf32(512);
  16085. distfix = new utils.Buf32(32);
  16086. /* literal/length table */
  16087. sym = 0;
  16088. while (sym < 144) { state.lens[sym++] = 8; }
  16089. while (sym < 256) { state.lens[sym++] = 9; }
  16090. while (sym < 280) { state.lens[sym++] = 7; }
  16091. while (sym < 288) { state.lens[sym++] = 8; }
  16092. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  16093. /* distance table */
  16094. sym = 0;
  16095. while (sym < 32) { state.lens[sym++] = 5; }
  16096. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  16097. /* do this just once */
  16098. virgin = false;
  16099. }
  16100. state.lencode = lenfix;
  16101. state.lenbits = 9;
  16102. state.distcode = distfix;
  16103. state.distbits = 5;
  16104. }
  16105. /*
  16106. Update the window with the last wsize (normally 32K) bytes written before
  16107. returning. If window does not exist yet, create it. This is only called
  16108. when a window is already in use, or when output has been written during this
  16109. inflate call, but the end of the deflate stream has not been reached yet.
  16110. It is also called to create a window for dictionary data when a dictionary
  16111. is loaded.
  16112. Providing output buffers larger than 32K to inflate() should provide a speed
  16113. advantage, since only the last 32K of output is copied to the sliding window
  16114. upon return from inflate(), and since all distances after the first 32K of
  16115. output will fall in the output data, making match copies simpler and faster.
  16116. The advantage may be dependent on the size of the processor's data caches.
  16117. */
  16118. function updatewindow(strm, src, end, copy) {
  16119. var dist;
  16120. var state = strm.state;
  16121. /* if it hasn't been done already, allocate space for the window */
  16122. if (state.window === null) {
  16123. state.wsize = 1 << state.wbits;
  16124. state.wnext = 0;
  16125. state.whave = 0;
  16126. state.window = new utils.Buf8(state.wsize);
  16127. }
  16128. /* copy state->wsize or less output bytes into the circular window */
  16129. if (copy >= state.wsize) {
  16130. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  16131. state.wnext = 0;
  16132. state.whave = state.wsize;
  16133. }
  16134. else {
  16135. dist = state.wsize - state.wnext;
  16136. if (dist > copy) {
  16137. dist = copy;
  16138. }
  16139. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16140. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  16141. copy -= dist;
  16142. if (copy) {
  16143. //zmemcpy(state->window, end - copy, copy);
  16144. utils.arraySet(state.window,src, end - copy, copy, 0);
  16145. state.wnext = copy;
  16146. state.whave = state.wsize;
  16147. }
  16148. else {
  16149. state.wnext += dist;
  16150. if (state.wnext === state.wsize) { state.wnext = 0; }
  16151. if (state.whave < state.wsize) { state.whave += dist; }
  16152. }
  16153. }
  16154. return 0;
  16155. }
  16156. function inflate(strm, flush) {
  16157. var state;
  16158. var input, output; // input/output buffers
  16159. var next; /* next input INDEX */
  16160. var put; /* next output INDEX */
  16161. var have, left; /* available input and output */
  16162. var hold; /* bit buffer */
  16163. var bits; /* bits in bit buffer */
  16164. var _in, _out; /* save starting available input and output */
  16165. var copy; /* number of stored or match bytes to copy */
  16166. var from; /* where to copy match bytes from */
  16167. var from_source;
  16168. var here = 0; /* current decoding table entry */
  16169. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16170. //var last; /* parent table entry */
  16171. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16172. var len; /* length to copy for repeats, bits to drop */
  16173. var ret; /* return code */
  16174. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16175. var opts;
  16176. var n; // temporary var for NEED_BITS
  16177. var order = /* permutation of code lengths */
  16178. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16179. if (!strm || !strm.state || !strm.output ||
  16180. (!strm.input && strm.avail_in !== 0)) {
  16181. return Z_STREAM_ERROR;
  16182. }
  16183. state = strm.state;
  16184. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16185. //--- LOAD() ---
  16186. put = strm.next_out;
  16187. output = strm.output;
  16188. left = strm.avail_out;
  16189. next = strm.next_in;
  16190. input = strm.input;
  16191. have = strm.avail_in;
  16192. hold = state.hold;
  16193. bits = state.bits;
  16194. //---
  16195. _in = have;
  16196. _out = left;
  16197. ret = Z_OK;
  16198. inf_leave: // goto emulation
  16199. for (;;) {
  16200. switch (state.mode) {
  16201. case HEAD:
  16202. if (state.wrap === 0) {
  16203. state.mode = TYPEDO;
  16204. break;
  16205. }
  16206. //=== NEEDBITS(16);
  16207. while (bits < 16) {
  16208. if (have === 0) { break inf_leave; }
  16209. have--;
  16210. hold += input[next++] << bits;
  16211. bits += 8;
  16212. }
  16213. //===//
  16214. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16215. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16216. //=== CRC2(state.check, hold);
  16217. hbuf[0] = hold & 0xff;
  16218. hbuf[1] = (hold >>> 8) & 0xff;
  16219. state.check = crc32(state.check, hbuf, 2, 0);
  16220. //===//
  16221. //=== INITBITS();
  16222. hold = 0;
  16223. bits = 0;
  16224. //===//
  16225. state.mode = FLAGS;
  16226. break;
  16227. }
  16228. state.flags = 0; /* expect zlib header */
  16229. if (state.head) {
  16230. state.head.done = false;
  16231. }
  16232. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16233. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16234. strm.msg = 'incorrect header check';
  16235. state.mode = BAD;
  16236. break;
  16237. }
  16238. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16239. strm.msg = 'unknown compression method';
  16240. state.mode = BAD;
  16241. break;
  16242. }
  16243. //--- DROPBITS(4) ---//
  16244. hold >>>= 4;
  16245. bits -= 4;
  16246. //---//
  16247. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16248. if (state.wbits === 0) {
  16249. state.wbits = len;
  16250. }
  16251. else if (len > state.wbits) {
  16252. strm.msg = 'invalid window size';
  16253. state.mode = BAD;
  16254. break;
  16255. }
  16256. state.dmax = 1 << len;
  16257. //Tracev((stderr, "inflate: zlib header ok\n"));
  16258. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16259. state.mode = hold & 0x200 ? DICTID : TYPE;
  16260. //=== INITBITS();
  16261. hold = 0;
  16262. bits = 0;
  16263. //===//
  16264. break;
  16265. case FLAGS:
  16266. //=== NEEDBITS(16); */
  16267. while (bits < 16) {
  16268. if (have === 0) { break inf_leave; }
  16269. have--;
  16270. hold += input[next++] << bits;
  16271. bits += 8;
  16272. }
  16273. //===//
  16274. state.flags = hold;
  16275. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16276. strm.msg = 'unknown compression method';
  16277. state.mode = BAD;
  16278. break;
  16279. }
  16280. if (state.flags & 0xe000) {
  16281. strm.msg = 'unknown header flags set';
  16282. state.mode = BAD;
  16283. break;
  16284. }
  16285. if (state.head) {
  16286. state.head.text = ((hold >> 8) & 1);
  16287. }
  16288. if (state.flags & 0x0200) {
  16289. //=== CRC2(state.check, hold);
  16290. hbuf[0] = hold & 0xff;
  16291. hbuf[1] = (hold >>> 8) & 0xff;
  16292. state.check = crc32(state.check, hbuf, 2, 0);
  16293. //===//
  16294. }
  16295. //=== INITBITS();
  16296. hold = 0;
  16297. bits = 0;
  16298. //===//
  16299. state.mode = TIME;
  16300. /* falls through */
  16301. case TIME:
  16302. //=== NEEDBITS(32); */
  16303. while (bits < 32) {
  16304. if (have === 0) { break inf_leave; }
  16305. have--;
  16306. hold += input[next++] << bits;
  16307. bits += 8;
  16308. }
  16309. //===//
  16310. if (state.head) {
  16311. state.head.time = hold;
  16312. }
  16313. if (state.flags & 0x0200) {
  16314. //=== CRC4(state.check, hold)
  16315. hbuf[0] = hold & 0xff;
  16316. hbuf[1] = (hold >>> 8) & 0xff;
  16317. hbuf[2] = (hold >>> 16) & 0xff;
  16318. hbuf[3] = (hold >>> 24) & 0xff;
  16319. state.check = crc32(state.check, hbuf, 4, 0);
  16320. //===
  16321. }
  16322. //=== INITBITS();
  16323. hold = 0;
  16324. bits = 0;
  16325. //===//
  16326. state.mode = OS;
  16327. /* falls through */
  16328. case OS:
  16329. //=== NEEDBITS(16); */
  16330. while (bits < 16) {
  16331. if (have === 0) { break inf_leave; }
  16332. have--;
  16333. hold += input[next++] << bits;
  16334. bits += 8;
  16335. }
  16336. //===//
  16337. if (state.head) {
  16338. state.head.xflags = (hold & 0xff);
  16339. state.head.os = (hold >> 8);
  16340. }
  16341. if (state.flags & 0x0200) {
  16342. //=== CRC2(state.check, hold);
  16343. hbuf[0] = hold & 0xff;
  16344. hbuf[1] = (hold >>> 8) & 0xff;
  16345. state.check = crc32(state.check, hbuf, 2, 0);
  16346. //===//
  16347. }
  16348. //=== INITBITS();
  16349. hold = 0;
  16350. bits = 0;
  16351. //===//
  16352. state.mode = EXLEN;
  16353. /* falls through */
  16354. case EXLEN:
  16355. if (state.flags & 0x0400) {
  16356. //=== NEEDBITS(16); */
  16357. while (bits < 16) {
  16358. if (have === 0) { break inf_leave; }
  16359. have--;
  16360. hold += input[next++] << bits;
  16361. bits += 8;
  16362. }
  16363. //===//
  16364. state.length = hold;
  16365. if (state.head) {
  16366. state.head.extra_len = hold;
  16367. }
  16368. if (state.flags & 0x0200) {
  16369. //=== CRC2(state.check, hold);
  16370. hbuf[0] = hold & 0xff;
  16371. hbuf[1] = (hold >>> 8) & 0xff;
  16372. state.check = crc32(state.check, hbuf, 2, 0);
  16373. //===//
  16374. }
  16375. //=== INITBITS();
  16376. hold = 0;
  16377. bits = 0;
  16378. //===//
  16379. }
  16380. else if (state.head) {
  16381. state.head.extra = null/*Z_NULL*/;
  16382. }
  16383. state.mode = EXTRA;
  16384. /* falls through */
  16385. case EXTRA:
  16386. if (state.flags & 0x0400) {
  16387. copy = state.length;
  16388. if (copy > have) { copy = have; }
  16389. if (copy) {
  16390. if (state.head) {
  16391. len = state.head.extra_len - state.length;
  16392. if (!state.head.extra) {
  16393. // Use untyped array for more conveniend processing later
  16394. state.head.extra = new Array(state.head.extra_len);
  16395. }
  16396. utils.arraySet(
  16397. state.head.extra,
  16398. input,
  16399. next,
  16400. // extra field is limited to 65536 bytes
  16401. // - no need for additional size check
  16402. copy,
  16403. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16404. len
  16405. );
  16406. //zmemcpy(state.head.extra + len, next,
  16407. // len + copy > state.head.extra_max ?
  16408. // state.head.extra_max - len : copy);
  16409. }
  16410. if (state.flags & 0x0200) {
  16411. state.check = crc32(state.check, input, copy, next);
  16412. }
  16413. have -= copy;
  16414. next += copy;
  16415. state.length -= copy;
  16416. }
  16417. if (state.length) { break inf_leave; }
  16418. }
  16419. state.length = 0;
  16420. state.mode = NAME;
  16421. /* falls through */
  16422. case NAME:
  16423. if (state.flags & 0x0800) {
  16424. if (have === 0) { break inf_leave; }
  16425. copy = 0;
  16426. do {
  16427. // TODO: 2 or 1 bytes?
  16428. len = input[next + copy++];
  16429. /* use constant limit because in js we should not preallocate memory */
  16430. if (state.head && len &&
  16431. (state.length < 65536 /*state.head.name_max*/)) {
  16432. state.head.name += String.fromCharCode(len);
  16433. }
  16434. } while (len && copy < have);
  16435. if (state.flags & 0x0200) {
  16436. state.check = crc32(state.check, input, copy, next);
  16437. }
  16438. have -= copy;
  16439. next += copy;
  16440. if (len) { break inf_leave; }
  16441. }
  16442. else if (state.head) {
  16443. state.head.name = null;
  16444. }
  16445. state.length = 0;
  16446. state.mode = COMMENT;
  16447. /* falls through */
  16448. case COMMENT:
  16449. if (state.flags & 0x1000) {
  16450. if (have === 0) { break inf_leave; }
  16451. copy = 0;
  16452. do {
  16453. len = input[next + copy++];
  16454. /* use constant limit because in js we should not preallocate memory */
  16455. if (state.head && len &&
  16456. (state.length < 65536 /*state.head.comm_max*/)) {
  16457. state.head.comment += String.fromCharCode(len);
  16458. }
  16459. } while (len && copy < have);
  16460. if (state.flags & 0x0200) {
  16461. state.check = crc32(state.check, input, copy, next);
  16462. }
  16463. have -= copy;
  16464. next += copy;
  16465. if (len) { break inf_leave; }
  16466. }
  16467. else if (state.head) {
  16468. state.head.comment = null;
  16469. }
  16470. state.mode = HCRC;
  16471. /* falls through */
  16472. case HCRC:
  16473. if (state.flags & 0x0200) {
  16474. //=== NEEDBITS(16); */
  16475. while (bits < 16) {
  16476. if (have === 0) { break inf_leave; }
  16477. have--;
  16478. hold += input[next++] << bits;
  16479. bits += 8;
  16480. }
  16481. //===//
  16482. if (hold !== (state.check & 0xffff)) {
  16483. strm.msg = 'header crc mismatch';
  16484. state.mode = BAD;
  16485. break;
  16486. }
  16487. //=== INITBITS();
  16488. hold = 0;
  16489. bits = 0;
  16490. //===//
  16491. }
  16492. if (state.head) {
  16493. state.head.hcrc = ((state.flags >> 9) & 1);
  16494. state.head.done = true;
  16495. }
  16496. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16497. state.mode = TYPE;
  16498. break;
  16499. case DICTID:
  16500. //=== NEEDBITS(32); */
  16501. while (bits < 32) {
  16502. if (have === 0) { break inf_leave; }
  16503. have--;
  16504. hold += input[next++] << bits;
  16505. bits += 8;
  16506. }
  16507. //===//
  16508. strm.adler = state.check = ZSWAP32(hold);
  16509. //=== INITBITS();
  16510. hold = 0;
  16511. bits = 0;
  16512. //===//
  16513. state.mode = DICT;
  16514. /* falls through */
  16515. case DICT:
  16516. if (state.havedict === 0) {
  16517. //--- RESTORE() ---
  16518. strm.next_out = put;
  16519. strm.avail_out = left;
  16520. strm.next_in = next;
  16521. strm.avail_in = have;
  16522. state.hold = hold;
  16523. state.bits = bits;
  16524. //---
  16525. return Z_NEED_DICT;
  16526. }
  16527. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16528. state.mode = TYPE;
  16529. /* falls through */
  16530. case TYPE:
  16531. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16532. /* falls through */
  16533. case TYPEDO:
  16534. if (state.last) {
  16535. //--- BYTEBITS() ---//
  16536. hold >>>= bits & 7;
  16537. bits -= bits & 7;
  16538. //---//
  16539. state.mode = CHECK;
  16540. break;
  16541. }
  16542. //=== NEEDBITS(3); */
  16543. while (bits < 3) {
  16544. if (have === 0) { break inf_leave; }
  16545. have--;
  16546. hold += input[next++] << bits;
  16547. bits += 8;
  16548. }
  16549. //===//
  16550. state.last = (hold & 0x01)/*BITS(1)*/;
  16551. //--- DROPBITS(1) ---//
  16552. hold >>>= 1;
  16553. bits -= 1;
  16554. //---//
  16555. switch ((hold & 0x03)/*BITS(2)*/) {
  16556. case 0: /* stored block */
  16557. //Tracev((stderr, "inflate: stored block%s\n",
  16558. // state.last ? " (last)" : ""));
  16559. state.mode = STORED;
  16560. break;
  16561. case 1: /* fixed block */
  16562. fixedtables(state);
  16563. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16564. // state.last ? " (last)" : ""));
  16565. state.mode = LEN_; /* decode codes */
  16566. if (flush === Z_TREES) {
  16567. //--- DROPBITS(2) ---//
  16568. hold >>>= 2;
  16569. bits -= 2;
  16570. //---//
  16571. break inf_leave;
  16572. }
  16573. break;
  16574. case 2: /* dynamic block */
  16575. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16576. // state.last ? " (last)" : ""));
  16577. state.mode = TABLE;
  16578. break;
  16579. case 3:
  16580. strm.msg = 'invalid block type';
  16581. state.mode = BAD;
  16582. }
  16583. //--- DROPBITS(2) ---//
  16584. hold >>>= 2;
  16585. bits -= 2;
  16586. //---//
  16587. break;
  16588. case STORED:
  16589. //--- BYTEBITS() ---// /* go to byte boundary */
  16590. hold >>>= bits & 7;
  16591. bits -= bits & 7;
  16592. //---//
  16593. //=== NEEDBITS(32); */
  16594. while (bits < 32) {
  16595. if (have === 0) { break inf_leave; }
  16596. have--;
  16597. hold += input[next++] << bits;
  16598. bits += 8;
  16599. }
  16600. //===//
  16601. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16602. strm.msg = 'invalid stored block lengths';
  16603. state.mode = BAD;
  16604. break;
  16605. }
  16606. state.length = hold & 0xffff;
  16607. //Tracev((stderr, "inflate: stored length %u\n",
  16608. // state.length));
  16609. //=== INITBITS();
  16610. hold = 0;
  16611. bits = 0;
  16612. //===//
  16613. state.mode = COPY_;
  16614. if (flush === Z_TREES) { break inf_leave; }
  16615. /* falls through */
  16616. case COPY_:
  16617. state.mode = COPY;
  16618. /* falls through */
  16619. case COPY:
  16620. copy = state.length;
  16621. if (copy) {
  16622. if (copy > have) { copy = have; }
  16623. if (copy > left) { copy = left; }
  16624. if (copy === 0) { break inf_leave; }
  16625. //--- zmemcpy(put, next, copy); ---
  16626. utils.arraySet(output, input, next, copy, put);
  16627. //---//
  16628. have -= copy;
  16629. next += copy;
  16630. left -= copy;
  16631. put += copy;
  16632. state.length -= copy;
  16633. break;
  16634. }
  16635. //Tracev((stderr, "inflate: stored end\n"));
  16636. state.mode = TYPE;
  16637. break;
  16638. case TABLE:
  16639. //=== NEEDBITS(14); */
  16640. while (bits < 14) {
  16641. if (have === 0) { break inf_leave; }
  16642. have--;
  16643. hold += input[next++] << bits;
  16644. bits += 8;
  16645. }
  16646. //===//
  16647. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16648. //--- DROPBITS(5) ---//
  16649. hold >>>= 5;
  16650. bits -= 5;
  16651. //---//
  16652. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16653. //--- DROPBITS(5) ---//
  16654. hold >>>= 5;
  16655. bits -= 5;
  16656. //---//
  16657. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16658. //--- DROPBITS(4) ---//
  16659. hold >>>= 4;
  16660. bits -= 4;
  16661. //---//
  16662. //#ifndef PKZIP_BUG_WORKAROUND
  16663. if (state.nlen > 286 || state.ndist > 30) {
  16664. strm.msg = 'too many length or distance symbols';
  16665. state.mode = BAD;
  16666. break;
  16667. }
  16668. //#endif
  16669. //Tracev((stderr, "inflate: table sizes ok\n"));
  16670. state.have = 0;
  16671. state.mode = LENLENS;
  16672. /* falls through */
  16673. case LENLENS:
  16674. while (state.have < state.ncode) {
  16675. //=== NEEDBITS(3);
  16676. while (bits < 3) {
  16677. if (have === 0) { break inf_leave; }
  16678. have--;
  16679. hold += input[next++] << bits;
  16680. bits += 8;
  16681. }
  16682. //===//
  16683. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16684. //--- DROPBITS(3) ---//
  16685. hold >>>= 3;
  16686. bits -= 3;
  16687. //---//
  16688. }
  16689. while (state.have < 19) {
  16690. state.lens[order[state.have++]] = 0;
  16691. }
  16692. // We have separate tables & no pointers. 2 commented lines below not needed.
  16693. //state.next = state.codes;
  16694. //state.lencode = state.next;
  16695. // Switch to use dynamic table
  16696. state.lencode = state.lendyn;
  16697. state.lenbits = 7;
  16698. opts = {bits: state.lenbits};
  16699. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16700. state.lenbits = opts.bits;
  16701. if (ret) {
  16702. strm.msg = 'invalid code lengths set';
  16703. state.mode = BAD;
  16704. break;
  16705. }
  16706. //Tracev((stderr, "inflate: code lengths ok\n"));
  16707. state.have = 0;
  16708. state.mode = CODELENS;
  16709. /* falls through */
  16710. case CODELENS:
  16711. while (state.have < state.nlen + state.ndist) {
  16712. for (;;) {
  16713. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16714. here_bits = here >>> 24;
  16715. here_op = (here >>> 16) & 0xff;
  16716. here_val = here & 0xffff;
  16717. if ((here_bits) <= bits) { break; }
  16718. //--- PULLBYTE() ---//
  16719. if (have === 0) { break inf_leave; }
  16720. have--;
  16721. hold += input[next++] << bits;
  16722. bits += 8;
  16723. //---//
  16724. }
  16725. if (here_val < 16) {
  16726. //--- DROPBITS(here.bits) ---//
  16727. hold >>>= here_bits;
  16728. bits -= here_bits;
  16729. //---//
  16730. state.lens[state.have++] = here_val;
  16731. }
  16732. else {
  16733. if (here_val === 16) {
  16734. //=== NEEDBITS(here.bits + 2);
  16735. n = here_bits + 2;
  16736. while (bits < n) {
  16737. if (have === 0) { break inf_leave; }
  16738. have--;
  16739. hold += input[next++] << bits;
  16740. bits += 8;
  16741. }
  16742. //===//
  16743. //--- DROPBITS(here.bits) ---//
  16744. hold >>>= here_bits;
  16745. bits -= here_bits;
  16746. //---//
  16747. if (state.have === 0) {
  16748. strm.msg = 'invalid bit length repeat';
  16749. state.mode = BAD;
  16750. break;
  16751. }
  16752. len = state.lens[state.have - 1];
  16753. copy = 3 + (hold & 0x03);//BITS(2);
  16754. //--- DROPBITS(2) ---//
  16755. hold >>>= 2;
  16756. bits -= 2;
  16757. //---//
  16758. }
  16759. else if (here_val === 17) {
  16760. //=== NEEDBITS(here.bits + 3);
  16761. n = here_bits + 3;
  16762. while (bits < n) {
  16763. if (have === 0) { break inf_leave; }
  16764. have--;
  16765. hold += input[next++] << bits;
  16766. bits += 8;
  16767. }
  16768. //===//
  16769. //--- DROPBITS(here.bits) ---//
  16770. hold >>>= here_bits;
  16771. bits -= here_bits;
  16772. //---//
  16773. len = 0;
  16774. copy = 3 + (hold & 0x07);//BITS(3);
  16775. //--- DROPBITS(3) ---//
  16776. hold >>>= 3;
  16777. bits -= 3;
  16778. //---//
  16779. }
  16780. else {
  16781. //=== NEEDBITS(here.bits + 7);
  16782. n = here_bits + 7;
  16783. while (bits < n) {
  16784. if (have === 0) { break inf_leave; }
  16785. have--;
  16786. hold += input[next++] << bits;
  16787. bits += 8;
  16788. }
  16789. //===//
  16790. //--- DROPBITS(here.bits) ---//
  16791. hold >>>= here_bits;
  16792. bits -= here_bits;
  16793. //---//
  16794. len = 0;
  16795. copy = 11 + (hold & 0x7f);//BITS(7);
  16796. //--- DROPBITS(7) ---//
  16797. hold >>>= 7;
  16798. bits -= 7;
  16799. //---//
  16800. }
  16801. if (state.have + copy > state.nlen + state.ndist) {
  16802. strm.msg = 'invalid bit length repeat';
  16803. state.mode = BAD;
  16804. break;
  16805. }
  16806. while (copy--) {
  16807. state.lens[state.have++] = len;
  16808. }
  16809. }
  16810. }
  16811. /* handle error breaks in while */
  16812. if (state.mode === BAD) { break; }
  16813. /* check for end-of-block code (better have one) */
  16814. if (state.lens[256] === 0) {
  16815. strm.msg = 'invalid code -- missing end-of-block';
  16816. state.mode = BAD;
  16817. break;
  16818. }
  16819. /* build code tables -- note: do not change the lenbits or distbits
  16820. values here (9 and 6) without reading the comments in inftrees.h
  16821. concerning the ENOUGH constants, which depend on those values */
  16822. state.lenbits = 9;
  16823. opts = {bits: state.lenbits};
  16824. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16825. // We have separate tables & no pointers. 2 commented lines below not needed.
  16826. // state.next_index = opts.table_index;
  16827. state.lenbits = opts.bits;
  16828. // state.lencode = state.next;
  16829. if (ret) {
  16830. strm.msg = 'invalid literal/lengths set';
  16831. state.mode = BAD;
  16832. break;
  16833. }
  16834. state.distbits = 6;
  16835. //state.distcode.copy(state.codes);
  16836. // Switch to use dynamic table
  16837. state.distcode = state.distdyn;
  16838. opts = {bits: state.distbits};
  16839. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16840. // We have separate tables & no pointers. 2 commented lines below not needed.
  16841. // state.next_index = opts.table_index;
  16842. state.distbits = opts.bits;
  16843. // state.distcode = state.next;
  16844. if (ret) {
  16845. strm.msg = 'invalid distances set';
  16846. state.mode = BAD;
  16847. break;
  16848. }
  16849. //Tracev((stderr, 'inflate: codes ok\n'));
  16850. state.mode = LEN_;
  16851. if (flush === Z_TREES) { break inf_leave; }
  16852. /* falls through */
  16853. case LEN_:
  16854. state.mode = LEN;
  16855. /* falls through */
  16856. case LEN:
  16857. if (have >= 6 && left >= 258) {
  16858. //--- RESTORE() ---
  16859. strm.next_out = put;
  16860. strm.avail_out = left;
  16861. strm.next_in = next;
  16862. strm.avail_in = have;
  16863. state.hold = hold;
  16864. state.bits = bits;
  16865. //---
  16866. inflate_fast(strm, _out);
  16867. //--- LOAD() ---
  16868. put = strm.next_out;
  16869. output = strm.output;
  16870. left = strm.avail_out;
  16871. next = strm.next_in;
  16872. input = strm.input;
  16873. have = strm.avail_in;
  16874. hold = state.hold;
  16875. bits = state.bits;
  16876. //---
  16877. if (state.mode === TYPE) {
  16878. state.back = -1;
  16879. }
  16880. break;
  16881. }
  16882. state.back = 0;
  16883. for (;;) {
  16884. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16885. here_bits = here >>> 24;
  16886. here_op = (here >>> 16) & 0xff;
  16887. here_val = here & 0xffff;
  16888. if (here_bits <= bits) { break; }
  16889. //--- PULLBYTE() ---//
  16890. if (have === 0) { break inf_leave; }
  16891. have--;
  16892. hold += input[next++] << bits;
  16893. bits += 8;
  16894. //---//
  16895. }
  16896. if (here_op && (here_op & 0xf0) === 0) {
  16897. last_bits = here_bits;
  16898. last_op = here_op;
  16899. last_val = here_val;
  16900. for (;;) {
  16901. here = state.lencode[last_val +
  16902. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16903. here_bits = here >>> 24;
  16904. here_op = (here >>> 16) & 0xff;
  16905. here_val = here & 0xffff;
  16906. if ((last_bits + here_bits) <= bits) { break; }
  16907. //--- PULLBYTE() ---//
  16908. if (have === 0) { break inf_leave; }
  16909. have--;
  16910. hold += input[next++] << bits;
  16911. bits += 8;
  16912. //---//
  16913. }
  16914. //--- DROPBITS(last.bits) ---//
  16915. hold >>>= last_bits;
  16916. bits -= last_bits;
  16917. //---//
  16918. state.back += last_bits;
  16919. }
  16920. //--- DROPBITS(here.bits) ---//
  16921. hold >>>= here_bits;
  16922. bits -= here_bits;
  16923. //---//
  16924. state.back += here_bits;
  16925. state.length = here_val;
  16926. if (here_op === 0) {
  16927. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16928. // "inflate: literal '%c'\n" :
  16929. // "inflate: literal 0x%02x\n", here.val));
  16930. state.mode = LIT;
  16931. break;
  16932. }
  16933. if (here_op & 32) {
  16934. //Tracevv((stderr, "inflate: end of block\n"));
  16935. state.back = -1;
  16936. state.mode = TYPE;
  16937. break;
  16938. }
  16939. if (here_op & 64) {
  16940. strm.msg = 'invalid literal/length code';
  16941. state.mode = BAD;
  16942. break;
  16943. }
  16944. state.extra = here_op & 15;
  16945. state.mode = LENEXT;
  16946. /* falls through */
  16947. case LENEXT:
  16948. if (state.extra) {
  16949. //=== NEEDBITS(state.extra);
  16950. n = state.extra;
  16951. while (bits < n) {
  16952. if (have === 0) { break inf_leave; }
  16953. have--;
  16954. hold += input[next++] << bits;
  16955. bits += 8;
  16956. }
  16957. //===//
  16958. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16959. //--- DROPBITS(state.extra) ---//
  16960. hold >>>= state.extra;
  16961. bits -= state.extra;
  16962. //---//
  16963. state.back += state.extra;
  16964. }
  16965. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16966. state.was = state.length;
  16967. state.mode = DIST;
  16968. /* falls through */
  16969. case DIST:
  16970. for (;;) {
  16971. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16972. here_bits = here >>> 24;
  16973. here_op = (here >>> 16) & 0xff;
  16974. here_val = here & 0xffff;
  16975. if ((here_bits) <= bits) { break; }
  16976. //--- PULLBYTE() ---//
  16977. if (have === 0) { break inf_leave; }
  16978. have--;
  16979. hold += input[next++] << bits;
  16980. bits += 8;
  16981. //---//
  16982. }
  16983. if ((here_op & 0xf0) === 0) {
  16984. last_bits = here_bits;
  16985. last_op = here_op;
  16986. last_val = here_val;
  16987. for (;;) {
  16988. here = state.distcode[last_val +
  16989. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16990. here_bits = here >>> 24;
  16991. here_op = (here >>> 16) & 0xff;
  16992. here_val = here & 0xffff;
  16993. if ((last_bits + here_bits) <= bits) { break; }
  16994. //--- PULLBYTE() ---//
  16995. if (have === 0) { break inf_leave; }
  16996. have--;
  16997. hold += input[next++] << bits;
  16998. bits += 8;
  16999. //---//
  17000. }
  17001. //--- DROPBITS(last.bits) ---//
  17002. hold >>>= last_bits;
  17003. bits -= last_bits;
  17004. //---//
  17005. state.back += last_bits;
  17006. }
  17007. //--- DROPBITS(here.bits) ---//
  17008. hold >>>= here_bits;
  17009. bits -= here_bits;
  17010. //---//
  17011. state.back += here_bits;
  17012. if (here_op & 64) {
  17013. strm.msg = 'invalid distance code';
  17014. state.mode = BAD;
  17015. break;
  17016. }
  17017. state.offset = here_val;
  17018. state.extra = (here_op) & 15;
  17019. state.mode = DISTEXT;
  17020. /* falls through */
  17021. case DISTEXT:
  17022. if (state.extra) {
  17023. //=== NEEDBITS(state.extra);
  17024. n = state.extra;
  17025. while (bits < n) {
  17026. if (have === 0) { break inf_leave; }
  17027. have--;
  17028. hold += input[next++] << bits;
  17029. bits += 8;
  17030. }
  17031. //===//
  17032. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17033. //--- DROPBITS(state.extra) ---//
  17034. hold >>>= state.extra;
  17035. bits -= state.extra;
  17036. //---//
  17037. state.back += state.extra;
  17038. }
  17039. //#ifdef INFLATE_STRICT
  17040. if (state.offset > state.dmax) {
  17041. strm.msg = 'invalid distance too far back';
  17042. state.mode = BAD;
  17043. break;
  17044. }
  17045. //#endif
  17046. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  17047. state.mode = MATCH;
  17048. /* falls through */
  17049. case MATCH:
  17050. if (left === 0) { break inf_leave; }
  17051. copy = _out - left;
  17052. if (state.offset > copy) { /* copy from window */
  17053. copy = state.offset - copy;
  17054. if (copy > state.whave) {
  17055. if (state.sane) {
  17056. strm.msg = 'invalid distance too far back';
  17057. state.mode = BAD;
  17058. break;
  17059. }
  17060. // (!) This block is disabled in zlib defailts,
  17061. // don't enable it for binary compatibility
  17062. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17063. // Trace((stderr, "inflate.c too far\n"));
  17064. // copy -= state.whave;
  17065. // if (copy > state.length) { copy = state.length; }
  17066. // if (copy > left) { copy = left; }
  17067. // left -= copy;
  17068. // state.length -= copy;
  17069. // do {
  17070. // output[put++] = 0;
  17071. // } while (--copy);
  17072. // if (state.length === 0) { state.mode = LEN; }
  17073. // break;
  17074. //#endif
  17075. }
  17076. if (copy > state.wnext) {
  17077. copy -= state.wnext;
  17078. from = state.wsize - copy;
  17079. }
  17080. else {
  17081. from = state.wnext - copy;
  17082. }
  17083. if (copy > state.length) { copy = state.length; }
  17084. from_source = state.window;
  17085. }
  17086. else { /* copy from output */
  17087. from_source = output;
  17088. from = put - state.offset;
  17089. copy = state.length;
  17090. }
  17091. if (copy > left) { copy = left; }
  17092. left -= copy;
  17093. state.length -= copy;
  17094. do {
  17095. output[put++] = from_source[from++];
  17096. } while (--copy);
  17097. if (state.length === 0) { state.mode = LEN; }
  17098. break;
  17099. case LIT:
  17100. if (left === 0) { break inf_leave; }
  17101. output[put++] = state.length;
  17102. left--;
  17103. state.mode = LEN;
  17104. break;
  17105. case CHECK:
  17106. if (state.wrap) {
  17107. //=== NEEDBITS(32);
  17108. while (bits < 32) {
  17109. if (have === 0) { break inf_leave; }
  17110. have--;
  17111. // Use '|' insdead of '+' to make sure that result is signed
  17112. hold |= input[next++] << bits;
  17113. bits += 8;
  17114. }
  17115. //===//
  17116. _out -= left;
  17117. strm.total_out += _out;
  17118. state.total += _out;
  17119. if (_out) {
  17120. strm.adler = state.check =
  17121. /*UPDATE(state.check, put - _out, _out);*/
  17122. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17123. }
  17124. _out = left;
  17125. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  17126. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  17127. strm.msg = 'incorrect data check';
  17128. state.mode = BAD;
  17129. break;
  17130. }
  17131. //=== INITBITS();
  17132. hold = 0;
  17133. bits = 0;
  17134. //===//
  17135. //Tracev((stderr, "inflate: check matches trailer\n"));
  17136. }
  17137. state.mode = LENGTH;
  17138. /* falls through */
  17139. case LENGTH:
  17140. if (state.wrap && state.flags) {
  17141. //=== NEEDBITS(32);
  17142. while (bits < 32) {
  17143. if (have === 0) { break inf_leave; }
  17144. have--;
  17145. hold += input[next++] << bits;
  17146. bits += 8;
  17147. }
  17148. //===//
  17149. if (hold !== (state.total & 0xffffffff)) {
  17150. strm.msg = 'incorrect length check';
  17151. state.mode = BAD;
  17152. break;
  17153. }
  17154. //=== INITBITS();
  17155. hold = 0;
  17156. bits = 0;
  17157. //===//
  17158. //Tracev((stderr, "inflate: length matches trailer\n"));
  17159. }
  17160. state.mode = DONE;
  17161. /* falls through */
  17162. case DONE:
  17163. ret = Z_STREAM_END;
  17164. break inf_leave;
  17165. case BAD:
  17166. ret = Z_DATA_ERROR;
  17167. break inf_leave;
  17168. case MEM:
  17169. return Z_MEM_ERROR;
  17170. case SYNC:
  17171. /* falls through */
  17172. default:
  17173. return Z_STREAM_ERROR;
  17174. }
  17175. }
  17176. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17177. /*
  17178. Return from inflate(), updating the total counts and the check value.
  17179. If there was no progress during the inflate() call, return a buffer
  17180. error. Call updatewindow() to create and/or update the window state.
  17181. Note: a memory error from inflate() is non-recoverable.
  17182. */
  17183. //--- RESTORE() ---
  17184. strm.next_out = put;
  17185. strm.avail_out = left;
  17186. strm.next_in = next;
  17187. strm.avail_in = have;
  17188. state.hold = hold;
  17189. state.bits = bits;
  17190. //---
  17191. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17192. (state.mode < CHECK || flush !== Z_FINISH))) {
  17193. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17194. state.mode = MEM;
  17195. return Z_MEM_ERROR;
  17196. }
  17197. }
  17198. _in -= strm.avail_in;
  17199. _out -= strm.avail_out;
  17200. strm.total_in += _in;
  17201. strm.total_out += _out;
  17202. state.total += _out;
  17203. if (state.wrap && _out) {
  17204. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17205. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17206. }
  17207. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17208. (state.mode === TYPE ? 128 : 0) +
  17209. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17210. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17211. ret = Z_BUF_ERROR;
  17212. }
  17213. return ret;
  17214. }
  17215. function inflateEnd(strm) {
  17216. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17217. return Z_STREAM_ERROR;
  17218. }
  17219. var state = strm.state;
  17220. if (state.window) {
  17221. state.window = null;
  17222. }
  17223. strm.state = null;
  17224. return Z_OK;
  17225. }
  17226. function inflateGetHeader(strm, head) {
  17227. var state;
  17228. /* check state */
  17229. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17230. state = strm.state;
  17231. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17232. /* save header structure */
  17233. state.head = head;
  17234. head.done = false;
  17235. return Z_OK;
  17236. }
  17237. exports.inflateReset = inflateReset;
  17238. exports.inflateReset2 = inflateReset2;
  17239. exports.inflateResetKeep = inflateResetKeep;
  17240. exports.inflateInit = inflateInit;
  17241. exports.inflateInit2 = inflateInit2;
  17242. exports.inflate = inflate;
  17243. exports.inflateEnd = inflateEnd;
  17244. exports.inflateGetHeader = inflateGetHeader;
  17245. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17246. /* Not implemented
  17247. exports.inflateCopy = inflateCopy;
  17248. exports.inflateGetDictionary = inflateGetDictionary;
  17249. exports.inflateMark = inflateMark;
  17250. exports.inflatePrime = inflatePrime;
  17251. exports.inflateSetDictionary = inflateSetDictionary;
  17252. exports.inflateSync = inflateSync;
  17253. exports.inflateSyncPoint = inflateSyncPoint;
  17254. exports.inflateUndermine = inflateUndermine;
  17255. */
  17256. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./inffast":59,"./inftrees":61}],61:[function(require,module,exports){
  17257. 'use strict';
  17258. var utils = require('../utils/common');
  17259. var MAXBITS = 15;
  17260. var ENOUGH_LENS = 852;
  17261. var ENOUGH_DISTS = 592;
  17262. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17263. var CODES = 0;
  17264. var LENS = 1;
  17265. var DISTS = 2;
  17266. var lbase = [ /* Length codes 257..285 base */
  17267. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17268. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17269. ];
  17270. var lext = [ /* Length codes 257..285 extra */
  17271. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17272. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17273. ];
  17274. var dbase = [ /* Distance codes 0..29 base */
  17275. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17276. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17277. 8193, 12289, 16385, 24577, 0, 0
  17278. ];
  17279. var dext = [ /* Distance codes 0..29 extra */
  17280. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17281. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17282. 28, 28, 29, 29, 64, 64
  17283. ];
  17284. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17285. {
  17286. var bits = opts.bits;
  17287. //here = opts.here; /* table entry for duplication */
  17288. var len = 0; /* a code's length in bits */
  17289. var sym = 0; /* index of code symbols */
  17290. var min = 0, max = 0; /* minimum and maximum code lengths */
  17291. var root = 0; /* number of index bits for root table */
  17292. var curr = 0; /* number of index bits for current table */
  17293. var drop = 0; /* code bits to drop for sub-table */
  17294. var left = 0; /* number of prefix codes available */
  17295. var used = 0; /* code entries in table used */
  17296. var huff = 0; /* Huffman code */
  17297. var incr; /* for incrementing code, index */
  17298. var fill; /* index for replicating entries */
  17299. var low; /* low bits for current root entry */
  17300. var mask; /* mask for low root bits */
  17301. var next; /* next available space in table */
  17302. var base = null; /* base value table to use */
  17303. var base_index = 0;
  17304. // var shoextra; /* extra bits table to use */
  17305. var end; /* use base and extra for symbol > end */
  17306. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17307. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17308. var extra = null;
  17309. var extra_index = 0;
  17310. var here_bits, here_op, here_val;
  17311. /*
  17312. Process a set of code lengths to create a canonical Huffman code. The
  17313. code lengths are lens[0..codes-1]. Each length corresponds to the
  17314. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17315. symbols by length from short to long, and retaining the symbol order
  17316. for codes with equal lengths. Then the code starts with all zero bits
  17317. for the first code of the shortest length, and the codes are integer
  17318. increments for the same length, and zeros are appended as the length
  17319. increases. For the deflate format, these bits are stored backwards
  17320. from their more natural integer increment ordering, and so when the
  17321. decoding tables are built in the large loop below, the integer codes
  17322. are incremented backwards.
  17323. This routine assumes, but does not check, that all of the entries in
  17324. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17325. 1..MAXBITS is interpreted as that code length. zero means that that
  17326. symbol does not occur in this code.
  17327. The codes are sorted by computing a count of codes for each length,
  17328. creating from that a table of starting indices for each length in the
  17329. sorted table, and then entering the symbols in order in the sorted
  17330. table. The sorted table is work[], with that space being provided by
  17331. the caller.
  17332. The length counts are used for other purposes as well, i.e. finding
  17333. the minimum and maximum length codes, determining if there are any
  17334. codes at all, checking for a valid set of lengths, and looking ahead
  17335. at length counts to determine sub-table sizes when building the
  17336. decoding tables.
  17337. */
  17338. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17339. for (len = 0; len <= MAXBITS; len++) {
  17340. count[len] = 0;
  17341. }
  17342. for (sym = 0; sym < codes; sym++) {
  17343. count[lens[lens_index + sym]]++;
  17344. }
  17345. /* bound code lengths, force root to be within code lengths */
  17346. root = bits;
  17347. for (max = MAXBITS; max >= 1; max--) {
  17348. if (count[max] !== 0) { break; }
  17349. }
  17350. if (root > max) {
  17351. root = max;
  17352. }
  17353. if (max === 0) { /* no symbols to code at all */
  17354. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17355. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17356. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17357. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17358. //table.op[opts.table_index] = 64;
  17359. //table.bits[opts.table_index] = 1;
  17360. //table.val[opts.table_index++] = 0;
  17361. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17362. opts.bits = 1;
  17363. return 0; /* no symbols, but wait for decoding to report error */
  17364. }
  17365. for (min = 1; min < max; min++) {
  17366. if (count[min] !== 0) { break; }
  17367. }
  17368. if (root < min) {
  17369. root = min;
  17370. }
  17371. /* check for an over-subscribed or incomplete set of lengths */
  17372. left = 1;
  17373. for (len = 1; len <= MAXBITS; len++) {
  17374. left <<= 1;
  17375. left -= count[len];
  17376. if (left < 0) {
  17377. return -1;
  17378. } /* over-subscribed */
  17379. }
  17380. if (left > 0 && (type === CODES || max !== 1)) {
  17381. return -1; /* incomplete set */
  17382. }
  17383. /* generate offsets into symbol table for each length for sorting */
  17384. offs[1] = 0;
  17385. for (len = 1; len < MAXBITS; len++) {
  17386. offs[len + 1] = offs[len] + count[len];
  17387. }
  17388. /* sort symbols by length, by symbol order within each length */
  17389. for (sym = 0; sym < codes; sym++) {
  17390. if (lens[lens_index + sym] !== 0) {
  17391. work[offs[lens[lens_index + sym]]++] = sym;
  17392. }
  17393. }
  17394. /*
  17395. Create and fill in decoding tables. In this loop, the table being
  17396. filled is at next and has curr index bits. The code being used is huff
  17397. with length len. That code is converted to an index by dropping drop
  17398. bits off of the bottom. For codes where len is less than drop + curr,
  17399. those top drop + curr - len bits are incremented through all values to
  17400. fill the table with replicated entries.
  17401. root is the number of index bits for the root table. When len exceeds
  17402. root, sub-tables are created pointed to by the root entry with an index
  17403. of the low root bits of huff. This is saved in low to check for when a
  17404. new sub-table should be started. drop is zero when the root table is
  17405. being filled, and drop is root when sub-tables are being filled.
  17406. When a new sub-table is needed, it is necessary to look ahead in the
  17407. code lengths to determine what size sub-table is needed. The length
  17408. counts are used for this, and so count[] is decremented as codes are
  17409. entered in the tables.
  17410. used keeps track of how many table entries have been allocated from the
  17411. provided *table space. It is checked for LENS and DIST tables against
  17412. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17413. the initial root table size constants. See the comments in inftrees.h
  17414. for more information.
  17415. sym increments through all symbols, and the loop terminates when
  17416. all codes of length max, i.e. all codes, have been processed. This
  17417. routine permits incomplete codes, so another loop after this one fills
  17418. in the rest of the decoding tables with invalid code markers.
  17419. */
  17420. /* set up for code type */
  17421. // poor man optimization - use if-else instead of switch,
  17422. // to avoid deopts in old v8
  17423. if (type === CODES) {
  17424. base = extra = work; /* dummy value--not used */
  17425. end = 19;
  17426. } else if (type === LENS) {
  17427. base = lbase;
  17428. base_index -= 257;
  17429. extra = lext;
  17430. extra_index -= 257;
  17431. end = 256;
  17432. } else { /* DISTS */
  17433. base = dbase;
  17434. extra = dext;
  17435. end = -1;
  17436. }
  17437. /* initialize opts for loop */
  17438. huff = 0; /* starting code */
  17439. sym = 0; /* starting code symbol */
  17440. len = min; /* starting code length */
  17441. next = table_index; /* current table to fill in */
  17442. curr = root; /* current table index bits */
  17443. drop = 0; /* current bits to drop from code for index */
  17444. low = -1; /* trigger new sub-table when len > root */
  17445. used = 1 << root; /* use root table entries */
  17446. mask = used - 1; /* mask for comparing low */
  17447. /* check available table space */
  17448. if ((type === LENS && used > ENOUGH_LENS) ||
  17449. (type === DISTS && used > ENOUGH_DISTS)) {
  17450. return 1;
  17451. }
  17452. var i=0;
  17453. /* process all codes and make table entries */
  17454. for (;;) {
  17455. i++;
  17456. /* create table entry */
  17457. here_bits = len - drop;
  17458. if (work[sym] < end) {
  17459. here_op = 0;
  17460. here_val = work[sym];
  17461. }
  17462. else if (work[sym] > end) {
  17463. here_op = extra[extra_index + work[sym]];
  17464. here_val = base[base_index + work[sym]];
  17465. }
  17466. else {
  17467. here_op = 32 + 64; /* end of block */
  17468. here_val = 0;
  17469. }
  17470. /* replicate for those indices with low len bits equal to huff */
  17471. incr = 1 << (len - drop);
  17472. fill = 1 << curr;
  17473. min = fill; /* save offset to next table */
  17474. do {
  17475. fill -= incr;
  17476. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17477. } while (fill !== 0);
  17478. /* backwards increment the len-bit code huff */
  17479. incr = 1 << (len - 1);
  17480. while (huff & incr) {
  17481. incr >>= 1;
  17482. }
  17483. if (incr !== 0) {
  17484. huff &= incr - 1;
  17485. huff += incr;
  17486. } else {
  17487. huff = 0;
  17488. }
  17489. /* go to next symbol, update count, len */
  17490. sym++;
  17491. if (--count[len] === 0) {
  17492. if (len === max) { break; }
  17493. len = lens[lens_index + work[sym]];
  17494. }
  17495. /* create new sub-table if needed */
  17496. if (len > root && (huff & mask) !== low) {
  17497. /* if first time, transition to sub-tables */
  17498. if (drop === 0) {
  17499. drop = root;
  17500. }
  17501. /* increment past last table */
  17502. next += min; /* here min is 1 << curr */
  17503. /* determine length of next table */
  17504. curr = len - drop;
  17505. left = 1 << curr;
  17506. while (curr + drop < max) {
  17507. left -= count[curr + drop];
  17508. if (left <= 0) { break; }
  17509. curr++;
  17510. left <<= 1;
  17511. }
  17512. /* check for enough space */
  17513. used += 1 << curr;
  17514. if ((type === LENS && used > ENOUGH_LENS) ||
  17515. (type === DISTS && used > ENOUGH_DISTS)) {
  17516. return 1;
  17517. }
  17518. /* point entry in root table to sub-table */
  17519. low = huff & mask;
  17520. /*table.op[low] = curr;
  17521. table.bits[low] = root;
  17522. table.val[low] = next - opts.table_index;*/
  17523. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17524. }
  17525. }
  17526. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17527. at most one remaining entry, since if the code is incomplete, the
  17528. maximum code length that was allowed to get this far is one bit) */
  17529. if (huff !== 0) {
  17530. //table.op[next + huff] = 64; /* invalid code marker */
  17531. //table.bits[next + huff] = len - drop;
  17532. //table.val[next + huff] = 0;
  17533. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17534. }
  17535. /* set return parameters */
  17536. //opts.table_index += used;
  17537. opts.bits = root;
  17538. return 0;
  17539. };
  17540. },{"../utils/common":52}],62:[function(require,module,exports){
  17541. 'use strict';
  17542. module.exports = {
  17543. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17544. '1': 'stream end', /* Z_STREAM_END 1 */
  17545. '0': '', /* Z_OK 0 */
  17546. '-1': 'file error', /* Z_ERRNO (-1) */
  17547. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17548. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17549. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17550. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17551. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17552. };
  17553. },{}],63:[function(require,module,exports){
  17554. 'use strict';
  17555. var utils = require('../utils/common');
  17556. /* Public constants ==========================================================*/
  17557. /* ===========================================================================*/
  17558. //var Z_FILTERED = 1;
  17559. //var Z_HUFFMAN_ONLY = 2;
  17560. //var Z_RLE = 3;
  17561. var Z_FIXED = 4;
  17562. //var Z_DEFAULT_STRATEGY = 0;
  17563. /* Possible values of the data_type field (though see inflate()) */
  17564. var Z_BINARY = 0;
  17565. var Z_TEXT = 1;
  17566. //var Z_ASCII = 1; // = Z_TEXT
  17567. var Z_UNKNOWN = 2;
  17568. /*============================================================================*/
  17569. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17570. // From zutil.h
  17571. var STORED_BLOCK = 0;
  17572. var STATIC_TREES = 1;
  17573. var DYN_TREES = 2;
  17574. /* The three kinds of block type */
  17575. var MIN_MATCH = 3;
  17576. var MAX_MATCH = 258;
  17577. /* The minimum and maximum match lengths */
  17578. // From deflate.h
  17579. /* ===========================================================================
  17580. * Internal compression state.
  17581. */
  17582. var LENGTH_CODES = 29;
  17583. /* number of length codes, not counting the special END_BLOCK code */
  17584. var LITERALS = 256;
  17585. /* number of literal bytes 0..255 */
  17586. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17587. /* number of Literal or Length codes, including the END_BLOCK code */
  17588. var D_CODES = 30;
  17589. /* number of distance codes */
  17590. var BL_CODES = 19;
  17591. /* number of codes used to transfer the bit lengths */
  17592. var HEAP_SIZE = 2*L_CODES + 1;
  17593. /* maximum heap size */
  17594. var MAX_BITS = 15;
  17595. /* All codes must not exceed MAX_BITS bits */
  17596. var Buf_size = 16;
  17597. /* size of bit buffer in bi_buf */
  17598. /* ===========================================================================
  17599. * Constants
  17600. */
  17601. var MAX_BL_BITS = 7;
  17602. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17603. var END_BLOCK = 256;
  17604. /* end of block literal code */
  17605. var REP_3_6 = 16;
  17606. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17607. var REPZ_3_10 = 17;
  17608. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17609. var REPZ_11_138 = 18;
  17610. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17611. var extra_lbits = /* extra bits for each length code */
  17612. [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];
  17613. var extra_dbits = /* extra bits for each distance code */
  17614. [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];
  17615. var extra_blbits = /* extra bits for each bit length code */
  17616. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17617. var bl_order =
  17618. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17619. /* The lengths of the bit length codes are sent in order of decreasing
  17620. * probability, to avoid transmitting the lengths for unused bit length codes.
  17621. */
  17622. /* ===========================================================================
  17623. * Local data. These are initialized only once.
  17624. */
  17625. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17626. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17627. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17628. var static_ltree = new Array((L_CODES+2) * 2);
  17629. zero(static_ltree);
  17630. /* The static literal tree. Since the bit lengths are imposed, there is no
  17631. * need for the L_CODES extra codes used during heap construction. However
  17632. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17633. * below).
  17634. */
  17635. var static_dtree = new Array(D_CODES * 2);
  17636. zero(static_dtree);
  17637. /* The static distance tree. (Actually a trivial tree since all codes use
  17638. * 5 bits.)
  17639. */
  17640. var _dist_code = new Array(DIST_CODE_LEN);
  17641. zero(_dist_code);
  17642. /* Distance codes. The first 256 values correspond to the distances
  17643. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17644. * the 15 bit distances.
  17645. */
  17646. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17647. zero(_length_code);
  17648. /* length code for each normalized match length (0 == MIN_MATCH) */
  17649. var base_length = new Array(LENGTH_CODES);
  17650. zero(base_length);
  17651. /* First normalized length for each code (0 = MIN_MATCH) */
  17652. var base_dist = new Array(D_CODES);
  17653. zero(base_dist);
  17654. /* First normalized distance for each code (0 = distance of 1) */
  17655. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17656. this.static_tree = static_tree; /* static tree or NULL */
  17657. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17658. this.extra_base = extra_base; /* base index for extra_bits */
  17659. this.elems = elems; /* max number of elements in the tree */
  17660. this.max_length = max_length; /* max bit length for the codes */
  17661. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17662. this.has_stree = static_tree && static_tree.length;
  17663. };
  17664. var static_l_desc;
  17665. var static_d_desc;
  17666. var static_bl_desc;
  17667. var TreeDesc = function(dyn_tree, stat_desc) {
  17668. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17669. this.max_code = 0; /* largest code with non zero frequency */
  17670. this.stat_desc = stat_desc; /* the corresponding static tree */
  17671. };
  17672. function d_code(dist) {
  17673. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17674. }
  17675. /* ===========================================================================
  17676. * Output a short LSB first on the stream.
  17677. * IN assertion: there is enough room in pendingBuf.
  17678. */
  17679. function put_short (s, w) {
  17680. // put_byte(s, (uch)((w) & 0xff));
  17681. // put_byte(s, (uch)((ush)(w) >> 8));
  17682. s.pending_buf[s.pending++] = (w) & 0xff;
  17683. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17684. }
  17685. /* ===========================================================================
  17686. * Send a value on a given number of bits.
  17687. * IN assertion: length <= 16 and value fits in length bits.
  17688. */
  17689. function send_bits(s, value, length) {
  17690. if (s.bi_valid > (Buf_size - length)) {
  17691. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17692. put_short(s, s.bi_buf);
  17693. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17694. s.bi_valid += length - Buf_size;
  17695. } else {
  17696. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17697. s.bi_valid += length;
  17698. }
  17699. }
  17700. function send_code(s, c, tree) {
  17701. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17702. }
  17703. /* ===========================================================================
  17704. * Reverse the first len bits of a code, using straightforward code (a faster
  17705. * method would use a table)
  17706. * IN assertion: 1 <= len <= 15
  17707. */
  17708. function bi_reverse(code, len) {
  17709. var res = 0;
  17710. do {
  17711. res |= code & 1;
  17712. code >>>= 1;
  17713. res <<= 1;
  17714. } while (--len > 0);
  17715. return res >>> 1;
  17716. }
  17717. /* ===========================================================================
  17718. * Flush the bit buffer, keeping at most 7 bits in it.
  17719. */
  17720. function bi_flush(s) {
  17721. if (s.bi_valid === 16) {
  17722. put_short(s, s.bi_buf);
  17723. s.bi_buf = 0;
  17724. s.bi_valid = 0;
  17725. } else if (s.bi_valid >= 8) {
  17726. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17727. s.bi_buf >>= 8;
  17728. s.bi_valid -= 8;
  17729. }
  17730. }
  17731. /* ===========================================================================
  17732. * Compute the optimal bit lengths for a tree and update the total bit length
  17733. * for the current block.
  17734. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17735. * above are the tree nodes sorted by increasing frequency.
  17736. * OUT assertions: the field len is set to the optimal bit length, the
  17737. * array bl_count contains the frequencies for each bit length.
  17738. * The length opt_len is updated; static_len is also updated if stree is
  17739. * not null.
  17740. */
  17741. function gen_bitlen(s, desc)
  17742. // deflate_state *s;
  17743. // tree_desc *desc; /* the tree descriptor */
  17744. {
  17745. var tree = desc.dyn_tree;
  17746. var max_code = desc.max_code;
  17747. var stree = desc.stat_desc.static_tree;
  17748. var has_stree = desc.stat_desc.has_stree;
  17749. var extra = desc.stat_desc.extra_bits;
  17750. var base = desc.stat_desc.extra_base;
  17751. var max_length = desc.stat_desc.max_length;
  17752. var h; /* heap index */
  17753. var n, m; /* iterate over the tree elements */
  17754. var bits; /* bit length */
  17755. var xbits; /* extra bits */
  17756. var f; /* frequency */
  17757. var overflow = 0; /* number of elements with bit length too large */
  17758. for (bits = 0; bits <= MAX_BITS; bits++) {
  17759. s.bl_count[bits] = 0;
  17760. }
  17761. /* In a first pass, compute the optimal bit lengths (which may
  17762. * overflow in the case of the bit length tree).
  17763. */
  17764. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17765. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17766. n = s.heap[h];
  17767. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17768. if (bits > max_length) {
  17769. bits = max_length;
  17770. overflow++;
  17771. }
  17772. tree[n*2 + 1]/*.Len*/ = bits;
  17773. /* We overwrite tree[n].Dad which is no longer needed */
  17774. if (n > max_code) { continue; } /* not a leaf node */
  17775. s.bl_count[bits]++;
  17776. xbits = 0;
  17777. if (n >= base) {
  17778. xbits = extra[n-base];
  17779. }
  17780. f = tree[n * 2]/*.Freq*/;
  17781. s.opt_len += f * (bits + xbits);
  17782. if (has_stree) {
  17783. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  17784. }
  17785. }
  17786. if (overflow === 0) { return; }
  17787. // Trace((stderr,"\nbit length overflow\n"));
  17788. /* This happens for example on obj2 and pic of the Calgary corpus */
  17789. /* Find the first bit length which could increase: */
  17790. do {
  17791. bits = max_length-1;
  17792. while (s.bl_count[bits] === 0) { bits--; }
  17793. s.bl_count[bits]--; /* move one leaf down the tree */
  17794. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  17795. s.bl_count[max_length]--;
  17796. /* The brother of the overflow item also moves one step up,
  17797. * but this does not affect bl_count[max_length]
  17798. */
  17799. overflow -= 2;
  17800. } while (overflow > 0);
  17801. /* Now recompute all bit lengths, scanning in increasing frequency.
  17802. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17803. * lengths instead of fixing only the wrong ones. This idea is taken
  17804. * from 'ar' written by Haruhiko Okumura.)
  17805. */
  17806. for (bits = max_length; bits !== 0; bits--) {
  17807. n = s.bl_count[bits];
  17808. while (n !== 0) {
  17809. m = s.heap[--h];
  17810. if (m > max_code) { continue; }
  17811. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  17812. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17813. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  17814. tree[m*2 + 1]/*.Len*/ = bits;
  17815. }
  17816. n--;
  17817. }
  17818. }
  17819. }
  17820. /* ===========================================================================
  17821. * Generate the codes for a given tree and bit counts (which need not be
  17822. * optimal).
  17823. * IN assertion: the array bl_count contains the bit length statistics for
  17824. * the given tree and the field len is set for all tree elements.
  17825. * OUT assertion: the field code is set for all tree elements of non
  17826. * zero code length.
  17827. */
  17828. function gen_codes(tree, max_code, bl_count)
  17829. // ct_data *tree; /* the tree to decorate */
  17830. // int max_code; /* largest code with non zero frequency */
  17831. // ushf *bl_count; /* number of codes at each bit length */
  17832. {
  17833. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17834. var code = 0; /* running code value */
  17835. var bits; /* bit index */
  17836. var n; /* code index */
  17837. /* The distribution counts are first used to generate the code values
  17838. * without bit reversal.
  17839. */
  17840. for (bits = 1; bits <= MAX_BITS; bits++) {
  17841. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17842. }
  17843. /* Check that the bit counts in bl_count are consistent. The last code
  17844. * must be all ones.
  17845. */
  17846. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17847. // "inconsistent bit counts");
  17848. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17849. for (n = 0; n <= max_code; n++) {
  17850. var len = tree[n*2 + 1]/*.Len*/;
  17851. if (len === 0) { continue; }
  17852. /* Now reverse the bits */
  17853. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17854. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17855. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17856. }
  17857. }
  17858. /* ===========================================================================
  17859. * Initialize the various 'constant' tables.
  17860. */
  17861. function tr_static_init() {
  17862. var n; /* iterates over tree elements */
  17863. var bits; /* bit counter */
  17864. var length; /* length value */
  17865. var code; /* code value */
  17866. var dist; /* distance index */
  17867. var bl_count = new Array(MAX_BITS+1);
  17868. /* number of codes at each bit length for an optimal tree */
  17869. // do check in _tr_init()
  17870. //if (static_init_done) return;
  17871. /* For some embedded targets, global variables are not initialized: */
  17872. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17873. static_l_desc.static_tree = static_ltree;
  17874. static_l_desc.extra_bits = extra_lbits;
  17875. static_d_desc.static_tree = static_dtree;
  17876. static_d_desc.extra_bits = extra_dbits;
  17877. static_bl_desc.extra_bits = extra_blbits;
  17878. #endif*/
  17879. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17880. length = 0;
  17881. for (code = 0; code < LENGTH_CODES-1; code++) {
  17882. base_length[code] = length;
  17883. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17884. _length_code[length++] = code;
  17885. }
  17886. }
  17887. //Assert (length == 256, "tr_static_init: length != 256");
  17888. /* Note that the length 255 (match length 258) can be represented
  17889. * in two different ways: code 284 + 5 bits or code 285, so we
  17890. * overwrite length_code[255] to use the best encoding:
  17891. */
  17892. _length_code[length-1] = code;
  17893. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17894. dist = 0;
  17895. for (code = 0 ; code < 16; code++) {
  17896. base_dist[code] = dist;
  17897. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17898. _dist_code[dist++] = code;
  17899. }
  17900. }
  17901. //Assert (dist == 256, "tr_static_init: dist != 256");
  17902. dist >>= 7; /* from now on, all distances are divided by 128 */
  17903. for (; code < D_CODES; code++) {
  17904. base_dist[code] = dist << 7;
  17905. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17906. _dist_code[256 + dist++] = code;
  17907. }
  17908. }
  17909. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17910. /* Construct the codes of the static literal tree */
  17911. for (bits = 0; bits <= MAX_BITS; bits++) {
  17912. bl_count[bits] = 0;
  17913. }
  17914. n = 0;
  17915. while (n <= 143) {
  17916. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17917. n++;
  17918. bl_count[8]++;
  17919. }
  17920. while (n <= 255) {
  17921. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17922. n++;
  17923. bl_count[9]++;
  17924. }
  17925. while (n <= 279) {
  17926. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17927. n++;
  17928. bl_count[7]++;
  17929. }
  17930. while (n <= 287) {
  17931. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17932. n++;
  17933. bl_count[8]++;
  17934. }
  17935. /* Codes 286 and 287 do not exist, but we must include them in the
  17936. * tree construction to get a canonical Huffman tree (longest code
  17937. * all ones)
  17938. */
  17939. gen_codes(static_ltree, L_CODES+1, bl_count);
  17940. /* The static distance tree is trivial: */
  17941. for (n = 0; n < D_CODES; n++) {
  17942. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17943. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17944. }
  17945. // Now data ready and we can init static trees
  17946. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17947. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17948. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17949. //static_init_done = true;
  17950. }
  17951. /* ===========================================================================
  17952. * Initialize a new block.
  17953. */
  17954. function init_block(s) {
  17955. var n; /* iterates over tree elements */
  17956. /* Initialize the trees. */
  17957. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17958. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17959. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17960. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17961. s.opt_len = s.static_len = 0;
  17962. s.last_lit = s.matches = 0;
  17963. }
  17964. /* ===========================================================================
  17965. * Flush the bit buffer and align the output on a byte boundary
  17966. */
  17967. function bi_windup(s)
  17968. {
  17969. if (s.bi_valid > 8) {
  17970. put_short(s, s.bi_buf);
  17971. } else if (s.bi_valid > 0) {
  17972. //put_byte(s, (Byte)s->bi_buf);
  17973. s.pending_buf[s.pending++] = s.bi_buf;
  17974. }
  17975. s.bi_buf = 0;
  17976. s.bi_valid = 0;
  17977. }
  17978. /* ===========================================================================
  17979. * Copy a stored block, storing first the length and its
  17980. * one's complement if requested.
  17981. */
  17982. function copy_block(s, buf, len, header)
  17983. //DeflateState *s;
  17984. //charf *buf; /* the input data */
  17985. //unsigned len; /* its length */
  17986. //int header; /* true if block header must be written */
  17987. {
  17988. bi_windup(s); /* align on byte boundary */
  17989. if (header) {
  17990. put_short(s, len);
  17991. put_short(s, ~len);
  17992. }
  17993. // while (len--) {
  17994. // put_byte(s, *buf++);
  17995. // }
  17996. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17997. s.pending += len;
  17998. }
  17999. /* ===========================================================================
  18000. * Compares to subtrees, using the tree depth as tie breaker when
  18001. * the subtrees have equal frequency. This minimizes the worst case length.
  18002. */
  18003. function smaller(tree, n, m, depth) {
  18004. var _n2 = n*2;
  18005. var _m2 = m*2;
  18006. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  18007. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  18008. }
  18009. /* ===========================================================================
  18010. * Restore the heap property by moving down the tree starting at node k,
  18011. * exchanging a node with the smallest of its two sons if necessary, stopping
  18012. * when the heap property is re-established (each father smaller than its
  18013. * two sons).
  18014. */
  18015. function pqdownheap(s, tree, k)
  18016. // deflate_state *s;
  18017. // ct_data *tree; /* the tree to restore */
  18018. // int k; /* node to move down */
  18019. {
  18020. var v = s.heap[k];
  18021. var j = k << 1; /* left son of k */
  18022. while (j <= s.heap_len) {
  18023. /* Set j to the smallest of the two sons: */
  18024. if (j < s.heap_len &&
  18025. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  18026. j++;
  18027. }
  18028. /* Exit if v is smaller than both sons */
  18029. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  18030. /* Exchange v with the smallest son */
  18031. s.heap[k] = s.heap[j];
  18032. k = j;
  18033. /* And continue down the tree, setting j to the left son of k */
  18034. j <<= 1;
  18035. }
  18036. s.heap[k] = v;
  18037. }
  18038. // inlined manually
  18039. // var SMALLEST = 1;
  18040. /* ===========================================================================
  18041. * Send the block data compressed using the given Huffman trees
  18042. */
  18043. function compress_block(s, ltree, dtree)
  18044. // deflate_state *s;
  18045. // const ct_data *ltree; /* literal tree */
  18046. // const ct_data *dtree; /* distance tree */
  18047. {
  18048. var dist; /* distance of matched string */
  18049. var lc; /* match length or unmatched char (if dist == 0) */
  18050. var lx = 0; /* running index in l_buf */
  18051. var code; /* the code to send */
  18052. var extra; /* number of extra bits to send */
  18053. if (s.last_lit !== 0) {
  18054. do {
  18055. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  18056. lc = s.pending_buf[s.l_buf + lx];
  18057. lx++;
  18058. if (dist === 0) {
  18059. send_code(s, lc, ltree); /* send a literal byte */
  18060. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18061. } else {
  18062. /* Here, lc is the match length - MIN_MATCH */
  18063. code = _length_code[lc];
  18064. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  18065. extra = extra_lbits[code];
  18066. if (extra !== 0) {
  18067. lc -= base_length[code];
  18068. send_bits(s, lc, extra); /* send the extra length bits */
  18069. }
  18070. dist--; /* dist is now the match distance - 1 */
  18071. code = d_code(dist);
  18072. //Assert (code < D_CODES, "bad d_code");
  18073. send_code(s, code, dtree); /* send the distance code */
  18074. extra = extra_dbits[code];
  18075. if (extra !== 0) {
  18076. dist -= base_dist[code];
  18077. send_bits(s, dist, extra); /* send the extra distance bits */
  18078. }
  18079. } /* literal or match pair ? */
  18080. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18081. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18082. // "pendingBuf overflow");
  18083. } while (lx < s.last_lit);
  18084. }
  18085. send_code(s, END_BLOCK, ltree);
  18086. }
  18087. /* ===========================================================================
  18088. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18089. * Update the total bit length for the current block.
  18090. * IN assertion: the field freq is set for all tree elements.
  18091. * OUT assertions: the fields len and code are set to the optimal bit length
  18092. * and corresponding code. The length opt_len is updated; static_len is
  18093. * also updated if stree is not null. The field max_code is set.
  18094. */
  18095. function build_tree(s, desc)
  18096. // deflate_state *s;
  18097. // tree_desc *desc; /* the tree descriptor */
  18098. {
  18099. var tree = desc.dyn_tree;
  18100. var stree = desc.stat_desc.static_tree;
  18101. var has_stree = desc.stat_desc.has_stree;
  18102. var elems = desc.stat_desc.elems;
  18103. var n, m; /* iterate over heap elements */
  18104. var max_code = -1; /* largest code with non zero frequency */
  18105. var node; /* new node being created */
  18106. /* Construct the initial heap, with least frequent element in
  18107. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18108. * heap[0] is not used.
  18109. */
  18110. s.heap_len = 0;
  18111. s.heap_max = HEAP_SIZE;
  18112. for (n = 0; n < elems; n++) {
  18113. if (tree[n * 2]/*.Freq*/ !== 0) {
  18114. s.heap[++s.heap_len] = max_code = n;
  18115. s.depth[n] = 0;
  18116. } else {
  18117. tree[n*2 + 1]/*.Len*/ = 0;
  18118. }
  18119. }
  18120. /* The pkzip format requires that at least one distance code exists,
  18121. * and that at least one bit should be sent even if there is only one
  18122. * possible code. So to avoid special checks later on we force at least
  18123. * two codes of non zero frequency.
  18124. */
  18125. while (s.heap_len < 2) {
  18126. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18127. tree[node * 2]/*.Freq*/ = 1;
  18128. s.depth[node] = 0;
  18129. s.opt_len--;
  18130. if (has_stree) {
  18131. s.static_len -= stree[node*2 + 1]/*.Len*/;
  18132. }
  18133. /* node is 0 or 1 so it does not have extra bits */
  18134. }
  18135. desc.max_code = max_code;
  18136. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18137. * establish sub-heaps of increasing lengths:
  18138. */
  18139. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18140. /* Construct the Huffman tree by repeatedly combining the least two
  18141. * frequent nodes.
  18142. */
  18143. node = elems; /* next internal node of the tree */
  18144. do {
  18145. //pqremove(s, tree, n); /* n = node of least frequency */
  18146. /*** pqremove ***/
  18147. n = s.heap[1/*SMALLEST*/];
  18148. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18149. pqdownheap(s, tree, 1/*SMALLEST*/);
  18150. /***/
  18151. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18152. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18153. s.heap[--s.heap_max] = m;
  18154. /* Create a new node father of n and m */
  18155. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18156. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18157. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  18158. /* and insert the new node in the heap */
  18159. s.heap[1/*SMALLEST*/] = node++;
  18160. pqdownheap(s, tree, 1/*SMALLEST*/);
  18161. } while (s.heap_len >= 2);
  18162. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18163. /* At this point, the fields freq and dad are set. We can now
  18164. * generate the bit lengths.
  18165. */
  18166. gen_bitlen(s, desc);
  18167. /* The field len is now set, we can generate the bit codes */
  18168. gen_codes(tree, max_code, s.bl_count);
  18169. }
  18170. /* ===========================================================================
  18171. * Scan a literal or distance tree to determine the frequencies of the codes
  18172. * in the bit length tree.
  18173. */
  18174. function scan_tree(s, tree, max_code)
  18175. // deflate_state *s;
  18176. // ct_data *tree; /* the tree to be scanned */
  18177. // int max_code; /* and its largest code of non zero frequency */
  18178. {
  18179. var n; /* iterates over all tree elements */
  18180. var prevlen = -1; /* last emitted length */
  18181. var curlen; /* length of current code */
  18182. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18183. var count = 0; /* repeat count of the current code */
  18184. var max_count = 7; /* max repeat count */
  18185. var min_count = 4; /* min repeat count */
  18186. if (nextlen === 0) {
  18187. max_count = 138;
  18188. min_count = 3;
  18189. }
  18190. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18191. for (n = 0; n <= max_code; n++) {
  18192. curlen = nextlen;
  18193. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18194. if (++count < max_count && curlen === nextlen) {
  18195. continue;
  18196. } else if (count < min_count) {
  18197. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18198. } else if (curlen !== 0) {
  18199. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18200. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18201. } else if (count <= 10) {
  18202. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18203. } else {
  18204. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18205. }
  18206. count = 0;
  18207. prevlen = curlen;
  18208. if (nextlen === 0) {
  18209. max_count = 138;
  18210. min_count = 3;
  18211. } else if (curlen === nextlen) {
  18212. max_count = 6;
  18213. min_count = 3;
  18214. } else {
  18215. max_count = 7;
  18216. min_count = 4;
  18217. }
  18218. }
  18219. }
  18220. /* ===========================================================================
  18221. * Send a literal or distance tree in compressed form, using the codes in
  18222. * bl_tree.
  18223. */
  18224. function send_tree(s, tree, max_code)
  18225. // deflate_state *s;
  18226. // ct_data *tree; /* the tree to be scanned */
  18227. // int max_code; /* and its largest code of non zero frequency */
  18228. {
  18229. var n; /* iterates over all tree elements */
  18230. var prevlen = -1; /* last emitted length */
  18231. var curlen; /* length of current code */
  18232. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18233. var count = 0; /* repeat count of the current code */
  18234. var max_count = 7; /* max repeat count */
  18235. var min_count = 4; /* min repeat count */
  18236. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18237. if (nextlen === 0) {
  18238. max_count = 138;
  18239. min_count = 3;
  18240. }
  18241. for (n = 0; n <= max_code; n++) {
  18242. curlen = nextlen;
  18243. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18244. if (++count < max_count && curlen === nextlen) {
  18245. continue;
  18246. } else if (count < min_count) {
  18247. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18248. } else if (curlen !== 0) {
  18249. if (curlen !== prevlen) {
  18250. send_code(s, curlen, s.bl_tree);
  18251. count--;
  18252. }
  18253. //Assert(count >= 3 && count <= 6, " 3_6?");
  18254. send_code(s, REP_3_6, s.bl_tree);
  18255. send_bits(s, count-3, 2);
  18256. } else if (count <= 10) {
  18257. send_code(s, REPZ_3_10, s.bl_tree);
  18258. send_bits(s, count-3, 3);
  18259. } else {
  18260. send_code(s, REPZ_11_138, s.bl_tree);
  18261. send_bits(s, count-11, 7);
  18262. }
  18263. count = 0;
  18264. prevlen = curlen;
  18265. if (nextlen === 0) {
  18266. max_count = 138;
  18267. min_count = 3;
  18268. } else if (curlen === nextlen) {
  18269. max_count = 6;
  18270. min_count = 3;
  18271. } else {
  18272. max_count = 7;
  18273. min_count = 4;
  18274. }
  18275. }
  18276. }
  18277. /* ===========================================================================
  18278. * Construct the Huffman tree for the bit lengths and return the index in
  18279. * bl_order of the last bit length code to send.
  18280. */
  18281. function build_bl_tree(s) {
  18282. var max_blindex; /* index of last bit length code of non zero freq */
  18283. /* Determine the bit length frequencies for literal and distance trees */
  18284. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18285. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18286. /* Build the bit length tree: */
  18287. build_tree(s, s.bl_desc);
  18288. /* opt_len now includes the length of the tree representations, except
  18289. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18290. */
  18291. /* Determine the number of bit length codes to send. The pkzip format
  18292. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18293. * 3 but the actual value used is 4.)
  18294. */
  18295. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18296. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18297. break;
  18298. }
  18299. }
  18300. /* Update opt_len to include the bit length tree and counts */
  18301. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18302. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18303. // s->opt_len, s->static_len));
  18304. return max_blindex;
  18305. }
  18306. /* ===========================================================================
  18307. * Send the header for a block using dynamic Huffman trees: the counts, the
  18308. * lengths of the bit length codes, the literal tree and the distance tree.
  18309. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18310. */
  18311. function send_all_trees(s, lcodes, dcodes, blcodes)
  18312. // deflate_state *s;
  18313. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18314. {
  18315. var rank; /* index in bl_order */
  18316. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18317. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18318. // "too many codes");
  18319. //Tracev((stderr, "\nbl counts: "));
  18320. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18321. send_bits(s, dcodes-1, 5);
  18322. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18323. for (rank = 0; rank < blcodes; rank++) {
  18324. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18325. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18326. }
  18327. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18328. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18329. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18330. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18331. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18332. }
  18333. /* ===========================================================================
  18334. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18335. * - TEXT if the two conditions below are satisfied:
  18336. * a) There are no non-portable control characters belonging to the
  18337. * "black list" (0..6, 14..25, 28..31).
  18338. * b) There is at least one printable character belonging to the
  18339. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18340. * - BINARY otherwise.
  18341. * - The following partially-portable control characters form a
  18342. * "gray list" that is ignored in this detection algorithm:
  18343. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18344. * IN assertion: the fields Freq of dyn_ltree are set.
  18345. */
  18346. function detect_data_type(s) {
  18347. /* black_mask is the bit mask of black-listed bytes
  18348. * set bits 0..6, 14..25, and 28..31
  18349. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18350. */
  18351. var black_mask = 0xf3ffc07f;
  18352. var n;
  18353. /* Check for non-textual ("black-listed") bytes. */
  18354. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18355. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18356. return Z_BINARY;
  18357. }
  18358. }
  18359. /* Check for textual ("white-listed") bytes. */
  18360. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18361. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18362. return Z_TEXT;
  18363. }
  18364. for (n = 32; n < LITERALS; n++) {
  18365. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18366. return Z_TEXT;
  18367. }
  18368. }
  18369. /* There are no "black-listed" or "white-listed" bytes:
  18370. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18371. */
  18372. return Z_BINARY;
  18373. }
  18374. var static_init_done = false;
  18375. /* ===========================================================================
  18376. * Initialize the tree data structures for a new zlib stream.
  18377. */
  18378. function _tr_init(s)
  18379. {
  18380. if (!static_init_done) {
  18381. tr_static_init();
  18382. static_init_done = true;
  18383. }
  18384. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18385. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18386. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18387. s.bi_buf = 0;
  18388. s.bi_valid = 0;
  18389. /* Initialize the first block of the first file: */
  18390. init_block(s);
  18391. }
  18392. /* ===========================================================================
  18393. * Send a stored block
  18394. */
  18395. function _tr_stored_block(s, buf, stored_len, last)
  18396. //DeflateState *s;
  18397. //charf *buf; /* input block */
  18398. //ulg stored_len; /* length of input block */
  18399. //int last; /* one if this is the last block for a file */
  18400. {
  18401. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18402. copy_block(s, buf, stored_len, true); /* with header */
  18403. }
  18404. /* ===========================================================================
  18405. * Send one empty static block to give enough lookahead for inflate.
  18406. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18407. */
  18408. function _tr_align(s) {
  18409. send_bits(s, STATIC_TREES<<1, 3);
  18410. send_code(s, END_BLOCK, static_ltree);
  18411. bi_flush(s);
  18412. }
  18413. /* ===========================================================================
  18414. * Determine the best encoding for the current block: dynamic trees, static
  18415. * trees or store, and output the encoded block to the zip file.
  18416. */
  18417. function _tr_flush_block(s, buf, stored_len, last)
  18418. //DeflateState *s;
  18419. //charf *buf; /* input block, or NULL if too old */
  18420. //ulg stored_len; /* length of input block */
  18421. //int last; /* one if this is the last block for a file */
  18422. {
  18423. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18424. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18425. /* Build the Huffman trees unless a stored block is forced */
  18426. if (s.level > 0) {
  18427. /* Check if the file is binary or text */
  18428. if (s.strm.data_type === Z_UNKNOWN) {
  18429. s.strm.data_type = detect_data_type(s);
  18430. }
  18431. /* Construct the literal and distance trees */
  18432. build_tree(s, s.l_desc);
  18433. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18434. // s->static_len));
  18435. build_tree(s, s.d_desc);
  18436. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18437. // s->static_len));
  18438. /* At this point, opt_len and static_len are the total bit lengths of
  18439. * the compressed block data, excluding the tree representations.
  18440. */
  18441. /* Build the bit length tree for the above two trees, and get the index
  18442. * in bl_order of the last bit length code to send.
  18443. */
  18444. max_blindex = build_bl_tree(s);
  18445. /* Determine the best encoding. Compute the block lengths in bytes. */
  18446. opt_lenb = (s.opt_len+3+7) >>> 3;
  18447. static_lenb = (s.static_len+3+7) >>> 3;
  18448. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18449. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18450. // s->last_lit));
  18451. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18452. } else {
  18453. // Assert(buf != (char*)0, "lost buf");
  18454. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18455. }
  18456. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18457. /* 4: two words for the lengths */
  18458. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18459. * Otherwise we can't have processed more than WSIZE input bytes since
  18460. * the last block flush, because compression would have been
  18461. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18462. * transform a block into a stored block.
  18463. */
  18464. _tr_stored_block(s, buf, stored_len, last);
  18465. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18466. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18467. compress_block(s, static_ltree, static_dtree);
  18468. } else {
  18469. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18470. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18471. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18472. }
  18473. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18474. /* The above check is made mod 2^32, for files larger than 512 MB
  18475. * and uLong implemented on 32 bits.
  18476. */
  18477. init_block(s);
  18478. if (last) {
  18479. bi_windup(s);
  18480. }
  18481. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18482. // s->compressed_len-7*last));
  18483. }
  18484. /* ===========================================================================
  18485. * Save the match info and tally the frequency counts. Return true if
  18486. * the current block must be flushed.
  18487. */
  18488. function _tr_tally(s, dist, lc)
  18489. // deflate_state *s;
  18490. // unsigned dist; /* distance of matched string */
  18491. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18492. {
  18493. //var out_length, in_length, dcode;
  18494. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18495. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18496. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18497. s.last_lit++;
  18498. if (dist === 0) {
  18499. /* lc is the unmatched char */
  18500. s.dyn_ltree[lc*2]/*.Freq*/++;
  18501. } else {
  18502. s.matches++;
  18503. /* Here, lc is the match length - MIN_MATCH */
  18504. dist--; /* dist = match distance - 1 */
  18505. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18506. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18507. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18508. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18509. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18510. }
  18511. // (!) This block is disabled in zlib defailts,
  18512. // don't enable it for binary compatibility
  18513. //#ifdef TRUNCATE_BLOCK
  18514. // /* Try to guess if it is profitable to stop the current block here */
  18515. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18516. // /* Compute an upper bound for the compressed length */
  18517. // out_length = s.last_lit*8;
  18518. // in_length = s.strstart - s.block_start;
  18519. //
  18520. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18521. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18522. // }
  18523. // out_length >>>= 3;
  18524. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18525. // // s->last_lit, in_length, out_length,
  18526. // // 100L - out_length*100L/in_length));
  18527. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18528. // return true;
  18529. // }
  18530. // }
  18531. //#endif
  18532. return (s.last_lit === s.lit_bufsize-1);
  18533. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18534. * on 16 bit machines and because stored blocks are restricted to
  18535. * 64K-1 bytes.
  18536. */
  18537. }
  18538. exports._tr_init = _tr_init;
  18539. exports._tr_stored_block = _tr_stored_block;
  18540. exports._tr_flush_block = _tr_flush_block;
  18541. exports._tr_tally = _tr_tally;
  18542. exports._tr_align = _tr_align;
  18543. },{"../utils/common":52}],64:[function(require,module,exports){
  18544. 'use strict';
  18545. function ZStream() {
  18546. /* next input byte */
  18547. this.input = null; // JS specific, because we have no pointers
  18548. this.next_in = 0;
  18549. /* number of bytes available at input */
  18550. this.avail_in = 0;
  18551. /* total number of input bytes read so far */
  18552. this.total_in = 0;
  18553. /* next output byte should be put there */
  18554. this.output = null; // JS specific, because we have no pointers
  18555. this.next_out = 0;
  18556. /* remaining free space at output */
  18557. this.avail_out = 0;
  18558. /* total number of bytes output so far */
  18559. this.total_out = 0;
  18560. /* last error message, NULL if no error */
  18561. this.msg = ''/*Z_NULL*/;
  18562. /* not visible by applications */
  18563. this.state = null;
  18564. /* best guess about the data type: binary or text */
  18565. this.data_type = 2/*Z_UNKNOWN*/;
  18566. /* adler32 value of the uncompressed data */
  18567. this.adler = 0;
  18568. }
  18569. module.exports = ZStream;
  18570. },{}],65:[function(require,module,exports){
  18571. /* Copyright @ 2015 Atlassian Pty Ltd
  18572. *
  18573. * Licensed under the Apache License, Version 2.0 (the "License");
  18574. * you may not use this file except in compliance with the License.
  18575. * You may obtain a copy of the License at
  18576. *
  18577. * http://www.apache.org/licenses/LICENSE-2.0
  18578. *
  18579. * Unless required by applicable law or agreed to in writing, software
  18580. * distributed under the License is distributed on an "AS IS" BASIS,
  18581. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18582. * See the License for the specific language governing permissions and
  18583. * limitations under the License.
  18584. */
  18585. module.exports = function arrayEquals(array) {
  18586. // if the other array is a falsy value, return
  18587. if (!array)
  18588. return false;
  18589. // compare lengths - can save a lot of time
  18590. if (this.length != array.length)
  18591. return false;
  18592. for (var i = 0, l = this.length; i < l; i++) {
  18593. // Check if we have nested arrays
  18594. if (this[i] instanceof Array && array[i] instanceof Array) {
  18595. // recurse into the nested arrays
  18596. if (!arrayEquals.apply(this[i], [array[i]]))
  18597. return false;
  18598. } else if (this[i] != array[i]) {
  18599. // Warning - two different object instances will never be equal:
  18600. // {x:20} != {x:20}
  18601. return false;
  18602. }
  18603. }
  18604. return true;
  18605. };
  18606. },{}],66:[function(require,module,exports){
  18607. /* Copyright @ 2015 Atlassian Pty Ltd
  18608. *
  18609. * Licensed under the Apache License, Version 2.0 (the "License");
  18610. * you may not use this file except in compliance with the License.
  18611. * You may obtain a copy of the License at
  18612. *
  18613. * http://www.apache.org/licenses/LICENSE-2.0
  18614. *
  18615. * Unless required by applicable law or agreed to in writing, software
  18616. * distributed under the License is distributed on an "AS IS" BASIS,
  18617. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18618. * See the License for the specific language governing permissions and
  18619. * limitations under the License.
  18620. */
  18621. exports.Interop = require('./interop');
  18622. },{"./interop":67}],67:[function(require,module,exports){
  18623. /* Copyright @ 2015 Atlassian Pty Ltd
  18624. *
  18625. * Licensed under the Apache License, Version 2.0 (the "License");
  18626. * you may not use this file except in compliance with the License.
  18627. * You may obtain a copy of the License at
  18628. *
  18629. * http://www.apache.org/licenses/LICENSE-2.0
  18630. *
  18631. * Unless required by applicable law or agreed to in writing, software
  18632. * distributed under the License is distributed on an "AS IS" BASIS,
  18633. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18634. * See the License for the specific language governing permissions and
  18635. * limitations under the License.
  18636. */
  18637. /* global RTCSessionDescription */
  18638. /* jshint -W097 */
  18639. "use strict";
  18640. var transform = require('./transform');
  18641. var arrayEquals = require('./array-equals');
  18642. function Interop() {
  18643. /**
  18644. * This map holds the most recent Unified Plan offer/answer SDP that was
  18645. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18646. * the SDP string as values.
  18647. *
  18648. * @type {{}}
  18649. */
  18650. this.cache = {};
  18651. }
  18652. module.exports = Interop;
  18653. /**
  18654. * Returns the index of the first m-line with the given media type and with a
  18655. * direction which allows sending, in the last Unified Plan description with
  18656. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18657. * answer, or if none of its m-lines with the given type allow sending.
  18658. * @param type the media type ("audio" or "video").
  18659. * @returns {*}
  18660. */
  18661. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18662. if (!this.cache.answer) {
  18663. return null;
  18664. }
  18665. var session = transform.parse(this.cache.answer);
  18666. if (session && session.media && Array.isArray(session.media)){
  18667. for (var i = 0; i < session.media.length; i++) {
  18668. if (session.media[i].type == type &&
  18669. (!session.media[i].direction /* default to sendrecv */ ||
  18670. session.media[i].direction === 'sendrecv' ||
  18671. session.media[i].direction === 'sendonly')){
  18672. return i;
  18673. }
  18674. }
  18675. }
  18676. return null;
  18677. };
  18678. /**
  18679. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18680. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18681. * application.
  18682. *
  18683. * @param desc
  18684. * @returns {*}
  18685. */
  18686. Interop.prototype.toPlanB = function(desc) {
  18687. var self = this;
  18688. //#region Preliminary input validation.
  18689. if (typeof desc !== 'object' || desc === null ||
  18690. typeof desc.sdp !== 'string') {
  18691. console.warn('An empty description was passed as an argument.');
  18692. return desc;
  18693. }
  18694. // Objectify the SDP for easier manipulation.
  18695. var session = transform.parse(desc.sdp);
  18696. // If the SDP contains no media, there's nothing to transform.
  18697. if (typeof session.media === 'undefined' ||
  18698. !Array.isArray(session.media) || session.media.length === 0) {
  18699. console.warn('The description has no media.');
  18700. return desc;
  18701. }
  18702. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18703. // SDP has a video, an audio and a data "channel" at most.
  18704. if (session.media.length <= 3 && session.media.every(function(m) {
  18705. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18706. })) {
  18707. console.warn('This description does not look like Unified Plan.');
  18708. return desc;
  18709. }
  18710. //#endregion
  18711. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18712. var sdp = desc.sdp;
  18713. var rewrite = false;
  18714. for (var i = 0; i < session.media.length; i++) {
  18715. var uLine = session.media[i];
  18716. uLine.rtp.forEach(function(rtp) {
  18717. if (rtp.codec === 'NULL')
  18718. {
  18719. rewrite = true;
  18720. var offer = transform.parse(self.cache['offer']);
  18721. rtp.codec = offer.media[i].rtp[0].codec;
  18722. }
  18723. });
  18724. };
  18725. if (rewrite) {
  18726. sdp = transform.write(session);
  18727. }
  18728. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18729. // -> Unified Plan transformation.
  18730. this.cache[desc.type] = sdp;
  18731. //#region Convert from Unified Plan to Plan B.
  18732. // We rebuild the session.media array.
  18733. var media = session.media;
  18734. session.media = [];
  18735. // Associative array that maps channel types to channel objects for fast
  18736. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18737. // obj.
  18738. var type2bl = {};
  18739. // Used to build the group:BUNDLE value after the channels construction
  18740. // loop.
  18741. var types = [];
  18742. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18743. media.forEach(function(uLine) {
  18744. // rtcp-mux is required in the Plan B SDP.
  18745. if ((typeof uLine.rtcpMux !== 'string' ||
  18746. uLine.rtcpMux !== 'rtcp-mux') &&
  18747. uLine.direction !== 'inactive') {
  18748. throw new Error('Cannot convert to Plan B because m-lines ' +
  18749. 'without the rtcp-mux attribute were found.');
  18750. }
  18751. if (uLine.type === 'application') {
  18752. session.media.push(uLine);
  18753. types.push(uLine.mid);
  18754. return;
  18755. }
  18756. // If we don't have a channel for this uLine.type, then use this
  18757. // uLine as the channel basis.
  18758. if (typeof type2bl[uLine.type] === 'undefined') {
  18759. type2bl[uLine.type] = uLine;
  18760. }
  18761. // Add sources to the channel and handle a=msid.
  18762. if (typeof uLine.sources === 'object') {
  18763. Object.keys(uLine.sources).forEach(function(ssrc) {
  18764. if (typeof type2bl[uLine.type].sources !== 'object')
  18765. type2bl[uLine.type].sources = {};
  18766. // Assign the sources to the channel.
  18767. type2bl[uLine.type].sources[ssrc] =
  18768. uLine.sources[ssrc];
  18769. if (typeof uLine.msid !== 'undefined') {
  18770. // In Plan B the msid is an SSRC attribute. Also, we don't
  18771. // care about the obsolete label and mslabel attributes.
  18772. //
  18773. // Note that it is not guaranteed that the uLine will
  18774. // have an msid. recvonly channels in particular don't have
  18775. // one.
  18776. type2bl[uLine.type].sources[ssrc].msid =
  18777. uLine.msid;
  18778. }
  18779. // NOTE ssrcs in ssrc groups will share msids, as
  18780. // draft-uberti-rtcweb-plan-00 mandates.
  18781. });
  18782. }
  18783. // Add ssrc groups to the channel.
  18784. if (typeof uLine.ssrcGroups !== 'undefined' &&
  18785. Array.isArray(uLine.ssrcGroups)) {
  18786. // Create the ssrcGroups array, if it's not defined.
  18787. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  18788. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  18789. type2bl[uLine.type].ssrcGroups = [];
  18790. }
  18791. type2bl[uLine.type].ssrcGroups =
  18792. type2bl[uLine.type].ssrcGroups.concat(
  18793. uLine.ssrcGroups);
  18794. }
  18795. if (type2bl[uLine.type] === uLine) {
  18796. // Copy ICE related stuff from the principal media line.
  18797. uLine.candidates = media[0].candidates;
  18798. uLine.iceUfrag = media[0].iceUfrag;
  18799. uLine.icePwd = media[0].icePwd;
  18800. uLine.fingerprint = media[0].fingerprint;
  18801. // Plan B mids are in ['audio', 'video', 'data']
  18802. uLine.mid = uLine.type;
  18803. // Plan B doesn't support/need the bundle-only attribute.
  18804. delete uLine.bundleOnly;
  18805. // In Plan B the msid is an SSRC attribute.
  18806. delete uLine.msid;
  18807. // Used to build the group:BUNDLE value after this loop.
  18808. types.push(uLine.type);
  18809. // Add the channel to the new media array.
  18810. session.media.push(uLine);
  18811. }
  18812. });
  18813. // We regenerate the BUNDLE group with the new mids.
  18814. session.groups.some(function(group) {
  18815. if (group.type === 'BUNDLE') {
  18816. group.mids = types.join(' ');
  18817. return true;
  18818. }
  18819. });
  18820. // msid semantic
  18821. session.msidSemantic = {
  18822. semantic: 'WMS',
  18823. token: '*'
  18824. };
  18825. var resStr = transform.write(session);
  18826. return new RTCSessionDescription({
  18827. type: desc.type,
  18828. sdp: resStr
  18829. });
  18830. //#endregion
  18831. };
  18832. /**
  18833. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18834. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18835. * to FF.
  18836. *
  18837. * @param desc
  18838. * @returns {*}
  18839. */
  18840. Interop.prototype.toUnifiedPlan = function(desc) {
  18841. var self = this;
  18842. //#region Preliminary input validation.
  18843. if (typeof desc !== 'object' || desc === null ||
  18844. typeof desc.sdp !== 'string') {
  18845. console.warn('An empty description was passed as an argument.');
  18846. return desc;
  18847. }
  18848. var session = transform.parse(desc.sdp);
  18849. // If the SDP contains no media, there's nothing to transform.
  18850. if (typeof session.media === 'undefined' ||
  18851. !Array.isArray(session.media) || session.media.length === 0) {
  18852. console.warn('The description has no media.');
  18853. return desc;
  18854. }
  18855. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18856. // a video, an audio and a data "channel" at most.
  18857. if (session.media.length > 3 || !session.media.every(function(m) {
  18858. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18859. })) {
  18860. console.warn('This description does not look like Plan B.');
  18861. return desc;
  18862. }
  18863. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18864. var mids = [];
  18865. session.media.forEach(function(m) {
  18866. mids.push(m.mid);
  18867. });
  18868. var hasBundle = false;
  18869. if (typeof session.groups !== 'undefined' &&
  18870. Array.isArray(session.groups)) {
  18871. hasBundle = session.groups.every(function(g) {
  18872. return g.type !== 'BUNDLE' ||
  18873. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18874. });
  18875. }
  18876. if (!hasBundle) {
  18877. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18878. " are not bundled were found.");
  18879. }
  18880. //#endregion
  18881. //#region Convert from Plan B to Unified Plan.
  18882. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18883. // rebuild an equivalent Unified Plan offer/answer.
  18884. //
  18885. // For example, if this is a local answer (in Unified Plan style) that we
  18886. // convert to Plan B prior to handing it over to the application (the
  18887. // PeerConnection wrapper called us, for instance, after a successful
  18888. // createAnswer), we want to remember the m-line at which we've seen the
  18889. // (local) SSRC. That's because when the application wants to do call the
  18890. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18891. // Unified Plan), we need to know to which m-line to assign the (local)
  18892. // SSRC. We also need to know all the other m-lines that the original
  18893. // answer had and include them in the transformed answer as well.
  18894. //
  18895. // Another example is if this is a remote offer that we convert to Plan B
  18896. // prior to giving it to the application, we want to remember the mid at
  18897. // which we've seen the (remote) SSRC.
  18898. //
  18899. // In the iteration that follows, we use the cached Unified Plan (if it
  18900. // exists) to assign mids to ssrcs.
  18901. var cached;
  18902. if (typeof this.cache[desc.type] !== 'undefined') {
  18903. cached = transform.parse(this.cache[desc.type]);
  18904. }
  18905. var recvonlySsrcs = {
  18906. audio: {},
  18907. video: {}
  18908. };
  18909. // A helper map that sends mids to m-line objects. We use it later to
  18910. // rebuild the Unified Plan style session.media array.
  18911. var mid2ul = {};
  18912. session.media.forEach(function(bLine) {
  18913. if ((typeof bLine.rtcpMux !== 'string' ||
  18914. bLine.rtcpMux !== 'rtcp-mux') &&
  18915. bLine.direction !== 'inactive') {
  18916. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18917. "without the rtcp-mux attribute were found.");
  18918. }
  18919. if (bLine.type === 'application') {
  18920. mid2ul[bLine.mid] = bLine;
  18921. return;
  18922. }
  18923. // With rtcp-mux and bundle all the channels should have the same ICE
  18924. // stuff.
  18925. var sources = bLine.sources;
  18926. var ssrcGroups = bLine.ssrcGroups;
  18927. var candidates = bLine.candidates;
  18928. var iceUfrag = bLine.iceUfrag;
  18929. var icePwd = bLine.icePwd;
  18930. var fingerprint = bLine.fingerprint;
  18931. var port = bLine.port;
  18932. // We'll use the "bLine" object as a prototype for each new "mLine"
  18933. // that we create, but first we need to clean it up a bit.
  18934. delete bLine.sources;
  18935. delete bLine.ssrcGroups;
  18936. delete bLine.candidates;
  18937. delete bLine.iceUfrag;
  18938. delete bLine.icePwd;
  18939. delete bLine.fingerprint;
  18940. delete bLine.port;
  18941. delete bLine.mid;
  18942. // inverted ssrc group map
  18943. var ssrc2group = {};
  18944. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18945. ssrcGroups.forEach(function (ssrcGroup) {
  18946. // TODO(gp) find out how to receive simulcast with FF. For the
  18947. // time being, hide it.
  18948. if (ssrcGroup.semantics === 'SIM') {
  18949. return;
  18950. }
  18951. // XXX This might brake if an SSRC is in more than one group
  18952. // for some reason.
  18953. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18954. Array.isArray(ssrcGroup.ssrcs)) {
  18955. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18956. if (typeof ssrc2group[ssrc] === 'undefined') {
  18957. ssrc2group[ssrc] = [];
  18958. }
  18959. ssrc2group[ssrc].push(ssrcGroup);
  18960. });
  18961. }
  18962. });
  18963. }
  18964. // ssrc to m-line index.
  18965. var ssrc2ml = {};
  18966. if (typeof sources === 'object') {
  18967. // Explode the Plan B channel sources with one m-line per source.
  18968. Object.keys(sources).forEach(function(ssrc) {
  18969. // The (unified) m-line for this SSRC. We either create it from
  18970. // scratch or, if it's a grouped SSRC, we re-use a related
  18971. // mline. In other words, if the source is grouped with another
  18972. // source, put the two together in the same m-line.
  18973. var uLine;
  18974. // We assume here that we are the answerer in the O/A, so any
  18975. // offers which we translate come from the remote side, while
  18976. // answers are local. So the check below is to make that we
  18977. // handle receive-only SSRCs in a special way only if they come
  18978. // from the remote side.
  18979. if (desc.type==='offer') {
  18980. // We want to detect SSRCs which are used by a remote peer
  18981. // in an m-line with direction=recvonly (i.e. they are
  18982. // being used for RTCP only).
  18983. // This information would have gotten lost if the remote
  18984. // peer used Unified Plan and their local description was
  18985. // translated to Plan B. So we use the lack of an MSID
  18986. // attribute to deduce a "receive only" SSRC.
  18987. if (!sources[ssrc].msid) {
  18988. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  18989. // Receive-only SSRCs must not create new m-lines. We
  18990. // will assign them to an existing m-line later.
  18991. return;
  18992. }
  18993. }
  18994. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  18995. Array.isArray(ssrc2group[ssrc])) {
  18996. ssrc2group[ssrc].some(function (ssrcGroup) {
  18997. // ssrcGroup.ssrcs *is* an Array, no need to check
  18998. // again here.
  18999. return ssrcGroup.ssrcs.some(function (related) {
  19000. if (typeof ssrc2ml[related] === 'object') {
  19001. uLine = ssrc2ml[related];
  19002. return true;
  19003. }
  19004. });
  19005. });
  19006. }
  19007. if (typeof uLine === 'object') {
  19008. // the m-line already exists. Just add the source.
  19009. uLine.sources[ssrc] = sources[ssrc];
  19010. delete sources[ssrc].msid;
  19011. } else {
  19012. // Use the "bLine" as a prototype for the "uLine".
  19013. uLine = Object.create(bLine);
  19014. ssrc2ml[ssrc] = uLine;
  19015. if (typeof sources[ssrc].msid !== 'undefined') {
  19016. // Assign the msid of the source to the m-line. Note
  19017. // that it is not guaranteed that the source will have
  19018. // msid. In particular "recvonly" sources don't have an
  19019. // msid. Note that "recvonly" is a term only defined
  19020. // for m-lines.
  19021. uLine.msid = sources[ssrc].msid;
  19022. uLine.direction = 'sendrecv';
  19023. delete sources[ssrc].msid;
  19024. }
  19025. // We assign one SSRC per media line.
  19026. uLine.sources = {};
  19027. uLine.sources[ssrc] = sources[ssrc];
  19028. uLine.ssrcGroups = ssrc2group[ssrc];
  19029. // Use the cached Unified Plan SDP (if it exists) to assign
  19030. // SSRCs to mids.
  19031. if (typeof cached !== 'undefined' &&
  19032. typeof cached.media !== 'undefined' &&
  19033. Array.isArray(cached.media)) {
  19034. cached.media.forEach(function (m) {
  19035. if (typeof m.sources === 'object') {
  19036. Object.keys(m.sources).forEach(function (s) {
  19037. if (s === ssrc) {
  19038. uLine.mid = m.mid;
  19039. }
  19040. });
  19041. }
  19042. });
  19043. }
  19044. if (typeof uLine.mid === 'undefined') {
  19045. // If this is an SSRC that we see for the first time
  19046. // assign it a new mid. This is typically the case when
  19047. // this method is called to transform a remote
  19048. // description for the first time or when there is a
  19049. // new SSRC in the remote description because a new
  19050. // peer has joined the conference. Local SSRCs should
  19051. // have already been added to the map in the toPlanB
  19052. // method.
  19053. //
  19054. // Because FF generates answers in Unified Plan style,
  19055. // we MUST already have a cached answer with all the
  19056. // local SSRCs mapped to some m-line/mid.
  19057. if (desc.type === 'answer') {
  19058. throw new Error("An unmapped SSRC was found.");
  19059. }
  19060. uLine.mid = [bLine.type, '-', ssrc].join('');
  19061. }
  19062. // Include the candidates in the 1st media line.
  19063. uLine.candidates = candidates;
  19064. uLine.iceUfrag = iceUfrag;
  19065. uLine.icePwd = icePwd;
  19066. uLine.fingerprint = fingerprint;
  19067. uLine.port = port;
  19068. mid2ul[uLine.mid] = uLine;
  19069. }
  19070. });
  19071. }
  19072. });
  19073. // Rebuild the media array in the right order and add the missing mLines
  19074. // (missing from the Plan B SDP).
  19075. session.media = [];
  19076. mids = []; // reuse
  19077. if (desc.type === 'answer') {
  19078. // The media lines in the answer must match the media lines in the
  19079. // offer. The order is important too. Here we assume that Firefox is
  19080. // the answerer, so we merely have to use the reconstructed (unified)
  19081. // answer to update the cached (unified) answer accordingly.
  19082. //
  19083. // In the general case, one would have to use the cached (unified)
  19084. // offer to find the m-lines that are missing from the reconstructed
  19085. // answer, potentially grabbing them from the cached (unified) answer.
  19086. // One has to be careful with this approach because inactive m-lines do
  19087. // not always have an mid, making it tricky (impossible?) to find where
  19088. // exactly and which m-lines are missing from the reconstructed answer.
  19089. for (var i = 0; i < cached.media.length; i++) {
  19090. var uLine = cached.media[i];
  19091. if (typeof mid2ul[uLine.mid] === 'undefined') {
  19092. // The mid isn't in the reconstructed (unified) answer.
  19093. // This is either a (unified) m-line containing a remote
  19094. // track only, or a (unified) m-line containing a remote
  19095. // track and a local track that has been removed.
  19096. // In either case, it MUST exist in the cached
  19097. // (unified) answer.
  19098. //
  19099. // In case this is a removed local track, clean-up
  19100. // the (unified) m-line and make sure it's 'recvonly' or
  19101. // 'inactive'.
  19102. delete uLine.msid;
  19103. delete uLine.sources;
  19104. delete uLine.ssrcGroups;
  19105. if (!uLine.direction
  19106. || uLine.direction === 'sendrecv')
  19107. uLine.direction = 'recvonly';
  19108. else if (uLine.direction === 'sendonly')
  19109. uLine.direction = 'inactive';
  19110. } else {
  19111. // This is an (unified) m-line/channel that contains a local
  19112. // track (sendrecv or sendonly channel) or it's a unified
  19113. // recvonly m-line/channel. In either case, since we're
  19114. // going from PlanB -> Unified Plan this m-line MUST
  19115. // exist in the cached answer.
  19116. }
  19117. session.media.push(uLine);
  19118. if (typeof uLine.mid === 'string') {
  19119. // inactive lines don't/may not have an mid.
  19120. mids.push(uLine.mid);
  19121. }
  19122. }
  19123. } else {
  19124. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  19125. // under any circumstances. If we are no longer interested in sending a
  19126. // track, we just remove the msid and ssrc attributes and set it to
  19127. // either a=recvonly (as the reofferer, we must use recvonly if the
  19128. // other side was previously sending on the m-section, but we can also
  19129. // leave the possibility open if it wasn't previously in use), or
  19130. // a=inactive.
  19131. if (typeof cached !== 'undefined' &&
  19132. typeof cached.media !== 'undefined' &&
  19133. Array.isArray(cached.media)) {
  19134. cached.media.forEach(function(uLine) {
  19135. mids.push(uLine.mid);
  19136. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  19137. session.media.push(mid2ul[uLine.mid]);
  19138. } else {
  19139. delete uLine.msid;
  19140. delete uLine.sources;
  19141. delete uLine.ssrcGroups;
  19142. if (!uLine.direction
  19143. || uLine.direction === 'sendrecv')
  19144. uLine.direction = 'recvonly';
  19145. if (!uLine.direction
  19146. || uLine.direction === 'sendonly')
  19147. uLine.direction = 'inactive';
  19148. session.media.push(uLine);
  19149. }
  19150. });
  19151. }
  19152. // Add all the remaining (new) m-lines of the transformed SDP.
  19153. Object.keys(mid2ul).forEach(function(mid) {
  19154. if (mids.indexOf(mid) === -1) {
  19155. mids.push(mid);
  19156. if (mid2ul[mid].direction === 'recvonly') {
  19157. // This is a remote recvonly channel. Add its SSRC to the
  19158. // appropriate sendrecv or sendonly channel.
  19159. // TODO(gp) what if we don't have sendrecv/sendonly
  19160. // channel?
  19161. session.media.some(function (uLine) {
  19162. if ((uLine.direction === 'sendrecv' ||
  19163. uLine.direction === 'sendonly') &&
  19164. uLine.type === mid2ul[mid].type) {
  19165. // mid2ul[mid] shouldn't have any ssrc-groups
  19166. Object.keys(mid2ul[mid].sources).forEach(
  19167. function (ssrc) {
  19168. uLine.sources[ssrc] =
  19169. mid2ul[mid].sources[ssrc];
  19170. });
  19171. return true;
  19172. }
  19173. });
  19174. } else {
  19175. session.media.push(mid2ul[mid]);
  19176. }
  19177. }
  19178. });
  19179. }
  19180. // After we have constructed the Plan Unified m-lines we can figure out
  19181. // where (in which m-line) to place the 'recvonly SSRCs'.
  19182. // Note: we assume here that we are the answerer in the O/A, so any offers
  19183. // which we translate come from the remote side, while answers are local
  19184. // (and so our last local description is cached as an 'answer').
  19185. ["audio", "video"].forEach(function (type) {
  19186. if (!session || !session.media || !Array.isArray(session.media))
  19187. return;
  19188. var idx = null;
  19189. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19190. idx = self.getFirstSendingIndexFromAnswer(type);
  19191. if (idx === null){
  19192. // If this is the first offer we receive, we don't have a
  19193. // cached answer. Assume that we will be sending media using
  19194. // the first m-line for each media type.
  19195. for (var i = 0; i < session.media.length; i++) {
  19196. if (session.media[i].type === type) {
  19197. idx = i;
  19198. break;
  19199. }
  19200. }
  19201. }
  19202. }
  19203. if (idx && session.media.length > idx) {
  19204. var mLine = session.media[idx];
  19205. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19206. if (mLine.sources && mLine.sources[ssrc]) {
  19207. console.warn("Replacing an existing SSRC.");
  19208. }
  19209. if (!mLine.sources) {
  19210. mLine.sources = {};
  19211. }
  19212. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19213. });
  19214. }
  19215. });
  19216. // We regenerate the BUNDLE group (since we regenerated the mids)
  19217. session.groups.some(function(group) {
  19218. if (group.type === 'BUNDLE') {
  19219. group.mids = mids.join(' ');
  19220. return true;
  19221. }
  19222. });
  19223. // msid semantic
  19224. session.msidSemantic = {
  19225. semantic: 'WMS',
  19226. token: '*'
  19227. };
  19228. var resStr = transform.write(session);
  19229. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19230. // function.
  19231. this.cache[desc.type] = resStr;
  19232. return new RTCSessionDescription({
  19233. type: desc.type,
  19234. sdp: resStr
  19235. });
  19236. //#endregion
  19237. };
  19238. },{"./array-equals":65,"./transform":68}],68:[function(require,module,exports){
  19239. /* Copyright @ 2015 Atlassian Pty Ltd
  19240. *
  19241. * Licensed under the Apache License, Version 2.0 (the "License");
  19242. * you may not use this file except in compliance with the License.
  19243. * You may obtain a copy of the License at
  19244. *
  19245. * http://www.apache.org/licenses/LICENSE-2.0
  19246. *
  19247. * Unless required by applicable law or agreed to in writing, software
  19248. * distributed under the License is distributed on an "AS IS" BASIS,
  19249. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19250. * See the License for the specific language governing permissions and
  19251. * limitations under the License.
  19252. */
  19253. var transform = require('sdp-transform');
  19254. exports.write = function(session, opts) {
  19255. if (typeof session !== 'undefined' &&
  19256. typeof session.media !== 'undefined' &&
  19257. Array.isArray(session.media)) {
  19258. session.media.forEach(function (mLine) {
  19259. // expand sources to ssrcs
  19260. if (typeof mLine.sources !== 'undefined' &&
  19261. Object.keys(mLine.sources).length !== 0) {
  19262. mLine.ssrcs = [];
  19263. Object.keys(mLine.sources).forEach(function (ssrc) {
  19264. var source = mLine.sources[ssrc];
  19265. Object.keys(source).forEach(function (attribute) {
  19266. mLine.ssrcs.push({
  19267. id: ssrc,
  19268. attribute: attribute,
  19269. value: source[attribute]
  19270. });
  19271. });
  19272. });
  19273. delete mLine.sources;
  19274. }
  19275. // join ssrcs in ssrc groups
  19276. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19277. Array.isArray(mLine.ssrcGroups)) {
  19278. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19279. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19280. Array.isArray(ssrcGroup.ssrcs)) {
  19281. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19282. }
  19283. });
  19284. }
  19285. });
  19286. }
  19287. // join group mids
  19288. if (typeof session !== 'undefined' &&
  19289. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19290. session.groups.forEach(function (g) {
  19291. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19292. g.mids = g.mids.join(' ');
  19293. }
  19294. });
  19295. }
  19296. return transform.write(session, opts);
  19297. };
  19298. exports.parse = function(sdp) {
  19299. var session = transform.parse(sdp);
  19300. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19301. Array.isArray(session.media)) {
  19302. session.media.forEach(function (mLine) {
  19303. // group sources attributes by ssrc
  19304. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19305. mLine.sources = {};
  19306. mLine.ssrcs.forEach(function (ssrc) {
  19307. if (!mLine.sources[ssrc.id])
  19308. mLine.sources[ssrc.id] = {};
  19309. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19310. });
  19311. delete mLine.ssrcs;
  19312. }
  19313. // split ssrcs in ssrc groups
  19314. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19315. Array.isArray(mLine.ssrcGroups)) {
  19316. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19317. if (typeof ssrcGroup.ssrcs === 'string') {
  19318. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19319. }
  19320. });
  19321. }
  19322. });
  19323. }
  19324. // split group mids
  19325. if (typeof session !== 'undefined' &&
  19326. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19327. session.groups.forEach(function (g) {
  19328. if (typeof g.mids === 'string') {
  19329. g.mids = g.mids.split(' ');
  19330. }
  19331. });
  19332. }
  19333. return session;
  19334. };
  19335. },{"sdp-transform":70}],69:[function(require,module,exports){
  19336. var grammar = module.exports = {
  19337. v: [{
  19338. name: 'version',
  19339. reg: /^(\d*)$/
  19340. }],
  19341. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19342. // NB: sessionId will be a String in most cases because it is huge
  19343. name: 'origin',
  19344. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19345. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19346. format: "%s %s %d %s IP%d %s"
  19347. }],
  19348. // default parsing of these only (though some of these feel outdated)
  19349. s: [{ name: 'name' }],
  19350. i: [{ name: 'description' }],
  19351. u: [{ name: 'uri' }],
  19352. e: [{ name: 'email' }],
  19353. p: [{ name: 'phone' }],
  19354. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19355. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19356. //k: [{}], // outdated thing ignored
  19357. t: [{ //t=0 0
  19358. name: 'timing',
  19359. reg: /^(\d*) (\d*)/,
  19360. names: ['start', 'stop'],
  19361. format: "%d %d"
  19362. }],
  19363. c: [{ //c=IN IP4 10.47.197.26
  19364. name: 'connection',
  19365. reg: /^IN IP(\d) (\S*)/,
  19366. names: ['version', 'ip'],
  19367. format: "IN IP%d %s"
  19368. }],
  19369. b: [{ //b=AS:4000
  19370. push: 'bandwidth',
  19371. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19372. names: ['type', 'limit'],
  19373. format: "%s:%s"
  19374. }],
  19375. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19376. // NB: special - pushes to session
  19377. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19378. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19379. names: ['type', 'port', 'protocol', 'payloads'],
  19380. format: "%s %d %s %s"
  19381. }],
  19382. a: [
  19383. { //a=rtpmap:110 opus/48000/2
  19384. push: 'rtp',
  19385. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  19386. names: ['payload', 'codec', 'rate', 'encoding'],
  19387. format: function (o) {
  19388. return (o.encoding) ?
  19389. "rtpmap:%d %s/%s/%s":
  19390. o.rate ?
  19391. "rtpmap:%d %s/%s":
  19392. "rtpmap:%d %s";
  19393. }
  19394. },
  19395. {
  19396. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19397. //a=fmtp:111 minptime=10; useinbandfec=1
  19398. push: 'fmtp',
  19399. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19400. names: ['payload', 'config'],
  19401. format: "fmtp:%d %s"
  19402. },
  19403. { //a=control:streamid=0
  19404. name: 'control',
  19405. reg: /^control:(.*)/,
  19406. format: "control:%s"
  19407. },
  19408. { //a=rtcp:65179 IN IP4 193.84.77.194
  19409. name: 'rtcp',
  19410. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19411. names: ['port', 'netType', 'ipVer', 'address'],
  19412. format: function (o) {
  19413. return (o.address != null) ?
  19414. "rtcp:%d %s IP%d %s":
  19415. "rtcp:%d";
  19416. }
  19417. },
  19418. { //a=rtcp-fb:98 trr-int 100
  19419. push: 'rtcpFbTrrInt',
  19420. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19421. names: ['payload', 'value'],
  19422. format: "rtcp-fb:%d trr-int %d"
  19423. },
  19424. { //a=rtcp-fb:98 nack rpsi
  19425. push: 'rtcpFb',
  19426. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19427. names: ['payload', 'type', 'subtype'],
  19428. format: function (o) {
  19429. return (o.subtype != null) ?
  19430. "rtcp-fb:%s %s %s":
  19431. "rtcp-fb:%s %s";
  19432. }
  19433. },
  19434. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19435. //a=extmap:1/recvonly URI-gps-string
  19436. push: 'ext',
  19437. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19438. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19439. format: function (o) {
  19440. return (o.config != null) ?
  19441. "extmap:%s %s %s":
  19442. "extmap:%s %s";
  19443. }
  19444. },
  19445. {
  19446. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19447. push: 'crypto',
  19448. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19449. names: ['id', 'suite', 'config', 'sessionConfig'],
  19450. format: function (o) {
  19451. return (o.sessionConfig != null) ?
  19452. "crypto:%d %s %s %s":
  19453. "crypto:%d %s %s";
  19454. }
  19455. },
  19456. { //a=setup:actpass
  19457. name: 'setup',
  19458. reg: /^setup:(\w*)/,
  19459. format: "setup:%s"
  19460. },
  19461. { //a=mid:1
  19462. name: 'mid',
  19463. reg: /^mid:([^\s]*)/,
  19464. format: "mid:%s"
  19465. },
  19466. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19467. name: 'msid',
  19468. reg: /^msid:(.*)/,
  19469. format: "msid:%s"
  19470. },
  19471. { //a=ptime:20
  19472. name: 'ptime',
  19473. reg: /^ptime:(\d*)/,
  19474. format: "ptime:%d"
  19475. },
  19476. { //a=maxptime:60
  19477. name: 'maxptime',
  19478. reg: /^maxptime:(\d*)/,
  19479. format: "maxptime:%d"
  19480. },
  19481. { //a=sendrecv
  19482. name: 'direction',
  19483. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19484. },
  19485. { //a=ice-lite
  19486. name: 'icelite',
  19487. reg: /^(ice-lite)/
  19488. },
  19489. { //a=ice-ufrag:F7gI
  19490. name: 'iceUfrag',
  19491. reg: /^ice-ufrag:(\S*)/,
  19492. format: "ice-ufrag:%s"
  19493. },
  19494. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19495. name: 'icePwd',
  19496. reg: /^ice-pwd:(\S*)/,
  19497. format: "ice-pwd:%s"
  19498. },
  19499. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19500. name: 'fingerprint',
  19501. reg: /^fingerprint:(\S*) (\S*)/,
  19502. names: ['type', 'hash'],
  19503. format: "fingerprint:%s %s"
  19504. },
  19505. {
  19506. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19507. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19508. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19509. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  19510. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  19511. push:'candidates',
  19512. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  19513. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  19514. format: function (o) {
  19515. var str = "candidate:%s %d %s %d %s %d typ %s";
  19516. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19517. // NB: candidate has three optional chunks, so %void middles one if it's missing
  19518. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  19519. if (o.generation != null) {
  19520. str += " generation %d";
  19521. }
  19522. return str;
  19523. }
  19524. },
  19525. { //a=end-of-candidates (keep after the candidates line for readability)
  19526. name: 'endOfCandidates',
  19527. reg: /^(end-of-candidates)/
  19528. },
  19529. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19530. name: 'remoteCandidates',
  19531. reg: /^remote-candidates:(.*)/,
  19532. format: "remote-candidates:%s"
  19533. },
  19534. { //a=ice-options:google-ice
  19535. name: 'iceOptions',
  19536. reg: /^ice-options:(\S*)/,
  19537. format: "ice-options:%s"
  19538. },
  19539. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19540. push: "ssrcs",
  19541. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19542. names: ['id', 'attribute', 'value'],
  19543. format: "ssrc:%d %s:%s"
  19544. },
  19545. { //a=ssrc-group:FEC 1 2
  19546. push: "ssrcGroups",
  19547. reg: /^ssrc-group:(\w*) (.*)/,
  19548. names: ['semantics', 'ssrcs'],
  19549. format: "ssrc-group:%s %s"
  19550. },
  19551. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19552. name: "msidSemantic",
  19553. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19554. names: ['semantic', 'token'],
  19555. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19556. },
  19557. { //a=group:BUNDLE audio video
  19558. push: 'groups',
  19559. reg: /^group:(\w*) (.*)/,
  19560. names: ['type', 'mids'],
  19561. format: "group:%s %s"
  19562. },
  19563. { //a=rtcp-mux
  19564. name: 'rtcpMux',
  19565. reg: /^(rtcp-mux)/
  19566. },
  19567. { //a=rtcp-rsize
  19568. name: 'rtcpRsize',
  19569. reg: /^(rtcp-rsize)/
  19570. },
  19571. { // any a= that we don't understand is kepts verbatim on media.invalid
  19572. push: 'invalid',
  19573. names: ["value"]
  19574. }
  19575. ]
  19576. };
  19577. // set sensible defaults to avoid polluting the grammar with boring details
  19578. Object.keys(grammar).forEach(function (key) {
  19579. var objs = grammar[key];
  19580. objs.forEach(function (obj) {
  19581. if (!obj.reg) {
  19582. obj.reg = /(.*)/;
  19583. }
  19584. if (!obj.format) {
  19585. obj.format = "%s";
  19586. }
  19587. });
  19588. });
  19589. },{}],70:[function(require,module,exports){
  19590. var parser = require('./parser');
  19591. var writer = require('./writer');
  19592. exports.write = writer;
  19593. exports.parse = parser.parse;
  19594. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19595. exports.parsePayloads = parser.parsePayloads;
  19596. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19597. },{"./parser":71,"./writer":72}],71:[function(require,module,exports){
  19598. var toIntIfInt = function (v) {
  19599. return String(Number(v)) === v ? Number(v) : v;
  19600. };
  19601. var attachProperties = function (match, location, names, rawName) {
  19602. if (rawName && !names) {
  19603. location[rawName] = toIntIfInt(match[1]);
  19604. }
  19605. else {
  19606. for (var i = 0; i < names.length; i += 1) {
  19607. if (match[i+1] != null) {
  19608. location[names[i]] = toIntIfInt(match[i+1]);
  19609. }
  19610. }
  19611. }
  19612. };
  19613. var parseReg = function (obj, location, content) {
  19614. var needsBlank = obj.name && obj.names;
  19615. if (obj.push && !location[obj.push]) {
  19616. location[obj.push] = [];
  19617. }
  19618. else if (needsBlank && !location[obj.name]) {
  19619. location[obj.name] = {};
  19620. }
  19621. var keyLocation = obj.push ?
  19622. {} : // blank object that will be pushed
  19623. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19624. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19625. if (obj.push) {
  19626. location[obj.push].push(keyLocation);
  19627. }
  19628. };
  19629. var grammar = require('./grammar');
  19630. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19631. exports.parse = function (sdp) {
  19632. var session = {}
  19633. , media = []
  19634. , location = session; // points at where properties go under (one of the above)
  19635. // parse lines we understand
  19636. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19637. var type = l[0];
  19638. var content = l.slice(2);
  19639. if (type === 'm') {
  19640. media.push({rtp: [], fmtp: []});
  19641. location = media[media.length-1]; // point at latest media line
  19642. }
  19643. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19644. var obj = grammar[type][j];
  19645. if (obj.reg.test(content)) {
  19646. return parseReg(obj, location, content);
  19647. }
  19648. }
  19649. });
  19650. session.media = media; // link it up
  19651. return session;
  19652. };
  19653. var fmtpReducer = function (acc, expr) {
  19654. var s = expr.split('=');
  19655. if (s.length === 2) {
  19656. acc[s[0]] = toIntIfInt(s[1]);
  19657. }
  19658. return acc;
  19659. };
  19660. exports.parseFmtpConfig = function (str) {
  19661. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  19662. };
  19663. exports.parsePayloads = function (str) {
  19664. return str.split(' ').map(Number);
  19665. };
  19666. exports.parseRemoteCandidates = function (str) {
  19667. var candidates = [];
  19668. var parts = str.split(' ').map(toIntIfInt);
  19669. for (var i = 0; i < parts.length; i += 3) {
  19670. candidates.push({
  19671. component: parts[i],
  19672. ip: parts[i + 1],
  19673. port: parts[i + 2]
  19674. });
  19675. }
  19676. return candidates;
  19677. };
  19678. },{"./grammar":69}],72:[function(require,module,exports){
  19679. var grammar = require('./grammar');
  19680. // customized util.format - discards excess arguments and can void middle ones
  19681. var formatRegExp = /%[sdv%]/g;
  19682. var format = function (formatStr) {
  19683. var i = 1;
  19684. var args = arguments;
  19685. var len = args.length;
  19686. return formatStr.replace(formatRegExp, function (x) {
  19687. if (i >= len) {
  19688. return x; // missing argument
  19689. }
  19690. var arg = args[i];
  19691. i += 1;
  19692. switch (x) {
  19693. case '%%':
  19694. return '%';
  19695. case '%s':
  19696. return String(arg);
  19697. case '%d':
  19698. return Number(arg);
  19699. case '%v':
  19700. return '';
  19701. }
  19702. });
  19703. // NB: we discard excess arguments - they are typically undefined from makeLine
  19704. };
  19705. var makeLine = function (type, obj, location) {
  19706. var str = obj.format instanceof Function ?
  19707. (obj.format(obj.push ? location : location[obj.name])) :
  19708. obj.format;
  19709. var args = [type + '=' + str];
  19710. if (obj.names) {
  19711. for (var i = 0; i < obj.names.length; i += 1) {
  19712. var n = obj.names[i];
  19713. if (obj.name) {
  19714. args.push(location[obj.name][n]);
  19715. }
  19716. else { // for mLine and push attributes
  19717. args.push(location[obj.names[i]]);
  19718. }
  19719. }
  19720. }
  19721. else {
  19722. args.push(location[obj.name]);
  19723. }
  19724. return format.apply(null, args);
  19725. };
  19726. // RFC specified order
  19727. // TODO: extend this with all the rest
  19728. var defaultOuterOrder = [
  19729. 'v', 'o', 's', 'i',
  19730. 'u', 'e', 'p', 'c',
  19731. 'b', 't', 'r', 'z', 'a'
  19732. ];
  19733. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19734. module.exports = function (session, opts) {
  19735. opts = opts || {};
  19736. // ensure certain properties exist
  19737. if (session.version == null) {
  19738. session.version = 0; // "v=0" must be there (only defined version atm)
  19739. }
  19740. if (session.name == null) {
  19741. session.name = " "; // "s= " must be there if no meaningful name set
  19742. }
  19743. session.media.forEach(function (mLine) {
  19744. if (mLine.payloads == null) {
  19745. mLine.payloads = "";
  19746. }
  19747. });
  19748. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19749. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19750. var sdp = [];
  19751. // loop through outerOrder for matching properties on session
  19752. outerOrder.forEach(function (type) {
  19753. grammar[type].forEach(function (obj) {
  19754. if (obj.name in session && session[obj.name] != null) {
  19755. sdp.push(makeLine(type, obj, session));
  19756. }
  19757. else if (obj.push in session && session[obj.push] != null) {
  19758. session[obj.push].forEach(function (el) {
  19759. sdp.push(makeLine(type, obj, el));
  19760. });
  19761. }
  19762. });
  19763. });
  19764. // then for each media line, follow the innerOrder
  19765. session.media.forEach(function (mLine) {
  19766. sdp.push(makeLine('m', grammar.m[0], mLine));
  19767. innerOrder.forEach(function (type) {
  19768. grammar[type].forEach(function (obj) {
  19769. if (obj.name in mLine && mLine[obj.name] != null) {
  19770. sdp.push(makeLine(type, obj, mLine));
  19771. }
  19772. else if (obj.push in mLine && mLine[obj.push] != null) {
  19773. mLine[obj.push].forEach(function (el) {
  19774. sdp.push(makeLine(type, obj, el));
  19775. });
  19776. }
  19777. });
  19778. });
  19779. });
  19780. return sdp.join('\r\n') + '\r\n';
  19781. };
  19782. },{"./grammar":69}],73:[function(require,module,exports){
  19783. /* Copyright @ 2015 Atlassian Pty Ltd
  19784. *
  19785. * Licensed under the Apache License, Version 2.0 (the "License");
  19786. * you may not use this file except in compliance with the License.
  19787. * You may obtain a copy of the License at
  19788. *
  19789. * http://www.apache.org/licenses/LICENSE-2.0
  19790. *
  19791. * Unless required by applicable law or agreed to in writing, software
  19792. * distributed under the License is distributed on an "AS IS" BASIS,
  19793. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19794. * See the License for the specific language governing permissions and
  19795. * limitations under the License.
  19796. */
  19797. var transform = require('sdp-transform');
  19798. var transformUtils = require('./transform-utils');
  19799. var parseSsrcs = transformUtils.parseSsrcs;
  19800. var writeSsrcs = transformUtils.writeSsrcs;
  19801. //region Constants
  19802. var DEFAULT_NUM_OF_LAYERS = 3;
  19803. //endregion
  19804. //region Ctor
  19805. function Simulcast(options) {
  19806. this.options = options ? options : {};
  19807. if (!this.options.numOfLayers) {
  19808. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  19809. }
  19810. this.layers = [];
  19811. }
  19812. //endregion
  19813. //region Stateless private utility functions
  19814. /**
  19815. * Returns a random integer between min (included) and max (excluded)
  19816. * Using Math.round() gives a non-uniform distribution!
  19817. * @returns {number}
  19818. */
  19819. function generateSSRC() {
  19820. var min = 0, max = 0xffffffff;
  19821. return Math.floor(Math.random() * (max - min)) + min;
  19822. };
  19823. function processVideo(session, action) {
  19824. if (session == null || !Array.isArray(session.media)) {
  19825. return;
  19826. }
  19827. session.media.forEach(function (mLine) {
  19828. if (mLine.type === 'video') {
  19829. action(mLine);
  19830. }
  19831. });
  19832. }
  19833. function validateDescription(desc)
  19834. {
  19835. return desc && desc != null
  19836. && desc.type && desc.type != ''
  19837. && desc.sdp && desc.sdp != '';
  19838. }
  19839. function explodeRemoteSimulcast(mLine) {
  19840. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19841. return;
  19842. }
  19843. var sources = parseSsrcs(mLine);
  19844. var order = [];
  19845. // Find the SIM group and explode its sources.
  19846. var j = mLine.ssrcGroups.length;
  19847. while (j--) {
  19848. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  19849. continue;
  19850. }
  19851. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  19852. for (var i = 0; i < simulcastSsrcs.length; i++) {
  19853. var ssrc = simulcastSsrcs[i];
  19854. order.push(ssrc);
  19855. var parts = sources[ssrc].msid.split(' ');
  19856. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  19857. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  19858. // Remove all the groups that this SSRC participates in.
  19859. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19860. if (relatedGroup.semantics === 'SIM') {
  19861. return;
  19862. }
  19863. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19864. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19865. return;
  19866. }
  19867. // Nuke all the related SSRCs.
  19868. relatedSsrcs.forEach(function (relatedSSRC) {
  19869. sources[relatedSSRC].msid = sources[ssrc].msid;
  19870. sources[relatedSSRC].cname = sources[ssrc].cname;
  19871. if (relatedSSRC !== ssrc) {
  19872. order.push(relatedSSRC);
  19873. }
  19874. });
  19875. // Schedule the related group for nuking.
  19876. })
  19877. }
  19878. mLine.ssrcs = writeSsrcs(sources, order);
  19879. mLine.ssrcGroups.splice(j, 1);
  19880. };
  19881. }
  19882. function implodeRemoteSimulcast(mLine) {
  19883. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19884. console.debug('Halt: There are no SSRC groups in the remote ' +
  19885. 'description.');
  19886. return;
  19887. }
  19888. var sources = parseSsrcs(mLine);
  19889. // Find the SIM group and nuke it.
  19890. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  19891. if (simulcastGroup.semantics !== 'SIM') {
  19892. return;
  19893. }
  19894. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  19895. // Schedule the SIM group for nuking.
  19896. simulcastGroup.nuke = true;
  19897. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  19898. // Nuke all the higher layer SSRCs.
  19899. for (var i = 1; i < simulcastSsrcs.length; i++) {
  19900. var ssrc = simulcastSsrcs[i];
  19901. delete sources[ssrc];
  19902. // Remove all the groups that this SSRC participates in.
  19903. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19904. if (relatedGroup.semantics === 'SIM') {
  19905. return;
  19906. }
  19907. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19908. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19909. return;
  19910. }
  19911. // Nuke all the related SSRCs.
  19912. relatedSsrcs.forEach(function (relatedSSRC) {
  19913. delete sources[relatedSSRC];
  19914. });
  19915. // Schedule the related group for nuking.
  19916. relatedGroup.nuke = true;
  19917. })
  19918. }
  19919. return;
  19920. });
  19921. mLine.ssrcs = writeSsrcs(sources);
  19922. // Nuke all the scheduled groups.
  19923. var i = mLine.ssrcGroups.length;
  19924. while (i--) {
  19925. if (mLine.ssrcGroups[i].nuke) {
  19926. mLine.ssrcGroups.splice(i, 1);
  19927. }
  19928. }
  19929. }
  19930. function removeGoogConference(mLine) {
  19931. if (!mLine || !Array.isArray(mLine.invalid)) {
  19932. return;
  19933. }
  19934. var i = mLine.invalid.length;
  19935. while (i--) {
  19936. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  19937. mLine.invalid.splice(i, 1);
  19938. }
  19939. }
  19940. }
  19941. function assertGoogConference(mLine) {
  19942. if (!mLine) {
  19943. return;
  19944. }
  19945. if (!Array.isArray(mLine.invalid)) {
  19946. mLine.invalid = [];
  19947. }
  19948. if (!mLine.invalid.some(
  19949. function (i) { return i.value === 'x-google-flag:conference' })) {
  19950. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19951. }
  19952. }
  19953. //endregion
  19954. //region "Private" functions
  19955. /**
  19956. *
  19957. * @param mLine
  19958. * @private
  19959. */
  19960. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19961. if (!mLine || mLine.type !== 'video') {
  19962. return;
  19963. }
  19964. var sources = parseSsrcs(mLine);
  19965. if (Object.keys(sources).length === 0) {
  19966. // no sources, disable simulcast.
  19967. if (this.layers.length !== 0) {
  19968. this.layers = [];
  19969. }
  19970. return;
  19971. }
  19972. // find the base layer (we'll reuse its msid and cname).
  19973. var baseLayerSSRC = Object.keys(sources)[0];
  19974. var baseLayer = sources[baseLayerSSRC];
  19975. // todo(gp) handle screen sharing.
  19976. // check if base CNAME has changed and reinitialise layers.
  19977. if (this.layers.length > 0
  19978. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  19979. this.layers = [];
  19980. }
  19981. // (re)initialise layers
  19982. if (this.layers.length < 1) {
  19983. // first push the base layer.
  19984. this.layers.push({
  19985. ssrc: baseLayerSSRC,
  19986. msid: baseLayer.msid,
  19987. cname: baseLayer.cname
  19988. });
  19989. var rtx = false; // RFC 4588
  19990. if (Array.isArray(mLine.rtp)) {
  19991. rtx = mLine.rtp.some(
  19992. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  19993. }
  19994. if (rtx) {
  19995. this.layers[0].rtx = generateSSRC();
  19996. }
  19997. // now push additional layers.
  19998. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  19999. var layer = { ssrc: generateSSRC() };
  20000. if (rtx) {
  20001. layer.rtx = generateSSRC();
  20002. }
  20003. this.layers.push(layer);
  20004. }
  20005. }
  20006. };
  20007. /**
  20008. *
  20009. * @param mLine
  20010. * @private
  20011. */
  20012. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  20013. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  20014. var sources = {};
  20015. var msid = this.layers[0].msid;
  20016. var cname = this.layers[0].cname;
  20017. var simulcastSsrcs = [];
  20018. var ssrcGroups = [];
  20019. for (var i = 0; i < this.layers.length; i++) {
  20020. var layer = this.layers[i];
  20021. sources[layer.ssrc] = { msid: msid, cname: cname };
  20022. simulcastSsrcs.push(layer.ssrc);
  20023. if (layer.rtx) {
  20024. sources[layer.rtx] = {
  20025. msid: msid,
  20026. cname: cname
  20027. }
  20028. ssrcGroups.push({
  20029. semantics: 'FID',
  20030. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  20031. });
  20032. }
  20033. }
  20034. ssrcGroups.push({
  20035. semantics: 'SIM',
  20036. ssrcs: simulcastSsrcs.join(' ')
  20037. });
  20038. mLine.ssrcGroups = ssrcGroups;
  20039. mLine.ssrcs = writeSsrcs(sources);
  20040. }
  20041. }
  20042. //endregion
  20043. //region "Public" functions
  20044. Simulcast.prototype.isSupported = function () {
  20045. return window.chrome;
  20046. // TODO this needs improvements. For example I doubt that Chrome in Android
  20047. // has simulcast support. Also, only recent versions of Chromium have native
  20048. // simulcast support.
  20049. }
  20050. /**
  20051. *
  20052. * @param desc
  20053. * @returns {RTCSessionDescription}
  20054. */
  20055. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  20056. if (!validateDescription(desc)) {
  20057. return desc;
  20058. }
  20059. var session = transform.parse(desc.sdp);
  20060. var self = this;
  20061. processVideo(session, function (mLine) {
  20062. // Handle simulcast reception.
  20063. if (self.options.explodeRemoteSimulcast) {
  20064. explodeRemoteSimulcast(mLine);
  20065. } else {
  20066. implodeRemoteSimulcast(mLine);
  20067. }
  20068. // If native simulcast is enabled, we must append the x-goog-conference
  20069. // attribute to the SDP.
  20070. if (self.layers.length < 1) {
  20071. removeGoogConference(mLine);
  20072. } else {
  20073. assertGoogConference(mLine);
  20074. }
  20075. });
  20076. return new RTCSessionDescription({
  20077. type: desc.type,
  20078. sdp: transform.write(session)
  20079. });
  20080. };
  20081. /**
  20082. *
  20083. * @param desc
  20084. * @returns {RTCSessionDescription}
  20085. */
  20086. Simulcast.prototype.mungeLocalDescription = function (desc) {
  20087. if (!validateDescription(desc) || !this.isSupported()) {
  20088. return desc;
  20089. }
  20090. var session = transform.parse(desc.sdp);
  20091. var self = this;
  20092. processVideo(session, function (mLine) {
  20093. // Initialize native simulcast layers, if not already done.
  20094. self._maybeInitializeLayers(mLine);
  20095. // Update the SDP with the simulcast layers.
  20096. self._restoreSimulcastView(mLine);
  20097. });
  20098. return new RTCSessionDescription({
  20099. type: desc.type,
  20100. sdp: transform.write(session)
  20101. });
  20102. };
  20103. //endregion
  20104. module.exports = Simulcast;
  20105. },{"./transform-utils":74,"sdp-transform":76}],74:[function(require,module,exports){
  20106. /* Copyright @ 2015 Atlassian Pty Ltd
  20107. *
  20108. * Licensed under the Apache License, Version 2.0 (the "License");
  20109. * you may not use this file except in compliance with the License.
  20110. * You may obtain a copy of the License at
  20111. *
  20112. * http://www.apache.org/licenses/LICENSE-2.0
  20113. *
  20114. * Unless required by applicable law or agreed to in writing, software
  20115. * distributed under the License is distributed on an "AS IS" BASIS,
  20116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20117. * See the License for the specific language governing permissions and
  20118. * limitations under the License.
  20119. */
  20120. exports.writeSsrcs = function(sources, order) {
  20121. var ssrcs = [];
  20122. // expand sources to ssrcs
  20123. if (typeof sources !== 'undefined' &&
  20124. Object.keys(sources).length !== 0) {
  20125. if (Array.isArray(order)) {
  20126. for (var i = 0; i < order.length; i++) {
  20127. var ssrc = order[i];
  20128. var source = sources[ssrc];
  20129. Object.keys(source).forEach(function (attribute) {
  20130. ssrcs.push({
  20131. id: ssrc,
  20132. attribute: attribute,
  20133. value: source[attribute]
  20134. });
  20135. });
  20136. }
  20137. } else {
  20138. Object.keys(sources).forEach(function (ssrc) {
  20139. var source = sources[ssrc];
  20140. Object.keys(source).forEach(function (attribute) {
  20141. ssrcs.push({
  20142. id: ssrc,
  20143. attribute: attribute,
  20144. value: source[attribute]
  20145. });
  20146. });
  20147. });
  20148. }
  20149. }
  20150. return ssrcs;
  20151. };
  20152. exports.parseSsrcs = function (mLine) {
  20153. var sources = {};
  20154. // group sources attributes by ssrc.
  20155. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20156. mLine.ssrcs.forEach(function (ssrc) {
  20157. if (!sources[ssrc.id])
  20158. sources[ssrc.id] = {};
  20159. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20160. });
  20161. }
  20162. return sources;
  20163. };
  20164. },{}],75:[function(require,module,exports){
  20165. arguments[4][69][0].apply(exports,arguments)
  20166. },{"dup":69}],76:[function(require,module,exports){
  20167. arguments[4][70][0].apply(exports,arguments)
  20168. },{"./parser":77,"./writer":78,"dup":70}],77:[function(require,module,exports){
  20169. arguments[4][71][0].apply(exports,arguments)
  20170. },{"./grammar":75,"dup":71}],78:[function(require,module,exports){
  20171. arguments[4][72][0].apply(exports,arguments)
  20172. },{"./grammar":75,"dup":72}],79:[function(require,module,exports){
  20173. arguments[4][69][0].apply(exports,arguments)
  20174. },{"dup":69}],80:[function(require,module,exports){
  20175. arguments[4][70][0].apply(exports,arguments)
  20176. },{"./parser":81,"./writer":82,"dup":70}],81:[function(require,module,exports){
  20177. arguments[4][71][0].apply(exports,arguments)
  20178. },{"./grammar":79,"dup":71}],82:[function(require,module,exports){
  20179. arguments[4][72][0].apply(exports,arguments)
  20180. },{"./grammar":79,"dup":72}],83:[function(require,module,exports){
  20181. var MediaStreamType = {
  20182. VIDEO_TYPE: "Video",
  20183. AUDIO_TYPE: "Audio"
  20184. };
  20185. module.exports = MediaStreamType;
  20186. },{}],84:[function(require,module,exports){
  20187. var RTCEvents = {
  20188. RTC_READY: "rtc.ready",
  20189. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20190. LASTN_CHANGED: "rtc.lastn_changed",
  20191. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20192. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20193. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20194. };
  20195. module.exports = RTCEvents;
  20196. },{}],85:[function(require,module,exports){
  20197. var Resolutions = {
  20198. "1080": {
  20199. width: 1920,
  20200. height: 1080,
  20201. order: 7
  20202. },
  20203. "fullhd": {
  20204. width: 1920,
  20205. height: 1080,
  20206. order: 7
  20207. },
  20208. "720": {
  20209. width: 1280,
  20210. height: 720,
  20211. order: 6
  20212. },
  20213. "hd": {
  20214. width: 1280,
  20215. height: 720,
  20216. order: 6
  20217. },
  20218. "960": {
  20219. width: 960,
  20220. height: 720,
  20221. order: 5
  20222. },
  20223. "640": {
  20224. width: 640,
  20225. height: 480,
  20226. order: 4
  20227. },
  20228. "vga": {
  20229. width: 640,
  20230. height: 480,
  20231. order: 4
  20232. },
  20233. "360": {
  20234. width: 640,
  20235. height: 360,
  20236. order: 3
  20237. },
  20238. "320": {
  20239. width: 320,
  20240. height: 240,
  20241. order: 2
  20242. },
  20243. "180": {
  20244. width: 320,
  20245. height: 180,
  20246. order: 1
  20247. }
  20248. };
  20249. module.exports = Resolutions;
  20250. },{}],86:[function(require,module,exports){
  20251. var XMPPEvents = {
  20252. // Designates an event indicating that the connection to the XMPP server
  20253. // failed.
  20254. CONNECTION_FAILED: "xmpp.connection.failed",
  20255. // Designates an event indicating that the media (ICE) connection was
  20256. // interrupted. This should go to the RTC module.
  20257. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20258. // Designates an event indicating that the media (ICE) connection was
  20259. // restored. This should go to the RTC module.
  20260. CONNECTION_RESTORED: "xmpp.connection.restored",
  20261. // Designates an event indicating that an offer (e.g. Jingle
  20262. // session-initiate) was received.
  20263. CALL_INCOMING: "xmpp.callincoming.jingle",
  20264. // Designates an event indicating that we were kicked from the XMPP MUC.
  20265. KICKED: "xmpp.kicked",
  20266. // Designates an event indicating that the userID for a specific JID has
  20267. // changed.
  20268. // Note: currently this event fires every time we receive presence from
  20269. // someone (regardless of whether or not the "userID" changed).
  20270. USER_ID_CHANGED: "xmpp.user_id_changed",
  20271. // Designates an event indicating that we have joined the XMPP MUC.
  20272. MUC_JOINED: "xmpp.muc_joined",
  20273. // Designates an event indicating that a participant joined the XMPP MUC.
  20274. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20275. // Designates an event indicating that a participant left the XMPP MUC.
  20276. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20277. // Designates an event indicating that the MUC role of a participant has
  20278. // changed.
  20279. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20280. // Designates an event indicating that the XMPP MUC was destroyed.
  20281. MUC_DESTROYED: "xmpp.muc_destroyed",
  20282. // Designates an event indicating that the display name of a participant
  20283. // has changed.
  20284. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20285. // Designates an event indicating that we received statistics from a
  20286. // participant in the MUC.
  20287. REMOTE_STATS: "xmpp.remote_stats",
  20288. // Designates an event indicating that our role in the XMPP MUC has changed.
  20289. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20290. // Designates an event indicating that the subject of the XMPP MUC has
  20291. // changed.
  20292. SUBJECT_CHANGED: "xmpp.subject_changed",
  20293. // Designates an event indicating that an XMPP message in the MUC was
  20294. // received.
  20295. MESSAGE_RECEIVED: "xmpp.message_received",
  20296. // Designates an event indicating that we sent an XMPP message to the MUC.
  20297. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20298. // Designates an event indicating that the video type (e.g. 'camera' or
  20299. // 'screen') for a participant has changed.
  20300. // Note: currently this event fires every time we receive presence from
  20301. // someone (regardless of whether or not the "video type" changed).
  20302. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20303. // Designates an event indicating that a participant in the XMPP MUC has
  20304. // advertised that they have audio muted (or unmuted).
  20305. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20306. // Designates an event indicating that a participant in the XMPP MUC has
  20307. // advertised that they have video muted (or unmuted).
  20308. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20309. // Designates an event indicating that the focus has asked us to mute our
  20310. // audio.
  20311. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20312. // Designates an event indicating that a moderator in the room changed the
  20313. // "start muted" settings for the conference.
  20314. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20315. // Designates an event indicating that we should join the conference with
  20316. // audio and/or video muted.
  20317. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20318. // Designates an event indicating that a remote participant's available
  20319. // devices (whether he supports a audio and/or video) changed.
  20320. // Note: currently this event fires every time we receive presence from
  20321. // someone (regardless of whether or not the devices changed).
  20322. DEVICE_AVAILABLE: "xmpp.device_available",
  20323. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20324. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20325. PASSWORD_REQUIRED: "xmpp.password_required",
  20326. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20327. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20328. ETHERPAD: "xmpp.etherpad",
  20329. BRIDGE_DOWN: "xmpp.bridge_down",
  20330. PRESENCE_STATUS: "xmpp.presence_status",
  20331. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20332. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20333. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20334. // TODO: only used in a hack, should probably be removed.
  20335. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20336. // TODO: only used in a hack, should probably be removed.
  20337. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20338. // TODO: only used in a hack, should probably be removed.
  20339. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20340. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20341. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20342. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20343. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20344. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20345. // xmpp is connected and obtained user media
  20346. READY_TO_JOIN: 'xmpp.ready_to_join',
  20347. FOCUS_LEFT: "xmpp.focus_left",
  20348. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  20349. /**
  20350. * Indicates that recording state changed.
  20351. */
  20352. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  20353. /**
  20354. * Indicates that phone number changed.
  20355. */
  20356. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  20357. };
  20358. module.exports = XMPPEvents;
  20359. },{}],87:[function(require,module,exports){
  20360. var AuthenticationEvents = {
  20361. /**
  20362. * Event callback arguments:
  20363. * function(authenticationEnabled, userIdentity)
  20364. * authenticationEnabled - indicates whether authentication has been enabled
  20365. * in this session
  20366. * userIdentity - if user has been logged in then it contains user name. If
  20367. * contains 'null' or 'undefined' then user is not logged in.
  20368. */
  20369. IDENTITY_UPDATED: "authentication.identity_updated"
  20370. };
  20371. module.exports = AuthenticationEvents;
  20372. },{}],88:[function(require,module,exports){
  20373. var DesktopSharingEventTypes = {
  20374. INIT: "ds.init",
  20375. SWITCHING_DONE: "ds.switching_done",
  20376. NEW_STREAM_CREATED: "ds.new_stream_created",
  20377. /**
  20378. * An event which indicates that the jidesha extension for Firefox is
  20379. * needed to proceed with screen sharing, and that it is not installed.
  20380. */
  20381. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20382. };
  20383. module.exports = DesktopSharingEventTypes;
  20384. },{}],89:[function(require,module,exports){
  20385. module.exports = {
  20386. /**
  20387. * An event carrying connection statistics.
  20388. */
  20389. CONNECTION_STATS: "statistics.connectionstats",
  20390. /**
  20391. * FIXME: needs documentation.
  20392. */
  20393. AUDIO_LEVEL: "statistics.audioLevel",
  20394. /**
  20395. * FIXME: needs documentation.
  20396. */
  20397. STOP: "statistics.stop"
  20398. };
  20399. },{}],90:[function(require,module,exports){
  20400. var Constants = {
  20401. LOCAL_JID: 'local'
  20402. };
  20403. module.exports = Constants;
  20404. },{}],91:[function(require,module,exports){
  20405. arguments[4][86][0].apply(exports,arguments)
  20406. },{"dup":86}]},{},[7])(7)
  20407. });