Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

lib-jitsi-meet.js 730KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467
  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. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var RTC = require("./modules/RTC/RTC");
  5. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  6. var StreamEventTypes = require("./service/RTC/StreamEventTypes");
  7. var RTCEvents = require("./service/RTC/RTCEvents");
  8. var EventEmitter = require("events");
  9. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  10. var JitsiParticipant = require("./JitsiParticipant");
  11. var Statistics = require("./modules/statistics/statistics");
  12. /**
  13. * Creates a JitsiConference object with the given name and properties.
  14. * Note: this constructor is not a part of the public API (objects should be
  15. * created using JitsiConnection.createConference).
  16. * @param options.config properties / settings related to the conference that will be created.
  17. * @param options.name the name of the conference
  18. * @param options.connection the JitsiConnection object for this JitsiConference.
  19. * @constructor
  20. */
  21. function JitsiConference(options) {
  22. if(!options.name || options.name.toLowerCase() !== options.name) {
  23. logger.error("Invalid conference name (no conference name passed or it"
  24. + "contains invalid characters like capital letters)!");
  25. return;
  26. }
  27. this.options = options;
  28. this.connection = this.options.connection;
  29. this.xmpp = this.connection.xmpp;
  30. this.eventEmitter = new EventEmitter();
  31. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  32. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  33. this.rtc = new RTC(this.room, options);
  34. if(!options.config.disableAudioLevels)
  35. this.statistics = new Statistics();
  36. setupListeners(this);
  37. this.participants = {};
  38. this.lastActiveSpeaker = null;
  39. }
  40. /**
  41. * Joins the conference.
  42. * @param password {string} the password
  43. */
  44. JitsiConference.prototype.join = function (password) {
  45. if(this.room)
  46. this.room.join(password, this.connection.tokenPassword);
  47. }
  48. /**
  49. * Leaves the conference.
  50. */
  51. JitsiConference.prototype.leave = function () {
  52. if(this.xmpp)
  53. this.xmpp.leaveRoom(this.room.roomjid);
  54. this.room = null;
  55. }
  56. /**
  57. * Returns the local tracks.
  58. */
  59. JitsiConference.prototype.getLocalTracks = function () {
  60. if(this.rtc)
  61. return this.rtc.localStreams;
  62. };
  63. /**
  64. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  65. * in JitsiConferenceEvents.
  66. * @param eventId the event ID.
  67. * @param handler handler for the event.
  68. *
  69. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  70. */
  71. JitsiConference.prototype.on = function (eventId, handler) {
  72. if(this.eventEmitter)
  73. this.eventEmitter.on(eventId, handler);
  74. }
  75. /**
  76. * Removes event listener
  77. * @param eventId the event ID.
  78. * @param [handler] optional, the specific handler to unbind
  79. *
  80. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  81. */
  82. JitsiConference.prototype.off = function (eventId, handler) {
  83. if(this.eventEmitter)
  84. this.eventEmitter.removeListener(eventId, listener);
  85. }
  86. // Common aliases for event emitter
  87. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  88. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  89. /**
  90. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  91. * @param command {String} the name of the command
  92. * @param handler {Function} handler for the command
  93. */
  94. JitsiConference.prototype.addCommandListener = function (command, handler) {
  95. if(this.room)
  96. this.room.addPresenceListener(command, handler);
  97. }
  98. /**
  99. * Removes command listener
  100. * @param command {String} the name of the command
  101. */
  102. JitsiConference.prototype.removeCommandListener = function (command) {
  103. if(this.room)
  104. this.room.removePresenceListener(command);
  105. }
  106. /**
  107. * Sends text message to the other participants in the conference
  108. * @param message the text message.
  109. */
  110. JitsiConference.prototype.sendTextMessage = function (message) {
  111. if(this.room)
  112. this.room.sendMessage(message);
  113. }
  114. /**
  115. * Send presence command.
  116. * @param name the name of the command.
  117. * @param values Object with keys and values that will be send.
  118. **/
  119. JitsiConference.prototype.sendCommand = function (name, values) {
  120. if(this.room) {
  121. this.room.addToPresence(name, values);
  122. this.room.sendPresence();
  123. }
  124. }
  125. /**
  126. * Send presence command one time.
  127. * @param name the name of the command.
  128. * @param values Object with keys and values that will be send.
  129. **/
  130. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  131. this.sendCommand(name, values);
  132. this.removeCommand(name);
  133. }
  134. /**
  135. * Send presence command.
  136. * @param name the name of the command.
  137. * @param values Object with keys and values that will be send.
  138. * @param persistent if false the command will be sent only one time
  139. **/
  140. JitsiConference.prototype.removeCommand = function (name) {
  141. if(this.room)
  142. this.room.removeFromPresence(name);
  143. }
  144. /**
  145. * Sets the display name for this conference.
  146. * @param name the display name to set
  147. */
  148. JitsiConference.prototype.setDisplayName = function(name) {
  149. if(this.room){
  150. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  151. this.room.sendPresence();
  152. }
  153. }
  154. /**
  155. * Adds JitsiLocalTrack object to the conference.
  156. * @param track the JitsiLocalTrack object.
  157. */
  158. JitsiConference.prototype.addTrack = function (track) {
  159. this.rtc.addLocalStream(track);
  160. this.room.addStream(track.getOriginalStream, function () {});
  161. }
  162. /**
  163. * Removes JitsiLocalTrack object to the conference.
  164. * @param track the JitsiLocalTrack object.
  165. */
  166. JitsiConference.prototype.removeTrack = function (track) {
  167. this.room.removeStream(track.getOriginalStream());
  168. this.rtc.removeLocalStream(track);
  169. }
  170. /**
  171. * Elects the participant with the given id to be the selected participant or the speaker.
  172. * @param id the identifier of the participant
  173. */
  174. JitsiConference.prototype.selectParticipant = function(participantId) {
  175. if (this.rtc) {
  176. this.rtc.selectedEndpoint(participantId);
  177. }
  178. }
  179. /**
  180. *
  181. * @param id the identifier of the participant
  182. */
  183. JitsiConference.prototype.pinParticipant = function(participantId) {
  184. if(this.rtc)
  185. this.rtc.pinEndpoint(participantId);
  186. }
  187. /**
  188. * Returns the list of participants for this conference.
  189. * @return Object a list of participant identifiers containing all conference participants.
  190. */
  191. JitsiConference.prototype.getParticipants = function() {
  192. return this.participants;
  193. }
  194. /**
  195. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  196. * null if there isn't one).
  197. * @param id the id of the participant.
  198. */
  199. JitsiConference.prototype.getParticipantById = function(id) {
  200. if(this.participants)
  201. return this.participants[id];
  202. return null;
  203. }
  204. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  205. if(this.eventEmitter)
  206. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, Strophe.getResourceFromJid(jid));
  207. // this.participants[jid] = new JitsiParticipant();
  208. }
  209. /**
  210. * Returns the local user's ID
  211. * @return {string} local user's ID
  212. */
  213. JitsiConference.prototype.myUserId = function () {
  214. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  215. }
  216. /**
  217. * Setups the listeners needed for the conference.
  218. * @param conference the conference
  219. */
  220. function setupListeners(conference) {
  221. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  222. conference.rtc.onIncommingCall(event);
  223. if(conference.statistics)
  224. conference.statistics.startRemoteStats(event.peerconnection);
  225. });
  226. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  227. conference.rtc.createRemoteStream.bind(conference.rtc));
  228. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  229. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  230. });
  231. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, function (stream) {
  232. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  233. });
  234. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  235. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  236. });
  237. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  238. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  239. });
  240. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  241. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  242. });
  243. // FIXME
  244. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  245. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  246. // });
  247. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  248. if(conference.lastActiveSpeaker !== id && conference.room
  249. && conference.myUserId() !== id) {
  250. conference.lastActiveSpeaker = id;
  251. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  252. }
  253. });
  254. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  255. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  256. });
  257. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  258. function (lastNEndpoints, endpointsEnteringLastN) {
  259. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  260. lastNEndpoints, endpointsEnteringLastN);
  261. });
  262. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  263. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT,function (jid) {
  264. conference.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, Strophe.getResourceFromJid(jid));
  265. });
  266. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (from, displayName) {
  267. conference.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  268. Strophe.getResourceFromJid(from), displayName);
  269. });
  270. if(conference.statistics) {
  271. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  272. var userId = null;
  273. if (ssrc === Statistics.LOCAL_JID) {
  274. userId = conference.myUserId();
  275. } else {
  276. var jid = conference.room.getJidBySSRC(ssrc);
  277. if (!jid)
  278. return;
  279. userId = Strophe.getResourceFromJid(jid);
  280. }
  281. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  282. userId, level);
  283. });
  284. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_CREATED, function (stream) {
  285. conference.statistics.startLocalStats(stream);
  286. });
  287. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  288. function () {
  289. conference.statistics.dispose();
  290. });
  291. RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  292. conference.room.updateDeviceAvailability(devices);
  293. });
  294. RTC.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  295. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  296. });
  297. }
  298. }
  299. module.exports = JitsiConference;
  300. }).call(this,"/JitsiConference.js")
  301. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/RTC/RTC":13,"./modules/statistics/statistics":21,"./service/RTC/RTCEvents":76,"./service/RTC/StreamEventTypes":78,"./service/xmpp/XMPPEvents":82,"events":40,"jitsi-meet-logger":44}],2:[function(require,module,exports){
  302. /**
  303. * Enumeration with the errors for the conference.
  304. * @type {{string: string}}
  305. */
  306. var JitsiConferenceErrors = {
  307. /**
  308. * Indicates that a password is required in order to join the conference.
  309. */
  310. PASSWORD_REQUIRED: "conference.passwordRequired",
  311. /**
  312. * Indicates that a connection error occurred when trying to join a conference.
  313. */
  314. CONNECTION_ERROR: "conference.connectionError",
  315. /**
  316. * Indicates that there is no available videobridge.
  317. */
  318. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  319. /**
  320. * Many more errors TBD here.
  321. */
  322. };
  323. module.exports = JitsiConferenceErrors;
  324. },{}],3:[function(require,module,exports){
  325. /**
  326. * Enumeration with the events for the conference.
  327. * @type {{string: string}}
  328. */
  329. var JitsiConferenceEvents = {
  330. /**
  331. * A new media track was added to the conference.
  332. */
  333. TRACK_ADDED: "conference.trackAdded",
  334. /**
  335. * The media track was removed to the conference.
  336. */
  337. TRACK_REMOVED: "conference.trackRemoved",
  338. /**
  339. * The active speaker was changed.
  340. */
  341. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  342. /**
  343. * A new user joinned the conference.
  344. */
  345. USER_JOINED: "conference.userJoined",
  346. /**
  347. * A user has left the conference.
  348. */
  349. USER_LEFT: "conference.userLeft",
  350. /**
  351. * New text message was received.
  352. */
  353. MESSAGE_RECEIVED: "conference.messageReceived",
  354. /**
  355. * A user has changed it display name
  356. */
  357. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  358. /**
  359. * A participant avatar has changed.
  360. */
  361. AVATAR_CHANGED: "conference.avatarChanged",
  362. /**
  363. * New connection statistics are received.
  364. */
  365. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  366. /**
  367. * The Last N set is changed.
  368. */
  369. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  370. /**
  371. * You are included / excluded in somebody's last N set
  372. */
  373. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  374. /**
  375. * A media track mute status was changed.
  376. */
  377. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  378. /**
  379. * Audio levels of a media track was changed.
  380. */
  381. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  382. /**
  383. * Indicates that the connection to the conference has been interrupted for some reason.
  384. */
  385. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  386. /**
  387. * Indicates that the connection to the conference has been restored.
  388. */
  389. CONNECTION_RESTORED: "conference.connecionRestored",
  390. /**
  391. * Indicates that conference has been joined.
  392. */
  393. CONFERENCE_JOINED: "conference.joined",
  394. /**
  395. * Indicates that conference has been left.
  396. */
  397. CONFERENCE_LEFT: "conference.left"
  398. };
  399. module.exports = JitsiConferenceEvents;
  400. },{}],4:[function(require,module,exports){
  401. var JitsiConference = require("./JitsiConference");
  402. var XMPP = require("./modules/xmpp/xmpp");
  403. var RandomUtil = require("./modules/util/RandomUtil");
  404. /**
  405. * Utility method that generates user name based on random hex values.
  406. * Eg. 12345678-1234-1234-12345678
  407. * @returns {string}
  408. */
  409. function generateUserName() {
  410. return RandomUtil.random8digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" +
  411. RandomUtil.random4digitsHex() + "-" + RandomUtil.random8digitsHex();
  412. }
  413. /**
  414. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  415. * JitsiConference interface.
  416. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  417. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  418. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  419. * The format is:
  420. * passwordToken = token + "_" + roomName + "_" + ts
  421. * See doc/tokens.md for more info on how tokens are generated.
  422. * @param options Object with properties / settings related to connection with the server.
  423. * @constructor
  424. */
  425. function JitsiConnection(appID, tokenPassword, options) {
  426. this.appID = appID;
  427. this.tokenPassword = tokenPassword;
  428. this.options = options;
  429. this.xmpp = new XMPP(options);
  430. this.conferences = {};
  431. }
  432. /**
  433. * Connect the client with the server.
  434. * @param options {object} connecting options (for example authentications parameters).
  435. */
  436. JitsiConnection.prototype.connect = function (options) {
  437. if(!options)
  438. options = {};
  439. // If we have token provided use it as a password and generate random username
  440. if (this.tokenPassword) {
  441. options.password = this.tokenPassword;
  442. if (!options.id) {
  443. options.id = generateUserName() + "@" + this.options.hosts.domain;
  444. }
  445. }
  446. this.xmpp.connect(options.id, options.password);
  447. }
  448. /**
  449. * Disconnect the client from the server.
  450. */
  451. JitsiConnection.prototype.disconnect = function () {
  452. this.xmpp.disconnect();
  453. }
  454. /**
  455. * This method allows renewal of the tokens if they are expiring.
  456. * @param token the new token.
  457. */
  458. JitsiConnection.prototype.setToken = function (token) {
  459. this.token = token;
  460. }
  461. /**
  462. * Creates and joins new conference.
  463. * @param name the name of the conference; if null - a generated name will be provided from the api
  464. * @param options Object with properties / settings related to the conference that will be created.
  465. * @returns {JitsiConference} returns the new conference object.
  466. */
  467. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  468. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  469. return this.conferences[name];
  470. }
  471. /**
  472. * Subscribes the passed listener to the event.
  473. * @param event {JitsiConnectionEvents} the connection event.
  474. * @param listener {Function} the function that will receive the event
  475. */
  476. JitsiConnection.prototype.addEventListener = function (event, listener) {
  477. this.xmpp.addListener(event, listener);
  478. }
  479. /**
  480. * Unsubscribes the passed handler.
  481. * @param event {JitsiConnectionEvents} the connection event.
  482. * @param listener {Function} the function that will receive the event
  483. */
  484. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  485. this.xmpp.removeListener(event, listener);
  486. }
  487. module.exports = JitsiConnection;
  488. },{"./JitsiConference":1,"./modules/util/RandomUtil":22,"./modules/xmpp/xmpp":38}],5:[function(require,module,exports){
  489. /**
  490. * Enumeration with the errors for the connection.
  491. * @type {{string: string}}
  492. */
  493. var JitsiConnectionErrors = {
  494. /**
  495. * Indicates that a password is required in order to join the conference.
  496. */
  497. PASSWORD_REQUIRED: "connection.passwordRequired",
  498. /**
  499. * Indicates that a connection error occurred when trying to join a conference.
  500. */
  501. CONNECTION_ERROR: "connection.connectionError",
  502. /**
  503. * Not specified errors.
  504. */
  505. OTHER_ERROR: "connection.otherError"
  506. };
  507. module.exports = JitsiConnectionErrors;
  508. },{}],6:[function(require,module,exports){
  509. /**
  510. * Enumeration with the events for the connection.
  511. * @type {{string: string}}
  512. */
  513. var JitsiConnnectionEvents = {
  514. /**
  515. * Indicates that the connection has been failed for some reason.
  516. */
  517. CONNECTION_FAILED: "connection.connecionFailed",
  518. /**
  519. * Indicates that the connection has been established.
  520. */
  521. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  522. /**
  523. * Indicates that the connection has been disconnected.
  524. */
  525. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  526. /**
  527. * Indicates that the perfomed action cannot be executed because the
  528. * connection is not in the correct state(connected, disconnected, etc.)
  529. */
  530. WRONG_STATE: "connection.wrongState"
  531. };
  532. module.exports = JitsiConnnectionEvents;
  533. },{}],7:[function(require,module,exports){
  534. var JitsiConnection = require("./JitsiConnection");
  535. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  536. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  537. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  538. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  539. var Logger = require("jitsi-meet-logger");
  540. var RTC = require("./modules/RTC/RTC");
  541. /**
  542. * Namespace for the interface of Jitsi Meet Library.
  543. */
  544. var LibJitsiMeet = {
  545. JitsiConnection: JitsiConnection,
  546. events: {
  547. conference: JitsiConferenceEvents,
  548. connection: JitsiConnectionEvents
  549. },
  550. errors: {
  551. conference: JitsiConferenceErrors,
  552. connection: JitsiConnectionErrors
  553. },
  554. logLevels: Logger.levels,
  555. init: function (options) {
  556. RTC.init(options || {});
  557. },
  558. setLogLevel: function (level) {
  559. Logger.setLogLevel(level);
  560. },
  561. /**
  562. * Creates the media tracks and returns them trough the callback.
  563. * @param options Object with properties / settings specifying the tracks which should be created.
  564. * should be created or some additional configurations about resolution for example.
  565. * @param {Array} options.devices the devices that will be requested
  566. * @param {string} options.resolution resolution constraints
  567. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  568. * type: "audio" or "video", videoType: "camera" or "desktop"}
  569. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  570. * @param {string} options.cameraDeviceId
  571. * @param {string} options.micDeviceId
  572. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  573. * or a JitsiConferenceError if rejected.
  574. */
  575. createLocalTracks: function (options) {
  576. return RTC.obtainAudioAndVideoPermissions(options || {});
  577. },
  578. isDeviceListAvailable: function () {
  579. return RTC.isDeviceListAvailable();
  580. },
  581. enumerateDevices: function (callback) {
  582. RTC.enumerateDevices(callback);
  583. }
  584. };
  585. //Setups the promise object.
  586. window.Promise = window.Promise || require("es6-promise").polyfill();
  587. module.exports = LibJitsiMeet;
  588. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":13,"es6-promise":42,"jitsi-meet-logger":44}],8:[function(require,module,exports){
  589. /**
  590. * Represents a participant in (a member of) a conference.
  591. */
  592. function JitsiParticipant(id, conference, displayName){
  593. this._id = id;
  594. this._conference = conference;
  595. this._displayName = displayName;
  596. }
  597. /**
  598. * @returns {JitsiConference} The conference that this participant belongs to.
  599. */
  600. JitsiParticipant.prototype.getConference = function() {
  601. return this._conference;
  602. }
  603. /**
  604. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  605. */
  606. JitsiParticipant.prototype.getTracks = function() {
  607. }
  608. /**
  609. * @returns {String} The ID (i.e. JID) of this participant.
  610. */
  611. JitsiParticipant.prototype.getId = function() {
  612. return this._id;
  613. }
  614. /**
  615. * @returns {String} The human-readable display name of this participant.
  616. */
  617. JitsiParticipant.prototype.getDisplayName = function() {
  618. return this._displayName;
  619. }
  620. /**
  621. * @returns {Boolean} Whether this participant is a moderator or not.
  622. */
  623. JitsiParticipant.prototype.isModerator = function() {
  624. }
  625. // Gets a link to an etherpad instance advertised by the participant?
  626. //JitsiParticipant.prototype.getEtherpad = function() {
  627. //
  628. //}
  629. /*
  630. * @returns {Boolean} Whether this participant has muted their audio.
  631. */
  632. JitsiParticipant.prototype.isAudioMuted = function() {
  633. }
  634. /*
  635. * @returns {Boolean} Whether this participant has muted their video.
  636. */
  637. JitsiParticipant.prototype.isVideoMuted = function() {
  638. }
  639. /*
  640. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  641. * TODO: do we expose this or handle it internally?
  642. */
  643. JitsiParticipant.prototype.getLatestStats = function() {
  644. }
  645. /**
  646. * @returns {String} The role of this participant.
  647. */
  648. JitsiParticipant.prototype.getRole = function() {
  649. }
  650. /*
  651. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  652. */
  653. JitsiParticipant.prototype.isFocus = function() {
  654. }
  655. /*
  656. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  657. */
  658. JitsiParticipant.prototype.isRecorder = function() {
  659. }
  660. /*
  661. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  662. */
  663. JitsiParticipant.prototype.isSipGateway = function() {
  664. }
  665. /**
  666. * @returns {String} The ID for this participant's avatar.
  667. */
  668. JitsiParticipant.prototype.getAvatarId = function() {
  669. }
  670. /**
  671. * @returns {Boolean} Whether this participant is currently sharing their screen.
  672. */
  673. JitsiParticipant.prototype.isScreenSharing = function() {
  674. }
  675. /**
  676. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  677. */
  678. JitsiParticipant.prototype.getUserAgent = function() {
  679. }
  680. /**
  681. * Kicks the participant from the conference (requires certain privileges).
  682. */
  683. JitsiParticipant.prototype.kick = function() {
  684. }
  685. /**
  686. * Asks this participant to mute themselves.
  687. */
  688. JitsiParticipant.prototype.askToMute = function() {
  689. }
  690. module.exports = JitsiParticipant();
  691. },{}],9:[function(require,module,exports){
  692. (function (__filename){
  693. /* global config, APP, Strophe */
  694. // cache datachannels to avoid garbage collection
  695. // https://code.google.com/p/chromium/issues/detail?id=405545
  696. var logger = require("jitsi-meet-logger").getLogger(__filename);
  697. var RTCEvents = require("../../service/RTC/RTCEvents");
  698. /**
  699. * Binds "ondatachannel" event listener to given PeerConnection instance.
  700. * @param peerConnection WebRTC peer connection instance.
  701. */
  702. function DataChannels(peerConnection, emitter) {
  703. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  704. this.eventEmitter = emitter;
  705. this._dataChannels = [];
  706. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  707. // Although it's not a requirement to open separate channels from both bridge
  708. // and peer as single channel can be used for sending and receiving data.
  709. // So either channel opened by the bridge or the one opened here is enough
  710. // for communication with the bridge.
  711. /*var dataChannelOptions =
  712. {
  713. reliable: true
  714. };
  715. var dataChannel
  716. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  717. // Can be used only when is in open state
  718. dataChannel.onopen = function ()
  719. {
  720. dataChannel.send("My channel !!!");
  721. };
  722. dataChannel.onmessage = function (event)
  723. {
  724. var msgData = event.data;
  725. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  726. };*/
  727. };
  728. /**
  729. * Callback triggered by PeerConnection when new data channel is opened
  730. * on the bridge.
  731. * @param event the event info object.
  732. */
  733. DataChannels.prototype.onDataChannel = function (event) {
  734. var dataChannel = event.channel;
  735. var self = this;
  736. dataChannel.onopen = function () {
  737. logger.info("Data channel opened by the Videobridge!", dataChannel);
  738. // Code sample for sending string and/or binary data
  739. // Sends String message to the bridge
  740. //dataChannel.send("Hello bridge!");
  741. // Sends 12 bytes binary message to the bridge
  742. //dataChannel.send(new ArrayBuffer(12));
  743. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  744. };
  745. dataChannel.onerror = function (error) {
  746. logger.error("Data Channel Error:", error, dataChannel);
  747. };
  748. dataChannel.onmessage = function (event) {
  749. var data = event.data;
  750. // JSON
  751. var obj;
  752. try {
  753. obj = JSON.parse(data);
  754. }
  755. catch (e) {
  756. logger.error(
  757. "Failed to parse data channel message as JSON: ",
  758. data,
  759. dataChannel);
  760. }
  761. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  762. var colibriClass = obj.colibriClass;
  763. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  764. // Endpoint ID from the Videobridge.
  765. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  766. logger.info(
  767. "Data channel new dominant speaker event: ",
  768. dominantSpeakerEndpoint);
  769. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  770. }
  771. else if ("InLastNChangeEvent" === colibriClass) {
  772. var oldValue = obj.oldValue;
  773. var newValue = obj.newValue;
  774. // Make sure that oldValue and newValue are of type boolean.
  775. var type;
  776. if ((type = typeof oldValue) !== 'boolean') {
  777. if (type === 'string') {
  778. oldValue = (oldValue == "true");
  779. } else {
  780. oldValue = new Boolean(oldValue).valueOf();
  781. }
  782. }
  783. if ((type = typeof newValue) !== 'boolean') {
  784. if (type === 'string') {
  785. newValue = (newValue == "true");
  786. } else {
  787. newValue = new Boolean(newValue).valueOf();
  788. }
  789. }
  790. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  791. }
  792. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  793. // The new/latest list of last-n endpoint IDs.
  794. var lastNEndpoints = obj.lastNEndpoints;
  795. // The list of endpoint IDs which are entering the list of
  796. // last-n at this time i.e. were not in the old list of last-n
  797. // endpoint IDs.
  798. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  799. logger.log(
  800. "Data channel new last-n event: ",
  801. lastNEndpoints, endpointsEnteringLastN, obj);
  802. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  803. lastNEndpoints, endpointsEnteringLastN, obj);
  804. }
  805. else {
  806. logger.debug("Data channel JSON-formatted message: ", obj);
  807. }
  808. }
  809. };
  810. dataChannel.onclose = function () {
  811. logger.info("The Data Channel closed", dataChannel);
  812. var idx = self._dataChannels.indexOf(dataChannel);
  813. if (idx > -1)
  814. self._dataChannels = self._dataChannels.splice(idx, 1);
  815. };
  816. this._dataChannels.push(dataChannel);
  817. };
  818. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  819. logger.log('selected endpoint changed: ', userResource);
  820. if (this._dataChannels && this._dataChannels.length != 0) {
  821. this._dataChannels.some(function (dataChannel) {
  822. if (dataChannel.readyState == 'open') {
  823. logger.log('sending selected endpoint changed ' +
  824. 'notification to the bridge: ', userResource);
  825. dataChannel.send(JSON.stringify({
  826. 'colibriClass': 'SelectedEndpointChangedEvent',
  827. 'selectedEndpoint':
  828. (!userResource || userResource === null)?
  829. null : userResource
  830. }));
  831. return true;
  832. }
  833. });
  834. }
  835. }
  836. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  837. logger.log('pinned endpoint changed: ', userResource);
  838. if (this._dataChannels && this._dataChannels.length != 0) {
  839. this._dataChannels.some(function (dataChannel) {
  840. if (dataChannel.readyState == 'open') {
  841. dataChannel.send(JSON.stringify({
  842. 'colibriClass': 'PinnedEndpointChangedEvent',
  843. 'pinnedEndpoint':
  844. (!userResource || userResource == null)?
  845. null : userResource
  846. }));
  847. return true;
  848. }
  849. });
  850. }
  851. }
  852. module.exports = DataChannels;
  853. }).call(this,"/modules/RTC/DataChannels.js")
  854. },{"../../service/RTC/RTCEvents":76,"jitsi-meet-logger":44}],10:[function(require,module,exports){
  855. var JitsiTrack = require("./JitsiTrack");
  856. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  857. var RTCBrowserType = require("./RTCBrowserType");
  858. /**
  859. * Represents a single media track (either audio or video).
  860. * @constructor
  861. */
  862. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType,
  863. resolution)
  864. {
  865. JitsiTrack.call(this, RTC, stream);
  866. this.eventEmitter = eventEmitter;
  867. this.videoType = videoType;
  868. this.dontFireRemoveEvent = false;
  869. this.resolution = resolution;
  870. var self = this;
  871. this.stream.onended = function () {
  872. if(!self.dontFireRemoveEvent)
  873. self.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  874. self.dontFireRemoveEvent = false;
  875. };
  876. }
  877. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  878. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  879. /**
  880. * Mutes / unmutes the track.
  881. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  882. */
  883. JitsiLocalTrack.prototype._setMute = function (mute) {
  884. if(!this.rtc) {
  885. console.error("Mute is not supported for streams not attached to conference!");
  886. return;
  887. }
  888. var isAudio = this.type === JitsiTrack.AUDIO;
  889. this.dontFireRemoveEvent = false;
  890. if ((window.location.protocol != "https:") ||
  891. (isAudio) || this.videoType === "screen" ||
  892. // FIXME FF does not support 'removeStream' method used to mute
  893. RTCBrowserType.isFirefox()) {
  894. var tracks = this._getTracks();
  895. for (var idx = 0; idx < tracks.length; idx++) {
  896. tracks[idx].enabled = !mute;
  897. }
  898. if(isAudio)
  899. this.rtc.room.setAudioMute(mute);
  900. else
  901. this.rtc.room.setVideoMute(mute);
  902. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  903. } else {
  904. if (mute) {
  905. this.dontFireRemoveEvent = true;
  906. this.rtc.room.removeStream(this.stream);
  907. this.stream.stop();
  908. if(isAudio)
  909. this.rtc.room.setAudioMute(mute);
  910. else
  911. this.rtc.room.setVideoMute(mute);
  912. this.stream = null;
  913. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  914. //FIXME: Maybe here we should set the SRC for the containers to something
  915. } else {
  916. var self = this;
  917. var RTC = require("./RTCUtils");
  918. RTC.obtainAudioAndVideoPermissions({
  919. devices: (isAudio ? ["audio"] : ["video"]),
  920. resolution: self.resolution,
  921. dontCreateJitsiTrack: true})
  922. .then(function (streams) {
  923. var stream = null;
  924. for(var i = 0; i < streams.length; i++) {
  925. stream = streams[i];
  926. if(stream.type === self.type) {
  927. self.stream = stream.stream;
  928. self.videoType = stream.videoType;
  929. break;
  930. }
  931. }
  932. if(!stream)
  933. return;
  934. for(var i = 0; i < self.containers.length; i++)
  935. {
  936. RTC.attachMediaStream(self.containers[i], self.stream);
  937. }
  938. self.rtc.room.addStream(stream.stream,
  939. function () {
  940. if(isAudio)
  941. self.rtc.room.setAudioMute(mute);
  942. else
  943. self.rtc.room.setVideoMute(mute);
  944. self.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  945. });
  946. });
  947. }
  948. }
  949. }
  950. /**
  951. * Stops sending the media track. And removes it from the HTML.
  952. * NOTE: Works for local tracks only.
  953. */
  954. JitsiLocalTrack.prototype.stop = function () {
  955. if(!this.stream)
  956. return;
  957. if(this.rtc)
  958. this.rtc.room.removeStream(this.stream);
  959. this.stream.stop();
  960. this.detach();
  961. }
  962. /**
  963. * Returns <tt>true</tt> - if the stream is muted
  964. * and <tt>false</tt> otherwise.
  965. * @returns {boolean} <tt>true</tt> - if the stream is muted
  966. * and <tt>false</tt> otherwise.
  967. */
  968. JitsiLocalTrack.prototype.isMuted = function () {
  969. if (!this.stream)
  970. return true;
  971. var tracks = [];
  972. var isAudio = this.type === JitsiTrack.AUDIO;
  973. if (isAudio) {
  974. tracks = this.stream.getAudioTracks();
  975. } else {
  976. if (this.stream.ended)
  977. return true;
  978. tracks = this.stream.getVideoTracks();
  979. }
  980. for (var idx = 0; idx < tracks.length; idx++) {
  981. if(tracks[idx].enabled)
  982. return false;
  983. }
  984. return true;
  985. };
  986. /**
  987. * Private method. Updates rtc property of the track.
  988. * @param rtc the rtc instance.
  989. */
  990. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  991. this.rtc = rtc;
  992. };
  993. module.exports = JitsiLocalTrack;
  994. },{"../../service/RTC/StreamEventTypes":78,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils":15}],11:[function(require,module,exports){
  995. var JitsiTrack = require("./JitsiTrack");
  996. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  997. /**
  998. * Represents a single media track (either audio or video).
  999. * @param RTC the rtc instance.
  1000. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1001. * @param sid sid for the Media Stream
  1002. * @param ssrc ssrc for the Media Stream
  1003. * @param eventEmitter the event emitter
  1004. * @constructor
  1005. */
  1006. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  1007. JitsiTrack.call(this, RTC, data.stream);
  1008. this.rtc = RTC;
  1009. this.sid = sid;
  1010. this.stream = data.stream;
  1011. this.peerjid = data.peerjid;
  1012. this.videoType = data.videoType;
  1013. this.ssrc = ssrc;
  1014. this.muted = false;
  1015. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1016. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1017. this.muted = true
  1018. }
  1019. this.eventEmitter = eventEmitter;
  1020. var self = this;
  1021. if(this.stream)
  1022. this.stream.onended = function () {
  1023. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  1024. }
  1025. }
  1026. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1027. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1028. /**
  1029. * Sets current muted status and fires an events for the change.
  1030. * @param value the muted status.
  1031. */
  1032. JitsiRemoteTrack.prototype.setMute = function (value) {
  1033. this.stream.muted = value;
  1034. this.muted = value;
  1035. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1036. };
  1037. /**
  1038. * Returns the current muted status of the track.
  1039. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1040. */
  1041. JitsiRemoteTrack.prototype.isMuted = function () {
  1042. return this.muted;
  1043. }
  1044. /**
  1045. * Returns the participant id which owns the track.
  1046. * @returns {string} the id of the participants.
  1047. */
  1048. JitsiRemoteTrack.prototype.getParitcipantId = function() {
  1049. return Strophe.getResourceFromJid(this.peerjid);
  1050. };
  1051. delete JitsiRemoteTrack.prototype.stop;
  1052. delete JitsiRemoteTrack.prototype.start;
  1053. module.exports = JitsiRemoteTrack;
  1054. },{"../../service/RTC/StreamEventTypes":78,"./JitsiTrack":12}],12:[function(require,module,exports){
  1055. var RTCBrowserType = require("./RTCBrowserType");
  1056. /**
  1057. * This implements 'onended' callback normally fired by WebRTC after the stream
  1058. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1059. * @param stream original WebRTC stream object to which 'onended' handling
  1060. * will be added.
  1061. */
  1062. function implementOnEndedHandling(stream) {
  1063. var originalStop = stream.stop;
  1064. stream.stop = function () {
  1065. originalStop.apply(stream);
  1066. if (!stream.ended) {
  1067. stream.ended = true;
  1068. stream.onended();
  1069. }
  1070. };
  1071. }
  1072. /**
  1073. * Represents a single media track (either audio or video).
  1074. * @constructor
  1075. */
  1076. function JitsiTrack(rtc, stream)
  1077. {
  1078. /**
  1079. * Array with the HTML elements that are displaying the streams.
  1080. * @type {Array}
  1081. */
  1082. this.containers = [];
  1083. this.rtc = rtc;
  1084. this.stream = stream;
  1085. this.type = (this.stream.getVideoTracks().length > 0)?
  1086. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1087. if(this.type == "audio") {
  1088. this._getTracks = function () {
  1089. return this.stream.getAudioTracks();
  1090. }.bind(this);
  1091. } else {
  1092. this._getTracks = function () {
  1093. return this.stream.getVideoTracks();
  1094. }.bind(this);
  1095. }
  1096. if (RTCBrowserType.isFirefox() && this.stream) {
  1097. implementOnEndedHandling(this.stream);
  1098. }
  1099. }
  1100. /**
  1101. * JitsiTrack video type.
  1102. * @type {string}
  1103. */
  1104. JitsiTrack.VIDEO = "video";
  1105. /**
  1106. * JitsiTrack audio type.
  1107. * @type {string}
  1108. */
  1109. JitsiTrack.AUDIO = "audio";
  1110. /**
  1111. * Returns the type (audio or video) of this track.
  1112. */
  1113. JitsiTrack.prototype.getType = function() {
  1114. return this.type;
  1115. };
  1116. /**
  1117. * Returns the RTCMediaStream from the browser (?).
  1118. */
  1119. JitsiTrack.prototype.getOriginalStream = function() {
  1120. return this.stream;
  1121. }
  1122. /**
  1123. * Mutes the track.
  1124. */
  1125. JitsiTrack.prototype.mute = function () {
  1126. this._setMute(true);
  1127. }
  1128. /**
  1129. * Unmutes the stream.
  1130. */
  1131. JitsiTrack.prototype.unmute = function () {
  1132. this._setMute(false);
  1133. }
  1134. /**
  1135. * Attaches the MediaStream of this track to an HTML container (?).
  1136. * Adds the container to the list of containers that are displaying the track.
  1137. * @param container the HTML container
  1138. */
  1139. JitsiTrack.prototype.attach = function (container) {
  1140. if(this.stream)
  1141. require("./RTCUtils").attachMediaStream(container, this.stream);
  1142. this.containers.push(container);
  1143. }
  1144. /**
  1145. * Removes the track from the passed HTML container.
  1146. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1147. */
  1148. JitsiTrack.prototype.detach = function (container) {
  1149. for(var i = 0; i < this.containers.length; i++)
  1150. {
  1151. if(this.containers[i].is(container))
  1152. {
  1153. this.containers.splice(i,1);
  1154. }
  1155. if(!container)
  1156. {
  1157. this.containers[i].find(">video").remove();
  1158. }
  1159. }
  1160. if(container)
  1161. $(container).find(">video").remove();
  1162. }
  1163. /**
  1164. * Stops sending the media track. And removes it from the HTML.
  1165. * NOTE: Works for local tracks only.
  1166. */
  1167. JitsiTrack.prototype.stop = function () {
  1168. }
  1169. /**
  1170. * Returns true if this is a video track and the source of the video is a
  1171. * screen capture as opposed to a camera.
  1172. */
  1173. JitsiTrack.prototype.isScreenSharing = function(){
  1174. }
  1175. /**
  1176. * Returns id of the track.
  1177. * @returns {string} id of the track or null if this is fake track.
  1178. */
  1179. JitsiTrack.prototype.getId = function () {
  1180. var tracks = this.stream.getTracks();
  1181. if(!tracks || tracks.length === 0)
  1182. return null;
  1183. return tracks[0].id;
  1184. };
  1185. module.exports = JitsiTrack;
  1186. },{"./RTCBrowserType":14,"./RTCUtils":15}],13:[function(require,module,exports){
  1187. /* global APP */
  1188. var EventEmitter = require("events");
  1189. var RTCBrowserType = require("./RTCBrowserType");
  1190. var RTCUtils = require("./RTCUtils.js");
  1191. var JitsiTrack = require("./JitsiTrack");
  1192. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1193. var DataChannels = require("./DataChannels");
  1194. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1195. var DesktopSharingEventTypes
  1196. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1197. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1198. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1199. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1200. var desktopsharing = require("../desktopsharing/desktopsharing");
  1201. function RTC(room, options) {
  1202. this.room = room;
  1203. this.localStreams = [];
  1204. this.remoteStreams = {};
  1205. this.localAudio = null;
  1206. this.localVideo = null;
  1207. this.eventEmitter = new EventEmitter();
  1208. var self = this;
  1209. this.options = options || {};
  1210. desktopsharing.addListener(
  1211. function (stream, isUsingScreenStream, callback) {
  1212. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1213. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1214. room.addPresenceListener("videomuted", function (values, from) {
  1215. if(self.remoteStreams[from])
  1216. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1217. });
  1218. room.addPresenceListener("audiomuted", function (values, from) {
  1219. if(self.remoteStreams[from])
  1220. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1221. });
  1222. }
  1223. /**
  1224. * Creates the local MediaStreams.
  1225. * @param {Object} [options] optional parameters
  1226. * @param {Array} options.devices the devices that will be requested
  1227. * @param {string} options.resolution resolution constraints
  1228. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1229. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1230. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1231. * @param {string} options.cameraDeviceId
  1232. * @param {string} options.micDeviceId
  1233. * @returns {*} Promise object that will receive the new JitsiTracks
  1234. */
  1235. RTC.obtainAudioAndVideoPermissions = function (options) {
  1236. return RTCUtils.obtainAudioAndVideoPermissions(options);
  1237. }
  1238. RTC.prototype.onIncommingCall = function(event) {
  1239. if(this.options.config.openSctp)
  1240. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1241. for(var i = 0; i < this.localStreams.length; i++)
  1242. if(this.localStreams[i])
  1243. {
  1244. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1245. }
  1246. }
  1247. RTC.prototype.selectedEndpoint = function (id) {
  1248. if(this.dataChannels)
  1249. this.dataChannels.handleSelectedEndpointEvent(id);
  1250. }
  1251. RTC.prototype.pinEndpoint = function (id) {
  1252. if(this.dataChannels)
  1253. this.dataChannels.handlePinnedEndpointEvent(id);
  1254. }
  1255. RTC.prototype.addListener = function (type, listener) {
  1256. this.eventEmitter.on(type, listener);
  1257. };
  1258. RTC.prototype.removeListener = function (eventType, listener) {
  1259. this.eventEmitter.removeListener(eventType, listener);
  1260. };
  1261. RTC.addListener = function (eventType, listener) {
  1262. RTCUtils.addListener(eventType, listener);
  1263. }
  1264. RTC.removeListener = function (eventType, listener) {
  1265. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1266. RTCUtils.removeListener(eventType, listener)
  1267. }
  1268. RTC.isRTCReady = function () {
  1269. return RTCUtils.isRTCReady();
  1270. }
  1271. RTC.init = function (options) {
  1272. RTCUtils.init(options || {});
  1273. }
  1274. RTC.getDeviceAvailability = function () {
  1275. return RTCUtils.getDeviceAvailability();
  1276. }
  1277. RTC.prototype.addLocalStream = function (stream) {
  1278. this.localStreams.push(stream);
  1279. stream._setRTC(this);
  1280. if (stream.type == "audio") {
  1281. this.localAudio = stream;
  1282. } else {
  1283. this.localVideo = stream;
  1284. }
  1285. };
  1286. RTC.prototype.removeLocalStream = function (stream) {
  1287. for(var i = 0; i < this.localStreams.length; i++) {
  1288. if(this.localStreams[i].getOriginalStream() === stream) {
  1289. delete this.localStreams[i];
  1290. return;
  1291. }
  1292. }
  1293. };
  1294. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1295. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1296. this.eventEmitter);
  1297. if(!data.peerjid)
  1298. return;
  1299. var jid = data.peerjid;
  1300. if(!this.remoteStreams[jid]) {
  1301. this.remoteStreams[jid] = {};
  1302. }
  1303. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1304. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1305. return remoteStream;
  1306. };
  1307. RTC.getPCConstraints = function () {
  1308. return RTCUtils.pc_constraints;
  1309. };
  1310. RTC.getUserMediaWithConstraints = function(um, success_callback,
  1311. failure_callback, options)
  1312. {
  1313. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  1314. failure_callback, options);
  1315. };
  1316. RTC.attachMediaStream = function (elSelector, stream) {
  1317. RTCUtils.attachMediaStream(elSelector, stream);
  1318. };
  1319. RTC.getStreamID = function (stream) {
  1320. return RTCUtils.getStreamID(stream);
  1321. };
  1322. RTC.getVideoSrc = function (element) {
  1323. return RTCUtils.getVideoSrc(element);
  1324. };
  1325. RTC.isDeviceListAvailable = function () {
  1326. return RTCUtils.isDeviceListAvailable();
  1327. };
  1328. /**
  1329. * Allows to receive list of available cameras/microphones.
  1330. * @param {function} callback would receive array of devices as an argument
  1331. */
  1332. RTC.enumerateDevices = function (callback) {
  1333. RTCUtils.enumerateDevices(callback);
  1334. };
  1335. RTC.setVideoSrc = function (element, src) {
  1336. RTCUtils.setVideoSrc(element, src);
  1337. };
  1338. RTC.prototype.getVideoElementName = function () {
  1339. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1340. };
  1341. RTC.prototype.dispose = function() {
  1342. };
  1343. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1344. var stream;
  1345. if(this.remoteStreams[jid] &&
  1346. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1347. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1348. }
  1349. if(!stream)
  1350. return true;
  1351. if (value != stream.muted) {
  1352. stream.setMute(value);
  1353. return true;
  1354. }
  1355. return false;
  1356. };
  1357. RTC.prototype.switchVideoStreams = function (new_stream) {
  1358. this.localVideo.stream = new_stream;
  1359. this.localStreams = [];
  1360. //in firefox we have only one stream object
  1361. if (this.localAudio.getOriginalStream() != new_stream)
  1362. this.localStreams.push(this.localAudio);
  1363. this.localStreams.push(this.localVideo);
  1364. };
  1365. /**
  1366. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local video.
  1367. * The method also handles the sdp changes.
  1368. * @param stream the new MediaStream received by the browser.
  1369. * @param isUsingScreenStream <tt>true</tt> if the stream is for desktop stream.
  1370. * @param callback - function that will be called after the operation is completed.
  1371. */
  1372. RTC.prototype.changeLocalVideo = function (stream, isUsingScreenStream, callback) {
  1373. var oldStream = this.localVideo.getOriginalStream();
  1374. var type = (isUsingScreenStream ? "screen" : "camera");
  1375. var localCallback = callback;
  1376. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1377. localCallback = function() {
  1378. this.room.setVideoMute(false, function(mute) {
  1379. this.eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1380. }.bind(this));
  1381. callback();
  1382. };
  1383. }
  1384. // FIXME: Workaround for FF/IE/Safari
  1385. if (stream && stream.videoStream) {
  1386. stream = stream.videoStream;
  1387. }
  1388. var videoStream = RTCUtils.createStream(stream, true);
  1389. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1390. // Stop the stream to trigger onended event for old stream
  1391. oldStream.stop();
  1392. this.switchVideoStreams(videoStream, oldStream);
  1393. this.room.switchStreams(videoStream, oldStream,localCallback);
  1394. };
  1395. /**
  1396. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local audio.
  1397. * The method also handles the sdp changes.
  1398. * @param stream the new MediaStream received by the browser.
  1399. * @param callback - function that will be called after the operation is completed.
  1400. */
  1401. RTC.prototype.changeLocalAudio = function (stream, callback) {
  1402. var oldStream = this.localAudio.getOriginalStream();
  1403. var newStream = RTCUtils.createStream(stream);
  1404. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1405. // Stop the stream to trigger onended event for old stream
  1406. oldStream.stop();
  1407. this.room.switchStreams(newStream, oldStream, callback, true);
  1408. };
  1409. RTC.prototype.isVideoMuted = function (jid) {
  1410. if (jid === APP.xmpp.myJid()) {
  1411. var localVideo = APP.RTC.localVideo;
  1412. return (!localVideo || localVideo.isMuted());
  1413. } else {
  1414. if (!this.remoteStreams[jid] ||
  1415. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1416. return null;
  1417. }
  1418. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1419. }
  1420. };
  1421. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1422. if (!this.localVideo)
  1423. return;
  1424. if (mute == this.localVideo.isMuted())
  1425. {
  1426. APP.xmpp.sendVideoInfoPresence(mute);
  1427. if (callback)
  1428. callback(mute);
  1429. }
  1430. else
  1431. {
  1432. this.localVideo.setMute(mute);
  1433. this.room.setVideoMute(
  1434. mute,
  1435. callback,
  1436. options);
  1437. }
  1438. };
  1439. module.exports = RTC;
  1440. },{"../../service/RTC/MediaStreamTypes":75,"../../service/RTC/RTCEvents.js":76,"../../service/RTC/StreamEventTypes.js":78,"../../service/desktopsharing/DesktopSharingEventTypes":80,"../desktopsharing/desktopsharing":17,"./DataChannels":9,"./JitsiLocalTrack.js":10,"./JitsiRemoteTrack.js":11,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils.js":15,"events":40}],14:[function(require,module,exports){
  1441. var currentBrowser;
  1442. var browserVersion;
  1443. var isAndroid;
  1444. var RTCBrowserType = {
  1445. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1446. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1447. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1448. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1449. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1450. getBrowserType: function () {
  1451. return currentBrowser;
  1452. },
  1453. isChrome: function () {
  1454. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1455. },
  1456. isOpera: function () {
  1457. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1458. },
  1459. isFirefox: function () {
  1460. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1461. },
  1462. isIExplorer: function () {
  1463. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1464. },
  1465. isSafari: function () {
  1466. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1467. },
  1468. isTemasysPluginUsed: function () {
  1469. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1470. },
  1471. getFirefoxVersion: function () {
  1472. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1473. },
  1474. getChromeVersion: function () {
  1475. return RTCBrowserType.isChrome() ? browserVersion : null;
  1476. },
  1477. usesPlanB: function() {
  1478. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1479. RTCBrowserType.isTemasysPluginUsed();
  1480. },
  1481. usesUnifiedPlan: function() {
  1482. return RTCBrowserType.isFirefox();
  1483. },
  1484. /**
  1485. * Whether the browser is running on an android device.
  1486. */
  1487. isAndroid: function() {
  1488. return isAndroid;
  1489. }
  1490. // Add version getters for other browsers when needed
  1491. };
  1492. // detectOpera() must be called before detectChrome() !!!
  1493. // otherwise Opera wil be detected as Chrome
  1494. function detectChrome() {
  1495. if (navigator.webkitGetUserMedia) {
  1496. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1497. var userAgent = navigator.userAgent.toLowerCase();
  1498. // We can assume that user agent is chrome, because it's
  1499. // enforced when 'ext' streaming method is set
  1500. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1501. console.log("This appears to be Chrome, ver: " + ver);
  1502. return ver;
  1503. }
  1504. return null;
  1505. }
  1506. function detectOpera() {
  1507. var userAgent = navigator.userAgent;
  1508. if (userAgent.match(/Opera|OPR/)) {
  1509. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1510. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1511. console.info("This appears to be Opera, ver: " + version);
  1512. return version;
  1513. }
  1514. return null;
  1515. }
  1516. function detectFirefox() {
  1517. if (navigator.mozGetUserMedia) {
  1518. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1519. var version = parseInt(
  1520. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1521. console.log('This appears to be Firefox, ver: ' + version);
  1522. return version;
  1523. }
  1524. return null;
  1525. }
  1526. function detectSafari() {
  1527. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1528. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1529. console.info("This appears to be Safari");
  1530. // FIXME detect Safari version when needed
  1531. return 1;
  1532. }
  1533. return null;
  1534. }
  1535. function detectIE() {
  1536. var version;
  1537. var ua = window.navigator.userAgent;
  1538. var msie = ua.indexOf('MSIE ');
  1539. if (msie > 0) {
  1540. // IE 10 or older => return version number
  1541. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1542. }
  1543. var trident = ua.indexOf('Trident/');
  1544. if (!version && trident > 0) {
  1545. // IE 11 => return version number
  1546. var rv = ua.indexOf('rv:');
  1547. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1548. }
  1549. var edge = ua.indexOf('Edge/');
  1550. if (!version && edge > 0) {
  1551. // IE 12 => return version number
  1552. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1553. }
  1554. if (version) {
  1555. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1556. console.info("This appears to be IExplorer, ver: " + version);
  1557. }
  1558. return version;
  1559. }
  1560. function detectBrowser() {
  1561. var version;
  1562. var detectors = [
  1563. detectOpera,
  1564. detectChrome,
  1565. detectFirefox,
  1566. detectIE,
  1567. detectSafari
  1568. ];
  1569. // Try all browser detectors
  1570. for (var i = 0; i < detectors.length; i++) {
  1571. version = detectors[i]();
  1572. if (version)
  1573. return version;
  1574. }
  1575. console.error("Failed to detect browser type");
  1576. return undefined;
  1577. }
  1578. browserVersion = detectBrowser();
  1579. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1580. module.exports = RTCBrowserType;
  1581. },{}],15:[function(require,module,exports){
  1582. (function (__filename){
  1583. /* global config, require, attachMediaStream, getUserMedia */
  1584. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1585. var RTCBrowserType = require("./RTCBrowserType");
  1586. var Resolutions = require("../../service/RTC/Resolutions");
  1587. var RTCEvents = require("../../service/RTC/RTCEvents");
  1588. var AdapterJS = require("./adapter.screenshare");
  1589. var SDPUtil = require("../xmpp/SDPUtil");
  1590. var EventEmitter = require("events");
  1591. var JitsiLocalTrack = require("./JitsiLocalTrack");
  1592. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1593. var eventEmitter = new EventEmitter();
  1594. var devices = {
  1595. audio: true,
  1596. video: true
  1597. }
  1598. var rtcReady = false;
  1599. function DummyMediaStream(id) {
  1600. this.id = id;
  1601. this.label = id;
  1602. this.stop = function() { };
  1603. this.getAudioTracks = function() { return []; };
  1604. this.getVideoTracks = function() { return []; };
  1605. }
  1606. function getPreviousResolution(resolution) {
  1607. if(!Resolutions[resolution])
  1608. return null;
  1609. var order = Resolutions[resolution].order;
  1610. var res = null;
  1611. var resName = null;
  1612. for(var i in Resolutions) {
  1613. var tmp = Resolutions[i];
  1614. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1615. resName = i;
  1616. res = tmp;
  1617. }
  1618. }
  1619. return resName;
  1620. }
  1621. function setResolutionConstraints(constraints, resolution) {
  1622. var isAndroid = RTCBrowserType.isAndroid();
  1623. if (Resolutions[resolution]) {
  1624. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1625. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1626. }
  1627. else if (isAndroid) {
  1628. // FIXME can't remember if the purpose of this was to always request
  1629. // low resolution on Android ? if yes it should be moved up front
  1630. constraints.video.mandatory.minWidth = 320;
  1631. constraints.video.mandatory.minHeight = 240;
  1632. constraints.video.mandatory.maxFrameRate = 15;
  1633. }
  1634. if (constraints.video.mandatory.minWidth)
  1635. constraints.video.mandatory.maxWidth =
  1636. constraints.video.mandatory.minWidth;
  1637. if (constraints.video.mandatory.minHeight)
  1638. constraints.video.mandatory.maxHeight =
  1639. constraints.video.mandatory.minHeight;
  1640. }
  1641. /**
  1642. * @param {string[]} um required user media types
  1643. *
  1644. * @param {Object} [options={}] optional parameters
  1645. * @param {string} options.resolution
  1646. * @param {number} options.bandwidth
  1647. * @param {number} options.fps
  1648. * @param {string} options.desktopStream
  1649. * @param {string} options.cameraDeviceId
  1650. * @param {string} options.micDeviceId
  1651. * @param {bool} firefox_fake_device
  1652. */
  1653. function getConstraints(um, options) {
  1654. var constraints = {audio: false, video: false};
  1655. if (um.indexOf('video') >= 0) {
  1656. // same behaviour as true
  1657. constraints.video = { mandatory: {}, optional: [] };
  1658. if (options.cameraDeviceId) {
  1659. constraints.video.optional.push({
  1660. sourceId: options.cameraDeviceId
  1661. });
  1662. }
  1663. constraints.video.optional.push({ googLeakyBucket: true });
  1664. setResolutionConstraints(constraints, options.resolution);
  1665. }
  1666. if (um.indexOf('audio') >= 0) {
  1667. if (!RTCBrowserType.isFirefox()) {
  1668. // same behaviour as true
  1669. constraints.audio = { mandatory: {}, optional: []};
  1670. if (options.micDeviceId) {
  1671. constraints.audio.optional.push({
  1672. sourceId: options.micDeviceId
  1673. });
  1674. }
  1675. // if it is good enough for hangouts...
  1676. constraints.audio.optional.push(
  1677. {googEchoCancellation: true},
  1678. {googAutoGainControl: true},
  1679. {googNoiseSupression: true},
  1680. {googHighpassFilter: true},
  1681. {googNoisesuppression2: true},
  1682. {googEchoCancellation2: true},
  1683. {googAutoGainControl2: true}
  1684. );
  1685. } else {
  1686. if (options.micDeviceId) {
  1687. constraints.audio = {
  1688. mandatory: {},
  1689. optional: [{
  1690. sourceId: options.micDeviceId
  1691. }]};
  1692. } else {
  1693. constraints.audio = true;
  1694. }
  1695. }
  1696. }
  1697. if (um.indexOf('screen') >= 0) {
  1698. if (RTCBrowserType.isChrome()) {
  1699. constraints.video = {
  1700. mandatory: {
  1701. chromeMediaSource: "screen",
  1702. googLeakyBucket: true,
  1703. maxWidth: window.screen.width,
  1704. maxHeight: window.screen.height,
  1705. maxFrameRate: 3
  1706. },
  1707. optional: []
  1708. };
  1709. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1710. constraints.video = {
  1711. optional: [
  1712. {
  1713. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1714. }
  1715. ]
  1716. };
  1717. } else {
  1718. logger.error(
  1719. "'screen' WebRTC media source is supported only in Chrome" +
  1720. " and with Temasys plugin");
  1721. }
  1722. }
  1723. if (um.indexOf('desktop') >= 0) {
  1724. constraints.video = {
  1725. mandatory: {
  1726. chromeMediaSource: "desktop",
  1727. chromeMediaSourceId: options.desktopStream,
  1728. googLeakyBucket: true,
  1729. maxWidth: window.screen.width,
  1730. maxHeight: window.screen.height,
  1731. maxFrameRate: 3
  1732. },
  1733. optional: []
  1734. };
  1735. }
  1736. if (options.bandwidth) {
  1737. if (!constraints.video) {
  1738. //same behaviour as true
  1739. constraints.video = {mandatory: {}, optional: []};
  1740. }
  1741. constraints.video.optional.push({bandwidth: options.bandwidth});
  1742. }
  1743. if (options.fps) {
  1744. // for some cameras it might be necessary to request 30fps
  1745. // so they choose 30fps mjpg over 10fps yuy2
  1746. if (!constraints.video) {
  1747. // same behaviour as true;
  1748. constraints.video = {mandatory: {}, optional: []};
  1749. }
  1750. constraints.video.mandatory.minFrameRate = options.fps;
  1751. }
  1752. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  1753. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  1754. // this later can be a problem with some of the tests
  1755. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  1756. {
  1757. constraints.audio = true;
  1758. constraints.fake = true;
  1759. }
  1760. return constraints;
  1761. }
  1762. function setAvailableDevices(um, available) {
  1763. if (um.indexOf("video") != -1) {
  1764. devices.video = available;
  1765. }
  1766. if (um.indexOf("audio") != -1) {
  1767. devices.audio = available;
  1768. }
  1769. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  1770. }
  1771. // In case of IE we continue from 'onReady' callback
  1772. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1773. // once it is initialized.
  1774. function onReady () {
  1775. rtcReady = true;
  1776. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1777. };
  1778. /**
  1779. * Apply function with arguments if function exists.
  1780. * Do nothing if function not provided.
  1781. * @param {function} [fn] function to apply
  1782. * @param {Array} [args=[]] arguments for function
  1783. */
  1784. function maybeApply(fn, args) {
  1785. if (fn) {
  1786. fn.apply(null, args || []);
  1787. }
  1788. }
  1789. var getUserMediaStatus = {
  1790. initialized: false,
  1791. callbacks: []
  1792. };
  1793. /**
  1794. * Wrap `getUserMedia` to allow others to know if it was executed at least
  1795. * once or not. Wrapper function uses `getUserMediaStatus` object.
  1796. * @param {Function} getUserMedia native function
  1797. * @returns {Function} wrapped function
  1798. */
  1799. function wrapGetUserMedia(getUserMedia) {
  1800. return function (constraints, successCallback, errorCallback) {
  1801. getUserMedia(constraints, function (stream) {
  1802. maybeApply(successCallback, [stream]);
  1803. if (!getUserMediaStatus.initialized) {
  1804. getUserMediaStatus.initialized = true;
  1805. getUserMediaStatus.callbacks.forEach(function (callback) {
  1806. callback();
  1807. });
  1808. getUserMediaStatus.callbacks.length = 0;
  1809. }
  1810. }, function (error) {
  1811. maybeApply(errorCallback, [error]);
  1812. });
  1813. };
  1814. }
  1815. /**
  1816. * Create stub device which equals to auto selected device.
  1817. * @param {string} kind if that should be `audio` or `video` device
  1818. * @returns {Object} stub device description in `enumerateDevices` format
  1819. */
  1820. function createAutoDeviceInfo(kind) {
  1821. return {
  1822. facing: null,
  1823. label: 'Auto',
  1824. kind: kind,
  1825. deviceId: '',
  1826. groupId: null
  1827. };
  1828. }
  1829. /**
  1830. * Execute function after getUserMedia was executed at least once.
  1831. * @param {Function} callback function to execute after getUserMedia
  1832. */
  1833. function afterUserMediaInitialized(callback) {
  1834. if (getUserMediaStatus.initialized) {
  1835. callback();
  1836. } else {
  1837. getUserMediaStatus.callbacks.push(callback);
  1838. }
  1839. }
  1840. /**
  1841. * Wrapper function which makes enumerateDevices to wait
  1842. * until someone executes getUserMedia first time.
  1843. * @param {Function} enumerateDevices native function
  1844. * @returns {Funtion} wrapped function
  1845. */
  1846. function wrapEnumerateDevices(enumerateDevices) {
  1847. return function (callback) {
  1848. // enumerate devices only after initial getUserMedia
  1849. afterUserMediaInitialized(function () {
  1850. enumerateDevices().then(function (devices) {
  1851. //add auto devices
  1852. devices.unshift(
  1853. createAutoDeviceInfo('audioinput'),
  1854. createAutoDeviceInfo('videoinput')
  1855. );
  1856. callback(devices);
  1857. }, function (err) {
  1858. console.error('cannot enumerate devices: ', err);
  1859. // return only auto devices
  1860. callback([createAutoDeviceInfo('audioInput'),
  1861. createAutoDeviceInfo('videoinput')]);
  1862. });
  1863. });
  1864. };
  1865. }
  1866. /**
  1867. * Use old MediaStreamTrack to get devices list and
  1868. * convert it to enumerateDevices format.
  1869. * @param {Function} callback function to call when received devices list.
  1870. */
  1871. function enumerateDevicesThroughMediaStreamTrack (callback) {
  1872. MediaStreamTrack.getSources(function (sources) {
  1873. var devices = sources.map(function (source) {
  1874. var kind = (source.kind || '').toLowerCase();
  1875. return {
  1876. facing: source.facing || null,
  1877. label: source.label,
  1878. kind: kind ? kind + 'input': null,
  1879. deviceId: source.id,
  1880. groupId: source.groupId || null
  1881. };
  1882. });
  1883. //add auto devices
  1884. devices.unshift(
  1885. createAutoDeviceInfo('audioinput'),
  1886. createAutoDeviceInfo('videoinput')
  1887. );
  1888. callback(devices);
  1889. });
  1890. }
  1891. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1892. var RTCUtils = {
  1893. init: function (options) {
  1894. var self = this;
  1895. if (RTCBrowserType.isFirefox()) {
  1896. var FFversion = RTCBrowserType.getFirefoxVersion();
  1897. if (FFversion >= 40) {
  1898. this.peerconnection = mozRTCPeerConnection;
  1899. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  1900. this.enumerateDevices = wrapEnumerateDevices(
  1901. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  1902. );
  1903. this.pc_constraints = {};
  1904. this.attachMediaStream = function (element, stream) {
  1905. // srcObject is being standardized and FF will eventually
  1906. // support that unprefixed. FF also supports the
  1907. // "element.src = URL.createObjectURL(...)" combo, but that
  1908. // will be deprecated in favour of srcObject.
  1909. //
  1910. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1911. // https://github.com/webrtc/samples/issues/302
  1912. if (!element[0])
  1913. return;
  1914. element[0].mozSrcObject = stream;
  1915. element[0].play();
  1916. };
  1917. this.getStreamID = function (stream) {
  1918. var id = stream.id;
  1919. if (!id) {
  1920. var tracks = stream.getVideoTracks();
  1921. if (!tracks || tracks.length === 0) {
  1922. tracks = stream.getAudioTracks();
  1923. }
  1924. id = tracks[0].id;
  1925. }
  1926. return SDPUtil.filter_special_chars(id);
  1927. };
  1928. this.getVideoSrc = function (element) {
  1929. if (!element)
  1930. return null;
  1931. return element.mozSrcObject;
  1932. };
  1933. this.setVideoSrc = function (element, src) {
  1934. if (element)
  1935. element.mozSrcObject = src;
  1936. };
  1937. RTCSessionDescription = mozRTCSessionDescription;
  1938. RTCIceCandidate = mozRTCIceCandidate;
  1939. } else {
  1940. logger.error(
  1941. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1942. window.location.href = 'unsupported_browser.html';
  1943. return;
  1944. }
  1945. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1946. this.peerconnection = webkitRTCPeerConnection;
  1947. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1948. if (navigator.mediaDevices) {
  1949. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  1950. this.enumerateDevices = wrapEnumerateDevices(
  1951. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  1952. );
  1953. } else {
  1954. this.getUserMedia = getUserMedia;
  1955. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  1956. }
  1957. this.attachMediaStream = function (element, stream) {
  1958. element.attr('src', webkitURL.createObjectURL(stream));
  1959. };
  1960. this.getStreamID = function (stream) {
  1961. // streams from FF endpoints have the characters '{' and '}'
  1962. // that make jQuery choke.
  1963. return SDPUtil.filter_special_chars(stream.id);
  1964. };
  1965. this.getVideoSrc = function (element) {
  1966. if (!element)
  1967. return null;
  1968. return element.getAttribute("src");
  1969. };
  1970. this.setVideoSrc = function (element, src) {
  1971. if (element)
  1972. element.setAttribute("src", src);
  1973. };
  1974. // DTLS should now be enabled by default but..
  1975. this.pc_constraints = {'optional': [
  1976. {'DtlsSrtpKeyAgreement': 'true'}
  1977. ]};
  1978. if (options.useIPv6) {
  1979. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1980. this.pc_constraints.optional.push({googIPv6: true});
  1981. }
  1982. if (RTCBrowserType.isAndroid()) {
  1983. this.pc_constraints = {}; // disable DTLS on Android
  1984. }
  1985. if (!webkitMediaStream.prototype.getVideoTracks) {
  1986. webkitMediaStream.prototype.getVideoTracks = function () {
  1987. return this.videoTracks;
  1988. };
  1989. }
  1990. if (!webkitMediaStream.prototype.getAudioTracks) {
  1991. webkitMediaStream.prototype.getAudioTracks = function () {
  1992. return this.audioTracks;
  1993. };
  1994. }
  1995. }
  1996. // Detect IE/Safari
  1997. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1998. //AdapterJS.WebRTCPlugin.setLogLevel(
  1999. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2000. AdapterJS.webRTCReady(function (isPlugin) {
  2001. self.peerconnection = RTCPeerConnection;
  2002. self.getUserMedia = getUserMedia;
  2003. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2004. self.attachMediaStream = function (elSel, stream) {
  2005. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2006. return;
  2007. }
  2008. attachMediaStream(elSel[0], stream);
  2009. };
  2010. self.getStreamID = function (stream) {
  2011. var id = SDPUtil.filter_special_chars(stream.label);
  2012. return id;
  2013. };
  2014. self.getVideoSrc = function (element) {
  2015. if (!element) {
  2016. logger.warn("Attempt to get video SRC of null element");
  2017. return null;
  2018. }
  2019. var children = element.children;
  2020. for (var i = 0; i !== children.length; ++i) {
  2021. if (children[i].name === 'streamId') {
  2022. return children[i].value;
  2023. }
  2024. }
  2025. //logger.info(element.id + " SRC: " + src);
  2026. return null;
  2027. };
  2028. self.setVideoSrc = function (element, src) {
  2029. //logger.info("Set video src: ", element, src);
  2030. if (!src) {
  2031. logger.warn("Not attaching video stream, 'src' is null");
  2032. return;
  2033. }
  2034. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2035. var stream = AdapterJS.WebRTCPlugin.plugin
  2036. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2037. attachMediaStream(element, stream);
  2038. };
  2039. onReady(isPlugin);
  2040. });
  2041. } else {
  2042. try {
  2043. logger.error('Browser does not appear to be WebRTC-capable');
  2044. } catch (e) {
  2045. }
  2046. return;
  2047. }
  2048. // Call onReady() if Temasys plugin is not used
  2049. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2050. onReady();
  2051. }
  2052. },
  2053. /**
  2054. * @param {string[]} um required user media types
  2055. * @param {function} success_callback
  2056. * @param {Function} failure_callback
  2057. * @param {Object} [options] optional parameters
  2058. * @param {string} options.resolution
  2059. * @param {number} options.bandwidth
  2060. * @param {number} options.fps
  2061. * @param {string} options.desktopStream
  2062. * @param {string} options.cameraDeviceId
  2063. * @param {string} options.micDeviceId
  2064. **/
  2065. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2066. options = options || {};
  2067. resolution = options.resolution;
  2068. var constraints = getConstraints(
  2069. um, options);
  2070. logger.info("Get media constraints", constraints);
  2071. try {
  2072. this.getUserMedia(constraints,
  2073. function (stream) {
  2074. logger.log('onUserMediaSuccess');
  2075. setAvailableDevices(um, true);
  2076. success_callback(stream);
  2077. },
  2078. function (error) {
  2079. setAvailableDevices(um, false);
  2080. logger.warn('Failed to get access to local media. Error ',
  2081. error, constraints);
  2082. if (failure_callback) {
  2083. failure_callback(error, resolution);
  2084. }
  2085. });
  2086. } catch (e) {
  2087. logger.error('GUM failed: ', e);
  2088. if (failure_callback) {
  2089. failure_callback(e);
  2090. }
  2091. }
  2092. },
  2093. /**
  2094. * Creates the local MediaStreams.
  2095. * @param {Object} [options] optional parameters
  2096. * @param {Array} options.devices the devices that will be requested
  2097. * @param {string} options.resolution resolution constraints
  2098. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2099. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2100. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2101. * @param {string} options.cameraDeviceId
  2102. * @param {string} options.micDeviceId
  2103. * @returns {*} Promise object that will receive the new JitsiTracks
  2104. */
  2105. obtainAudioAndVideoPermissions: function (options) {
  2106. var self = this;
  2107. options = options || {};
  2108. return new Promise(function (resolve, reject) {
  2109. var successCallback = function (stream) {
  2110. var streams = self.successCallback(stream, options.resolution);
  2111. resolve(options.dontCreateJitsiTracks?
  2112. streams: self.createLocalTracks(streams));
  2113. };
  2114. options.devices = options.devices || ['audio', 'video'];
  2115. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  2116. // With FF/IE we can't split the stream into audio and video because FF
  2117. // doesn't support media stream constructors. So, we need to get the
  2118. // audio stream separately from the video stream using two distinct GUM
  2119. // calls. Not very user friendly :-( but we don't have many other
  2120. // options neither.
  2121. //
  2122. // Note that we pack those 2 streams in a single object and pass it to
  2123. // the successCallback method.
  2124. var obtainVideo = function (audioStream) {
  2125. self.getUserMediaWithConstraints(
  2126. ['video'],
  2127. function (videoStream) {
  2128. return successCallback({
  2129. audioStream: audioStream,
  2130. videoStream: videoStream
  2131. });
  2132. },
  2133. function (error, resolution) {
  2134. logger.error(
  2135. 'failed to obtain video stream - stop', error);
  2136. self.errorCallback(error, resolve, options);
  2137. },
  2138. {resolution: options.resolution || '360',
  2139. cameraDeviceId: options.cameraDeviceId});
  2140. };
  2141. var obtainAudio = function () {
  2142. self.getUserMediaWithConstraints(
  2143. ['audio'],
  2144. function (audioStream) {
  2145. (options.devices.indexOf('video') === -1) ||
  2146. obtainVideo(audioStream);
  2147. },
  2148. function (error) {
  2149. logger.error(
  2150. 'failed to obtain audio stream - stop', error);
  2151. self.errorCallback(error, resolve, options);
  2152. },{micDeviceId: options.micDeviceId});
  2153. };
  2154. if((devices.indexOf('audio') === -1))
  2155. obtainVideo(null)
  2156. else
  2157. obtainAudio();
  2158. } else {
  2159. this.getUserMediaWithConstraints(
  2160. options.devices,
  2161. function (stream) {
  2162. successCallback(stream);
  2163. },
  2164. function (error, resolution) {
  2165. self.errorCallback(error, resolve, options);
  2166. },
  2167. {resolution: options.resolution || '360',
  2168. cameraDeviceId: options.cameraDeviceId,
  2169. micDeviceId: options.micDeviceId});
  2170. }
  2171. }.bind(this));
  2172. },
  2173. /**
  2174. * Successful callback called from GUM.
  2175. * @param stream the new MediaStream
  2176. * @param resolution the resolution of the video stream.
  2177. * @returns {*}
  2178. */
  2179. successCallback: function (stream, resolution) {
  2180. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  2181. // it's an object with two properties: audioStream, videoStream.
  2182. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  2183. logger.log('got', stream, stream.getAudioTracks().length,
  2184. stream.getVideoTracks().length);
  2185. return this.handleLocalStream(stream, resolution);
  2186. },
  2187. /**
  2188. * Error callback called from GUM. Retries the GUM call with different resolutions.
  2189. * @param error the error
  2190. * @param resolve the resolve funtion that will be called on success.
  2191. * @param {Object} options with the following properties:
  2192. * @param resolution the last resolution used for GUM.
  2193. * @param dontCreateJitsiTracks if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2194. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2195. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2196. */
  2197. errorCallback: function (error, resolve, options) {
  2198. var self = this;
  2199. options = options || {};
  2200. logger.error('failed to obtain audio/video stream - trying audio only', error);
  2201. var resolution = getPreviousResolution(options.resolution);
  2202. if (typeof error == "object" && error.constraintName && error.name
  2203. && (error.name == "ConstraintNotSatisfiedError" ||
  2204. error.name == "OverconstrainedError") &&
  2205. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  2206. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  2207. && resolution != null) {
  2208. self.getUserMediaWithConstraints(['audio', 'video'],
  2209. function (stream) {
  2210. var streams = self.successCallback(stream, resolution);
  2211. resolve(options.dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2212. }, function (error, resolution) {
  2213. return self.errorCallback(error, resolve,
  2214. {resolution: resolution,
  2215. dontCreateJitsiTracks: options.dontCreateJitsiTracks});
  2216. },
  2217. {resolution: options.resolution});
  2218. }
  2219. else {
  2220. self.getUserMediaWithConstraints(
  2221. ['audio'],
  2222. function (stream) {
  2223. var streams = self.successCallback(stream, resolution);
  2224. resolve(options.dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2225. },
  2226. function (error) {
  2227. logger.error('failed to obtain audio/video stream - stop',
  2228. error);
  2229. var streams = self.successCallback(null);
  2230. resolve(options.dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2231. }
  2232. );
  2233. }
  2234. },
  2235. /**
  2236. * Handles the newly created Media Streams.
  2237. * @param stream the new Media Streams
  2238. * @param resolution the resolution of the video stream.
  2239. * @returns {*[]} Promise object with the new Media Streams.
  2240. */
  2241. handleLocalStream: function (stream, resolution) {
  2242. var audioStream, videoStream;
  2243. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2244. // an object with two properties: audioStream, videoStream.
  2245. if (window.webkitMediaStream) {
  2246. audioStream = new webkitMediaStream();
  2247. videoStream = new webkitMediaStream();
  2248. if (stream) {
  2249. var audioTracks = stream.getAudioTracks();
  2250. for (var i = 0; i < audioTracks.length; i++) {
  2251. audioStream.addTrack(audioTracks[i]);
  2252. }
  2253. var videoTracks = stream.getVideoTracks();
  2254. for (i = 0; i < videoTracks.length; i++) {
  2255. videoStream.addTrack(videoTracks[i]);
  2256. }
  2257. }
  2258. }
  2259. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2260. if (stream && stream.audioStream)
  2261. audioStream = stream.audioStream;
  2262. else
  2263. audioStream = new DummyMediaStream("dummyAudio");
  2264. if (stream && stream.videoStream)
  2265. videoStream = stream.videoStream;
  2266. else
  2267. videoStream = new DummyMediaStream("dummyVideo");
  2268. }
  2269. return [
  2270. {stream: audioStream, type: "audio", videoType: null},
  2271. {stream: videoStream, type: "video", videoType: "camera",
  2272. resolution: resolution}
  2273. ];
  2274. },
  2275. createStream: function (stream, isVideo) {
  2276. var newStream = null;
  2277. if (window.webkitMediaStream) {
  2278. newStream = new webkitMediaStream();
  2279. if (newStream) {
  2280. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  2281. for (var i = 0; i < tracks.length; i++) {
  2282. newStream.addTrack(tracks[i]);
  2283. }
  2284. }
  2285. } else {
  2286. // FIXME: this is duplicated with 'handleLocalStream' !!!
  2287. if (stream) {
  2288. newStream = stream;
  2289. } else {
  2290. newStream =
  2291. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  2292. }
  2293. }
  2294. return newStream;
  2295. },
  2296. addListener: function (eventType, listener) {
  2297. eventEmitter.on(eventType, listener);
  2298. },
  2299. removeListener: function (eventType, listener) {
  2300. eventEmitter.removeListener(eventType, listener);
  2301. },
  2302. getDeviceAvailability: function () {
  2303. return devices;
  2304. },
  2305. isRTCReady: function () {
  2306. return rtcReady;
  2307. },
  2308. createLocalTracks: function (streams) {
  2309. var newStreams = []
  2310. for (var i = 0; i < streams.length; i++) {
  2311. var localStream = new JitsiLocalTrack(null, streams[i].stream,
  2312. eventEmitter, streams[i].videoType, streams[i].resolution);
  2313. newStreams.push(localStream);
  2314. if (streams[i].isMuted === true)
  2315. localStream.setMute(true);
  2316. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  2317. eventEmitter.emit(eventType, localStream);
  2318. }
  2319. return newStreams;
  2320. },
  2321. /**
  2322. * Checks if its possible to enumerate available cameras/micropones.
  2323. * @returns {boolean} true if available, false otherwise.
  2324. */
  2325. isDeviceListAvailable: function () {
  2326. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2327. if (isEnumerateDevicesAvailable) {
  2328. return true;
  2329. }
  2330. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2331. }
  2332. };
  2333. module.exports = RTCUtils;
  2334. }).call(this,"/modules/RTC/RTCUtils.js")
  2335. },{"../../service/RTC/RTCEvents":76,"../../service/RTC/Resolutions":77,"../../service/RTC/StreamEventTypes.js":78,"../xmpp/SDPUtil":29,"./JitsiLocalTrack":10,"./RTCBrowserType":14,"./adapter.screenshare":16,"events":40,"jitsi-meet-logger":44}],16:[function(require,module,exports){
  2336. (function (__filename){
  2337. /*! adapterjs - v0.12.0 - 2015-09-04 */
  2338. var console = require("jitsi-meet-logger").getLogger(__filename);
  2339. // Adapter's interface.
  2340. var AdapterJS = AdapterJS || {};
  2341. // Browserify compatibility
  2342. if(typeof exports !== 'undefined') {
  2343. module.exports = AdapterJS;
  2344. }
  2345. AdapterJS.options = AdapterJS.options || {};
  2346. // uncomment to get virtual webcams
  2347. // AdapterJS.options.getAllCams = true;
  2348. // uncomment to prevent the install prompt when the plugin in not yet installed
  2349. // AdapterJS.options.hidePluginInstallPrompt = true;
  2350. // AdapterJS version
  2351. AdapterJS.VERSION = '0.12.0';
  2352. // This function will be called when the WebRTC API is ready to be used
  2353. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2354. // the plugin
  2355. // You may Override this function to synchronise the start of your application
  2356. // with the WebRTC API being ready.
  2357. // If you decide not to override use this synchronisation, it may result in
  2358. // an extensive CPU usage on the plugin start (once per tab loaded)
  2359. // Params:
  2360. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2361. //
  2362. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2363. // The WebRTC API is ready.
  2364. // Override me and do whatever you want here
  2365. };
  2366. // Sets a callback function to be called when the WebRTC interface is ready.
  2367. // The first argument is the function to callback.\
  2368. // Throws an error if the first argument is not a function
  2369. AdapterJS.webRTCReady = function (callback) {
  2370. if (typeof callback !== 'function') {
  2371. throw new Error('Callback provided is not a function');
  2372. }
  2373. if (true === AdapterJS.onwebrtcreadyDone) {
  2374. // All WebRTC interfaces are ready, just call the callback
  2375. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2376. } else {
  2377. // will be triggered automatically when your browser/plugin is ready.
  2378. AdapterJS.onwebrtcready = callback;
  2379. }
  2380. };
  2381. // Plugin namespace
  2382. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2383. // The object to store plugin information
  2384. AdapterJS.WebRTCPlugin.pluginInfo = {
  2385. prefix : 'Tem',
  2386. plugName : 'TemWebRTCPlugin',
  2387. pluginId : 'plugin0',
  2388. type : 'application/x-temwebrtcplugin',
  2389. onload : '__TemWebRTCReady0',
  2390. portalLink : 'http://skylink.io/plugin/',
  2391. downloadLink : null, //set below
  2392. companyName: 'Temasys'
  2393. };
  2394. if(!!navigator.platform.match(/^Mac/i)) {
  2395. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2396. }
  2397. else if(!!navigator.platform.match(/^Win/i)) {
  2398. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2399. }
  2400. AdapterJS.WebRTCPlugin.TAGS = {
  2401. NONE : 'none',
  2402. AUDIO : 'audio',
  2403. VIDEO : 'video'
  2404. };
  2405. // Unique identifier of each opened page
  2406. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2407. // Use this whenever you want to call the plugin.
  2408. AdapterJS.WebRTCPlugin.plugin = null;
  2409. // Set log level for the plugin once it is ready.
  2410. // The different values are
  2411. // This is an asynchronous function that will run when the plugin is ready
  2412. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2413. // Defines webrtc's JS interface according to the plugin's implementation.
  2414. // Define plugin Browsers as WebRTC Interface.
  2415. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2416. // This function detects whether or not a plugin is installed.
  2417. // Checks if Not IE (firefox, for example), else if it's IE,
  2418. // we're running IE and do something. If not it is not supported.
  2419. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2420. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2421. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2422. // Inject the HTML DOM object element into the page.
  2423. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2424. // States of readiness that the plugin goes through when
  2425. // being injected and stated
  2426. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2427. NONE : 0, // no plugin use
  2428. INITIALIZING : 1, // Detected need for plugin
  2429. INJECTING : 2, // Injecting plugin
  2430. INJECTED: 3, // Plugin element injected but not usable yet
  2431. READY: 4 // Plugin ready to be used
  2432. };
  2433. // Current state of the plugin. You cannot use the plugin before this is
  2434. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2435. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2436. // True is AdapterJS.onwebrtcready was already called, false otherwise
  2437. // Used to make sure AdapterJS.onwebrtcready is only called once
  2438. AdapterJS.onwebrtcreadyDone = false;
  2439. // Log levels for the plugin.
  2440. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  2441. /*
  2442. Log outputs are prefixed in some cases.
  2443. INFO: Information reported by the plugin.
  2444. ERROR: Errors originating from within the plugin.
  2445. WEBRTC: Error originating from within the libWebRTC library
  2446. */
  2447. // From the least verbose to the most verbose
  2448. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  2449. NONE : 'NONE',
  2450. ERROR : 'ERROR',
  2451. WARNING : 'WARNING',
  2452. INFO: 'INFO',
  2453. VERBOSE: 'VERBOSE',
  2454. SENSITIVE: 'SENSITIVE'
  2455. };
  2456. // Does a waiting check before proceeding to load the plugin.
  2457. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  2458. // This methid will use an interval to wait for the plugin to be ready.
  2459. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  2460. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  2461. // This function will be called when plugin is ready. It sends necessary
  2462. // details to the plugin.
  2463. // The function will wait for the document to be ready and the set the
  2464. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2465. // indicating that it can start being requested.
  2466. // This function is not in the IE/Safari condition brackets so that
  2467. // TemPluginLoaded function might be called on Chrome/Firefox.
  2468. // This function is the only private function that is not encapsulated to
  2469. // allow the plugin method to be called.
  2470. __TemWebRTCReady0 = function () {
  2471. if (document.readyState === 'complete') {
  2472. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2473. AdapterJS.maybeThroughWebRTCReady();
  2474. } else {
  2475. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2476. if (document.readyState === 'complete') {
  2477. // TODO: update comments, we wait for the document to be ready
  2478. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2479. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2480. AdapterJS.maybeThroughWebRTCReady();
  2481. }
  2482. }, 100);
  2483. }
  2484. };
  2485. AdapterJS.maybeThroughWebRTCReady = function() {
  2486. if (!AdapterJS.onwebrtcreadyDone) {
  2487. AdapterJS.onwebrtcreadyDone = true;
  2488. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2489. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2490. }
  2491. }
  2492. };
  2493. // Text namespace
  2494. AdapterJS.TEXT = {
  2495. PLUGIN: {
  2496. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2497. 'to work on this browser.',
  2498. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2499. BUTTON: 'Install Now'
  2500. },
  2501. REFRESH: {
  2502. REQUIRE_REFRESH: 'Please refresh page',
  2503. BUTTON: 'Refresh Page'
  2504. }
  2505. };
  2506. // The result of ice connection states.
  2507. // - starting: Ice connection is starting.
  2508. // - checking: Ice connection is checking.
  2509. // - connected Ice connection is connected.
  2510. // - completed Ice connection is connected.
  2511. // - done Ice connection has been completed.
  2512. // - disconnected Ice connection has been disconnected.
  2513. // - failed Ice connection has failed.
  2514. // - closed Ice connection is closed.
  2515. AdapterJS._iceConnectionStates = {
  2516. starting : 'starting',
  2517. checking : 'checking',
  2518. connected : 'connected',
  2519. completed : 'connected',
  2520. done : 'completed',
  2521. disconnected : 'disconnected',
  2522. failed : 'failed',
  2523. closed : 'closed'
  2524. };
  2525. //The IceConnection states that has been fired for each peer.
  2526. AdapterJS._iceConnectionFiredStates = [];
  2527. // Check if WebRTC Interface is defined.
  2528. AdapterJS.isDefined = null;
  2529. // This function helps to retrieve the webrtc detected browser information.
  2530. // This sets:
  2531. // - webrtcDetectedBrowser: The browser agent name.
  2532. // - webrtcDetectedVersion: The browser version.
  2533. // - webrtcDetectedType: The types of webRTC support.
  2534. // - 'moz': Mozilla implementation of webRTC.
  2535. // - 'webkit': WebKit implementation of webRTC.
  2536. // - 'plugin': Using the plugin implementation.
  2537. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2538. var hasMatch, checkMatch = navigator.userAgent.match(
  2539. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2540. if (/trident/i.test(checkMatch[1])) {
  2541. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2542. webrtcDetectedBrowser = 'IE';
  2543. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2544. } else if (checkMatch[1] === 'Chrome') {
  2545. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2546. if (hasMatch !== null) {
  2547. webrtcDetectedBrowser = 'opera';
  2548. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2549. }
  2550. }
  2551. if (navigator.userAgent.indexOf('Safari')) {
  2552. if (typeof InstallTrigger !== 'undefined') {
  2553. webrtcDetectedBrowser = 'firefox';
  2554. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2555. webrtcDetectedBrowser = 'IE';
  2556. } else if (
  2557. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2558. webrtcDetectedBrowser = 'safari';
  2559. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2560. webrtcDetectedBrowser = 'opera';
  2561. } else if (!!window.chrome) {
  2562. webrtcDetectedBrowser = 'chrome';
  2563. }
  2564. }
  2565. if (!webrtcDetectedBrowser) {
  2566. webrtcDetectedVersion = checkMatch[1];
  2567. }
  2568. if (!webrtcDetectedVersion) {
  2569. try {
  2570. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2571. [navigator.appName, navigator.appVersion, '-?'];
  2572. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2573. checkMatch.splice(1, 1, hasMatch[1]);
  2574. }
  2575. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2576. } catch (error) { }
  2577. }
  2578. };
  2579. // To fix configuration as some browsers does not support
  2580. // the 'urls' attribute.
  2581. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2582. if (pcConfig === null) {
  2583. return;
  2584. }
  2585. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2586. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2587. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2588. delete pcConfig.iceServers[i].urls;
  2589. }
  2590. }
  2591. };
  2592. AdapterJS.addEvent = function(elem, evnt, func) {
  2593. if (elem.addEventListener) { // W3C DOM
  2594. elem.addEventListener(evnt, func, false);
  2595. } else if (elem.attachEvent) {// OLD IE DOM
  2596. elem.attachEvent('on'+evnt, func);
  2597. } else { // No much to do
  2598. elem[evnt] = func;
  2599. }
  2600. };
  2601. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2602. // only inject once the page is ready
  2603. if (document.readyState !== 'complete') {
  2604. return;
  2605. }
  2606. var w = window;
  2607. var i = document.createElement('iframe');
  2608. i.style.position = 'fixed';
  2609. i.style.top = '-41px';
  2610. i.style.left = 0;
  2611. i.style.right = 0;
  2612. i.style.width = '100%';
  2613. i.style.height = '40px';
  2614. i.style.backgroundColor = '#ffffe1';
  2615. i.style.border = 'none';
  2616. i.style.borderBottom = '1px solid #888888';
  2617. i.style.zIndex = '9999999';
  2618. if(typeof i.style.webkitTransition === 'string') {
  2619. i.style.webkitTransition = 'all .5s ease-out';
  2620. } else if(typeof i.style.transition === 'string') {
  2621. i.style.transition = 'all .5s ease-out';
  2622. }
  2623. document.body.appendChild(i);
  2624. c = (i.contentWindow) ? i.contentWindow :
  2625. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2626. c.document.open();
  2627. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2628. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2629. 'middle; cursor: default;">' + text + '</span>');
  2630. if(buttonText && buttonLink) {
  2631. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  2632. c.document.close();
  2633. // On click on okay
  2634. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2635. if (!!displayRefreshBar) {
  2636. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2637. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2638. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2639. }
  2640. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2641. e.preventDefault();
  2642. try {
  2643. event.cancelBubble = true;
  2644. } catch(error) { }
  2645. var pluginInstallInterval = setInterval(function(){
  2646. if(! isIE) {
  2647. navigator.plugins.refresh(false);
  2648. }
  2649. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2650. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2651. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2652. function() { // plugin now installed
  2653. clearInterval(pluginInstallInterval);
  2654. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2655. },
  2656. function() {
  2657. // still no plugin detected, nothing to do
  2658. });
  2659. } , 500);
  2660. });
  2661. // On click on Cancel
  2662. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  2663. w.document.body.removeChild(i);
  2664. });
  2665. } else {
  2666. c.document.close();
  2667. }
  2668. setTimeout(function() {
  2669. if(typeof i.style.webkitTransform === 'string') {
  2670. i.style.webkitTransform = 'translateY(40px)';
  2671. } else if(typeof i.style.transform === 'string') {
  2672. i.style.transform = 'translateY(40px)';
  2673. } else {
  2674. i.style.top = '0px';
  2675. }
  2676. }, 300);
  2677. };
  2678. // -----------------------------------------------------------
  2679. // Detected webrtc implementation. Types are:
  2680. // - 'moz': Mozilla implementation of webRTC.
  2681. // - 'webkit': WebKit implementation of webRTC.
  2682. // - 'plugin': Using the plugin implementation.
  2683. webrtcDetectedType = null;
  2684. // Detected webrtc datachannel support. Types are:
  2685. // - 'SCTP': SCTP datachannel support.
  2686. // - 'RTP': RTP datachannel support.
  2687. webrtcDetectedDCSupport = null;
  2688. // Set the settings for creating DataChannels, MediaStream for
  2689. // Cross-browser compability.
  2690. // - This is only for SCTP based support browsers.
  2691. // the 'urls' attribute.
  2692. checkMediaDataChannelSettings =
  2693. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2694. if (typeof callback !== 'function') {
  2695. return;
  2696. }
  2697. var beOfferer = true;
  2698. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2699. // Nightly version does not require MozDontOfferDataChannel for interop
  2700. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2701. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2702. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2703. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2704. // Resends an updated version of constraints for MozDataChannel to work
  2705. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2706. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2707. try {
  2708. delete constraints.mandatory.MozDontOfferDataChannel;
  2709. } catch (error) {
  2710. console.error('Failed deleting MozDontOfferDataChannel');
  2711. console.error(error);
  2712. }
  2713. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2714. constraints.mandatory.MozDontOfferDataChannel = true;
  2715. }
  2716. if (!isLocalFirefox) {
  2717. // temporary measure to remove Moz* constraints in non Firefox browsers
  2718. for (var prop in constraints.mandatory) {
  2719. if (constraints.mandatory.hasOwnProperty(prop)) {
  2720. if (prop.indexOf('Moz') !== -1) {
  2721. delete constraints.mandatory[prop];
  2722. }
  2723. }
  2724. }
  2725. }
  2726. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2727. // interopability of the media stream
  2728. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2729. beOfferer = false;
  2730. }
  2731. callback(beOfferer, constraints);
  2732. };
  2733. // Handles the differences for all browsers ice connection state output.
  2734. // - Tested outcomes are:
  2735. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2736. // - Chrome (answerer) : 'checking' > 'connected'
  2737. // - Firefox (offerer) : 'checking' > 'connected'
  2738. // - Firefox (answerer): 'checking' > 'connected'
  2739. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2740. if (typeof callback !== 'function') {
  2741. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2742. return;
  2743. }
  2744. peerId = (peerId) ? peerId : 'peer';
  2745. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2746. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2747. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2748. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2749. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2750. }
  2751. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2752. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2753. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2754. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2755. setTimeout(function () {
  2756. AdapterJS._iceConnectionFiredStates[peerId]
  2757. .push(AdapterJS._iceConnectionStates.done);
  2758. callback(AdapterJS._iceConnectionStates.done);
  2759. }, 1000);
  2760. }
  2761. callback(iceConnectionState);
  2762. }
  2763. return;
  2764. };
  2765. // Firefox:
  2766. // - Creates iceServer from the url for Firefox.
  2767. // - Create iceServer with stun url.
  2768. // - Create iceServer with turn url.
  2769. // - Ignore the transport parameter from TURN url for FF version <=27.
  2770. // - Return null for createIceServer if transport=tcp.
  2771. // - FF 27 and above supports transport parameters in TURN url,
  2772. // - So passing in the full url to create iceServer.
  2773. // Chrome:
  2774. // - Creates iceServer from the url for Chrome M33 and earlier.
  2775. // - Create iceServer with stun url.
  2776. // - Chrome M28 & above uses below TURN format.
  2777. // Plugin:
  2778. // - Creates Ice Server for Plugin Browsers
  2779. // - If Stun - Create iceServer with stun url.
  2780. // - Else - Create iceServer with turn url
  2781. // - This is a WebRTC Function
  2782. createIceServer = null;
  2783. // Firefox:
  2784. // - Creates IceServers for Firefox
  2785. // - Use .url for FireFox.
  2786. // - Multiple Urls support
  2787. // Chrome:
  2788. // - Creates iceServers from the urls for Chrome M34 and above.
  2789. // - .urls is supported since Chrome M34.
  2790. // - Multiple Urls support
  2791. // Plugin:
  2792. // - Creates Ice Servers for Plugin Browsers
  2793. // - Multiple Urls support
  2794. // - This is a WebRTC Function
  2795. createIceServers = null;
  2796. //------------------------------------------------------------
  2797. //The RTCPeerConnection object.
  2798. RTCPeerConnection = null;
  2799. // Creates RTCSessionDescription object for Plugin Browsers
  2800. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2801. RTCSessionDescription : null;
  2802. // Creates RTCIceCandidate object for Plugin Browsers
  2803. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2804. RTCIceCandidate : null;
  2805. // Get UserMedia (only difference is the prefix).
  2806. // Code from Adam Barth.
  2807. getUserMedia = null;
  2808. // Attach a media stream to an element.
  2809. attachMediaStream = null;
  2810. // Re-attach a media stream to an element.
  2811. reattachMediaStream = null;
  2812. // Detected browser agent name. Types are:
  2813. // - 'firefox': Firefox browser.
  2814. // - 'chrome': Chrome browser.
  2815. // - 'opera': Opera browser.
  2816. // - 'safari': Safari browser.
  2817. // - 'IE' - Internet Explorer browser.
  2818. webrtcDetectedBrowser = null;
  2819. // Detected browser version.
  2820. webrtcDetectedVersion = null;
  2821. // Check for browser types and react accordingly
  2822. if (navigator.mozGetUserMedia) {
  2823. webrtcDetectedBrowser = 'firefox';
  2824. webrtcDetectedVersion = parseInt(navigator
  2825. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2826. webrtcDetectedType = 'moz';
  2827. webrtcDetectedDCSupport = 'SCTP';
  2828. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2829. AdapterJS.maybeFixConfiguration(pcConfig);
  2830. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2831. };
  2832. // The RTCSessionDescription object.
  2833. RTCSessionDescription = mozRTCSessionDescription;
  2834. window.RTCSessionDescription = RTCSessionDescription;
  2835. // The RTCIceCandidate object.
  2836. RTCIceCandidate = mozRTCIceCandidate;
  2837. window.RTCIceCandidate = RTCIceCandidate;
  2838. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2839. navigator.getUserMedia = window.getUserMedia;
  2840. // Shim for MediaStreamTrack.getSources.
  2841. MediaStreamTrack.getSources = function(successCb) {
  2842. setTimeout(function() {
  2843. var infos = [
  2844. { kind: 'audio', id: 'default', label:'', facing:'' },
  2845. { kind: 'video', id: 'default', label:'', facing:'' }
  2846. ];
  2847. successCb(infos);
  2848. }, 0);
  2849. };
  2850. createIceServer = function (url, username, password) {
  2851. var iceServer = null;
  2852. var url_parts = url.split(':');
  2853. if (url_parts[0].indexOf('stun') === 0) {
  2854. iceServer = { url : url };
  2855. } else if (url_parts[0].indexOf('turn') === 0) {
  2856. if (webrtcDetectedVersion < 27) {
  2857. var turn_url_parts = url.split('?');
  2858. if (turn_url_parts.length === 1 ||
  2859. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2860. iceServer = {
  2861. url : turn_url_parts[0],
  2862. credential : password,
  2863. username : username
  2864. };
  2865. }
  2866. } else {
  2867. iceServer = {
  2868. url : url,
  2869. credential : password,
  2870. username : username
  2871. };
  2872. }
  2873. }
  2874. return iceServer;
  2875. };
  2876. createIceServers = function (urls, username, password) {
  2877. var iceServers = [];
  2878. for (i = 0; i < urls.length; i++) {
  2879. var iceServer = createIceServer(urls[i], username, password);
  2880. if (iceServer !== null) {
  2881. iceServers.push(iceServer);
  2882. }
  2883. }
  2884. return iceServers;
  2885. };
  2886. attachMediaStream = function (element, stream) {
  2887. element.mozSrcObject = stream;
  2888. if (stream !== null)
  2889. element.play();
  2890. return element;
  2891. };
  2892. reattachMediaStream = function (to, from) {
  2893. to.mozSrcObject = from.mozSrcObject;
  2894. to.play();
  2895. return to;
  2896. };
  2897. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2898. if (!callback) {
  2899. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2900. ': 1 argument required, but only 0 present.');
  2901. }
  2902. return callback([]);
  2903. };
  2904. // Fake get{Video,Audio}Tracks
  2905. if (!MediaStream.prototype.getVideoTracks) {
  2906. MediaStream.prototype.getVideoTracks = function () {
  2907. return [];
  2908. };
  2909. }
  2910. if (!MediaStream.prototype.getAudioTracks) {
  2911. MediaStream.prototype.getAudioTracks = function () {
  2912. return [];
  2913. };
  2914. }
  2915. AdapterJS.maybeThroughWebRTCReady();
  2916. } else if (navigator.webkitGetUserMedia) {
  2917. webrtcDetectedBrowser = 'chrome';
  2918. webrtcDetectedType = 'webkit';
  2919. webrtcDetectedVersion = parseInt(navigator
  2920. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2921. // check if browser is opera 20+
  2922. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2923. if (checkIfOpera !== null) {
  2924. webrtcDetectedBrowser = 'opera';
  2925. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2926. }
  2927. // check browser datachannel support
  2928. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2929. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2930. webrtcDetectedDCSupport = 'SCTP';
  2931. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2932. webrtcDetectedVersion > 24) {
  2933. webrtcDetectedDCSupport = 'RTP';
  2934. } else {
  2935. webrtcDetectedDCSupport = '';
  2936. }
  2937. createIceServer = function (url, username, password) {
  2938. var iceServer = null;
  2939. var url_parts = url.split(':');
  2940. if (url_parts[0].indexOf('stun') === 0) {
  2941. iceServer = { 'url' : url };
  2942. } else if (url_parts[0].indexOf('turn') === 0) {
  2943. iceServer = {
  2944. 'url' : url,
  2945. 'credential' : password,
  2946. 'username' : username
  2947. };
  2948. }
  2949. return iceServer;
  2950. };
  2951. createIceServers = function (urls, username, password) {
  2952. var iceServers = [];
  2953. if (webrtcDetectedVersion >= 34) {
  2954. iceServers = {
  2955. 'urls' : urls,
  2956. 'credential' : password,
  2957. 'username' : username
  2958. };
  2959. } else {
  2960. for (i = 0; i < urls.length; i++) {
  2961. var iceServer = createIceServer(urls[i], username, password);
  2962. if (iceServer !== null) {
  2963. iceServers.push(iceServer);
  2964. }
  2965. }
  2966. }
  2967. return iceServers;
  2968. };
  2969. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2970. if (webrtcDetectedVersion < 34) {
  2971. AdapterJS.maybeFixConfiguration(pcConfig);
  2972. }
  2973. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2974. };
  2975. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2976. navigator.getUserMedia = window.getUserMedia;
  2977. attachMediaStream = function (element, stream) {
  2978. if (typeof element.srcObject !== 'undefined') {
  2979. element.srcObject = stream;
  2980. } else if (typeof element.mozSrcObject !== 'undefined') {
  2981. element.mozSrcObject = stream;
  2982. } else if (typeof element.src !== 'undefined') {
  2983. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2984. } else {
  2985. console.log('Error attaching stream to element.');
  2986. }
  2987. return element;
  2988. };
  2989. reattachMediaStream = function (to, from) {
  2990. to.src = from.src;
  2991. return to;
  2992. };
  2993. AdapterJS.maybeThroughWebRTCReady();
  2994. } else if (navigator.mediaDevices && navigator.userAgent.match(
  2995. /Edge\/(\d+).(\d+)$/)) {
  2996. webrtcDetectedBrowser = 'edge';
  2997. webrtcDetectedVersion =
  2998. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  2999. // the minimum version still supported by adapter.
  3000. webrtcMinimumVersion = 12;
  3001. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3002. attachMediaStream = function(element, stream) {
  3003. element.srcObject = stream;
  3004. return element;
  3005. };
  3006. reattachMediaStream = function(to, from) {
  3007. to.srcObject = from.srcObject;
  3008. return to;
  3009. };
  3010. AdapterJS.maybeThroughWebRTCReady();
  3011. } else { // TRY TO USE PLUGIN
  3012. // IE 9 is not offering an implementation of console.log until you open a console
  3013. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3014. /* jshint -W020 */
  3015. console = {} || console;
  3016. // Implemented based on console specs from MDN
  3017. // You may override these functions
  3018. console.log = function (arg) {};
  3019. console.info = function (arg) {};
  3020. console.error = function (arg) {};
  3021. console.dir = function (arg) {};
  3022. console.exception = function (arg) {};
  3023. console.trace = function (arg) {};
  3024. console.warn = function (arg) {};
  3025. console.count = function (arg) {};
  3026. console.debug = function (arg) {};
  3027. console.count = function (arg) {};
  3028. console.time = function (arg) {};
  3029. console.timeEnd = function (arg) {};
  3030. console.group = function (arg) {};
  3031. console.groupCollapsed = function (arg) {};
  3032. console.groupEnd = function (arg) {};
  3033. /* jshint +W020 */
  3034. }
  3035. webrtcDetectedType = 'plugin';
  3036. webrtcDetectedDCSupport = 'plugin';
  3037. AdapterJS.parseWebrtcDetectedBrowser();
  3038. isIE = webrtcDetectedBrowser === 'IE';
  3039. /* jshint -W035 */
  3040. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3041. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3042. /* empty because it needs to prevent the function from running. */
  3043. }
  3044. };
  3045. /* jshint +W035 */
  3046. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3047. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3048. // Call immediately if possible
  3049. // Once the plugin is set, the code will always take this path
  3050. callback();
  3051. } else {
  3052. // otherwise start a 100ms interval
  3053. var checkPluginReadyState = setInterval(function () {
  3054. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3055. clearInterval(checkPluginReadyState);
  3056. callback();
  3057. }
  3058. }, 100);
  3059. }
  3060. };
  3061. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3062. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3063. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3064. });
  3065. };
  3066. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3067. // only inject once the page is ready
  3068. if (document.readyState !== 'complete') {
  3069. return;
  3070. }
  3071. // Prevent multiple injections
  3072. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3073. return;
  3074. }
  3075. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3076. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3077. var frag = document.createDocumentFragment();
  3078. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3079. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3080. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3081. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3082. '<param name="pluginId" value="' +
  3083. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3084. '<param name="windowless" value="false" /> ' +
  3085. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3086. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3087. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3088. // uncomment to be able to use virtual cams
  3089. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3090. '</object>';
  3091. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3092. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3093. }
  3094. document.body.appendChild(frag);
  3095. // Need to re-fetch the plugin
  3096. AdapterJS.WebRTCPlugin.plugin =
  3097. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3098. } else {
  3099. // Load Plugin
  3100. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3101. AdapterJS.WebRTCPlugin.plugin.id =
  3102. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3103. // IE will only start the plugin if it's ACTUALLY visible
  3104. if (isIE) {
  3105. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3106. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3107. } else { // The size of the plugin on Safari should be 0x0px
  3108. // so that the autorisation prompt is at the top
  3109. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3110. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3111. }
  3112. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3113. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3114. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3115. '<param name="pluginId" value="' +
  3116. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3117. '<param name="windowless" value="false" /> ' +
  3118. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3119. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3120. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3121. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3122. }
  3123. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3124. };
  3125. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3126. function (comName, plugName, installedCb, notInstalledCb) {
  3127. if (!isIE) {
  3128. var pluginArray = navigator.plugins;
  3129. for (var i = 0; i < pluginArray.length; i++) {
  3130. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3131. installedCb();
  3132. return;
  3133. }
  3134. }
  3135. notInstalledCb();
  3136. } else {
  3137. try {
  3138. var axo = new ActiveXObject(comName + '.' + plugName);
  3139. } catch (e) {
  3140. notInstalledCb();
  3141. return;
  3142. }
  3143. installedCb();
  3144. }
  3145. };
  3146. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3147. if (AdapterJS.WebRTCPlugin.pluginState ===
  3148. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3149. console.error("AdapterJS - WebRTC interface has already been defined");
  3150. return;
  3151. }
  3152. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3153. AdapterJS.isDefined = function (variable) {
  3154. return variable !== null && variable !== undefined;
  3155. };
  3156. createIceServer = function (url, username, password) {
  3157. var iceServer = null;
  3158. var url_parts = url.split(':');
  3159. if (url_parts[0].indexOf('stun') === 0) {
  3160. iceServer = {
  3161. 'url' : url,
  3162. 'hasCredentials' : false
  3163. };
  3164. } else if (url_parts[0].indexOf('turn') === 0) {
  3165. iceServer = {
  3166. 'url' : url,
  3167. 'hasCredentials' : true,
  3168. 'credential' : password,
  3169. 'username' : username
  3170. };
  3171. }
  3172. return iceServer;
  3173. };
  3174. createIceServers = function (urls, username, password) {
  3175. var iceServers = [];
  3176. for (var i = 0; i < urls.length; ++i) {
  3177. iceServers.push(createIceServer(urls[i], username, password));
  3178. }
  3179. return iceServers;
  3180. };
  3181. RTCSessionDescription = function (info) {
  3182. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3183. return AdapterJS.WebRTCPlugin.plugin.
  3184. ConstructSessionDescription(info.type, info.sdp);
  3185. };
  3186. RTCPeerConnection = function (servers, constraints) {
  3187. var iceServers = null;
  3188. if (servers) {
  3189. iceServers = servers.iceServers;
  3190. for (var i = 0; i < iceServers.length; i++) {
  3191. if (iceServers[i].urls && !iceServers[i].url) {
  3192. iceServers[i].url = iceServers[i].urls;
  3193. }
  3194. iceServers[i].hasCredentials = AdapterJS.
  3195. isDefined(iceServers[i].username) &&
  3196. AdapterJS.isDefined(iceServers[i].credential);
  3197. }
  3198. }
  3199. var mandatory = (constraints && constraints.mandatory) ?
  3200. constraints.mandatory : null;
  3201. var optional = (constraints && constraints.optional) ?
  3202. constraints.optional : null;
  3203. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3204. return AdapterJS.WebRTCPlugin.plugin.
  3205. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3206. iceServers, mandatory, optional);
  3207. };
  3208. MediaStreamTrack = {};
  3209. MediaStreamTrack.getSources = function (callback) {
  3210. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3211. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  3212. });
  3213. };
  3214. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  3215. constraints.audio = constraints.audio || false;
  3216. constraints.video = constraints.video || false;
  3217. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3218. AdapterJS.WebRTCPlugin.plugin.
  3219. getUserMedia(constraints, successCallback, failureCallback);
  3220. });
  3221. };
  3222. window.navigator.getUserMedia = window.getUserMedia;
  3223. attachMediaStream = function (element, stream) {
  3224. if (!element || !element.parentNode) {
  3225. return;
  3226. }
  3227. var streamId
  3228. if (stream === null) {
  3229. streamId = '';
  3230. }
  3231. else {
  3232. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  3233. streamId = stream.id;
  3234. }
  3235. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  3236. var nodeName = element.nodeName.toLowerCase();
  3237. if (nodeName !== 'object') { // not a plugin <object> tag yet
  3238. var tag;
  3239. switch(nodeName) {
  3240. case 'audio':
  3241. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  3242. break;
  3243. case 'video':
  3244. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  3245. break;
  3246. default:
  3247. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  3248. }
  3249. var frag = document.createDocumentFragment();
  3250. var temp = document.createElement('div');
  3251. var classHTML = '';
  3252. if (element.className) {
  3253. classHTML = 'class="' + element.className + '" ';
  3254. } else if (element.attributes && element.attributes['class']) {
  3255. classHTML = 'class="' + element.attributes['class'].value + '" ';
  3256. }
  3257. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  3258. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  3259. '<param name="pluginId" value="' + elementId + '" /> ' +
  3260. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3261. '<param name="windowless" value="true" /> ' +
  3262. '<param name="streamId" value="' + streamId + '" /> ' +
  3263. '<param name="tag" value="' + tag + '" /> ' +
  3264. '</object>';
  3265. while (temp.firstChild) {
  3266. frag.appendChild(temp.firstChild);
  3267. }
  3268. var height = '';
  3269. var width = '';
  3270. if (element.getBoundingClientRect) {
  3271. var rectObject = element.getBoundingClientRect();
  3272. width = rectObject.width + 'px';
  3273. height = rectObject.height + 'px';
  3274. }
  3275. else if (element.width) {
  3276. width = element.width;
  3277. height = element.height;
  3278. } else {
  3279. // TODO: What scenario could bring us here?
  3280. }
  3281. element.parentNode.insertBefore(frag, element);
  3282. frag = document.getElementById(elementId);
  3283. frag.width = width;
  3284. frag.height = height;
  3285. element.parentNode.removeChild(element);
  3286. } else { // already an <object> tag, just change the stream id
  3287. var children = element.children;
  3288. for (var i = 0; i !== children.length; ++i) {
  3289. if (children[i].name === 'streamId') {
  3290. children[i].value = streamId;
  3291. break;
  3292. }
  3293. }
  3294. element.setStreamId(streamId);
  3295. }
  3296. var newElement = document.getElementById(elementId);
  3297. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  3298. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  3299. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  3300. if (isIE) { // on IE the event needs to be plugged manually
  3301. newElement.attachEvent('onplaying', newElement.onplaying);
  3302. newElement.attachEvent('onplay', newElement.onplay);
  3303. newElement._TemOnClick = function (id) {
  3304. var arg = {
  3305. srcElement : document.getElementById(id)
  3306. };
  3307. newElement.onclick(arg);
  3308. };
  3309. }
  3310. return newElement;
  3311. };
  3312. reattachMediaStream = function (to, from) {
  3313. var stream = null;
  3314. var children = from.children;
  3315. for (var i = 0; i !== children.length; ++i) {
  3316. if (children[i].name === 'streamId') {
  3317. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3318. stream = AdapterJS.WebRTCPlugin.plugin
  3319. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  3320. break;
  3321. }
  3322. }
  3323. if (stream !== null) {
  3324. return attachMediaStream(to, stream);
  3325. } else {
  3326. console.log('Could not find the stream associated with this element');
  3327. }
  3328. };
  3329. RTCIceCandidate = function (candidate) {
  3330. if (!candidate.sdpMid) {
  3331. candidate.sdpMid = '';
  3332. }
  3333. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3334. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  3335. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  3336. );
  3337. };
  3338. // inject plugin
  3339. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  3340. AdapterJS.WebRTCPlugin.injectPlugin();
  3341. };
  3342. // This function will be called if the plugin is needed (browser different
  3343. // from Chrome or Firefox), but the plugin is not installed.
  3344. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  3345. function() {
  3346. AdapterJS.addEvent(document,
  3347. 'readystatechange',
  3348. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  3349. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  3350. };
  3351. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  3352. if (AdapterJS.options.hidePluginInstallPrompt) {
  3353. return;
  3354. }
  3355. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3356. if(downloadLink) { // if download link
  3357. var popupString;
  3358. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3359. popupString = 'This website requires you to install the ' +
  3360. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3361. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3362. ' WebRTC Plugin</a>' +
  3363. ' to work on this browser.';
  3364. } else { // no portal link, just print a generic explanation
  3365. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3366. }
  3367. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3368. } else { // no download link, just print a generic explanation
  3369. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3370. }
  3371. };
  3372. // Try to detect the plugin and act accordingly
  3373. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3374. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3375. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3376. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3377. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3378. }
  3379. }).call(this,"/modules/RTC/adapter.screenshare.js")
  3380. },{"jitsi-meet-logger":44}],17:[function(require,module,exports){
  3381. (function (__filename){
  3382. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  3383. getUserMediaWithConstraints */
  3384. /**
  3385. * Indicates that desktop stream is currently in use(for toggle purpose).
  3386. * @type {boolean}
  3387. */
  3388. var isUsingScreenStream = false;
  3389. /**
  3390. * Indicates that switch stream operation is in progress and prevent from
  3391. * triggering new events.
  3392. * @type {boolean}
  3393. */
  3394. var switchInProgress = false;
  3395. /**
  3396. * Method used to get screen sharing stream.
  3397. *
  3398. * @type {function (stream_callback, failure_callback}
  3399. */
  3400. var obtainDesktopStream = null;
  3401. /**
  3402. * Indicates whether desktop sharing extension is installed.
  3403. * @type {boolean}
  3404. */
  3405. var extInstalled = false;
  3406. /**
  3407. * Indicates whether update of desktop sharing extension is required.
  3408. * @type {boolean}
  3409. */
  3410. var extUpdateRequired = false;
  3411. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3412. var AdapterJS = require("../RTC/adapter.screenshare");
  3413. var EventEmitter = require("events");
  3414. var eventEmitter = new EventEmitter();
  3415. var DesktopSharingEventTypes
  3416. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3417. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3418. var RTCEvents = require("../../service/RTC/RTCEvents");
  3419. /**
  3420. * Method obtains desktop stream from WebRTC 'screen' source.
  3421. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  3422. */
  3423. function obtainWebRTCScreen(streamCallback, failCallback) {
  3424. APP.RTC.getUserMediaWithConstraints(
  3425. ['screen'],
  3426. streamCallback,
  3427. failCallback
  3428. );
  3429. }
  3430. /**
  3431. * Constructs inline install URL for Chrome desktop streaming extension.
  3432. * The 'chromeExtensionId' must be defined in config.js.
  3433. * @returns {string}
  3434. */
  3435. function getWebStoreInstallUrl()
  3436. {
  3437. return "https://chrome.google.com/webstore/detail/" +
  3438. config.chromeExtensionId;
  3439. }
  3440. /**
  3441. * Checks whether extension update is required.
  3442. * @param minVersion minimal required version
  3443. * @param extVersion current extension version
  3444. * @returns {boolean}
  3445. */
  3446. function isUpdateRequired(minVersion, extVersion)
  3447. {
  3448. try
  3449. {
  3450. var s1 = minVersion.split('.');
  3451. var s2 = extVersion.split('.');
  3452. var len = Math.max(s1.length, s2.length);
  3453. for (var i = 0; i < len; i++)
  3454. {
  3455. var n1 = 0,
  3456. n2 = 0;
  3457. if (i < s1.length)
  3458. n1 = parseInt(s1[i]);
  3459. if (i < s2.length)
  3460. n2 = parseInt(s2[i]);
  3461. if (isNaN(n1) || isNaN(n2))
  3462. {
  3463. return true;
  3464. }
  3465. else if (n1 !== n2)
  3466. {
  3467. return n1 > n2;
  3468. }
  3469. }
  3470. // will happen if boths version has identical numbers in
  3471. // their components (even if one of them is longer, has more components)
  3472. return false;
  3473. }
  3474. catch (e)
  3475. {
  3476. logger.error("Failed to parse extension version", e);
  3477. APP.UI.messageHandler.showError("dialog.error",
  3478. "dialog.detectext");
  3479. return true;
  3480. }
  3481. }
  3482. function checkChromeExtInstalled(callback) {
  3483. if (!chrome.runtime) {
  3484. // No API, so no extension for sure
  3485. callback(false, false);
  3486. return;
  3487. }
  3488. chrome.runtime.sendMessage(
  3489. config.chromeExtensionId,
  3490. { getVersion: true },
  3491. function (response) {
  3492. if (!response || !response.version) {
  3493. // Communication failure - assume that no endpoint exists
  3494. logger.warn(
  3495. "Extension not installed?: ", chrome.runtime.lastError);
  3496. callback(false, false);
  3497. return;
  3498. }
  3499. // Check installed extension version
  3500. var extVersion = response.version;
  3501. logger.log('Extension version is: ' + extVersion);
  3502. var updateRequired
  3503. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  3504. callback(!updateRequired, updateRequired);
  3505. }
  3506. );
  3507. }
  3508. function doGetStreamFromExtension(streamCallback, failCallback) {
  3509. // Sends 'getStream' msg to the extension.
  3510. // Extension id must be defined in the config.
  3511. chrome.runtime.sendMessage(
  3512. config.chromeExtensionId,
  3513. { getStream: true, sources: config.desktopSharingSources },
  3514. function (response) {
  3515. if (!response) {
  3516. failCallback(chrome.runtime.lastError);
  3517. return;
  3518. }
  3519. logger.log("Response from extension: " + response);
  3520. if (response.streamId) {
  3521. APP.RTC.getUserMediaWithConstraints(
  3522. ['desktop'],
  3523. function (stream) {
  3524. streamCallback(stream);
  3525. },
  3526. failCallback,
  3527. null, null, null,
  3528. response.streamId);
  3529. } else {
  3530. failCallback("Extension failed to get the stream");
  3531. }
  3532. }
  3533. );
  3534. }
  3535. /**
  3536. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3537. * stream for returned stream token.
  3538. */
  3539. function obtainScreenFromExtension(streamCallback, failCallback) {
  3540. if (extInstalled) {
  3541. doGetStreamFromExtension(streamCallback, failCallback);
  3542. } else {
  3543. if (extUpdateRequired) {
  3544. alert(
  3545. 'Jitsi Desktop Streamer requires update. ' +
  3546. 'Changes will take effect after next Chrome restart.');
  3547. }
  3548. chrome.webstore.install(
  3549. getWebStoreInstallUrl(),
  3550. function (arg) {
  3551. logger.log("Extension installed successfully", arg);
  3552. extInstalled = true;
  3553. // We need to give a moment for the endpoint to become available
  3554. window.setTimeout(function () {
  3555. doGetStreamFromExtension(streamCallback, failCallback);
  3556. }, 500);
  3557. },
  3558. function (arg) {
  3559. logger.log("Failed to install the extension", arg);
  3560. failCallback(arg);
  3561. APP.UI.messageHandler.showError("dialog.error",
  3562. "dialog.failtoinstall");
  3563. }
  3564. );
  3565. }
  3566. }
  3567. /**
  3568. * Call this method to toggle desktop sharing feature.
  3569. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  3570. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  3571. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  3572. * enabled), pass any other string or nothing in order to disable this
  3573. * feature completely.
  3574. */
  3575. function setDesktopSharing(method) {
  3576. obtainDesktopStream = null;
  3577. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  3578. // care about 'method' parameter
  3579. if (RTCBrowserType.isTemasysPluginUsed()) {
  3580. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3581. logger.info("Screensharing not supported by this plugin version");
  3582. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3583. logger.info(
  3584. "Screensharing not available with Temasys plugin on this site");
  3585. } else {
  3586. obtainDesktopStream = obtainWebRTCScreen;
  3587. logger.info("Using Temasys plugin for desktop sharing");
  3588. }
  3589. } else if (RTCBrowserType.isChrome()) {
  3590. if (method == "ext") {
  3591. if (RTCBrowserType.getChromeVersion() >= 34) {
  3592. obtainDesktopStream = obtainScreenFromExtension;
  3593. logger.info("Using Chrome extension for desktop sharing");
  3594. initChromeExtension();
  3595. } else {
  3596. logger.info("Chrome extension not supported until ver 34");
  3597. }
  3598. } else if (method == "webrtc") {
  3599. obtainDesktopStream = obtainWebRTCScreen;
  3600. logger.info("Using Chrome WebRTC for desktop sharing");
  3601. }
  3602. }
  3603. if (!obtainDesktopStream) {
  3604. logger.info("Desktop sharing disabled");
  3605. }
  3606. }
  3607. /**
  3608. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3609. * config.js to support inline installs. Host site must be selected as main
  3610. * website of published extension.
  3611. */
  3612. function initInlineInstalls()
  3613. {
  3614. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3615. }
  3616. function initChromeExtension() {
  3617. // Initialize Chrome extension inline installs
  3618. initInlineInstalls();
  3619. // Check if extension is installed
  3620. checkChromeExtInstalled(function (installed, updateRequired) {
  3621. extInstalled = installed;
  3622. extUpdateRequired = updateRequired;
  3623. logger.info(
  3624. "Chrome extension installed: " + extInstalled +
  3625. " updateRequired: " + extUpdateRequired);
  3626. });
  3627. }
  3628. function getVideoStreamFailed(error) {
  3629. logger.error("Failed to obtain the stream to switch to", error);
  3630. switchInProgress = false;
  3631. isUsingScreenStream = false;
  3632. newStreamCreated(null);
  3633. }
  3634. function getDesktopStreamFailed(error) {
  3635. logger.error("Failed to obtain the stream to switch to", error);
  3636. switchInProgress = false;
  3637. }
  3638. function streamSwitchDone() {
  3639. switchInProgress = false;
  3640. eventEmitter.emit(
  3641. DesktopSharingEventTypes.SWITCHING_DONE,
  3642. isUsingScreenStream);
  3643. }
  3644. function newStreamCreated(stream)
  3645. {
  3646. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3647. stream, isUsingScreenStream, streamSwitchDone);
  3648. }
  3649. function onEndedHandler(stream) {
  3650. if (!switchInProgress && isUsingScreenStream) {
  3651. APP.desktopsharing.toggleScreenSharing();
  3652. }
  3653. //FIXME: to be verified
  3654. if (stream.removeEventListener) {
  3655. stream.removeEventListener('ended', onEndedHandler);
  3656. } else {
  3657. stream.detachEvent('ended', onEndedHandler);
  3658. }
  3659. }
  3660. // Called when RTC finishes initialization
  3661. function onWebRtcReady() {
  3662. setDesktopSharing(config.desktopSharing);
  3663. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3664. }
  3665. module.exports = {
  3666. isUsingScreenStream: function () {
  3667. return isUsingScreenStream;
  3668. },
  3669. /**
  3670. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3671. * and enabled.
  3672. */
  3673. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  3674. init: function () {
  3675. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  3676. },
  3677. addListener: function (listener, type)
  3678. {
  3679. eventEmitter.on(type, listener);
  3680. },
  3681. removeListener: function (listener, type) {
  3682. eventEmitter.removeListener(type, listener);
  3683. },
  3684. /*
  3685. * Toggles screen sharing.
  3686. */
  3687. toggleScreenSharing: function () {
  3688. if (switchInProgress || !obtainDesktopStream) {
  3689. logger.warn("Switch in progress or no method defined");
  3690. return;
  3691. }
  3692. switchInProgress = true;
  3693. if (!isUsingScreenStream)
  3694. {
  3695. // Switch to desktop stream
  3696. obtainDesktopStream(
  3697. function (stream) {
  3698. // We now use screen stream
  3699. isUsingScreenStream = true;
  3700. // Hook 'ended' event to restore camera
  3701. // when screen stream stops
  3702. //FIXME: to be verified
  3703. if (stream.addEventListener) {
  3704. stream.addEventListener('ended', function () {
  3705. onEndedHandler(stream);
  3706. });
  3707. } else {
  3708. stream.attachEvent('ended', function () {
  3709. onEndedHandler(stream);
  3710. });
  3711. }
  3712. newStreamCreated(stream);
  3713. },
  3714. getDesktopStreamFailed);
  3715. } else {
  3716. // Disable screen stream
  3717. APP.RTC.getUserMediaWithConstraints(
  3718. ['video'],
  3719. function (stream) {
  3720. // We are now using camera stream
  3721. isUsingScreenStream = false;
  3722. newStreamCreated(stream);
  3723. },
  3724. getVideoStreamFailed, config.resolution || '360'
  3725. );
  3726. }
  3727. }
  3728. };
  3729. }).call(this,"/modules/desktopsharing/desktopsharing.js")
  3730. },{"../../service/RTC/RTCEvents":76,"../../service/desktopsharing/DesktopSharingEventTypes":80,"../RTC/RTCBrowserType":14,"../RTC/adapter.screenshare":16,"events":40,"jitsi-meet-logger":44}],18:[function(require,module,exports){
  3731. (function (__filename){
  3732. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3733. function supportsLocalStorage() {
  3734. try {
  3735. return 'localStorage' in window && window.localStorage !== null;
  3736. } catch (e) {
  3737. logger.log("localstorage is not supported");
  3738. return false;
  3739. }
  3740. }
  3741. function generateUniqueId() {
  3742. function _p8() {
  3743. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3744. }
  3745. return _p8() + _p8() + _p8() + _p8();
  3746. }
  3747. function Settings(conferenceID) {
  3748. this.email = '';
  3749. this.displayName = '';
  3750. this.userId;
  3751. this.language = null;
  3752. this.confSettings = null;
  3753. this.conferenceID = conferenceID;
  3754. if (supportsLocalStorage()) {
  3755. if(!window.localStorage.getItem(conferenceID))
  3756. this.confSettings = {};
  3757. else
  3758. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3759. if(!this.confSettings.jitsiMeetId) {
  3760. this.confSettings.jitsiMeetId = generateUniqueId();
  3761. logger.log("generated id",
  3762. this.confSettings.jitsiMeetId);
  3763. this.save();
  3764. }
  3765. this.userId = this.confSettings.jitsiMeetId || '';
  3766. this.email = this.confSettings.email || '';
  3767. this.displayName = this.confSettings.displayname || '';
  3768. this.language = this.confSettings.language;
  3769. } else {
  3770. logger.log("local storage is not supported");
  3771. this.userId = generateUniqueId();
  3772. }
  3773. }
  3774. Settings.prototype.save = function () {
  3775. if(!supportsLocalStorage())
  3776. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3777. }
  3778. Settings.prototype.setDisplayName = function (newDisplayName) {
  3779. this.displayName = newDisplayName;
  3780. if(this.confSettings != null)
  3781. this.confSettings.displayname = displayName;
  3782. this.save();
  3783. return this.displayName;
  3784. },
  3785. Settings.prototype.setEmail = function (newEmail) {
  3786. this.email = newEmail;
  3787. if(this.confSettings != null)
  3788. this.confSettings.email = newEmail;
  3789. this.save();
  3790. return this.email;
  3791. },
  3792. Settings.prototype.getSettings = function () {
  3793. return {
  3794. email: this.email,
  3795. displayName: this.displayName,
  3796. uid: this.userId,
  3797. language: this.language
  3798. };
  3799. },
  3800. Settings.prototype.setLanguage = function (lang) {
  3801. this.language = lang;
  3802. if(this.confSettings != null)
  3803. this.confSettings.language = lang;
  3804. this.save();
  3805. }
  3806. module.exports = Settings;
  3807. }).call(this,"/modules/settings/Settings.js")
  3808. },{"jitsi-meet-logger":44}],19:[function(require,module,exports){
  3809. /* global config */
  3810. /**
  3811. * Provides statistics for the local stream.
  3812. */
  3813. var RTCBrowserType = require('../RTC/RTCBrowserType');
  3814. var LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  3815. /**
  3816. * Size of the webaudio analyzer buffer.
  3817. * @type {number}
  3818. */
  3819. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  3820. /**
  3821. * Value of the webaudio analyzer smoothing time parameter.
  3822. * @type {number}
  3823. */
  3824. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  3825. /**
  3826. * Converts time domain data array to audio level.
  3827. * @param samples the time domain data array.
  3828. * @returns {number} the audio level
  3829. */
  3830. function timeDomainDataToAudioLevel(samples) {
  3831. var maxVolume = 0;
  3832. var length = samples.length;
  3833. for (var i = 0; i < length; i++) {
  3834. if (maxVolume < samples[i])
  3835. maxVolume = samples[i];
  3836. }
  3837. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  3838. }
  3839. /**
  3840. * Animates audio level change
  3841. * @param newLevel the new audio level
  3842. * @param lastLevel the last audio level
  3843. * @returns {Number} the audio level to be set
  3844. */
  3845. function animateLevel(newLevel, lastLevel) {
  3846. var value = 0;
  3847. var diff = lastLevel - newLevel;
  3848. if(diff > 0.2) {
  3849. value = lastLevel - 0.2;
  3850. }
  3851. else if(diff < -0.4) {
  3852. value = lastLevel + 0.4;
  3853. }
  3854. else {
  3855. value = newLevel;
  3856. }
  3857. return parseFloat(value.toFixed(3));
  3858. }
  3859. /**
  3860. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  3861. *
  3862. * @param stream the local stream
  3863. * @param interval stats refresh interval given in ms.
  3864. * @constructor
  3865. */
  3866. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  3867. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  3868. this.stream = stream;
  3869. this.intervalId = null;
  3870. this.intervalMilis = interval;
  3871. this.eventEmitter = eventEmitter;
  3872. this.audioLevel = 0;
  3873. this.statisticsService = statisticsService;
  3874. }
  3875. /**
  3876. * Starts the collecting the statistics.
  3877. */
  3878. LocalStatsCollector.prototype.start = function () {
  3879. if (!window.AudioContext ||
  3880. RTCBrowserType.isTemasysPluginUsed())
  3881. return;
  3882. var context = new AudioContext();
  3883. var analyser = context.createAnalyser();
  3884. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  3885. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  3886. var source = context.createMediaStreamSource(this.stream);
  3887. source.connect(analyser);
  3888. var self = this;
  3889. this.intervalId = setInterval(
  3890. function () {
  3891. var array = new Uint8Array(analyser.frequencyBinCount);
  3892. analyser.getByteTimeDomainData(array);
  3893. var audioLevel = timeDomainDataToAudioLevel(array);
  3894. if (audioLevel != self.audioLevel) {
  3895. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  3896. self.eventEmitter.emit(
  3897. "statistics.audioLevel",
  3898. LOCAL_JID,
  3899. self.audioLevel);
  3900. }
  3901. },
  3902. this.intervalMilis
  3903. );
  3904. };
  3905. /**
  3906. * Stops collecting the statistics.
  3907. */
  3908. LocalStatsCollector.prototype.stop = function () {
  3909. if (this.intervalId) {
  3910. clearInterval(this.intervalId);
  3911. this.intervalId = null;
  3912. }
  3913. };
  3914. module.exports = LocalStatsCollector;
  3915. },{"../../service/statistics/constants":81,"../RTC/RTCBrowserType":14}],20:[function(require,module,exports){
  3916. (function (__filename){
  3917. /* global require, ssrc2jid */
  3918. /* jshint -W117 */
  3919. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3920. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3921. /* Whether we support the browser we are running into for logging statistics */
  3922. var browserSupported = RTCBrowserType.isChrome() ||
  3923. RTCBrowserType.isOpera();
  3924. var keyMap = {};
  3925. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  3926. "ssrc": "ssrc",
  3927. "packetsReceived": "packetsReceived",
  3928. "packetsLost": "packetsLost",
  3929. "packetsSent": "packetsSent",
  3930. "bytesReceived": "bytesReceived",
  3931. "bytesSent": "bytesSent"
  3932. };
  3933. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  3934. "receiveBandwidth": "googAvailableReceiveBandwidth",
  3935. "sendBandwidth": "googAvailableSendBandwidth",
  3936. "remoteAddress": "googRemoteAddress",
  3937. "transportType": "googTransportType",
  3938. "localAddress": "googLocalAddress",
  3939. "activeConnection": "googActiveConnection",
  3940. "ssrc": "ssrc",
  3941. "packetsReceived": "packetsReceived",
  3942. "packetsSent": "packetsSent",
  3943. "packetsLost": "packetsLost",
  3944. "bytesReceived": "bytesReceived",
  3945. "bytesSent": "bytesSent",
  3946. "googFrameHeightReceived": "googFrameHeightReceived",
  3947. "googFrameWidthReceived": "googFrameWidthReceived",
  3948. "googFrameHeightSent": "googFrameHeightSent",
  3949. "googFrameWidthSent": "googFrameWidthSent",
  3950. "audioInputLevel": "audioInputLevel",
  3951. "audioOutputLevel": "audioOutputLevel"
  3952. };
  3953. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  3954. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  3955. /**
  3956. * Calculates packet lost percent using the number of lost packets and the
  3957. * number of all packet.
  3958. * @param lostPackets the number of lost packets
  3959. * @param totalPackets the number of all packets.
  3960. * @returns {number} packet loss percent
  3961. */
  3962. function calculatePacketLoss(lostPackets, totalPackets) {
  3963. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  3964. return 0;
  3965. return Math.round((lostPackets/totalPackets)*100);
  3966. }
  3967. function getStatValue(item, name) {
  3968. var browserType = RTCBrowserType.getBrowserType();
  3969. if (!keyMap[browserType][name])
  3970. throw "The property isn't supported!";
  3971. var key = keyMap[browserType][name];
  3972. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  3973. item.stat(key) : item[key];
  3974. }
  3975. function formatAudioLevel(audioLevel) {
  3976. return Math.min(Math.max(audioLevel, 0), 1);
  3977. }
  3978. /**
  3979. * Checks whether a certain record should be included in the logged statistics.
  3980. */
  3981. function acceptStat(reportId, reportType, statName) {
  3982. if (reportType == "googCandidatePair" && statName == "googChannelId")
  3983. return false;
  3984. if (reportType == "ssrc") {
  3985. if (statName == "googTrackId" ||
  3986. statName == "transportId" ||
  3987. statName == "ssrc")
  3988. return false;
  3989. }
  3990. return true;
  3991. }
  3992. /**
  3993. * Checks whether a certain record should be included in the logged statistics.
  3994. */
  3995. function acceptReport(id, type) {
  3996. if (id.substring(0, 15) == "googCertificate" ||
  3997. id.substring(0, 9) == "googTrack" ||
  3998. id.substring(0, 20) == "googLibjingleSession")
  3999. return false;
  4000. if (type == "googComponent")
  4001. return false;
  4002. return true;
  4003. }
  4004. /**
  4005. * Peer statistics data holder.
  4006. * @constructor
  4007. */
  4008. function PeerStats()
  4009. {
  4010. this.ssrc2Loss = {};
  4011. this.ssrc2AudioLevel = {};
  4012. this.ssrc2bitrate = {};
  4013. this.ssrc2resolution = {};
  4014. }
  4015. /**
  4016. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4017. * represented by this instance.
  4018. * @param lossRate new packet loss rate value to be set.
  4019. */
  4020. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4021. {
  4022. this.ssrc2Loss = lossRate;
  4023. };
  4024. /**
  4025. * Sets resolution that belong to the ssrc
  4026. * represented by this instance.
  4027. * @param resolution new resolution value to be set.
  4028. */
  4029. PeerStats.prototype.setSsrcResolution = function (resolution)
  4030. {
  4031. if(resolution === null && this.ssrc2resolution[ssrc])
  4032. {
  4033. delete this.ssrc2resolution[ssrc];
  4034. }
  4035. else if(resolution !== null)
  4036. this.ssrc2resolution[ssrc] = resolution;
  4037. };
  4038. /**
  4039. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4040. * represented by this instance.
  4041. * @param ssrc audio or video RTP stream SSRC.
  4042. * @param bitrate new bitrate value to be set.
  4043. */
  4044. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4045. {
  4046. if(this.ssrc2bitrate[ssrc])
  4047. {
  4048. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4049. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4050. }
  4051. else {
  4052. this.ssrc2bitrate[ssrc] = bitrate;
  4053. }
  4054. };
  4055. /**
  4056. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4057. * the stream which belongs to the peer represented by this instance.
  4058. * @param ssrc RTP stream SSRC for which current audio level value will be
  4059. * updated.
  4060. * @param audioLevel the new audio level value to be set. Value is truncated to
  4061. * fit the range from 0 to 1.
  4062. */
  4063. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4064. {
  4065. // Range limit 0 - 1
  4066. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4067. };
  4068. function ConferenceStats() {
  4069. /**
  4070. * The bandwidth
  4071. * @type {{}}
  4072. */
  4073. this.bandwidth = {};
  4074. /**
  4075. * The bit rate
  4076. * @type {{}}
  4077. */
  4078. this.bitrate = {};
  4079. /**
  4080. * The packet loss rate
  4081. * @type {{}}
  4082. */
  4083. this.packetLoss = null;
  4084. /**
  4085. * Array with the transport information.
  4086. * @type {Array}
  4087. */
  4088. this.transport = [];
  4089. }
  4090. /**
  4091. * <tt>StatsCollector</tt> registers for stats updates of given
  4092. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4093. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4094. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4095. * instance as an event source.
  4096. *
  4097. * @param peerconnection webRTC peer connection object.
  4098. * @param interval stats refresh interval given in ms.
  4099. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4100. * called on stats update.
  4101. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4102. * @constructor
  4103. */
  4104. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4105. {
  4106. this.peerconnection = peerconnection;
  4107. this.baselineAudioLevelsReport = null;
  4108. this.currentAudioLevelsReport = null;
  4109. this.currentStatsReport = null;
  4110. this.baselineStatsReport = null;
  4111. this.audioLevelsIntervalId = null;
  4112. this.eventEmitter = eventEmitter;
  4113. this.config = config || {};
  4114. this.conferenceStats = new ConferenceStats();
  4115. /**
  4116. * Gather PeerConnection stats once every this many milliseconds.
  4117. */
  4118. this.GATHER_INTERVAL = 15000;
  4119. /**
  4120. * Log stats via the focus once every this many milliseconds.
  4121. */
  4122. this.LOG_INTERVAL = 60000;
  4123. /**
  4124. * Gather stats and store them in this.statsToBeLogged.
  4125. */
  4126. this.gatherStatsIntervalId = null;
  4127. /**
  4128. * Send the stats already saved in this.statsToBeLogged to be logged via
  4129. * the focus.
  4130. */
  4131. this.logStatsIntervalId = null;
  4132. /**
  4133. * Stores the statistics which will be send to the focus to be logged.
  4134. */
  4135. this.statsToBeLogged =
  4136. {
  4137. timestamps: [],
  4138. stats: {}
  4139. };
  4140. // Updates stats interval
  4141. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4142. this.statsIntervalId = null;
  4143. this.statsIntervalMilis = statsInterval;
  4144. // Map of ssrcs to PeerStats
  4145. this.ssrc2stats = {};
  4146. }
  4147. module.exports = StatsCollector;
  4148. /**
  4149. * Stops stats updates.
  4150. */
  4151. StatsCollector.prototype.stop = function () {
  4152. if (this.audioLevelsIntervalId) {
  4153. clearInterval(this.audioLevelsIntervalId);
  4154. this.audioLevelsIntervalId = null;
  4155. }
  4156. if (this.statsIntervalId)
  4157. {
  4158. clearInterval(this.statsIntervalId);
  4159. this.statsIntervalId = null;
  4160. }
  4161. if(this.logStatsIntervalId)
  4162. {
  4163. clearInterval(this.logStatsIntervalId);
  4164. this.logStatsIntervalId = null;
  4165. }
  4166. if(this.gatherStatsIntervalId)
  4167. {
  4168. clearInterval(this.gatherStatsIntervalId);
  4169. this.gatherStatsIntervalId = null;
  4170. }
  4171. };
  4172. /**
  4173. * Callback passed to <tt>getStats</tt> method.
  4174. * @param error an error that occurred on <tt>getStats</tt> call.
  4175. */
  4176. StatsCollector.prototype.errorCallback = function (error)
  4177. {
  4178. logger.error("Get stats error", error);
  4179. this.stop();
  4180. };
  4181. /**
  4182. * Starts stats updates.
  4183. */
  4184. StatsCollector.prototype.start = function ()
  4185. {
  4186. var self = this;
  4187. this.audioLevelsIntervalId = setInterval(
  4188. function () {
  4189. // Interval updates
  4190. self.peerconnection.getStats(
  4191. function (report) {
  4192. var results = null;
  4193. if (!report || !report.result ||
  4194. typeof report.result != 'function') {
  4195. results = report;
  4196. }
  4197. else {
  4198. results = report.result();
  4199. }
  4200. //logger.error("Got interval report", results);
  4201. self.currentAudioLevelsReport = results;
  4202. self.processAudioLevelReport();
  4203. self.baselineAudioLevelsReport =
  4204. self.currentAudioLevelsReport;
  4205. },
  4206. self.errorCallback
  4207. );
  4208. },
  4209. self.audioLevelsIntervalMilis
  4210. );
  4211. // if (!this.config.disableStats && browserSupported) {
  4212. // this.statsIntervalId = setInterval(
  4213. // function () {
  4214. // // Interval updates
  4215. // self.peerconnection.getStats(
  4216. // function (report) {
  4217. // var results = null;
  4218. // if (!report || !report.result ||
  4219. // typeof report.result != 'function') {
  4220. // //firefox
  4221. // results = report;
  4222. // }
  4223. // else {
  4224. // //chrome
  4225. // results = report.result();
  4226. // }
  4227. // //logger.error("Got interval report", results);
  4228. // self.currentStatsReport = results;
  4229. // try {
  4230. // self.processStatsReport();
  4231. // }
  4232. // catch (e) {
  4233. // logger.error("Unsupported key:" + e, e);
  4234. // }
  4235. //
  4236. // self.baselineStatsReport = self.currentStatsReport;
  4237. // },
  4238. // self.errorCallback
  4239. // );
  4240. // },
  4241. // self.statsIntervalMilis
  4242. // );
  4243. // }
  4244. //
  4245. // if (this.config.logStats && browserSupported) {
  4246. // this.gatherStatsIntervalId = setInterval(
  4247. // function () {
  4248. // self.peerconnection.getStats(
  4249. // function (report) {
  4250. // self.addStatsToBeLogged(report.result());
  4251. // },
  4252. // function () {
  4253. // }
  4254. // );
  4255. // },
  4256. // this.GATHER_INTERVAL
  4257. // );
  4258. //
  4259. // this.logStatsIntervalId = setInterval(
  4260. // function() { self.logStats(); },
  4261. // this.LOG_INTERVAL);
  4262. // }
  4263. };
  4264. /**
  4265. * Converts the stats to the format used for logging, and saves the data in
  4266. * this.statsToBeLogged.
  4267. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4268. */
  4269. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4270. var self = this;
  4271. var num_records = this.statsToBeLogged.timestamps.length;
  4272. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4273. reports.map(function (report) {
  4274. if (!acceptReport(report.id, report.type))
  4275. return;
  4276. var stat = self.statsToBeLogged.stats[report.id];
  4277. if (!stat) {
  4278. stat = self.statsToBeLogged.stats[report.id] = {};
  4279. }
  4280. stat.type = report.type;
  4281. report.names().map(function (name) {
  4282. if (!acceptStat(report.id, report.type, name))
  4283. return;
  4284. var values = stat[name];
  4285. if (!values) {
  4286. values = stat[name] = [];
  4287. }
  4288. while (values.length < num_records) {
  4289. values.push(null);
  4290. }
  4291. values.push(report.stat(name));
  4292. });
  4293. });
  4294. };
  4295. //FIXME:
  4296. //StatsCollector.prototype.logStats = function () {
  4297. //
  4298. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4299. // return;
  4300. // // Reset the stats
  4301. // this.statsToBeLogged.stats = {};
  4302. // this.statsToBeLogged.timestamps = [];
  4303. //};
  4304. /**
  4305. * Stats processing logic.
  4306. */
  4307. StatsCollector.prototype.processStatsReport = function () {
  4308. if (!this.baselineStatsReport) {
  4309. return;
  4310. }
  4311. for (var idx in this.currentStatsReport) {
  4312. var now = this.currentStatsReport[idx];
  4313. try {
  4314. if (getStatValue(now, 'receiveBandwidth') ||
  4315. getStatValue(now, 'sendBandwidth')) {
  4316. this.conferenceStats.bandwidth = {
  4317. "download": Math.round(
  4318. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4319. "upload": Math.round(
  4320. (getStatValue(now, 'sendBandwidth')) / 1000)
  4321. };
  4322. }
  4323. }
  4324. catch(e){/*not supported*/}
  4325. if(now.type == 'googCandidatePair')
  4326. {
  4327. var ip, type, localIP, active;
  4328. try {
  4329. ip = getStatValue(now, 'remoteAddress');
  4330. type = getStatValue(now, "transportType");
  4331. localIP = getStatValue(now, "localAddress");
  4332. active = getStatValue(now, "activeConnection");
  4333. }
  4334. catch(e){/*not supported*/}
  4335. if(!ip || !type || !localIP || active != "true")
  4336. continue;
  4337. var addressSaved = false;
  4338. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4339. {
  4340. if(this.conferenceStats.transport[i].ip == ip &&
  4341. this.conferenceStats.transport[i].type == type &&
  4342. this.conferenceStats.transport[i].localip == localIP)
  4343. {
  4344. addressSaved = true;
  4345. }
  4346. }
  4347. if(addressSaved)
  4348. continue;
  4349. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4350. continue;
  4351. }
  4352. if(now.type == "candidatepair")
  4353. {
  4354. if(now.state == "succeeded")
  4355. continue;
  4356. var local = this.currentStatsReport[now.localCandidateId];
  4357. var remote = this.currentStatsReport[now.remoteCandidateId];
  4358. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4359. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4360. }
  4361. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4362. now.type != "inboundrtp") {
  4363. continue;
  4364. }
  4365. var before = this.baselineStatsReport[idx];
  4366. if (!before) {
  4367. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4368. continue;
  4369. }
  4370. var ssrc = getStatValue(now, 'ssrc');
  4371. if(!ssrc)
  4372. continue;
  4373. var ssrcStats = this.ssrc2stats[ssrc];
  4374. if (!ssrcStats) {
  4375. ssrcStats = new PeerStats();
  4376. this.ssrc2stats[ssrc] = ssrcStats;
  4377. }
  4378. var isDownloadStream = true;
  4379. var key = 'packetsReceived';
  4380. if (!getStatValue(now, key))
  4381. {
  4382. isDownloadStream = false;
  4383. key = 'packetsSent';
  4384. if (!getStatValue(now, key))
  4385. {
  4386. logger.warn("No packetsReceived nor packetSent stat found");
  4387. continue;
  4388. }
  4389. }
  4390. var packetsNow = getStatValue(now, key);
  4391. if(!packetsNow || packetsNow < 0)
  4392. packetsNow = 0;
  4393. var packetsBefore = getStatValue(before, key);
  4394. if(!packetsBefore || packetsBefore < 0)
  4395. packetsBefore = 0;
  4396. var packetRate = packetsNow - packetsBefore;
  4397. if(!packetRate || packetRate < 0)
  4398. packetRate = 0;
  4399. var currentLoss = getStatValue(now, 'packetsLost');
  4400. if(!currentLoss || currentLoss < 0)
  4401. currentLoss = 0;
  4402. var previousLoss = getStatValue(before, 'packetsLost');
  4403. if(!previousLoss || previousLoss < 0)
  4404. previousLoss = 0;
  4405. var lossRate = currentLoss - previousLoss;
  4406. if(!lossRate || lossRate < 0)
  4407. lossRate = 0;
  4408. var packetsTotal = (packetRate + lossRate);
  4409. ssrcStats.setSsrcLoss(ssrc,
  4410. {"packetsTotal": packetsTotal,
  4411. "packetsLost": lossRate,
  4412. "isDownloadStream": isDownloadStream});
  4413. var bytesReceived = 0, bytesSent = 0;
  4414. if(getStatValue(now, "bytesReceived"))
  4415. {
  4416. bytesReceived = getStatValue(now, "bytesReceived") -
  4417. getStatValue(before, "bytesReceived");
  4418. }
  4419. if(getStatValue(now, "bytesSent"))
  4420. {
  4421. bytesSent = getStatValue(now, "bytesSent") -
  4422. getStatValue(before, "bytesSent");
  4423. }
  4424. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4425. if(bytesReceived <= 0 || time <= 0)
  4426. {
  4427. bytesReceived = 0;
  4428. }
  4429. else
  4430. {
  4431. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4432. }
  4433. if(bytesSent <= 0 || time <= 0)
  4434. {
  4435. bytesSent = 0;
  4436. }
  4437. else
  4438. {
  4439. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4440. }
  4441. ssrcStats.setSsrcBitrate(ssrc, {
  4442. "download": bytesReceived,
  4443. "upload": bytesSent});
  4444. var resolution = {height: null, width: null};
  4445. try {
  4446. if (getStatValue(now, "googFrameHeightReceived") &&
  4447. getStatValue(now, "googFrameWidthReceived")) {
  4448. resolution.height = getStatValue(now, "googFrameHeightReceived");
  4449. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4450. }
  4451. else if (getStatValue(now, "googFrameHeightSent") &&
  4452. getStatValue(now, "googFrameWidthSent")) {
  4453. resolution.height = getStatValue(now, "googFrameHeightSent");
  4454. resolution.width = getStatValue(now, "googFrameWidthSent");
  4455. }
  4456. }
  4457. catch(e){/*not supported*/}
  4458. if(resolution.height && resolution.width)
  4459. {
  4460. ssrcStats.setSsrcResolution(ssrc, resolution);
  4461. }
  4462. else
  4463. {
  4464. ssrcStats.setSsrcResolution(ssrc, null);
  4465. }
  4466. }
  4467. var self = this;
  4468. // Jid stats
  4469. var totalPackets = {download: 0, upload: 0};
  4470. var lostPackets = {download: 0, upload: 0};
  4471. var bitrateDownload = 0;
  4472. var bitrateUpload = 0;
  4473. var resolutions = {};
  4474. Object.keys(this.ssrc2stats).forEach(
  4475. function (jid)
  4476. {
  4477. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4478. function (ssrc)
  4479. {
  4480. var type = "upload";
  4481. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4482. type = "download";
  4483. totalPackets[type] +=
  4484. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4485. lostPackets[type] +=
  4486. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4487. }
  4488. );
  4489. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4490. function (ssrc) {
  4491. bitrateDownload +=
  4492. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4493. bitrateUpload +=
  4494. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4495. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4496. }
  4497. );
  4498. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4499. }
  4500. );
  4501. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4502. this.conferenceStats.packetLoss = {
  4503. total:
  4504. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4505. totalPackets.download + totalPackets.upload),
  4506. download:
  4507. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4508. upload:
  4509. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4510. };
  4511. this.eventEmitter.emit("statistics.connectionstats",
  4512. {
  4513. "bitrate": this.conferenceStats.bitrate,
  4514. "packetLoss": this.conferenceStats.packetLoss,
  4515. "bandwidth": this.conferenceStats.bandwidth,
  4516. "resolution": resolutions,
  4517. "transport": this.conferenceStats.transport
  4518. });
  4519. this.conferenceStats.transport = [];
  4520. };
  4521. /**
  4522. * Stats processing logic.
  4523. */
  4524. StatsCollector.prototype.processAudioLevelReport = function () {
  4525. if (!this.baselineAudioLevelsReport) {
  4526. return;
  4527. }
  4528. for (var idx in this.currentAudioLevelsReport) {
  4529. var now = this.currentAudioLevelsReport[idx];
  4530. //if we don't have "packetsReceived" this is local stream
  4531. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4532. continue;
  4533. }
  4534. var before = this.baselineAudioLevelsReport[idx];
  4535. if (!before) {
  4536. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4537. continue;
  4538. }
  4539. var ssrc = getStatValue(now, 'ssrc');
  4540. if (!ssrc) {
  4541. if((Date.now() - now.timestamp) < 3000)
  4542. logger.warn("No ssrc: ");
  4543. continue;
  4544. }
  4545. var ssrcStats = this.ssrc2stats[ssrc];
  4546. if (!ssrcStats) {
  4547. ssrcStats = new PeerStats();
  4548. this.ssrc2stats[ssrc] = ssrcStats;
  4549. }
  4550. // Audio level
  4551. var audioLevel = null;
  4552. try {
  4553. audioLevel = getStatValue(now, 'audioInputLevel');
  4554. if (!audioLevel)
  4555. audioLevel = getStatValue(now, 'audioOutputLevel');
  4556. }
  4557. catch(e) {/*not supported*/
  4558. logger.warn("Audio Levels are not available in the statistics.");
  4559. clearInterval(this.audioLevelsIntervalId);
  4560. return;
  4561. }
  4562. if (audioLevel) {
  4563. // TODO: can't find specs about what this value really is,
  4564. // but it seems to vary between 0 and around 32k.
  4565. audioLevel = audioLevel / 32767;
  4566. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4567. this.eventEmitter.emit("statistics.audioLevel", ssrc, audioLevel);
  4568. }
  4569. }
  4570. };
  4571. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4572. },{"../RTC/RTCBrowserType":14,"jitsi-meet-logger":44}],21:[function(require,module,exports){
  4573. /* global require, APP */
  4574. var LocalStats = require("./LocalStatsCollector.js");
  4575. var RTPStats = require("./RTPStatsCollector.js");
  4576. var EventEmitter = require("events");
  4577. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4578. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4579. //var CallStats = require("./CallStats");
  4580. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4581. //
  4582. //function onDisposeConference(onUnload) {
  4583. // CallStats.sendTerminateEvent();
  4584. // stopRemote();
  4585. // if(onUnload) {
  4586. // stopLocal();
  4587. // eventEmitter.removeAllListeners();
  4588. // }
  4589. //}
  4590. function Statistics() {
  4591. this.localStats = null;
  4592. this.rtpStats = null;
  4593. this.eventEmitter = new EventEmitter();
  4594. }
  4595. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4596. if (this.rtpStats) {
  4597. this.rtpStats.stop();
  4598. }
  4599. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4600. this.rtpStats.start();
  4601. }
  4602. Statistics.prototype.startLocalStats = function (stream) {
  4603. if(stream.getType() !== "audio")
  4604. return;
  4605. this.localStats = new LocalStats(stream.getOriginalStream(), 200, this,
  4606. this.eventEmitter);
  4607. this.localStats.start();
  4608. }
  4609. Statistics.prototype.addAudioLevelListener = function(listener)
  4610. {
  4611. this.eventEmitter.on("statistics.audioLevel", listener);
  4612. }
  4613. Statistics.prototype.removeAudioLevelListener = function(listener)
  4614. {
  4615. this.eventEmitter.removeListener("statistics.audioLevel", listener);
  4616. }
  4617. Statistics.prototype.dispose = function () {
  4618. this.stopLocal();
  4619. this.stopRemote();
  4620. if(this.eventEmitter)
  4621. {
  4622. this.eventEmitter.removeAllListeners();
  4623. }
  4624. }
  4625. Statistics.prototype.stopLocal = function () {
  4626. if (this.localStats) {
  4627. this.localStats.stop();
  4628. this.localStats = null;
  4629. }
  4630. }
  4631. Statistics.prototype.stopRemote = function () {
  4632. if (this.rtpStats) {
  4633. this.rtpStats.stop();
  4634. this.eventEmitter.emit("statistics.stop");
  4635. this.rtpStats = null;
  4636. }
  4637. }
  4638. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  4639. //
  4640. //var statistics = {
  4641. // /**
  4642. // * Indicates that this audio level is for local jid.
  4643. // * @type {string}
  4644. // */
  4645. // LOCAL_JID: 'local',
  4646. //
  4647. // addConnectionStatsListener: function(listener)
  4648. // {
  4649. // eventEmitter.on("statistics.connectionstats", listener);
  4650. // },
  4651. //
  4652. // removeConnectionStatsListener: function(listener)
  4653. // {
  4654. // eventEmitter.removeListener("statistics.connectionstats", listener);
  4655. // },
  4656. //
  4657. //
  4658. // addRemoteStatsStopListener: function(listener)
  4659. // {
  4660. // eventEmitter.on("statistics.stop", listener);
  4661. // },
  4662. //
  4663. // removeRemoteStatsStopListener: function(listener)
  4664. // {
  4665. // eventEmitter.removeListener("statistics.stop", listener);
  4666. // },
  4667. //
  4668. //
  4669. // stopRemoteStatistics: function()
  4670. // {
  4671. // stopRemote();
  4672. // },
  4673. //
  4674. //// Already implemented with the constructor
  4675. // start: function () {
  4676. // APP.RTC.addStreamListener(onStreamCreated,
  4677. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  4678. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  4679. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  4680. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  4681. // startRemoteStats(event.peerconnection);
  4682. //// CallStats.init(event);
  4683. // });
  4684. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  4685. //// CallStats.init(session);
  4686. //// });
  4687. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4688. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  4689. //// CallStats.sendMuteEvent(mute, "audio");
  4690. //// });
  4691. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  4692. //// CallStats.sendSetupFailedEvent();
  4693. //// });
  4694. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4695. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  4696. //// CallStats.sendMuteEvent(mute, "video");
  4697. //// });
  4698. // }
  4699. //};
  4700. module.exports = Statistics;
  4701. },{"../../service/statistics/constants":81,"./LocalStatsCollector.js":19,"./RTPStatsCollector.js":20,"events":40}],22:[function(require,module,exports){
  4702. /**
  4703. * Generates random hex number within the range [min, max]
  4704. * @param max the maximum value for the generated number
  4705. * @param min the minimum value for the generated number
  4706. * @returns random hex number
  4707. */
  4708. function rangeRandomHex(min, max)
  4709. {
  4710. return Math.floor(Math.random() * (max - min) + min).toString(16);
  4711. }
  4712. /**
  4713. * Exported interface.
  4714. */
  4715. var RandomUtil = {
  4716. /**
  4717. * Generates hex number with length 4
  4718. */
  4719. random4digitsHex: function() {
  4720. return rangeRandomHex(4096, 65535);
  4721. },
  4722. /**
  4723. * Generates hex number with length 8
  4724. */
  4725. random8digitsHex: function() {
  4726. return rangeRandomHex(268435456, 4294967295);
  4727. },
  4728. /**
  4729. * Generates hex number with length 12
  4730. */
  4731. random12digitsHex: function() {
  4732. return rangeRandomHex(17592186044416, 281474976710655);
  4733. }
  4734. };
  4735. module.exports = RandomUtil;
  4736. },{}],23:[function(require,module,exports){
  4737. (function (__filename){
  4738. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4739. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4740. var Moderator = require("./moderator");
  4741. var EventEmitter = require("events");
  4742. var parser = {
  4743. packet2JSON: function (packet, nodes) {
  4744. var self = this;
  4745. $(packet).children().each(function (index) {
  4746. var tagName = $(this).prop("tagName");
  4747. var node = {}
  4748. node["tagName"] = tagName;
  4749. node.attributes = {};
  4750. $($(this)[0].attributes).each(function( index, attr ) {
  4751. node.attributes[ attr.name ] = attr.value;
  4752. } );
  4753. var text = Strophe.getText($(this)[0]);
  4754. if(text)
  4755. node.value = text;
  4756. node.children = [];
  4757. nodes.push(node);
  4758. self.packet2JSON($(this), node.children);
  4759. })
  4760. },
  4761. JSON2packet: function (nodes, packet) {
  4762. for(var i = 0; i < nodes.length; i++)
  4763. {
  4764. var node = nodes[i];
  4765. if(!node || node === null){
  4766. continue;
  4767. }
  4768. packet.c(node.tagName, node.attributes);
  4769. if(node.value)
  4770. packet.t(node.value);
  4771. if(node.children)
  4772. this.JSON2packet(node.children, packet);
  4773. packet.up();
  4774. }
  4775. // packet.up();
  4776. }
  4777. };
  4778. /**
  4779. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  4780. * @param pres the presence JSON
  4781. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  4782. */
  4783. function filterNodeFromPresenceJSON(pres, nodeName){
  4784. var res = [];
  4785. for(var i = 0; i < pres.length; i++)
  4786. if(pres[i].tagName === nodeName)
  4787. res.push(pres[i]);
  4788. return res;
  4789. }
  4790. function ChatRoom(connection, jid, password, XMPP, options) {
  4791. this.eventEmitter = new EventEmitter();
  4792. this.xmpp = XMPP;
  4793. this.connection = connection;
  4794. this.roomjid = Strophe.getBareJidFromJid(jid);
  4795. this.myroomjid = jid;
  4796. this.password = password;
  4797. logger.info("Joined MUC as " + this.myroomjid);
  4798. this.members = {};
  4799. this.presMap = {};
  4800. this.presHandlers = {};
  4801. this.joined = false;
  4802. this.role = null;
  4803. this.focusMucJid = null;
  4804. this.bridgeIsDown = false;
  4805. this.options = options || {};
  4806. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  4807. this.initPresenceMap();
  4808. this.session = null;
  4809. var self = this;
  4810. this.lastPresences = {};
  4811. }
  4812. ChatRoom.prototype.initPresenceMap = function () {
  4813. this.presMap['to'] = this.myroomjid;
  4814. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  4815. this.presMap["nodes"] = [];
  4816. this.presMap["nodes"].push( {
  4817. "tagName": "user-agent",
  4818. "value": navigator.userAgent,
  4819. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  4820. });
  4821. };
  4822. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  4823. this.presMap["nodes"].push( {
  4824. "tagName": "devices",
  4825. "children": [
  4826. {
  4827. "tagName": "audio",
  4828. "value": devices.audio,
  4829. },
  4830. {
  4831. "tagName": "video",
  4832. "value": devices.video,
  4833. }
  4834. ]
  4835. });
  4836. }
  4837. ChatRoom.prototype.join = function (password, tokenPassword) {
  4838. if(password)
  4839. this.password = password;
  4840. var self = this;
  4841. this.moderator.allocateConferenceFocus(function()
  4842. {
  4843. self.sendPresence(tokenPassword);
  4844. }.bind(this));
  4845. };
  4846. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  4847. if (!this.presMap['to']) {
  4848. // Too early to send presence - not initialized
  4849. return;
  4850. }
  4851. var pres = $pres({to: this.presMap['to'] });
  4852. pres.c('x', {xmlns: this.presMap['xns']});
  4853. if (this.password) {
  4854. pres.c('password').t(this.password).up();
  4855. }
  4856. pres.up();
  4857. // Send XEP-0115 'c' stanza that contains our capabilities info
  4858. if (this.connection.caps) {
  4859. this.connection.caps.node = this.xmpp.options.clientNode;
  4860. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  4861. }
  4862. if (tokenPassword) {
  4863. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  4864. .t(tokenPassword).up();
  4865. }
  4866. parser.JSON2packet(this.presMap.nodes, pres);
  4867. this.connection.send(pres);
  4868. };
  4869. ChatRoom.prototype.doLeave = function () {
  4870. logger.log("do leave", this.myroomjid);
  4871. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  4872. this.presMap.length = 0;
  4873. this.connection.send(pres);
  4874. };
  4875. ChatRoom.prototype.createNonAnonymousRoom = function () {
  4876. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  4877. var getForm = $iq({type: 'get', to: this.roomjid})
  4878. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  4879. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  4880. var self = this;
  4881. this.connection.sendIQ(getForm, function (form) {
  4882. if (!$(form).find(
  4883. '>query>x[xmlns="jabber:x:data"]' +
  4884. '>field[var="muc#roomconfig_whois"]').length) {
  4885. logger.error('non-anonymous rooms not supported');
  4886. return;
  4887. }
  4888. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  4889. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  4890. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  4891. formSubmit.c('field', {'var': 'FORM_TYPE'})
  4892. .c('value')
  4893. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  4894. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  4895. .c('value').t('anyone').up().up();
  4896. self.connection.sendIQ(formSubmit);
  4897. }, function (error) {
  4898. logger.error("Error getting room configuration form");
  4899. });
  4900. };
  4901. ChatRoom.prototype.onPresence = function (pres) {
  4902. var from = pres.getAttribute('from');
  4903. // Parse roles.
  4904. var member = {};
  4905. member.show = $(pres).find('>show').text();
  4906. member.status = $(pres).find('>status').text();
  4907. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  4908. member.affiliation = tmp.attr('affiliation');
  4909. member.role = tmp.attr('role');
  4910. // Focus recognition
  4911. member.jid = tmp.attr('jid');
  4912. member.isFocus = false;
  4913. if (member.jid
  4914. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  4915. member.isFocus = true;
  4916. }
  4917. $(pres).find(">x").remove();
  4918. var nodes = [];
  4919. parser.packet2JSON(pres, nodes);
  4920. this.lastPresences[from] = nodes;
  4921. for(var i = 0; i < nodes.length; i++)
  4922. {
  4923. var node = nodes[i];
  4924. switch(node.tagName)
  4925. {
  4926. case "nick":
  4927. member.nick = node.value;
  4928. if(!member.isFocus) {
  4929. var displayName = !this.xmpp.options.displayJids
  4930. ? member.nick : Strophe.getResourceFromJid(from);
  4931. if (displayName && displayName.length > 0) {
  4932. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  4933. }
  4934. logger.info("Display name: " + displayName, pres);
  4935. }
  4936. break;
  4937. case "userId":
  4938. member.id = node.value;
  4939. break;
  4940. case "email":
  4941. member.email = node.value;
  4942. break;
  4943. case "bridgeIsDown":
  4944. if(!this.bridgeIsDown) {
  4945. this.bridgeIsDown = true;
  4946. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  4947. }
  4948. break;
  4949. default :
  4950. this.processNode(node, from);
  4951. }
  4952. }
  4953. if (from == this.myroomjid) {
  4954. if (member.affiliation == 'owner')
  4955. if (this.role !== member.role) {
  4956. this.role = member.role;
  4957. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  4958. member, this.isModerator());
  4959. }
  4960. if (!this.joined) {
  4961. this.joined = true;
  4962. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  4963. }
  4964. } else if (this.members[from] === undefined) {
  4965. // new participant
  4966. this.members[from] = member;
  4967. logger.log('entered', from, member);
  4968. if (member.isFocus) {
  4969. this.focusMucJid = from;
  4970. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  4971. }
  4972. else {
  4973. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  4974. }
  4975. } else {
  4976. // Presence update for existing participant
  4977. // Watch role change:
  4978. if (this.members[from].role != member.role) {
  4979. this.members[from].role = member.role;
  4980. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  4981. member.role, member.nick);
  4982. }
  4983. }
  4984. if(!member.isFocus)
  4985. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  4986. // Trigger status message update
  4987. if (member.status) {
  4988. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  4989. }
  4990. };
  4991. ChatRoom.prototype.processNode = function (node, from) {
  4992. if(this.presHandlers[node.tagName])
  4993. this.presHandlers[node.tagName](node, from);
  4994. };
  4995. ChatRoom.prototype.sendMessage = function (body, nickname) {
  4996. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  4997. msg.c('body', body).up();
  4998. if (nickname) {
  4999. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5000. }
  5001. this.connection.send(msg);
  5002. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5003. };
  5004. ChatRoom.prototype.setSubject = function (subject) {
  5005. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5006. msg.c('subject', subject);
  5007. this.connection.send(msg);
  5008. logger.log("topic changed to " + subject);
  5009. };
  5010. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5011. delete this.lastPresences[jid];
  5012. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5013. this.moderator.onMucMemberLeft(jid);
  5014. };
  5015. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5016. // room destroyed ?
  5017. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5018. '>destroy').length) {
  5019. var reason;
  5020. var reasonSelect = $(pres).find(
  5021. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5022. '>destroy>reason');
  5023. if (reasonSelect.length) {
  5024. reason = reasonSelect.text();
  5025. }
  5026. this.xmpp.disposeConference(false);
  5027. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5028. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  5029. return true;
  5030. }
  5031. // Status code 110 indicates that this notification is "self-presence".
  5032. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5033. delete this.members[from];
  5034. this.onParticipantLeft(from);
  5035. }
  5036. // If the status code is 110 this means we're leaving and we would like
  5037. // to remove everyone else from our view, so we trigger the event.
  5038. else if (Object.keys(this.members).length > 1) {
  5039. for (var i in this.members) {
  5040. var member = this.members[i];
  5041. delete this.members[i];
  5042. this.onParticipantLeft(member);
  5043. }
  5044. }
  5045. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5046. if (this.myroomjid === from) {
  5047. this.xmpp.disposeConference(false);
  5048. this.eventEmitter.emit(XMPPEvents.KICKED);
  5049. }
  5050. }
  5051. };
  5052. ChatRoom.prototype.onMessage = function (msg, from) {
  5053. var nick =
  5054. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5055. .text() ||
  5056. Strophe.getResourceFromJid(from);
  5057. var txt = $(msg).find('>body').text();
  5058. var type = msg.getAttribute("type");
  5059. if (type == "error") {
  5060. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5061. $(msg).find('>text').text(), txt);
  5062. return true;
  5063. }
  5064. var subject = $(msg).find('>subject');
  5065. if (subject.length) {
  5066. var subjectText = subject.text();
  5067. if (subjectText || subjectText == "") {
  5068. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5069. logger.log("Subject is changed to " + subjectText);
  5070. }
  5071. }
  5072. // xep-0203 delay
  5073. var stamp = $(msg).find('>delay').attr('stamp');
  5074. if (!stamp) {
  5075. // or xep-0091 delay, UTC timestamp
  5076. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5077. if (stamp) {
  5078. // the format is CCYYMMDDThh:mm:ss
  5079. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5080. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5081. }
  5082. }
  5083. if (txt) {
  5084. logger.log('chat', nick, txt);
  5085. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5086. from, nick, txt, this.myroomjid, stamp);
  5087. }
  5088. }
  5089. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5090. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5091. logger.log('on password required', from);
  5092. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5093. } else if ($(pres).find(
  5094. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5095. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5096. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5097. // enter the room by replying with 'not-authorized'. This would
  5098. // result in reconnection from authorized domain.
  5099. // We're either missing Jicofo/Prosody config for anonymous
  5100. // domains or something is wrong.
  5101. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5102. } else {
  5103. logger.warn('onPresError ', pres);
  5104. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5105. }
  5106. } else {
  5107. logger.warn('onPresError ', pres);
  5108. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5109. }
  5110. };
  5111. ChatRoom.prototype.kick = function (jid) {
  5112. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5113. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5114. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5115. .c('reason').t('You have been kicked.').up().up().up();
  5116. this.connection.sendIQ(
  5117. kickIQ,
  5118. function (result) {
  5119. logger.log('Kick participant with jid: ', jid, result);
  5120. },
  5121. function (error) {
  5122. logger.log('Kick participant error: ', error);
  5123. });
  5124. };
  5125. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5126. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5127. var ob = this;
  5128. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5129. function (res) {
  5130. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5131. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5132. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5133. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5134. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5135. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5136. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5137. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5138. ob.connection.sendIQ(formsubmit,
  5139. onSuccess,
  5140. onError);
  5141. } else {
  5142. onNotSupported();
  5143. }
  5144. }, onError);
  5145. };
  5146. ChatRoom.prototype.addToPresence = function (key, values) {
  5147. values.tagName = key;
  5148. this.presMap["nodes"].push(values);
  5149. };
  5150. ChatRoom.prototype.removeFromPresence = function (key) {
  5151. for(var i = 0; i < this.presMap.nodes.length; i++)
  5152. {
  5153. if(key === this.presMap.nodes[i].tagName)
  5154. this.presMap.nodes.splice(i, 1);
  5155. }
  5156. };
  5157. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5158. this.presHandlers[name] = handler;
  5159. }
  5160. ChatRoom.prototype.removePresenceListener = function (name) {
  5161. delete this.presHandlers[name];
  5162. }
  5163. ChatRoom.prototype.isModerator = function (jid) {
  5164. return this.role === 'moderator';
  5165. };
  5166. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5167. if (this.members[peerJid]) {
  5168. return this.members[peerJid].role;
  5169. }
  5170. return null;
  5171. };
  5172. ChatRoom.prototype.setJingleSession = function(session){
  5173. this.session = session;
  5174. this.session.room = this;
  5175. };
  5176. ChatRoom.prototype.removeStream = function (stream) {
  5177. if(!this.session)
  5178. return;
  5179. this.session.peerconnection.removeStream(stream)
  5180. }
  5181. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5182. if(this.session) {
  5183. // FIXME: will block switchInProgress on true value in case of exception
  5184. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5185. } else {
  5186. // We are done immediately
  5187. logger.warn("No conference handler or conference not started yet");
  5188. callback();
  5189. }
  5190. };
  5191. ChatRoom.prototype.addStream = function (stream, callback) {
  5192. if(this.session) {
  5193. // FIXME: will block switchInProgress on true value in case of exception
  5194. this.session.addStream(stream, callback);
  5195. } else {
  5196. // We are done immediately
  5197. logger.warn("No conference handler or conference not started yet");
  5198. callback();
  5199. }
  5200. }
  5201. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5202. var self = this;
  5203. var localCallback = function (mute) {
  5204. self.sendVideoInfoPresence(mute);
  5205. if(callback)
  5206. callback(mute)
  5207. };
  5208. if(this.session)
  5209. {
  5210. this.session.setVideoMute(
  5211. mute, localCallback, options);
  5212. }
  5213. else {
  5214. localCallback(mute);
  5215. }
  5216. };
  5217. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5218. //This will be for remote streams only
  5219. // if (this.forceMuted && !mute) {
  5220. // logger.info("Asking focus for unmute");
  5221. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5222. // // FIXME: wait for result before resetting muted status
  5223. // this.forceMuted = false;
  5224. // }
  5225. return this.sendAudioInfoPresence(mute, callback);
  5226. };
  5227. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5228. this.removeFromPresence("audiomuted");
  5229. this.addToPresence("audiomuted",
  5230. {attributes:
  5231. {"audions": "http://jitsi.org/jitmeet/audio"},
  5232. value: mute.toString()});
  5233. }
  5234. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5235. this.addAudioInfoToPresence(mute);
  5236. if(this.connection) {
  5237. this.sendPresence();
  5238. }
  5239. if(callback)
  5240. callback();
  5241. };
  5242. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5243. this.removeFromPresence("videomuted");
  5244. this.addToPresence("videomuted",
  5245. {attributes:
  5246. {"videons": "http://jitsi.org/jitmeet/video"},
  5247. value: mute.toString()});
  5248. }
  5249. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5250. this.addVideoInfoToPresence(mute);
  5251. if(!this.connection)
  5252. return;
  5253. this.sendPresence();
  5254. };
  5255. ChatRoom.prototype.addListener = function(type, listener) {
  5256. this.eventEmitter.on(type, listener);
  5257. };
  5258. ChatRoom.prototype.removeListener = function (type, listener) {
  5259. this.eventEmitter.removeListener(type, listener);
  5260. };
  5261. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5262. if(this.lastPresences[data.peerjid])
  5263. {
  5264. var pres = this.lastPresences[data.peerjid];
  5265. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5266. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5267. data.videomuted = ((videomuted.length > 0
  5268. && videomuted[0]
  5269. && videomuted[0]["value"] === "true")? true : false);
  5270. data.audiomuted = ((audiomuted.length > 0
  5271. && audiomuted[0]
  5272. && audiomuted[0]["value"] === "true")? true : false);
  5273. }
  5274. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5275. }
  5276. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5277. if (!this.session)
  5278. return null;
  5279. return this.session.getSsrcOwner(ssrc);
  5280. };
  5281. module.exports = ChatRoom;
  5282. }).call(this,"/modules/xmpp/ChatRoom.js")
  5283. },{"../../service/xmpp/XMPPEvents":82,"./moderator":31,"events":40,"jitsi-meet-logger":44}],24:[function(require,module,exports){
  5284. (function (__filename){
  5285. /*
  5286. * JingleSession provides an API to manage a single Jingle session. We will
  5287. * have different implementations depending on the underlying interface used
  5288. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5289. */
  5290. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5291. function JingleSession(me, sid, connection, service, eventEmitter) {
  5292. /**
  5293. * Our JID.
  5294. */
  5295. this.me = me;
  5296. /**
  5297. * The Jingle session identifier.
  5298. */
  5299. this.sid = sid;
  5300. /**
  5301. * The XMPP connection.
  5302. */
  5303. this.connection = connection;
  5304. /**
  5305. * The XMPP service.
  5306. */
  5307. this.service = service;
  5308. /**
  5309. * The event emitter.
  5310. */
  5311. this.eventEmitter = eventEmitter;
  5312. /**
  5313. * Whether to use dripping or not. Dripping is sending trickle candidates
  5314. * not one-by-one.
  5315. * Note: currently we do not support 'false'.
  5316. */
  5317. this.usedrip = true;
  5318. /**
  5319. * When dripping is used, stores ICE candidates which are to be sent.
  5320. */
  5321. this.drip_container = [];
  5322. // Media constraints. Is this WebRTC only?
  5323. this.media_constraints = null;
  5324. // ICE servers config (RTCConfiguration?).
  5325. this.ice_config = {};
  5326. // The chat room instance associated with the session.
  5327. this.room = null;
  5328. }
  5329. /**
  5330. * Prepares this object to initiate a session.
  5331. * @param peerjid the JID of the remote peer.
  5332. * @param isInitiator whether we will be the Jingle initiator.
  5333. * @param media_constraints
  5334. * @param ice_config
  5335. */
  5336. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5337. media_constraints, ice_config) {
  5338. this.media_constraints = media_constraints;
  5339. this.ice_config = ice_config;
  5340. if (this.state !== null) {
  5341. logger.error('attempt to initiate on session ' + this.sid +
  5342. 'in state ' + this.state);
  5343. return;
  5344. }
  5345. this.state = 'pending';
  5346. this.initiator = isInitiator ? this.me : peerjid;
  5347. this.responder = !isInitiator ? this.me : peerjid;
  5348. this.peerjid = peerjid;
  5349. this.doInitialize();
  5350. };
  5351. /**
  5352. * Finishes initialization.
  5353. */
  5354. JingleSession.prototype.doInitialize = function() {};
  5355. /**
  5356. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5357. * Note: currently only used on transport-info
  5358. */
  5359. JingleSession.prototype.addIceCandidates = function(contents) {};
  5360. /**
  5361. * Handles an 'add-source' event.
  5362. *
  5363. * @param contents an array of Jingle 'content' elements.
  5364. */
  5365. JingleSession.prototype.addSources = function(contents) {};
  5366. /**
  5367. * Handles a 'remove-source' event.
  5368. *
  5369. * @param contents an array of Jingle 'content' elements.
  5370. */
  5371. JingleSession.prototype.removeSources = function(contents) {};
  5372. /**
  5373. * Terminates this Jingle session (stops sending media and closes the streams?)
  5374. */
  5375. JingleSession.prototype.terminate = function() {};
  5376. /**
  5377. * Sends a Jingle session-terminate message to the peer and terminates the
  5378. * session.
  5379. * @param reason
  5380. * @param text
  5381. */
  5382. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5383. /**
  5384. * Handles an offer from the remote peer (prepares to accept a session).
  5385. * @param jingle the 'jingle' XML element.
  5386. */
  5387. JingleSession.prototype.setOffer = function(jingle) {};
  5388. /**
  5389. * Handles an answer from the remote peer (prepares to accept a session).
  5390. * @param jingle the 'jingle' XML element.
  5391. */
  5392. JingleSession.prototype.setAnswer = function(jingle) {};
  5393. module.exports = JingleSession;
  5394. }).call(this,"/modules/xmpp/JingleSession.js")
  5395. },{"jitsi-meet-logger":44}],25:[function(require,module,exports){
  5396. (function (__filename){
  5397. /* jshint -W117 */
  5398. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5399. var JingleSession = require("./JingleSession");
  5400. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5401. var SDPDiffer = require("./SDPDiffer");
  5402. var SDPUtil = require("./SDPUtil");
  5403. var SDP = require("./SDP");
  5404. var async = require("async");
  5405. var transform = require("sdp-transform");
  5406. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5407. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5408. var SSRCReplacement = require("./LocalSSRCReplacement");
  5409. var RTC = require("../RTC/RTC");
  5410. // Jingle stuff
  5411. function JingleSessionPC(me, sid, connection, service) {
  5412. JingleSession.call(this, me, sid, connection, service);
  5413. this.initiator = null;
  5414. this.responder = null;
  5415. this.peerjid = null;
  5416. this.state = null;
  5417. this.localSDP = null;
  5418. this.remoteSDP = null;
  5419. this.relayedStreams = [];
  5420. this.usetrickle = true;
  5421. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5422. this.hadstuncandidate = false;
  5423. this.hadturncandidate = false;
  5424. this.lasticecandidate = false;
  5425. this.statsinterval = null;
  5426. this.reason = null;
  5427. this.addssrc = [];
  5428. this.removessrc = [];
  5429. this.pendingop = null;
  5430. this.switchstreams = false;
  5431. this.addingStreams = false;
  5432. this.wait = true;
  5433. this.localStreamsSSRC = null;
  5434. this.ssrcOwners = {};
  5435. this.ssrcVideoTypes = {};
  5436. /**
  5437. * The indicator which determines whether the (local) video has been muted
  5438. * in response to a user command in contrast to an automatic decision made
  5439. * by the application logic.
  5440. */
  5441. this.videoMuteByUser = false;
  5442. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5443. // We start with the queue paused. We resume it when the signaling state is
  5444. // stable and the ice connection state is connected.
  5445. this.modifySourcesQueue.pause();
  5446. }
  5447. JingleSessionPC.prototype = JingleSession.prototype;
  5448. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5449. JingleSessionPC.prototype.setOffer = function(offer) {
  5450. this.setRemoteDescription(offer, 'offer');
  5451. };
  5452. JingleSessionPC.prototype.setAnswer = function(answer) {
  5453. this.setRemoteDescription(answer, 'answer');
  5454. };
  5455. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5456. var signalingState = this.peerconnection.signalingState;
  5457. var iceConnectionState = this.peerconnection.iceConnectionState;
  5458. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5459. this.modifySourcesQueue.resume();
  5460. } else {
  5461. this.modifySourcesQueue.pause();
  5462. }
  5463. };
  5464. JingleSessionPC.prototype.doInitialize = function () {
  5465. var self = this;
  5466. this.hadstuncandidate = false;
  5467. this.hadturncandidate = false;
  5468. this.lasticecandidate = false;
  5469. // True if reconnect is in progress
  5470. this.isreconnect = false;
  5471. // Set to true if the connection was ever stable
  5472. this.wasstable = false;
  5473. this.peerconnection = new TraceablePeerConnection(
  5474. this.connection.jingle.ice_config,
  5475. RTC.getPCConstraints(),
  5476. this);
  5477. this.peerconnection.onicecandidate = function (event) {
  5478. self.sendIceCandidate(event.candidate);
  5479. };
  5480. this.peerconnection.onaddstream = function (event) {
  5481. if (event.stream.id !== 'default') {
  5482. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5483. self.remoteStreamAdded(event);
  5484. } else {
  5485. // This is a recvonly stream. Clients that implement Unified Plan,
  5486. // such as Firefox use recvonly "streams/channels/tracks" for
  5487. // receiving remote stream/tracks, as opposed to Plan B where there
  5488. // are only 3 channels: audio, video and data.
  5489. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5490. }
  5491. };
  5492. this.peerconnection.onremovestream = function (event) {
  5493. // Remove the stream from remoteStreams
  5494. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5495. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5496. };
  5497. this.peerconnection.onsignalingstatechange = function (event) {
  5498. if (!(self && self.peerconnection)) return;
  5499. if (self.peerconnection.signalingState === 'stable') {
  5500. self.wasstable = true;
  5501. }
  5502. self.updateModifySourcesQueue();
  5503. };
  5504. /**
  5505. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  5506. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  5507. * RTCPeerConnection.iceConnectionState changes.
  5508. *
  5509. * @param event the event containing information about the change
  5510. */
  5511. this.peerconnection.oniceconnectionstatechange = function (event) {
  5512. if (!(self && self.peerconnection)) return;
  5513. self.updateModifySourcesQueue();
  5514. switch (self.peerconnection.iceConnectionState) {
  5515. case 'connected':
  5516. // Informs interested parties that the connection has been restored.
  5517. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  5518. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  5519. self.isreconnect = false;
  5520. break;
  5521. case 'disconnected':
  5522. self.isreconnect = true;
  5523. // Informs interested parties that the connection has been interrupted.
  5524. if (self.wasstable)
  5525. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  5526. break;
  5527. case 'failed':
  5528. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5529. break;
  5530. }
  5531. onIceConnectionStateChange(self.sid, self);
  5532. };
  5533. this.peerconnection.onnegotiationneeded = function (event) {
  5534. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  5535. };
  5536. this.relayedStreams.forEach(function(stream) {
  5537. self.peerconnection.addStream(stream);
  5538. });
  5539. };
  5540. function onIceConnectionStateChange(sid, session) {
  5541. switch (session.peerconnection.iceConnectionState) {
  5542. case 'checking':
  5543. session.timeChecking = (new Date()).getTime();
  5544. session.firstconnect = true;
  5545. break;
  5546. case 'completed': // on caller side
  5547. case 'connected':
  5548. if (session.firstconnect) {
  5549. session.firstconnect = false;
  5550. var metadata = {};
  5551. metadata.setupTime
  5552. = (new Date()).getTime() - session.timeChecking;
  5553. session.peerconnection.getStats(function (res) {
  5554. if(res && res.result) {
  5555. res.result().forEach(function (report) {
  5556. if (report.type == 'googCandidatePair' &&
  5557. report.stat('googActiveConnection') == 'true') {
  5558. metadata.localCandidateType
  5559. = report.stat('googLocalCandidateType');
  5560. metadata.remoteCandidateType
  5561. = report.stat('googRemoteCandidateType');
  5562. // log pair as well so we can get nice pie
  5563. // charts
  5564. metadata.candidatePair
  5565. = report.stat('googLocalCandidateType') +
  5566. ';' +
  5567. report.stat('googRemoteCandidateType');
  5568. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  5569. {
  5570. metadata.ipv6 = true;
  5571. }
  5572. }
  5573. });
  5574. }
  5575. });
  5576. }
  5577. break;
  5578. }
  5579. }
  5580. JingleSessionPC.prototype.accept = function () {
  5581. this.state = 'active';
  5582. var pranswer = this.peerconnection.localDescription;
  5583. if (!pranswer || pranswer.type != 'pranswer') {
  5584. return;
  5585. }
  5586. logger.log('going from pranswer to answer');
  5587. if (this.usetrickle) {
  5588. // remove candidates already sent from session-accept
  5589. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  5590. for (var i = 0; i < lines.length; i++) {
  5591. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  5592. }
  5593. }
  5594. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  5595. // FIXME: change any inactive to sendrecv or whatever they were originally
  5596. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  5597. }
  5598. var prsdp = new SDP(pranswer.sdp);
  5599. var accept = $iq({to: this.peerjid,
  5600. type: 'set'})
  5601. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5602. action: 'session-accept',
  5603. initiator: this.initiator,
  5604. responder: this.responder,
  5605. sid: this.sid });
  5606. // FIXME why do we generate session-accept in 3 different places ?
  5607. prsdp.toJingle(
  5608. accept,
  5609. this.initiator == this.me ? 'initiator' : 'responder',
  5610. this.localStreamsSSRC);
  5611. var sdp = this.peerconnection.localDescription.sdp;
  5612. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  5613. // FIXME: change any inactive to sendrecv or whatever they were originally
  5614. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  5615. }
  5616. var self = this;
  5617. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  5618. function () {
  5619. //logger.log('setLocalDescription success');
  5620. self.setLocalDescription();
  5621. SSRCReplacement.processSessionInit(accept);
  5622. self.connection.sendIQ(accept,
  5623. function () {
  5624. var ack = {};
  5625. ack.source = 'answer';
  5626. $(document).trigger('ack.jingle', [self.sid, ack]);
  5627. },
  5628. function (stanza) {
  5629. var error = ($(stanza).find('error').length) ? {
  5630. code: $(stanza).find('error').attr('code'),
  5631. reason: $(stanza).find('error :first')[0].tagName
  5632. }:{};
  5633. error.source = 'answer';
  5634. JingleSessionPC.onJingleError(self.sid, error);
  5635. },
  5636. 10000);
  5637. },
  5638. function (e) {
  5639. logger.error('setLocalDescription failed', e);
  5640. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5641. }
  5642. );
  5643. };
  5644. JingleSessionPC.prototype.terminate = function (reason) {
  5645. this.state = 'ended';
  5646. this.reason = reason;
  5647. this.peerconnection.close();
  5648. if (this.statsinterval !== null) {
  5649. window.clearInterval(this.statsinterval);
  5650. this.statsinterval = null;
  5651. }
  5652. };
  5653. JingleSessionPC.prototype.active = function () {
  5654. return this.state == 'active';
  5655. };
  5656. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  5657. var self = this;
  5658. if (candidate && !this.lasticecandidate) {
  5659. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  5660. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  5661. if (!(ice && jcand)) {
  5662. logger.error('failed to get ice && jcand');
  5663. return;
  5664. }
  5665. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5666. if (jcand.type === 'srflx') {
  5667. this.hadstuncandidate = true;
  5668. } else if (jcand.type === 'relay') {
  5669. this.hadturncandidate = true;
  5670. }
  5671. if (this.usetrickle) {
  5672. if (this.usedrip) {
  5673. if (this.drip_container.length === 0) {
  5674. // start 20ms callout
  5675. window.setTimeout(function () {
  5676. if (self.drip_container.length === 0) return;
  5677. self.sendIceCandidates(self.drip_container);
  5678. self.drip_container = [];
  5679. }, 20);
  5680. }
  5681. this.drip_container.push(candidate);
  5682. return;
  5683. } else {
  5684. self.sendIceCandidate([candidate]);
  5685. }
  5686. }
  5687. } else {
  5688. //logger.log('sendIceCandidate: last candidate.');
  5689. if (!this.usetrickle) {
  5690. //logger.log('should send full offer now...');
  5691. //FIXME why do we generate session-accept in 3 different places ?
  5692. var init = $iq({to: this.peerjid,
  5693. type: 'set'})
  5694. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5695. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  5696. initiator: this.initiator,
  5697. sid: this.sid});
  5698. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  5699. var sendJingle = function (ssrc) {
  5700. if(!ssrc)
  5701. ssrc = {};
  5702. self.localSDP.toJingle(
  5703. init,
  5704. self.initiator == self.me ? 'initiator' : 'responder',
  5705. ssrc);
  5706. SSRCReplacement.processSessionInit(init);
  5707. self.connection.sendIQ(init,
  5708. function () {
  5709. //logger.log('session initiate ack');
  5710. var ack = {};
  5711. ack.source = 'offer';
  5712. $(document).trigger('ack.jingle', [self.sid, ack]);
  5713. },
  5714. function (stanza) {
  5715. self.state = 'error';
  5716. self.peerconnection.close();
  5717. var error = ($(stanza).find('error').length) ? {
  5718. code: $(stanza).find('error').attr('code'),
  5719. reason: $(stanza).find('error :first')[0].tagName,
  5720. }:{};
  5721. error.source = 'offer';
  5722. JingleSessionPC.onJingleError(self.sid, error);
  5723. },
  5724. 10000);
  5725. };
  5726. sendJingle();
  5727. }
  5728. this.lasticecandidate = true;
  5729. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  5730. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  5731. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  5732. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  5733. }
  5734. }
  5735. };
  5736. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  5737. logger.log('sendIceCandidates', candidates);
  5738. var cand = $iq({to: this.peerjid, type: 'set'})
  5739. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5740. action: 'transport-info',
  5741. initiator: this.initiator,
  5742. sid: this.sid});
  5743. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  5744. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  5745. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  5746. if (cands.length > 0) {
  5747. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  5748. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5749. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  5750. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  5751. }).c('transport', ice);
  5752. for (var i = 0; i < cands.length; i++) {
  5753. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  5754. }
  5755. // add fingerprint
  5756. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  5757. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  5758. tmp.required = true;
  5759. cand.c(
  5760. 'fingerprint',
  5761. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  5762. .t(tmp.fingerprint);
  5763. delete tmp.fingerprint;
  5764. cand.attrs(tmp);
  5765. cand.up();
  5766. }
  5767. cand.up(); // transport
  5768. cand.up(); // content
  5769. }
  5770. }
  5771. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  5772. //logger.log('was this the last candidate', this.lasticecandidate);
  5773. this.connection.sendIQ(cand,
  5774. function () {
  5775. var ack = {};
  5776. ack.source = 'transportinfo';
  5777. $(document).trigger('ack.jingle', [this.sid, ack]);
  5778. },
  5779. function (stanza) {
  5780. var error = ($(stanza).find('error').length) ? {
  5781. code: $(stanza).find('error').attr('code'),
  5782. reason: $(stanza).find('error :first')[0].tagName,
  5783. }:{};
  5784. error.source = 'transportinfo';
  5785. JingleSessionPC.onJingleError(this.sid, error);
  5786. },
  5787. 10000);
  5788. };
  5789. JingleSessionPC.prototype.sendOffer = function () {
  5790. //logger.log('sendOffer...');
  5791. var self = this;
  5792. this.peerconnection.createOffer(function (sdp) {
  5793. self.createdOffer(sdp);
  5794. },
  5795. function (e) {
  5796. logger.error('createOffer failed', e);
  5797. },
  5798. this.media_constraints
  5799. );
  5800. };
  5801. // FIXME createdOffer is never used in jitsi-meet
  5802. JingleSessionPC.prototype.createdOffer = function (sdp) {
  5803. //logger.log('createdOffer', sdp);
  5804. var self = this;
  5805. this.localSDP = new SDP(sdp.sdp);
  5806. //this.localSDP.mangle();
  5807. var sendJingle = function () {
  5808. var init = $iq({to: this.peerjid,
  5809. type: 'set'})
  5810. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5811. action: 'session-initiate',
  5812. initiator: this.initiator,
  5813. sid: this.sid});
  5814. self.localSDP.toJingle(
  5815. init,
  5816. this.initiator == this.me ? 'initiator' : 'responder',
  5817. this.localStreamsSSRC);
  5818. SSRCReplacement.processSessionInit(init);
  5819. self.connection.sendIQ(init,
  5820. function () {
  5821. var ack = {};
  5822. ack.source = 'offer';
  5823. $(document).trigger('ack.jingle', [self.sid, ack]);
  5824. },
  5825. function (stanza) {
  5826. self.state = 'error';
  5827. self.peerconnection.close();
  5828. var error = ($(stanza).find('error').length) ? {
  5829. code: $(stanza).find('error').attr('code'),
  5830. reason: $(stanza).find('error :first')[0].tagName,
  5831. }:{};
  5832. error.source = 'offer';
  5833. JingleSessionPC.onJingleError(self.sid, error);
  5834. },
  5835. 10000);
  5836. }
  5837. sdp.sdp = this.localSDP.raw;
  5838. this.peerconnection.setLocalDescription(sdp,
  5839. function () {
  5840. if(self.usetrickle)
  5841. {
  5842. sendJingle();
  5843. }
  5844. self.setLocalDescription();
  5845. //logger.log('setLocalDescription success');
  5846. },
  5847. function (e) {
  5848. logger.error('setLocalDescription failed', e);
  5849. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5850. }
  5851. );
  5852. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  5853. for (var i = 0; i < cands.length; i++) {
  5854. var cand = SDPUtil.parse_icecandidate(cands[i]);
  5855. if (cand.type == 'srflx') {
  5856. this.hadstuncandidate = true;
  5857. } else if (cand.type == 'relay') {
  5858. this.hadturncandidate = true;
  5859. }
  5860. }
  5861. };
  5862. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  5863. var self = this;
  5864. $(contents).each(function (idx, content) {
  5865. var name = $(content).attr('name');
  5866. var mediaType = this.getAttribute('name');
  5867. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  5868. ssrcs.each(function () {
  5869. var ssrc = this.getAttribute('ssrc');
  5870. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  5871. function () {
  5872. var owner = this.getAttribute('owner');
  5873. self.ssrcOwners[ssrc] = owner;
  5874. }
  5875. );
  5876. });
  5877. });
  5878. };
  5879. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  5880. return this.ssrcOwners[ssrc];
  5881. };
  5882. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  5883. //logger.log('setting remote description... ', desctype);
  5884. this.remoteSDP = new SDP('');
  5885. this.remoteSDP.fromJingle(elem);
  5886. this.readSsrcInfo($(elem).find(">content"));
  5887. if (this.peerconnection.remoteDescription !== null) {
  5888. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  5889. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  5890. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  5891. for (var i = 0; i < pranswer.media.length; i++) {
  5892. // make sure we have ice ufrag and pwd
  5893. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  5894. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  5895. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  5896. } else {
  5897. logger.warn('no ice ufrag?');
  5898. }
  5899. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  5900. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  5901. } else {
  5902. logger.warn('no ice pwd?');
  5903. }
  5904. }
  5905. // copy over candidates
  5906. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  5907. for (var j = 0; j < lines.length; j++) {
  5908. this.remoteSDP.media[i] += lines[j] + '\r\n';
  5909. }
  5910. }
  5911. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  5912. }
  5913. }
  5914. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  5915. this.peerconnection.setRemoteDescription(remotedesc,
  5916. function () {
  5917. //logger.log('setRemoteDescription success');
  5918. },
  5919. function (e) {
  5920. logger.error('setRemoteDescription error', e);
  5921. JingleSessionPC.onJingleFatalError(self, e);
  5922. }
  5923. );
  5924. };
  5925. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  5926. var self = this;
  5927. if (this.peerconnection.signalingState == 'closed') {
  5928. return;
  5929. }
  5930. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  5931. logger.log('trickle ice candidate arriving before session accept...');
  5932. // create a PRANSWER for setRemoteDescription
  5933. if (!this.remoteSDP) {
  5934. var cobbled = 'v=0\r\n' +
  5935. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  5936. 's=-\r\n' +
  5937. 't=0 0\r\n';
  5938. // first, take some things from the local description
  5939. for (var i = 0; i < this.localSDP.media.length; i++) {
  5940. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  5941. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  5942. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  5943. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  5944. }
  5945. cobbled += 'a=inactive\r\n';
  5946. }
  5947. this.remoteSDP = new SDP(cobbled);
  5948. }
  5949. // then add things like ice and dtls from remote candidate
  5950. elem.each(function () {
  5951. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  5952. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  5953. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  5954. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  5955. var tmp = $(this).find('transport');
  5956. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  5957. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  5958. tmp = $(this).find('transport>fingerprint');
  5959. if (tmp.length) {
  5960. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  5961. } else {
  5962. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  5963. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  5964. }
  5965. break;
  5966. }
  5967. }
  5968. }
  5969. });
  5970. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  5971. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  5972. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  5973. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  5974. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  5975. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  5976. }).length == this.remoteSDP.media.length;
  5977. if (iscomplete) {
  5978. logger.log('setting pranswer');
  5979. try {
  5980. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  5981. function() {
  5982. },
  5983. function(e) {
  5984. logger.log('setRemoteDescription pranswer failed', e.toString());
  5985. });
  5986. } catch (e) {
  5987. logger.error('setting pranswer failed', e);
  5988. }
  5989. } else {
  5990. //logger.log('not yet setting pranswer');
  5991. }
  5992. }
  5993. // operate on each content element
  5994. elem.each(function () {
  5995. // would love to deactivate this, but firefox still requires it
  5996. var idx = -1;
  5997. var i;
  5998. for (i = 0; i < self.remoteSDP.media.length; i++) {
  5999. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6000. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6001. idx = i;
  6002. break;
  6003. }
  6004. }
  6005. if (idx == -1) { // fall back to localdescription
  6006. for (i = 0; i < self.localSDP.media.length; i++) {
  6007. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6008. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6009. idx = i;
  6010. break;
  6011. }
  6012. }
  6013. }
  6014. var name = $(this).attr('name');
  6015. // TODO: check ice-pwd and ice-ufrag?
  6016. $(this).find('transport>candidate').each(function () {
  6017. var line, candidate;
  6018. line = SDPUtil.candidateFromJingle(this);
  6019. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6020. sdpMid: name,
  6021. candidate: line});
  6022. try {
  6023. self.peerconnection.addIceCandidate(candidate);
  6024. } catch (e) {
  6025. logger.error('addIceCandidate failed', e.toString(), line);
  6026. }
  6027. });
  6028. });
  6029. };
  6030. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6031. //logger.log('createAnswer', provisional);
  6032. var self = this;
  6033. this.peerconnection.createAnswer(
  6034. function (sdp) {
  6035. self.createdAnswer(sdp, provisional);
  6036. },
  6037. function (e) {
  6038. logger.error('createAnswer failed', e);
  6039. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6040. },
  6041. this.media_constraints
  6042. );
  6043. };
  6044. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6045. //logger.log('createAnswer callback');
  6046. var self = this;
  6047. this.localSDP = new SDP(sdp.sdp);
  6048. //this.localSDP.mangle();
  6049. this.usepranswer = provisional === true;
  6050. if (this.usetrickle) {
  6051. if (this.usepranswer) {
  6052. sdp.type = 'pranswer';
  6053. for (var i = 0; i < this.localSDP.media.length; i++) {
  6054. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6055. }
  6056. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6057. }
  6058. }
  6059. var self = this;
  6060. var sendJingle = function (ssrcs) {
  6061. // FIXME why do we generate session-accept in 3 different places ?
  6062. var accept = $iq({to: self.peerjid,
  6063. type: 'set'})
  6064. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6065. action: 'session-accept',
  6066. initiator: self.initiator,
  6067. responder: self.responder,
  6068. sid: self.sid });
  6069. self.localSDP.toJingle(
  6070. accept,
  6071. self.initiator == self.me ? 'initiator' : 'responder',
  6072. ssrcs);
  6073. SSRCReplacement.processSessionInit(accept);
  6074. self.connection.sendIQ(accept,
  6075. function () {
  6076. var ack = {};
  6077. ack.source = 'answer';
  6078. $(document).trigger('ack.jingle', [self.sid, ack]);
  6079. },
  6080. function (stanza) {
  6081. var error = ($(stanza).find('error').length) ? {
  6082. code: $(stanza).find('error').attr('code'),
  6083. reason: $(stanza).find('error :first')[0].tagName,
  6084. }:{};
  6085. error.source = 'answer';
  6086. JingleSessionPC.onJingleError(self.sid, error);
  6087. },
  6088. 10000);
  6089. }
  6090. sdp.sdp = this.localSDP.raw;
  6091. this.peerconnection.setLocalDescription(sdp,
  6092. function () {
  6093. //logger.log('setLocalDescription success');
  6094. if (self.usetrickle && !self.usepranswer) {
  6095. sendJingle();
  6096. }
  6097. self.setLocalDescription();
  6098. },
  6099. function (e) {
  6100. logger.error('setLocalDescription failed', e);
  6101. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6102. }
  6103. );
  6104. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6105. for (var j = 0; j < cands.length; j++) {
  6106. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6107. if (cand.type == 'srflx') {
  6108. this.hadstuncandidate = true;
  6109. } else if (cand.type == 'relay') {
  6110. this.hadturncandidate = true;
  6111. }
  6112. }
  6113. };
  6114. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6115. var self = this,
  6116. term = $iq({to: this.peerjid,
  6117. type: 'set'})
  6118. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6119. action: 'session-terminate',
  6120. initiator: this.initiator,
  6121. sid: this.sid})
  6122. .c('reason')
  6123. .c(reason || 'success');
  6124. if (text) {
  6125. term.up().c('text').t(text);
  6126. }
  6127. this.connection.sendIQ(term,
  6128. function () {
  6129. self.peerconnection.close();
  6130. self.peerconnection = null;
  6131. self.terminate();
  6132. var ack = {};
  6133. ack.source = 'terminate';
  6134. $(document).trigger('ack.jingle', [self.sid, ack]);
  6135. },
  6136. function (stanza) {
  6137. var error = ($(stanza).find('error').length) ? {
  6138. code: $(stanza).find('error').attr('code'),
  6139. reason: $(stanza).find('error :first')[0].tagName,
  6140. }:{};
  6141. $(document).trigger('ack.jingle', [self.sid, error]);
  6142. },
  6143. 10000);
  6144. if (this.statsinterval !== null) {
  6145. window.clearInterval(this.statsinterval);
  6146. this.statsinterval = null;
  6147. }
  6148. };
  6149. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  6150. var self = this;
  6151. // FIXME: dirty waiting
  6152. if (!this.peerconnection.localDescription)
  6153. {
  6154. logger.warn("addSource - localDescription not ready yet")
  6155. setTimeout(function()
  6156. {
  6157. self.addSource(elem, fromJid);
  6158. },
  6159. 200
  6160. );
  6161. return;
  6162. }
  6163. logger.log('addssrc', new Date().getTime());
  6164. logger.log('ice', this.peerconnection.iceConnectionState);
  6165. this.readSsrcInfo(elem);
  6166. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6167. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6168. $(elem).each(function (idx, content) {
  6169. var name = $(content).attr('name');
  6170. var lines = '';
  6171. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6172. var semantics = this.getAttribute('semantics');
  6173. var ssrcs = $(this).find('>source').map(function () {
  6174. return this.getAttribute('ssrc');
  6175. }).get();
  6176. if (ssrcs.length != 0) {
  6177. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6178. }
  6179. });
  6180. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6181. tmp.each(function () {
  6182. var ssrc = $(this).attr('ssrc');
  6183. if(mySdp.containsSSRC(ssrc)){
  6184. /**
  6185. * This happens when multiple participants change their streams at the same time and
  6186. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6187. * addssrc are scheduled for update IQ. See
  6188. */
  6189. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6190. return;
  6191. }
  6192. if (sdp.containsSSRC(ssrc)) {
  6193. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6194. return;
  6195. }
  6196. $(this).find('>parameter').each(function () {
  6197. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6198. if ($(this).attr('value') && $(this).attr('value').length)
  6199. lines += ':' + $(this).attr('value');
  6200. lines += '\r\n';
  6201. });
  6202. });
  6203. sdp.media.forEach(function(media, idx) {
  6204. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6205. return;
  6206. sdp.media[idx] += lines;
  6207. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6208. self.addssrc[idx] += lines;
  6209. });
  6210. sdp.raw = sdp.session + sdp.media.join('');
  6211. });
  6212. this.modifySourcesQueue.push(function() {
  6213. // When a source is added and if this is FF, a new channel is allocated
  6214. // for receiving the added source. We need to diffuse the SSRC of this
  6215. // new recvonly channel to the rest of the peers.
  6216. logger.log('modify sources done');
  6217. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6218. logger.log("SDPs", mySdp, newSdp);
  6219. self.notifyMySSRCUpdate(mySdp, newSdp);
  6220. });
  6221. };
  6222. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  6223. var self = this;
  6224. // FIXME: dirty waiting
  6225. if (!this.peerconnection.localDescription)
  6226. {
  6227. logger.warn("removeSource - localDescription not ready yet")
  6228. setTimeout(function()
  6229. {
  6230. self.removeSource(elem, fromJid);
  6231. },
  6232. 200
  6233. );
  6234. return;
  6235. }
  6236. logger.log('removessrc', new Date().getTime());
  6237. logger.log('ice', this.peerconnection.iceConnectionState);
  6238. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6239. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6240. $(elem).each(function (idx, content) {
  6241. var name = $(content).attr('name');
  6242. var lines = '';
  6243. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6244. var semantics = this.getAttribute('semantics');
  6245. var ssrcs = $(this).find('>source').map(function () {
  6246. return this.getAttribute('ssrc');
  6247. }).get();
  6248. if (ssrcs.length != 0) {
  6249. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6250. }
  6251. });
  6252. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6253. tmp.each(function () {
  6254. var ssrc = $(this).attr('ssrc');
  6255. // This should never happen, but can be useful for bug detection
  6256. if(mySdp.containsSSRC(ssrc)){
  6257. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6258. return;
  6259. }
  6260. $(this).find('>parameter').each(function () {
  6261. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6262. if ($(this).attr('value') && $(this).attr('value').length)
  6263. lines += ':' + $(this).attr('value');
  6264. lines += '\r\n';
  6265. });
  6266. });
  6267. sdp.media.forEach(function(media, idx) {
  6268. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6269. return;
  6270. sdp.media[idx] += lines;
  6271. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6272. self.removessrc[idx] += lines;
  6273. });
  6274. sdp.raw = sdp.session + sdp.media.join('');
  6275. });
  6276. this.modifySourcesQueue.push(function() {
  6277. // When a source is removed and if this is FF, the recvonly channel that
  6278. // receives the remote stream is deactivated . We need to diffuse the
  6279. // recvonly SSRC removal to the rest of the peers.
  6280. logger.log('modify sources done');
  6281. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6282. logger.log("SDPs", mySdp, newSdp);
  6283. self.notifyMySSRCUpdate(mySdp, newSdp);
  6284. });
  6285. };
  6286. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6287. var self = this;
  6288. if (this.peerconnection.signalingState == 'closed') return;
  6289. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6290. || this.switchstreams || this.addingStreams)){
  6291. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6292. this.setLocalDescription();
  6293. if(successCallback){
  6294. successCallback();
  6295. }
  6296. queueCallback();
  6297. return;
  6298. }
  6299. // Reset switch streams flags
  6300. this.switchstreams = false;
  6301. this.addingStreams = false;
  6302. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6303. // add sources
  6304. this.addssrc.forEach(function(lines, idx) {
  6305. sdp.media[idx] += lines;
  6306. });
  6307. this.addssrc = [];
  6308. // remove sources
  6309. this.removessrc.forEach(function(lines, idx) {
  6310. lines = lines.split('\r\n');
  6311. lines.pop(); // remove empty last element;
  6312. lines.forEach(function(line) {
  6313. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6314. });
  6315. });
  6316. this.removessrc = [];
  6317. sdp.raw = sdp.session + sdp.media.join('');
  6318. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6319. function() {
  6320. if(self.signalingState == 'closed') {
  6321. logger.error("createAnswer attempt on closed state");
  6322. queueCallback("createAnswer attempt on closed state");
  6323. return;
  6324. }
  6325. self.peerconnection.createAnswer(
  6326. function(modifiedAnswer) {
  6327. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6328. if (self.pendingop !== null) {
  6329. var sdp = new SDP(modifiedAnswer.sdp);
  6330. if (sdp.media.length > 1) {
  6331. switch(self.pendingop) {
  6332. case 'mute':
  6333. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6334. break;
  6335. case 'unmute':
  6336. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6337. break;
  6338. }
  6339. sdp.raw = sdp.session + sdp.media.join('');
  6340. modifiedAnswer.sdp = sdp.raw;
  6341. }
  6342. self.pendingop = null;
  6343. }
  6344. // FIXME: pushing down an answer while ice connection state
  6345. // is still checking is bad...
  6346. //logger.log(self.peerconnection.iceConnectionState);
  6347. // trying to work around another chrome bug
  6348. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6349. self.peerconnection.setLocalDescription(modifiedAnswer,
  6350. function() {
  6351. //logger.log('modified setLocalDescription ok');
  6352. self.setLocalDescription();
  6353. if(successCallback){
  6354. successCallback();
  6355. }
  6356. queueCallback();
  6357. },
  6358. function(error) {
  6359. logger.error('modified setLocalDescription failed', error);
  6360. queueCallback(error);
  6361. }
  6362. );
  6363. },
  6364. function(error) {
  6365. logger.error('modified answer failed', error);
  6366. queueCallback(error);
  6367. }
  6368. );
  6369. },
  6370. function(error) {
  6371. logger.error('modify failed', error);
  6372. queueCallback(error);
  6373. }
  6374. );
  6375. };
  6376. /**
  6377. * Switches video streams.
  6378. * @param new_stream new stream that will be used as video of this session.
  6379. * @param oldStream old video stream of this session.
  6380. * @param success_callback callback executed after successful stream switch.
  6381. */
  6382. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  6383. var self = this;
  6384. // Remember SDP to figure out added/removed SSRCs
  6385. var oldSdp = null;
  6386. if(self.peerconnection) {
  6387. if(self.peerconnection.localDescription) {
  6388. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6389. }
  6390. self.peerconnection.removeStream(oldStream, true);
  6391. if(new_stream)
  6392. self.peerconnection.addStream(new_stream);
  6393. }
  6394. // Conference is not active
  6395. if(!oldSdp || !self.peerconnection) {
  6396. success_callback();
  6397. return;
  6398. }
  6399. self.switchstreams = true;
  6400. self.modifySourcesQueue.push(function() {
  6401. logger.log('modify sources done');
  6402. success_callback();
  6403. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6404. logger.log("SDPs", oldSdp, newSdp);
  6405. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6406. });
  6407. };
  6408. /**
  6409. * Adds streams.
  6410. * @param stream new stream that will be added.
  6411. * @param success_callback callback executed after successful stream addition.
  6412. */
  6413. JingleSessionPC.prototype.addStream = function (stream, callback) {
  6414. var self = this;
  6415. // Remember SDP to figure out added/removed SSRCs
  6416. var oldSdp = null;
  6417. if(this.peerconnection) {
  6418. if(this.peerconnection.localDescription) {
  6419. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  6420. }
  6421. if(stream)
  6422. this.peerconnection.addStream(stream);
  6423. }
  6424. // Conference is not active
  6425. if(!oldSdp || !this.peerconnection) {
  6426. callback();
  6427. return;
  6428. }
  6429. this.addingStreams = true;
  6430. this.modifySourcesQueue.push(function() {
  6431. logger.log('modify sources done');
  6432. callback();
  6433. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6434. logger.log("SDPs", oldSdp, newSdp);
  6435. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6436. });
  6437. }
  6438. /**
  6439. * Figures out added/removed ssrcs and send update IQs.
  6440. * @param old_sdp SDP object for old description.
  6441. * @param new_sdp SDP object for new description.
  6442. */
  6443. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  6444. if (!(this.peerconnection.signalingState == 'stable' &&
  6445. this.peerconnection.iceConnectionState == 'connected')){
  6446. logger.log("Too early to send updates");
  6447. return;
  6448. }
  6449. // send source-remove IQ.
  6450. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  6451. var remove = $iq({to: this.peerjid, type: 'set'})
  6452. .c('jingle', {
  6453. xmlns: 'urn:xmpp:jingle:1',
  6454. action: 'source-remove',
  6455. initiator: this.initiator,
  6456. sid: this.sid
  6457. }
  6458. );
  6459. var removed = sdpDiffer.toJingle(remove);
  6460. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  6461. // it in the current form
  6462. if (removed)
  6463. remove = SSRCReplacement.processSourceRemove(remove);
  6464. if (removed && remove) {
  6465. logger.info("Sending source-remove", remove);
  6466. this.connection.sendIQ(remove,
  6467. function (res) {
  6468. logger.info('got remove result', res);
  6469. },
  6470. function (err) {
  6471. logger.error('got remove error', err);
  6472. }
  6473. );
  6474. } else {
  6475. logger.log('removal not necessary');
  6476. }
  6477. // send source-add IQ.
  6478. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  6479. var add = $iq({to: this.peerjid, type: 'set'})
  6480. .c('jingle', {
  6481. xmlns: 'urn:xmpp:jingle:1',
  6482. action: 'source-add',
  6483. initiator: this.initiator,
  6484. sid: this.sid
  6485. }
  6486. );
  6487. var added = sdpDiffer.toJingle(add);
  6488. // Let 'source-add' IQ through the hack and see if we're allowed to send
  6489. // it in the current form
  6490. if (added)
  6491. add = SSRCReplacement.processSourceAdd(add);
  6492. if (added && add) {
  6493. logger.info("Sending source-add", add);
  6494. this.connection.sendIQ(add,
  6495. function (res) {
  6496. logger.info('got add result', res);
  6497. },
  6498. function (err) {
  6499. logger.error('got add error', err);
  6500. }
  6501. );
  6502. } else {
  6503. logger.log('addition not necessary');
  6504. }
  6505. };
  6506. /**
  6507. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  6508. *
  6509. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  6510. * tracks; otherwise, <tt>false</tt>
  6511. * @param callback a function to be invoked with <tt>mute</tt> after all video
  6512. * tracks have been enabled/disabled. The function may, optionally, return
  6513. * another function which is to be invoked after the whole mute/unmute operation
  6514. * has completed successfully.
  6515. * @param options an object which specifies optional arguments such as the
  6516. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  6517. * specifies whether the method was initiated in response to a user command (in
  6518. * contrast to an automatic decision made by the application logic)
  6519. */
  6520. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  6521. var byUser;
  6522. if (options) {
  6523. byUser = options.byUser;
  6524. if (typeof byUser === 'undefined') {
  6525. byUser = true;
  6526. }
  6527. } else {
  6528. byUser = true;
  6529. }
  6530. // The user's command to mute the (local) video takes precedence over any
  6531. // automatic decision made by the application logic.
  6532. if (byUser) {
  6533. this.videoMuteByUser = mute;
  6534. } else if (this.videoMuteByUser) {
  6535. return;
  6536. }
  6537. this.hardMuteVideo(mute);
  6538. var self = this;
  6539. var oldSdp = null;
  6540. if(self.peerconnection) {
  6541. if(self.peerconnection.localDescription) {
  6542. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6543. }
  6544. }
  6545. this.modifySourcesQueue.push(function() {
  6546. logger.log('modify sources done');
  6547. callback(mute);
  6548. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6549. logger.log("SDPs", oldSdp, newSdp);
  6550. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6551. });
  6552. };
  6553. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  6554. this.pendingop = muted ? 'mute' : 'unmute';
  6555. };
  6556. JingleSessionPC.prototype.sendMute = function (muted, content) {
  6557. var info = $iq({to: this.peerjid,
  6558. type: 'set'})
  6559. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6560. action: 'session-info',
  6561. initiator: this.initiator,
  6562. sid: this.sid });
  6563. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6564. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  6565. if (content) {
  6566. info.attrs({'name': content});
  6567. }
  6568. this.connection.send(info);
  6569. };
  6570. JingleSessionPC.prototype.sendRinging = function () {
  6571. var info = $iq({to: this.peerjid,
  6572. type: 'set'})
  6573. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6574. action: 'session-info',
  6575. initiator: this.initiator,
  6576. sid: this.sid });
  6577. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6578. this.connection.send(info);
  6579. };
  6580. JingleSessionPC.prototype.getStats = function (interval) {
  6581. var self = this;
  6582. var recv = {audio: 0, video: 0};
  6583. var lost = {audio: 0, video: 0};
  6584. var lastrecv = {audio: 0, video: 0};
  6585. var lastlost = {audio: 0, video: 0};
  6586. var loss = {audio: 0, video: 0};
  6587. var delta = {audio: 0, video: 0};
  6588. this.statsinterval = window.setInterval(function () {
  6589. if (self && self.peerconnection && self.peerconnection.getStats) {
  6590. self.peerconnection.getStats(function (stats) {
  6591. var results = stats.result();
  6592. // TODO: there are so much statistics you can get from this..
  6593. for (var i = 0; i < results.length; ++i) {
  6594. if (results[i].type == 'ssrc') {
  6595. var packetsrecv = results[i].stat('packetsReceived');
  6596. var packetslost = results[i].stat('packetsLost');
  6597. if (packetsrecv && packetslost) {
  6598. packetsrecv = parseInt(packetsrecv, 10);
  6599. packetslost = parseInt(packetslost, 10);
  6600. if (results[i].stat('googFrameRateReceived')) {
  6601. lastlost.video = lost.video;
  6602. lastrecv.video = recv.video;
  6603. recv.video = packetsrecv;
  6604. lost.video = packetslost;
  6605. } else {
  6606. lastlost.audio = lost.audio;
  6607. lastrecv.audio = recv.audio;
  6608. recv.audio = packetsrecv;
  6609. lost.audio = packetslost;
  6610. }
  6611. }
  6612. }
  6613. }
  6614. delta.audio = recv.audio - lastrecv.audio;
  6615. delta.video = recv.video - lastrecv.video;
  6616. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  6617. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  6618. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  6619. });
  6620. }
  6621. }, interval || 3000);
  6622. return this.statsinterval;
  6623. };
  6624. JingleSessionPC.onJingleError = function (session, error)
  6625. {
  6626. logger.error("Jingle error", error);
  6627. }
  6628. JingleSessionPC.onJingleFatalError = function (session, error)
  6629. {
  6630. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6631. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  6632. }
  6633. JingleSessionPC.prototype.setLocalDescription = function () {
  6634. var self = this;
  6635. var newssrcs = [];
  6636. var session = transform.parse(this.peerconnection.localDescription.sdp);
  6637. session.media.forEach(function (media) {
  6638. if (media.ssrcs != null && media.ssrcs.length > 0) {
  6639. // TODO(gp) maybe exclude FID streams?
  6640. media.ssrcs.forEach(function (ssrc) {
  6641. if (ssrc.attribute !== 'cname') {
  6642. return;
  6643. }
  6644. newssrcs.push({
  6645. 'ssrc': ssrc.id,
  6646. 'type': media.type
  6647. });
  6648. });
  6649. }
  6650. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  6651. {
  6652. newssrcs.push({
  6653. 'ssrc': self.localStreamsSSRC[media.type],
  6654. 'type': media.type
  6655. });
  6656. }
  6657. });
  6658. logger.log('new ssrcs', newssrcs);
  6659. // Bind us as local SSRCs owner
  6660. if (newssrcs.length > 0) {
  6661. for (var i = 1; i <= newssrcs.length; i ++) {
  6662. var ssrc = newssrcs[i-1].ssrc;
  6663. var myJid = self.connection.emuc.myroomjid;
  6664. self.ssrcOwners[ssrc] = myJid;
  6665. }
  6666. }
  6667. }
  6668. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  6669. JingleSessionPC.prototype.sendKeyframe = function () {
  6670. var pc = this.peerconnection;
  6671. logger.log('sendkeyframe', pc.iceConnectionState);
  6672. if (pc.iceConnectionState !== 'connected') return; // safe...
  6673. var self = this;
  6674. pc.setRemoteDescription(
  6675. pc.remoteDescription,
  6676. function () {
  6677. pc.createAnswer(
  6678. function (modifiedAnswer) {
  6679. pc.setLocalDescription(
  6680. modifiedAnswer,
  6681. function () {
  6682. // noop
  6683. },
  6684. function (error) {
  6685. logger.log('triggerKeyframe setLocalDescription failed', error);
  6686. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  6687. }
  6688. );
  6689. },
  6690. function (error) {
  6691. logger.log('triggerKeyframe createAnswer failed', error);
  6692. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  6693. }
  6694. );
  6695. },
  6696. function (error) {
  6697. logger.log('triggerKeyframe setRemoteDescription failed', error);
  6698. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  6699. }
  6700. );
  6701. }
  6702. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  6703. var self = this;
  6704. var thessrc;
  6705. var streamId = RTC.getStreamID(data.stream);
  6706. // look up an associated JID for a stream id
  6707. if (!streamId) {
  6708. logger.error("No stream ID for", data.stream);
  6709. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  6710. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  6711. var ssrclines
  6712. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  6713. ssrclines = ssrclines.filter(function (line) {
  6714. // NOTE(gp) previously we filtered on the mslabel, but that property
  6715. // is not always present.
  6716. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  6717. if (RTCBrowserType.isTemasysPluginUsed()) {
  6718. return ((line.indexOf('mslabel:' + streamId) !== -1));
  6719. } else {
  6720. return ((line.indexOf('msid:' + streamId) !== -1));
  6721. }
  6722. });
  6723. if (ssrclines.length) {
  6724. thessrc = ssrclines[0].substring(7).split(' ')[0];
  6725. if (!self.ssrcOwners[thessrc]) {
  6726. logger.error("No SSRC owner known for: " + thessrc);
  6727. return;
  6728. }
  6729. data.peerjid = self.ssrcOwners[thessrc];
  6730. logger.log('associated jid', self.ssrcOwners[thessrc]);
  6731. } else {
  6732. logger.error("No SSRC lines for ", streamId);
  6733. }
  6734. }
  6735. this.room.remoteStreamAdded(data, this.sid, thessrc);
  6736. var isVideo = data.stream.getVideoTracks().length > 0;
  6737. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  6738. if (isVideo &&
  6739. data.peerjid && this.peerjid === data.peerjid &&
  6740. data.stream.getVideoTracks().length === 0 &&
  6741. RTC.localVideo.getTracks().length > 0) {
  6742. window.setTimeout(function () {
  6743. self.sendKeyframe();
  6744. }, 3000);
  6745. }
  6746. }
  6747. module.exports = JingleSessionPC;
  6748. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  6749. },{"../../service/xmpp/XMPPEvents":82,"../RTC/RTC":13,"../RTC/RTCBrowserType":14,"./JingleSession":24,"./LocalSSRCReplacement":26,"./SDP":27,"./SDPDiffer":28,"./SDPUtil":29,"./TraceablePeerConnection":30,"async":39,"jitsi-meet-logger":44,"sdp-transform":72}],26:[function(require,module,exports){
  6750. (function (__filename){
  6751. /* global $ */
  6752. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6753. /*
  6754. Here we do modifications of local video SSRCs. There are 2 situations we have
  6755. to handle:
  6756. 1. We generate SSRC for local recvonly video stream. This is the case when we
  6757. have no local camera and it is not generated automatically, but SSRC=1 is
  6758. used implicitly. If that happens RTCP packets will be dropped by the JVB
  6759. and we won't be able to request video key frames correctly.
  6760. 2. A hack to re-use SSRC of the first video stream for any new stream created
  6761. in future. It turned out that Chrome may keep on using the SSRC of removed
  6762. video stream in RTCP even though a new one has been created. So we just
  6763. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  6764. notifications are blocked once first video SSRC is advertised to the focus.
  6765. What this hack does:
  6766. 1. Stores the SSRC of the first video stream created by
  6767. a) scanning Jingle session-accept/session-invite for existing video SSRC
  6768. b) watching for 'source-add' for new video stream if it has not been
  6769. created in step a)
  6770. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  6771. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  6772. returned to the other parts of the application.
  6773. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  6774. blocks those notifications. This makes Jicofo and all participants think
  6775. that it exists all the time even if the video stream has been removed or
  6776. replaced locally. Thanks to that there is no additional signaling activity
  6777. on video mute or when switching to the desktop stream.
  6778. */
  6779. var SDP = require('./SDP');
  6780. var RandomUtil = require('../util/RandomUtil');
  6781. var RTCBrowserType = require('../RTC/RTCBrowserType');
  6782. /**
  6783. * The hack is enabled on all browsers except FF by default
  6784. * FIXME finish the hack once removeStream method is implemented in FF
  6785. * @type {boolean}
  6786. */
  6787. var isEnabled = !RTCBrowserType.isFirefox();
  6788. /**
  6789. * Stored SSRC of local video stream.
  6790. */
  6791. var localVideoSSRC;
  6792. /**
  6793. * SSRC, msid, mslabel, label used for recvonly video stream when we have no local camera.
  6794. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  6795. * instead of 1.
  6796. */
  6797. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  6798. /**
  6799. * cname for <tt>localRecvOnlySSRC</tt>
  6800. */
  6801. var localRecvOnlyCName;
  6802. /**
  6803. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  6804. * from given Jingle IQ.
  6805. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  6806. * @param actionName display name of the action which will be printed in log
  6807. * messages.
  6808. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  6809. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  6810. * other SSRCs left to be signaled after removing it.
  6811. */
  6812. var filterOutSource = function (modifyIq, actionName) {
  6813. var modifyIqTree = $(modifyIq.tree());
  6814. if (!localVideoSSRC)
  6815. return modifyIqTree[0];
  6816. var videoSSRC = modifyIqTree.find(
  6817. '>jingle>content[name="video"]' +
  6818. '>description>source[ssrc="' + localVideoSSRC + '"]');
  6819. if (!videoSSRC.length) {
  6820. return modifyIqTree[0];
  6821. }
  6822. logger.info(
  6823. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  6824. videoSSRC.remove();
  6825. // Check if any sources still left to be added/removed
  6826. if (modifyIqTree.find('>jingle>content>description>source').length) {
  6827. return modifyIqTree[0];
  6828. } else {
  6829. return null;
  6830. }
  6831. };
  6832. /**
  6833. * Scans given Jingle IQ for video SSRC and stores it.
  6834. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  6835. */
  6836. var storeLocalVideoSSRC = function (jingleIq) {
  6837. var videoSSRCs =
  6838. $(jingleIq.tree())
  6839. .find('>jingle>content[name="video"]>description>source');
  6840. videoSSRCs.each(function (idx, ssrcElem) {
  6841. if (localVideoSSRC)
  6842. return;
  6843. // We consider SSRC real only if it has msid attribute
  6844. // recvonly streams in FF do not have it as well as local SSRCs
  6845. // we generate for recvonly streams in Chrome
  6846. var ssrSel = $(ssrcElem);
  6847. var msid = ssrSel.find('>parameter[name="msid"]');
  6848. if (msid.length) {
  6849. var ssrcVal = ssrSel.attr('ssrc');
  6850. if (ssrcVal) {
  6851. localVideoSSRC = ssrcVal;
  6852. logger.info('Stored local video SSRC' +
  6853. ' for future re-use: ' + localVideoSSRC);
  6854. }
  6855. }
  6856. });
  6857. };
  6858. /**
  6859. * Generates new label/mslabel attribute
  6860. * @returns {string} label/mslabel attribute
  6861. */
  6862. function generateLabel() {
  6863. return RandomUtil.random8digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" +
  6864. RandomUtil.random4digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" + RandomUtil.random12digitsHex();
  6865. }
  6866. /**
  6867. * Generates new SSRC, CNAME, mslabel, label and msid for local video recvonly stream.
  6868. * FIXME what about eventual SSRC collision ?
  6869. */
  6870. function generateRecvonlySSRC() {
  6871. localRecvOnlySSRC =
  6872. Math.random().toString(10).substring(2, 11);
  6873. localRecvOnlyCName =
  6874. Math.random().toString(36).substring(2);
  6875. localRecvOnlyMSLabel = generateLabel();
  6876. localRecvOnlyLabel = generateLabel();
  6877. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  6878. logger.info(
  6879. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  6880. ", cname: " + localRecvOnlyCName);
  6881. }
  6882. var LocalSSRCReplacement = {
  6883. /**
  6884. * Method must be called before 'session-initiate' or 'session-invite' is
  6885. * sent. Scans the IQ for local video SSRC and stores it if detected.
  6886. *
  6887. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  6888. * which will be scanned for local video SSRC.
  6889. */
  6890. processSessionInit: function (sessionInit) {
  6891. if (!isEnabled)
  6892. return;
  6893. if (localVideoSSRC) {
  6894. logger.error("Local SSRC stored already: " + localVideoSSRC);
  6895. return;
  6896. }
  6897. storeLocalVideoSSRC(sessionInit);
  6898. },
  6899. /**
  6900. * If we have local video SSRC stored searched given
  6901. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  6902. * with the stored one.
  6903. * @param localDescription local description object that will have local
  6904. * video SSRC replaced with the stored one
  6905. * @returns modified <tt>localDescription</tt> object.
  6906. */
  6907. mungeLocalVideoSSRC: function (localDescription) {
  6908. if (!isEnabled)
  6909. return localDescription;
  6910. if (!localDescription) {
  6911. logger.warn("localDescription is null or undefined");
  6912. return localDescription;
  6913. }
  6914. // IF we have local video SSRC stored make sure it is replaced
  6915. // with old SSRC
  6916. if (localVideoSSRC) {
  6917. var newSdp = new SDP(localDescription.sdp);
  6918. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  6919. !newSdp.containsSSRC(localVideoSSRC)) {
  6920. // Get new video SSRC
  6921. var map = newSdp.getMediaSsrcMap();
  6922. var videoPart = map[1];
  6923. var videoSSRCs = videoPart.ssrcs;
  6924. var newSSRC = Object.keys(videoSSRCs)[0];
  6925. logger.info(
  6926. "Replacing new video SSRC: " + newSSRC +
  6927. " with " + localVideoSSRC);
  6928. localDescription.sdp =
  6929. newSdp.raw.replace(
  6930. new RegExp('a=ssrc:' + newSSRC, 'g'),
  6931. 'a=ssrc:' + localVideoSSRC);
  6932. }
  6933. } else {
  6934. // Make sure we have any SSRC for recvonly video stream
  6935. var sdp = new SDP(localDescription.sdp);
  6936. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  6937. sdp.media[1].indexOf('a=recvonly') !== -1) {
  6938. if (!localRecvOnlySSRC) {
  6939. generateRecvonlySSRC();
  6940. }
  6941. localVideoSSRC = localRecvOnlySSRC;
  6942. logger.info('No SSRC in video recvonly stream' +
  6943. ' - adding SSRC: ' + localRecvOnlySSRC);
  6944. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  6945. ' cname:' + localRecvOnlyCName + '\r\n' +
  6946. 'a=ssrc:' + localRecvOnlySSRC +
  6947. ' msid:' + localRecvOnlyMSID + '\r\n' +
  6948. 'a=ssrc:' + localRecvOnlySSRC +
  6949. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  6950. 'a=ssrc:' + localRecvOnlySSRC +
  6951. ' label:' + localRecvOnlyLabel + '\r\n';
  6952. localDescription.sdp = sdp.session + sdp.media.join('');
  6953. }
  6954. }
  6955. return localDescription;
  6956. },
  6957. /**
  6958. * Method must be called before 'source-add' notification is sent. In case
  6959. * we have local video SSRC advertised already it will be removed from the
  6960. * notification. If no other SSRCs are described by given IQ null will be
  6961. * returned which means that there is no point in sending the notification.
  6962. * @param sourceAdd 'source-add' Jingle IQ to be processed
  6963. * @returns modified 'source-add' IQ which can be sent to the focus or
  6964. * <tt>null</tt> if no notification shall be sent. It is no longer
  6965. * a Strophe IQ Builder instance, but DOM element tree.
  6966. */
  6967. processSourceAdd: function (sourceAdd) {
  6968. if (!isEnabled)
  6969. return sourceAdd;
  6970. if (!localVideoSSRC) {
  6971. // Store local SSRC if available
  6972. storeLocalVideoSSRC(sourceAdd);
  6973. return sourceAdd;
  6974. } else {
  6975. return filterOutSource(sourceAdd, 'source-add');
  6976. }
  6977. },
  6978. /**
  6979. * Method must be called before 'source-remove' notification is sent.
  6980. * Removes local video SSRC from the notification. If there are no other
  6981. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  6982. * means that there is no point in sending the notification.
  6983. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  6984. * @returns modified 'source-remove' IQ which can be sent to the focus or
  6985. * <tt>null</tt> if no notification shall be sent. It is no longer
  6986. * a Strophe IQ Builder instance, but DOM element tree.
  6987. */
  6988. processSourceRemove: function (sourceRemove) {
  6989. if (!isEnabled)
  6990. return sourceRemove;
  6991. return filterOutSource(sourceRemove, 'source-remove');
  6992. },
  6993. /**
  6994. * Turns the hack on or off
  6995. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  6996. * to disable it
  6997. */
  6998. setEnabled: function (enabled) {
  6999. isEnabled = enabled;
  7000. }
  7001. };
  7002. module.exports = LocalSSRCReplacement;
  7003. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7004. },{"../RTC/RTCBrowserType":14,"../util/RandomUtil":22,"./SDP":27,"jitsi-meet-logger":44}],27:[function(require,module,exports){
  7005. (function (__filename){
  7006. /* jshint -W117 */
  7007. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7008. var SDPUtil = require("./SDPUtil");
  7009. // SDP STUFF
  7010. function SDP(sdp) {
  7011. this.media = sdp.split('\r\nm=');
  7012. for (var i = 1; i < this.media.length; i++) {
  7013. this.media[i] = 'm=' + this.media[i];
  7014. if (i != this.media.length - 1) {
  7015. this.media[i] += '\r\n';
  7016. }
  7017. }
  7018. this.session = this.media.shift() + '\r\n';
  7019. this.raw = this.session + this.media.join('');
  7020. }
  7021. /**
  7022. * Returns map of MediaChannel mapped per channel idx.
  7023. */
  7024. SDP.prototype.getMediaSsrcMap = function() {
  7025. var self = this;
  7026. var media_ssrcs = {};
  7027. var tmp;
  7028. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7029. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7030. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7031. var media = {
  7032. mediaindex: mediaindex,
  7033. mid: mid,
  7034. ssrcs: {},
  7035. ssrcGroups: []
  7036. };
  7037. media_ssrcs[mediaindex] = media;
  7038. tmp.forEach(function (line) {
  7039. var linessrc = line.substring(7).split(' ')[0];
  7040. // allocate new ChannelSsrc
  7041. if(!media.ssrcs[linessrc]) {
  7042. media.ssrcs[linessrc] = {
  7043. ssrc: linessrc,
  7044. lines: []
  7045. };
  7046. }
  7047. media.ssrcs[linessrc].lines.push(line);
  7048. });
  7049. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7050. tmp.forEach(function(line){
  7051. var semantics = line.substr(0, idx).substr(13);
  7052. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7053. if (ssrcs.length != 0) {
  7054. media.ssrcGroups.push({
  7055. semantics: semantics,
  7056. ssrcs: ssrcs
  7057. });
  7058. }
  7059. });
  7060. }
  7061. return media_ssrcs;
  7062. };
  7063. /**
  7064. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7065. * @param ssrc the ssrc to check.
  7066. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7067. */
  7068. SDP.prototype.containsSSRC = function(ssrc) {
  7069. var medias = this.getMediaSsrcMap();
  7070. var contains = false;
  7071. Object.keys(medias).forEach(function(mediaindex){
  7072. var media = medias[mediaindex];
  7073. //logger.log("Check", channel, ssrc);
  7074. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  7075. contains = true;
  7076. }
  7077. });
  7078. return contains;
  7079. };
  7080. // remove iSAC and CN from SDP
  7081. SDP.prototype.mangle = function () {
  7082. var i, j, mline, lines, rtpmap, newdesc;
  7083. for (i = 0; i < this.media.length; i++) {
  7084. lines = this.media[i].split('\r\n');
  7085. lines.pop(); // remove empty last element
  7086. mline = SDPUtil.parse_mline(lines.shift());
  7087. if (mline.media != 'audio')
  7088. continue;
  7089. newdesc = '';
  7090. mline.fmt.length = 0;
  7091. for (j = 0; j < lines.length; j++) {
  7092. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7093. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7094. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7095. continue;
  7096. mline.fmt.push(rtpmap.id);
  7097. newdesc += lines[j] + '\r\n';
  7098. } else {
  7099. newdesc += lines[j] + '\r\n';
  7100. }
  7101. }
  7102. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7103. this.media[i] += newdesc;
  7104. }
  7105. this.raw = this.session + this.media.join('');
  7106. };
  7107. // remove lines matching prefix from session section
  7108. SDP.prototype.removeSessionLines = function(prefix) {
  7109. var self = this;
  7110. var lines = SDPUtil.find_lines(this.session, prefix);
  7111. lines.forEach(function(line) {
  7112. self.session = self.session.replace(line + '\r\n', '');
  7113. });
  7114. this.raw = this.session + this.media.join('');
  7115. return lines;
  7116. }
  7117. // remove lines matching prefix from a media section specified by mediaindex
  7118. // TODO: non-numeric mediaindex could match mid
  7119. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7120. var self = this;
  7121. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7122. lines.forEach(function(line) {
  7123. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7124. });
  7125. this.raw = this.session + this.media.join('');
  7126. return lines;
  7127. }
  7128. // add content's to a jingle element
  7129. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  7130. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7131. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  7132. var self = this;
  7133. // new bundle plan
  7134. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7135. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7136. for (i = 0; i < lines.length; i++) {
  7137. tmp = lines[i].split(' ');
  7138. var semantics = tmp.shift().substr(8);
  7139. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7140. for (j = 0; j < tmp.length; j++) {
  7141. elem.c('content', {name: tmp[j]}).up();
  7142. }
  7143. elem.up();
  7144. }
  7145. }
  7146. for (i = 0; i < this.media.length; i++) {
  7147. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7148. if (!(mline.media === 'audio' ||
  7149. mline.media === 'video' ||
  7150. mline.media === 'application'))
  7151. {
  7152. continue;
  7153. }
  7154. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7155. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7156. } else {
  7157. if(ssrcs && ssrcs[mline.media])
  7158. {
  7159. ssrc = ssrcs[mline.media];
  7160. }
  7161. else
  7162. ssrc = false;
  7163. }
  7164. elem.c('content', {creator: thecreator, name: mline.media});
  7165. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7166. // prefer identifier from a=mid if present
  7167. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7168. elem.attrs({ name: mid });
  7169. }
  7170. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  7171. {
  7172. elem.c('description',
  7173. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7174. media: mline.media });
  7175. if (ssrc) {
  7176. elem.attrs({ssrc: ssrc});
  7177. }
  7178. for (j = 0; j < mline.fmt.length; j++) {
  7179. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7180. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7181. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7182. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7183. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7184. for (k = 0; k < tmp.length; k++) {
  7185. elem.c('parameter', tmp[k]).up();
  7186. }
  7187. }
  7188. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7189. elem.up();
  7190. }
  7191. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7192. elem.c('encryption', {required: 1});
  7193. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7194. crypto.forEach(function(line) {
  7195. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7196. });
  7197. elem.up(); // end of encryption
  7198. }
  7199. if (ssrc) {
  7200. // new style mapping
  7201. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7202. // FIXME: group by ssrc and support multiple different ssrcs
  7203. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7204. if(ssrclines.length > 0) {
  7205. ssrclines.forEach(function (line) {
  7206. idx = line.indexOf(' ');
  7207. var linessrc = line.substr(0, idx).substr(7);
  7208. if (linessrc != ssrc) {
  7209. elem.up();
  7210. ssrc = linessrc;
  7211. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7212. }
  7213. var kv = line.substr(idx + 1);
  7214. elem.c('parameter');
  7215. if (kv.indexOf(':') == -1) {
  7216. elem.attrs({ name: kv });
  7217. } else {
  7218. var k = kv.split(':', 2)[0];
  7219. elem.attrs({ name: k });
  7220. var v = kv.split(':', 2)[1];
  7221. v = SDPUtil.filter_special_chars(v);
  7222. elem.attrs({ value: v });
  7223. }
  7224. elem.up();
  7225. });
  7226. }
  7227. else
  7228. {
  7229. elem.up();
  7230. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7231. elem.c('parameter');
  7232. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7233. elem.up();
  7234. var msid = null;
  7235. if(mline.media == "audio")
  7236. {
  7237. msid = APP.RTC.localAudio.getId();
  7238. }
  7239. else
  7240. {
  7241. msid = APP.RTC.localVideo.getId();
  7242. }
  7243. if(msid != null)
  7244. {
  7245. msid = SDPUtil.filter_special_chars(msid);
  7246. elem.c('parameter');
  7247. elem.attrs({name: "msid", value:msid});
  7248. elem.up();
  7249. elem.c('parameter');
  7250. elem.attrs({name: "mslabel", value:msid});
  7251. elem.up();
  7252. elem.c('parameter');
  7253. elem.attrs({name: "label", value:msid});
  7254. elem.up();
  7255. }
  7256. }
  7257. elem.up();
  7258. // XEP-0339 handle ssrc-group attributes
  7259. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7260. ssrc_group_lines.forEach(function(line) {
  7261. idx = line.indexOf(' ');
  7262. var semantics = line.substr(0, idx).substr(13);
  7263. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7264. if (ssrcs.length != 0) {
  7265. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7266. ssrcs.forEach(function(ssrc) {
  7267. elem.c('source', { ssrc: ssrc })
  7268. .up();
  7269. });
  7270. elem.up();
  7271. }
  7272. });
  7273. }
  7274. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7275. elem.c('rtcp-mux').up();
  7276. }
  7277. // XEP-0293 -- map a=rtcp-fb:*
  7278. this.RtcpFbToJingle(i, elem, '*');
  7279. // XEP-0294
  7280. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7281. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7282. for (j = 0; j < lines.length; j++) {
  7283. tmp = SDPUtil.parse_extmap(lines[j]);
  7284. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7285. uri: tmp.uri,
  7286. id: tmp.value });
  7287. if (tmp.hasOwnProperty('direction')) {
  7288. switch (tmp.direction) {
  7289. case 'sendonly':
  7290. elem.attrs({senders: 'responder'});
  7291. break;
  7292. case 'recvonly':
  7293. elem.attrs({senders: 'initiator'});
  7294. break;
  7295. case 'sendrecv':
  7296. elem.attrs({senders: 'both'});
  7297. break;
  7298. case 'inactive':
  7299. elem.attrs({senders: 'none'});
  7300. break;
  7301. }
  7302. }
  7303. // TODO: handle params
  7304. elem.up();
  7305. }
  7306. }
  7307. elem.up(); // end of description
  7308. }
  7309. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7310. this.TransportToJingle(i, elem);
  7311. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7312. elem.attrs({senders: 'both'});
  7313. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7314. elem.attrs({senders: 'initiator'});
  7315. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7316. elem.attrs({senders: 'responder'});
  7317. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7318. elem.attrs({senders: 'none'});
  7319. }
  7320. if (mline.port == '0') {
  7321. // estos hack to reject an m-line
  7322. elem.attrs({senders: 'rejected'});
  7323. }
  7324. elem.up(); // end of content
  7325. }
  7326. elem.up();
  7327. return elem;
  7328. };
  7329. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  7330. var i = mediaindex;
  7331. var tmp;
  7332. var self = this;
  7333. elem.c('transport');
  7334. // XEP-0343 DTLS/SCTP
  7335. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7336. {
  7337. var sctpmap = SDPUtil.find_line(
  7338. this.media[i], 'a=sctpmap:', self.session);
  7339. if (sctpmap)
  7340. {
  7341. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7342. elem.c('sctpmap',
  7343. {
  7344. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7345. number: sctpAttrs[0], /* SCTP port */
  7346. protocol: sctpAttrs[1], /* protocol */
  7347. });
  7348. // Optional stream count attribute
  7349. if (sctpAttrs.length > 2)
  7350. elem.attrs({ streams: sctpAttrs[2]});
  7351. elem.up();
  7352. }
  7353. }
  7354. // XEP-0320
  7355. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7356. fingerprints.forEach(function(line) {
  7357. tmp = SDPUtil.parse_fingerprint(line);
  7358. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7359. elem.c('fingerprint').t(tmp.fingerprint);
  7360. delete tmp.fingerprint;
  7361. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7362. if (line) {
  7363. tmp.setup = line.substr(8);
  7364. }
  7365. elem.attrs(tmp);
  7366. elem.up(); // end of fingerprint
  7367. });
  7368. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7369. if (tmp) {
  7370. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7371. elem.attrs(tmp);
  7372. // XEP-0176
  7373. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7374. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7375. lines.forEach(function (line) {
  7376. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  7377. });
  7378. }
  7379. }
  7380. elem.up(); // end of transport
  7381. }
  7382. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7383. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7384. lines.forEach(function (line) {
  7385. var tmp = SDPUtil.parse_rtcpfb(line);
  7386. if (tmp.type == 'trr-int') {
  7387. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7388. elem.up();
  7389. } else {
  7390. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7391. if (tmp.params.length > 0) {
  7392. elem.attrs({'subtype': tmp.params[0]});
  7393. }
  7394. elem.up();
  7395. }
  7396. });
  7397. };
  7398. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  7399. var media = '';
  7400. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7401. if (tmp.length) {
  7402. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  7403. if (tmp.attr('value')) {
  7404. media += tmp.attr('value');
  7405. } else {
  7406. media += '0';
  7407. }
  7408. media += '\r\n';
  7409. }
  7410. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7411. tmp.each(function () {
  7412. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  7413. if ($(this).attr('subtype')) {
  7414. media += ' ' + $(this).attr('subtype');
  7415. }
  7416. media += '\r\n';
  7417. });
  7418. return media;
  7419. };
  7420. // construct an SDP from a jingle stanza
  7421. SDP.prototype.fromJingle = function (jingle) {
  7422. var self = this;
  7423. this.raw = 'v=0\r\n' +
  7424. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7425. 's=-\r\n' +
  7426. 't=0 0\r\n';
  7427. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  7428. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  7429. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  7430. var contents = $(group).find('>content').map(function (idx, content) {
  7431. return content.getAttribute('name');
  7432. }).get();
  7433. if (contents.length > 0) {
  7434. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  7435. }
  7436. });
  7437. }
  7438. this.session = this.raw;
  7439. jingle.find('>content').each(function () {
  7440. var m = self.jingle2media($(this));
  7441. self.media.push(m);
  7442. });
  7443. // reconstruct msid-semantic -- apparently not necessary
  7444. /*
  7445. var msid = SDPUtil.parse_ssrc(this.raw);
  7446. if (msid.hasOwnProperty('mslabel')) {
  7447. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  7448. }
  7449. */
  7450. this.raw = this.session + this.media.join('');
  7451. };
  7452. // translate a jingle content element into an an SDP media part
  7453. SDP.prototype.jingle2media = function (content) {
  7454. var media = '',
  7455. desc = content.find('description'),
  7456. ssrc = desc.attr('ssrc'),
  7457. self = this,
  7458. tmp;
  7459. var sctp = content.find(
  7460. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  7461. tmp = { media: desc.attr('media') };
  7462. tmp.port = '1';
  7463. if (content.attr('senders') == 'rejected') {
  7464. // estos hack to reject an m-line.
  7465. tmp.port = '0';
  7466. }
  7467. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  7468. if (sctp.length)
  7469. tmp.proto = 'DTLS/SCTP';
  7470. else
  7471. tmp.proto = 'RTP/SAVPF';
  7472. } else {
  7473. tmp.proto = 'RTP/AVPF';
  7474. }
  7475. if (!sctp.length)
  7476. {
  7477. tmp.fmt = desc.find('payload-type').map(
  7478. function () { return this.getAttribute('id'); }).get();
  7479. media += SDPUtil.build_mline(tmp) + '\r\n';
  7480. }
  7481. else
  7482. {
  7483. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  7484. media += 'a=sctpmap:' + sctp.attr('number') +
  7485. ' ' + sctp.attr('protocol');
  7486. var streamCount = sctp.attr('streams');
  7487. if (streamCount)
  7488. media += ' ' + streamCount + '\r\n';
  7489. else
  7490. media += '\r\n';
  7491. }
  7492. media += 'c=IN IP4 0.0.0.0\r\n';
  7493. if (!sctp.length)
  7494. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  7495. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  7496. if (tmp.length) {
  7497. if (tmp.attr('ufrag')) {
  7498. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  7499. }
  7500. if (tmp.attr('pwd')) {
  7501. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  7502. }
  7503. tmp.find('>fingerprint').each(function () {
  7504. // FIXME: check namespace at some point
  7505. media += 'a=fingerprint:' + this.getAttribute('hash');
  7506. media += ' ' + $(this).text();
  7507. media += '\r\n';
  7508. if (this.getAttribute('setup')) {
  7509. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  7510. }
  7511. });
  7512. }
  7513. switch (content.attr('senders')) {
  7514. case 'initiator':
  7515. media += 'a=sendonly\r\n';
  7516. break;
  7517. case 'responder':
  7518. media += 'a=recvonly\r\n';
  7519. break;
  7520. case 'none':
  7521. media += 'a=inactive\r\n';
  7522. break;
  7523. case 'both':
  7524. media += 'a=sendrecv\r\n';
  7525. break;
  7526. }
  7527. media += 'a=mid:' + content.attr('name') + '\r\n';
  7528. // <description><rtcp-mux/></description>
  7529. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  7530. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  7531. if (desc.find('rtcp-mux').length) {
  7532. media += 'a=rtcp-mux\r\n';
  7533. }
  7534. if (desc.find('encryption').length) {
  7535. desc.find('encryption>crypto').each(function () {
  7536. media += 'a=crypto:' + this.getAttribute('tag');
  7537. media += ' ' + this.getAttribute('crypto-suite');
  7538. media += ' ' + this.getAttribute('key-params');
  7539. if (this.getAttribute('session-params')) {
  7540. media += ' ' + this.getAttribute('session-params');
  7541. }
  7542. media += '\r\n';
  7543. });
  7544. }
  7545. desc.find('payload-type').each(function () {
  7546. media += SDPUtil.build_rtpmap(this) + '\r\n';
  7547. if ($(this).find('>parameter').length) {
  7548. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  7549. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  7550. media += '\r\n';
  7551. }
  7552. // xep-0293
  7553. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  7554. });
  7555. // xep-0293
  7556. media += self.RtcpFbFromJingle(desc, '*');
  7557. // xep-0294
  7558. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  7559. tmp.each(function () {
  7560. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  7561. });
  7562. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  7563. media += SDPUtil.candidateFromJingle(this);
  7564. });
  7565. // XEP-0339 handle ssrc-group attributes
  7566. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7567. var semantics = this.getAttribute('semantics');
  7568. var ssrcs = $(this).find('>source').map(function() {
  7569. return this.getAttribute('ssrc');
  7570. }).get();
  7571. if (ssrcs.length != 0) {
  7572. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7573. }
  7574. });
  7575. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7576. tmp.each(function () {
  7577. var ssrc = this.getAttribute('ssrc');
  7578. $(this).find('>parameter').each(function () {
  7579. var name = this.getAttribute('name');
  7580. var value = this.getAttribute('value');
  7581. value = SDPUtil.filter_special_chars(value);
  7582. media += 'a=ssrc:' + ssrc + ' ' + name;
  7583. if (value && value.length)
  7584. media += ':' + value;
  7585. media += '\r\n';
  7586. });
  7587. });
  7588. return media;
  7589. };
  7590. module.exports = SDP;
  7591. }).call(this,"/modules/xmpp/SDP.js")
  7592. },{"./SDPUtil":29,"jitsi-meet-logger":44}],28:[function(require,module,exports){
  7593. var SDPUtil = require("./SDPUtil");
  7594. function SDPDiffer(mySDP, otherSDP) {
  7595. this.mySDP = mySDP;
  7596. this.otherSDP = otherSDP;
  7597. }
  7598. /**
  7599. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  7600. * @param otherSdp the other SDP to check ssrc with.
  7601. */
  7602. SDPDiffer.prototype.getNewMedia = function() {
  7603. // this could be useful in Array.prototype.
  7604. function arrayEquals(array) {
  7605. // if the other array is a falsy value, return
  7606. if (!array)
  7607. return false;
  7608. // compare lengths - can save a lot of time
  7609. if (this.length != array.length)
  7610. return false;
  7611. for (var i = 0, l=this.length; i < l; i++) {
  7612. // Check if we have nested arrays
  7613. if (this[i] instanceof Array && array[i] instanceof Array) {
  7614. // recurse into the nested arrays
  7615. if (!this[i].equals(array[i]))
  7616. return false;
  7617. }
  7618. else if (this[i] != array[i]) {
  7619. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  7620. return false;
  7621. }
  7622. }
  7623. return true;
  7624. }
  7625. var myMedias = this.mySDP.getMediaSsrcMap();
  7626. var othersMedias = this.otherSDP.getMediaSsrcMap();
  7627. var newMedia = {};
  7628. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  7629. var myMedia = myMedias[othersMediaIdx];
  7630. var othersMedia = othersMedias[othersMediaIdx];
  7631. if(!myMedia && othersMedia) {
  7632. // Add whole channel
  7633. newMedia[othersMediaIdx] = othersMedia;
  7634. return;
  7635. }
  7636. // Look for new ssrcs accross the channel
  7637. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  7638. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  7639. // Allocate channel if we've found ssrc that doesn't exist in our channel
  7640. if(!newMedia[othersMediaIdx]){
  7641. newMedia[othersMediaIdx] = {
  7642. mediaindex: othersMedia.mediaindex,
  7643. mid: othersMedia.mid,
  7644. ssrcs: {},
  7645. ssrcGroups: []
  7646. };
  7647. }
  7648. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  7649. }
  7650. });
  7651. // Look for new ssrc groups across the channels
  7652. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  7653. // try to match the other ssrc-group with an ssrc-group of ours
  7654. var matched = false;
  7655. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  7656. var mySsrcGroup = myMedia.ssrcGroups[i];
  7657. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  7658. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  7659. matched = true;
  7660. break;
  7661. }
  7662. }
  7663. if (!matched) {
  7664. // Allocate channel if we've found an ssrc-group that doesn't
  7665. // exist in our channel
  7666. if(!newMedia[othersMediaIdx]){
  7667. newMedia[othersMediaIdx] = {
  7668. mediaindex: othersMedia.mediaindex,
  7669. mid: othersMedia.mid,
  7670. ssrcs: {},
  7671. ssrcGroups: []
  7672. };
  7673. }
  7674. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  7675. }
  7676. });
  7677. });
  7678. return newMedia;
  7679. };
  7680. /**
  7681. * Sends SSRC update IQ.
  7682. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  7683. * @param sid session identifier that will be put into the IQ.
  7684. * @param initiator initiator identifier.
  7685. * @param toJid destination Jid
  7686. * @param isAdd indicates if this is remove or add operation.
  7687. */
  7688. SDPDiffer.prototype.toJingle = function(modify) {
  7689. var sdpMediaSsrcs = this.getNewMedia();
  7690. var self = this;
  7691. // FIXME: only announce video ssrcs since we mix audio and dont need
  7692. // the audio ssrcs therefore
  7693. var modified = false;
  7694. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  7695. modified = true;
  7696. var media = sdpMediaSsrcs[mediaindex];
  7697. modify.c('content', {name: media.mid});
  7698. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  7699. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  7700. // generate sources from lines
  7701. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  7702. var mediaSsrc = media.ssrcs[ssrcNum];
  7703. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7704. modify.attrs({ssrc: mediaSsrc.ssrc});
  7705. // iterate over ssrc lines
  7706. mediaSsrc.lines.forEach(function (line) {
  7707. var idx = line.indexOf(' ');
  7708. var kv = line.substr(idx + 1);
  7709. modify.c('parameter');
  7710. if (kv.indexOf(':') == -1) {
  7711. modify.attrs({ name: kv });
  7712. } else {
  7713. var nv = kv.split(':', 2);
  7714. var name = nv[0];
  7715. var value = SDPUtil.filter_special_chars(nv[1]);
  7716. modify.attrs({ name: name });
  7717. modify.attrs({ value: value });
  7718. }
  7719. modify.up(); // end of parameter
  7720. });
  7721. modify.up(); // end of source
  7722. });
  7723. // generate source groups from lines
  7724. media.ssrcGroups.forEach(function(ssrcGroup) {
  7725. if (ssrcGroup.ssrcs.length != 0) {
  7726. modify.c('ssrc-group', {
  7727. semantics: ssrcGroup.semantics,
  7728. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  7729. });
  7730. ssrcGroup.ssrcs.forEach(function (ssrc) {
  7731. modify.c('source', { ssrc: ssrc })
  7732. .up(); // end of source
  7733. });
  7734. modify.up(); // end of ssrc-group
  7735. }
  7736. });
  7737. modify.up(); // end of description
  7738. modify.up(); // end of content
  7739. });
  7740. return modified;
  7741. };
  7742. module.exports = SDPDiffer;
  7743. },{"./SDPUtil":29}],29:[function(require,module,exports){
  7744. (function (__filename){
  7745. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7746. SDPUtil = {
  7747. filter_special_chars: function (text) {
  7748. return text.replace(/[\\\/\{,\}\+]/g, "");
  7749. },
  7750. iceparams: function (mediadesc, sessiondesc) {
  7751. var data = null;
  7752. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  7753. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  7754. data = {
  7755. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  7756. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  7757. };
  7758. }
  7759. return data;
  7760. },
  7761. parse_iceufrag: function (line) {
  7762. return line.substring(12);
  7763. },
  7764. build_iceufrag: function (frag) {
  7765. return 'a=ice-ufrag:' + frag;
  7766. },
  7767. parse_icepwd: function (line) {
  7768. return line.substring(10);
  7769. },
  7770. build_icepwd: function (pwd) {
  7771. return 'a=ice-pwd:' + pwd;
  7772. },
  7773. parse_mid: function (line) {
  7774. return line.substring(6);
  7775. },
  7776. parse_mline: function (line) {
  7777. var parts = line.substring(2).split(' '),
  7778. data = {};
  7779. data.media = parts.shift();
  7780. data.port = parts.shift();
  7781. data.proto = parts.shift();
  7782. if (parts[parts.length - 1] === '') { // trailing whitespace
  7783. parts.pop();
  7784. }
  7785. data.fmt = parts;
  7786. return data;
  7787. },
  7788. build_mline: function (mline) {
  7789. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  7790. },
  7791. parse_rtpmap: function (line) {
  7792. var parts = line.substring(9).split(' '),
  7793. data = {};
  7794. data.id = parts.shift();
  7795. parts = parts[0].split('/');
  7796. data.name = parts.shift();
  7797. data.clockrate = parts.shift();
  7798. data.channels = parts.length ? parts.shift() : '1';
  7799. return data;
  7800. },
  7801. /**
  7802. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  7803. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  7804. * @returns [SCTP port number, protocol, streams]
  7805. */
  7806. parse_sctpmap: function (line)
  7807. {
  7808. var parts = line.substring(10).split(' ');
  7809. var sctpPort = parts[0];
  7810. var protocol = parts[1];
  7811. // Stream count is optional
  7812. var streamCount = parts.length > 2 ? parts[2] : null;
  7813. return [sctpPort, protocol, streamCount];// SCTP port
  7814. },
  7815. build_rtpmap: function (el) {
  7816. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  7817. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  7818. line += '/' + el.getAttribute('channels');
  7819. }
  7820. return line;
  7821. },
  7822. parse_crypto: function (line) {
  7823. var parts = line.substring(9).split(' '),
  7824. data = {};
  7825. data.tag = parts.shift();
  7826. data['crypto-suite'] = parts.shift();
  7827. data['key-params'] = parts.shift();
  7828. if (parts.length) {
  7829. data['session-params'] = parts.join(' ');
  7830. }
  7831. return data;
  7832. },
  7833. parse_fingerprint: function (line) { // RFC 4572
  7834. var parts = line.substring(14).split(' '),
  7835. data = {};
  7836. data.hash = parts.shift();
  7837. data.fingerprint = parts.shift();
  7838. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  7839. return data;
  7840. },
  7841. parse_fmtp: function (line) {
  7842. var parts = line.split(' '),
  7843. i, key, value,
  7844. data = [];
  7845. parts.shift();
  7846. parts = parts.join(' ').split(';');
  7847. for (i = 0; i < parts.length; i++) {
  7848. key = parts[i].split('=')[0];
  7849. while (key.length && key[0] == ' ') {
  7850. key = key.substring(1);
  7851. }
  7852. value = parts[i].split('=')[1];
  7853. if (key && value) {
  7854. data.push({name: key, value: value});
  7855. } else if (key) {
  7856. // rfc 4733 (DTMF) style stuff
  7857. data.push({name: '', value: key});
  7858. }
  7859. }
  7860. return data;
  7861. },
  7862. parse_icecandidate: function (line) {
  7863. var candidate = {},
  7864. elems = line.split(' ');
  7865. candidate.foundation = elems[0].substring(12);
  7866. candidate.component = elems[1];
  7867. candidate.protocol = elems[2].toLowerCase();
  7868. candidate.priority = elems[3];
  7869. candidate.ip = elems[4];
  7870. candidate.port = elems[5];
  7871. // elems[6] => "typ"
  7872. candidate.type = elems[7];
  7873. candidate.generation = 0; // default value, may be overwritten below
  7874. for (var i = 8; i < elems.length; i += 2) {
  7875. switch (elems[i]) {
  7876. case 'raddr':
  7877. candidate['rel-addr'] = elems[i + 1];
  7878. break;
  7879. case 'rport':
  7880. candidate['rel-port'] = elems[i + 1];
  7881. break;
  7882. case 'generation':
  7883. candidate.generation = elems[i + 1];
  7884. break;
  7885. case 'tcptype':
  7886. candidate.tcptype = elems[i + 1];
  7887. break;
  7888. default: // TODO
  7889. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  7890. }
  7891. }
  7892. candidate.network = '1';
  7893. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  7894. return candidate;
  7895. },
  7896. build_icecandidate: function (cand) {
  7897. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  7898. line += ' ';
  7899. switch (cand.type) {
  7900. case 'srflx':
  7901. case 'prflx':
  7902. case 'relay':
  7903. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  7904. line += 'raddr';
  7905. line += ' ';
  7906. line += cand['rel-addr'];
  7907. line += ' ';
  7908. line += 'rport';
  7909. line += ' ';
  7910. line += cand['rel-port'];
  7911. line += ' ';
  7912. }
  7913. break;
  7914. }
  7915. if (cand.hasOwnAttribute('tcptype')) {
  7916. line += 'tcptype';
  7917. line += ' ';
  7918. line += cand.tcptype;
  7919. line += ' ';
  7920. }
  7921. line += 'generation';
  7922. line += ' ';
  7923. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  7924. return line;
  7925. },
  7926. parse_ssrc: function (desc) {
  7927. // proprietary mapping of a=ssrc lines
  7928. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  7929. // and parse according to that
  7930. var lines = desc.split('\r\n'),
  7931. data = {};
  7932. for (var i = 0; i < lines.length; i++) {
  7933. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  7934. var idx = lines[i].indexOf(' ');
  7935. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  7936. }
  7937. }
  7938. return data;
  7939. },
  7940. parse_rtcpfb: function (line) {
  7941. var parts = line.substr(10).split(' ');
  7942. var data = {};
  7943. data.pt = parts.shift();
  7944. data.type = parts.shift();
  7945. data.params = parts;
  7946. return data;
  7947. },
  7948. parse_extmap: function (line) {
  7949. var parts = line.substr(9).split(' ');
  7950. var data = {};
  7951. data.value = parts.shift();
  7952. if (data.value.indexOf('/') != -1) {
  7953. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  7954. data.value = data.value.substr(0, data.value.indexOf('/'));
  7955. } else {
  7956. data.direction = 'both';
  7957. }
  7958. data.uri = parts.shift();
  7959. data.params = parts;
  7960. return data;
  7961. },
  7962. find_line: function (haystack, needle, sessionpart) {
  7963. var lines = haystack.split('\r\n');
  7964. for (var i = 0; i < lines.length; i++) {
  7965. if (lines[i].substring(0, needle.length) == needle) {
  7966. return lines[i];
  7967. }
  7968. }
  7969. if (!sessionpart) {
  7970. return false;
  7971. }
  7972. // search session part
  7973. lines = sessionpart.split('\r\n');
  7974. for (var j = 0; j < lines.length; j++) {
  7975. if (lines[j].substring(0, needle.length) == needle) {
  7976. return lines[j];
  7977. }
  7978. }
  7979. return false;
  7980. },
  7981. find_lines: function (haystack, needle, sessionpart) {
  7982. var lines = haystack.split('\r\n'),
  7983. needles = [];
  7984. for (var i = 0; i < lines.length; i++) {
  7985. if (lines[i].substring(0, needle.length) == needle)
  7986. needles.push(lines[i]);
  7987. }
  7988. if (needles.length || !sessionpart) {
  7989. return needles;
  7990. }
  7991. // search session part
  7992. lines = sessionpart.split('\r\n');
  7993. for (var j = 0; j < lines.length; j++) {
  7994. if (lines[j].substring(0, needle.length) == needle) {
  7995. needles.push(lines[j]);
  7996. }
  7997. }
  7998. return needles;
  7999. },
  8000. candidateToJingle: function (line) {
  8001. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8002. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8003. if (line.indexOf('candidate:') === 0) {
  8004. line = 'a=' + line;
  8005. } else if (line.substring(0, 12) != 'a=candidate:') {
  8006. logger.log('parseCandidate called with a line that is not a candidate line');
  8007. logger.log(line);
  8008. return null;
  8009. }
  8010. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8011. line = line.substring(0, line.length - 2);
  8012. var candidate = {},
  8013. elems = line.split(' '),
  8014. i;
  8015. if (elems[6] != 'typ') {
  8016. logger.log('did not find typ in the right place');
  8017. logger.log(line);
  8018. return null;
  8019. }
  8020. candidate.foundation = elems[0].substring(12);
  8021. candidate.component = elems[1];
  8022. candidate.protocol = elems[2].toLowerCase();
  8023. candidate.priority = elems[3];
  8024. candidate.ip = elems[4];
  8025. candidate.port = elems[5];
  8026. // elems[6] => "typ"
  8027. candidate.type = elems[7];
  8028. candidate.generation = '0'; // default, may be overwritten below
  8029. for (i = 8; i < elems.length; i += 2) {
  8030. switch (elems[i]) {
  8031. case 'raddr':
  8032. candidate['rel-addr'] = elems[i + 1];
  8033. break;
  8034. case 'rport':
  8035. candidate['rel-port'] = elems[i + 1];
  8036. break;
  8037. case 'generation':
  8038. candidate.generation = elems[i + 1];
  8039. break;
  8040. case 'tcptype':
  8041. candidate.tcptype = elems[i + 1];
  8042. break;
  8043. default: // TODO
  8044. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8045. }
  8046. }
  8047. candidate.network = '1';
  8048. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8049. return candidate;
  8050. },
  8051. candidateFromJingle: function (cand) {
  8052. var line = 'a=candidate:';
  8053. line += cand.getAttribute('foundation');
  8054. line += ' ';
  8055. line += cand.getAttribute('component');
  8056. line += ' ';
  8057. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  8058. line += ' ';
  8059. line += cand.getAttribute('priority');
  8060. line += ' ';
  8061. line += cand.getAttribute('ip');
  8062. line += ' ';
  8063. line += cand.getAttribute('port');
  8064. line += ' ';
  8065. line += 'typ';
  8066. line += ' ' + cand.getAttribute('type');
  8067. line += ' ';
  8068. switch (cand.getAttribute('type')) {
  8069. case 'srflx':
  8070. case 'prflx':
  8071. case 'relay':
  8072. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8073. line += 'raddr';
  8074. line += ' ';
  8075. line += cand.getAttribute('rel-addr');
  8076. line += ' ';
  8077. line += 'rport';
  8078. line += ' ';
  8079. line += cand.getAttribute('rel-port');
  8080. line += ' ';
  8081. }
  8082. break;
  8083. }
  8084. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  8085. line += 'tcptype';
  8086. line += ' ';
  8087. line += cand.getAttribute('tcptype');
  8088. line += ' ';
  8089. }
  8090. line += 'generation';
  8091. line += ' ';
  8092. line += cand.getAttribute('generation') || '0';
  8093. return line + '\r\n';
  8094. }
  8095. };
  8096. module.exports = SDPUtil;
  8097. }).call(this,"/modules/xmpp/SDPUtil.js")
  8098. },{"jitsi-meet-logger":44}],30:[function(require,module,exports){
  8099. (function (__filename){
  8100. var RTC = require('../RTC/RTC');
  8101. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8102. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8103. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8104. var SSRCReplacement = require("./LocalSSRCReplacement");
  8105. function TraceablePeerConnection(ice_config, constraints, session) {
  8106. var self = this;
  8107. this.session = session;
  8108. var RTCPeerConnectionType = null;
  8109. if (RTCBrowserType.isFirefox()) {
  8110. RTCPeerConnectionType = mozRTCPeerConnection;
  8111. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8112. RTCPeerConnectionType = RTCPeerConnection;
  8113. } else {
  8114. RTCPeerConnectionType = webkitRTCPeerConnection;
  8115. }
  8116. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8117. this.updateLog = [];
  8118. this.stats = {};
  8119. this.statsinterval = null;
  8120. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8121. var Interop = require('sdp-interop').Interop;
  8122. this.interop = new Interop();
  8123. var Simulcast = require('sdp-simulcast');
  8124. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  8125. // override as desired
  8126. this.trace = function (what, info) {
  8127. /*logger.warn('WTRACE', what, info);
  8128. if (info && RTCBrowserType.isIExplorer()) {
  8129. if (info.length > 1024) {
  8130. logger.warn('WTRACE', what, info.substr(1024));
  8131. }
  8132. if (info.length > 2048) {
  8133. logger.warn('WTRACE', what, info.substr(2048));
  8134. }
  8135. }*/
  8136. self.updateLog.push({
  8137. time: new Date(),
  8138. type: what,
  8139. value: info || ""
  8140. });
  8141. };
  8142. this.onicecandidate = null;
  8143. this.peerconnection.onicecandidate = function (event) {
  8144. // FIXME: this causes stack overflow with Temasys Plugin
  8145. if (!RTCBrowserType.isTemasysPluginUsed())
  8146. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8147. if (self.onicecandidate !== null) {
  8148. self.onicecandidate(event);
  8149. }
  8150. };
  8151. this.onaddstream = null;
  8152. this.peerconnection.onaddstream = function (event) {
  8153. self.trace('onaddstream', event.stream.id);
  8154. if (self.onaddstream !== null) {
  8155. self.onaddstream(event);
  8156. }
  8157. };
  8158. this.onremovestream = null;
  8159. this.peerconnection.onremovestream = function (event) {
  8160. self.trace('onremovestream', event.stream.id);
  8161. if (self.onremovestream !== null) {
  8162. self.onremovestream(event);
  8163. }
  8164. };
  8165. this.onsignalingstatechange = null;
  8166. this.peerconnection.onsignalingstatechange = function (event) {
  8167. self.trace('onsignalingstatechange', self.signalingState);
  8168. if (self.onsignalingstatechange !== null) {
  8169. self.onsignalingstatechange(event);
  8170. }
  8171. };
  8172. this.oniceconnectionstatechange = null;
  8173. this.peerconnection.oniceconnectionstatechange = function (event) {
  8174. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8175. if (self.oniceconnectionstatechange !== null) {
  8176. self.oniceconnectionstatechange(event);
  8177. }
  8178. };
  8179. this.onnegotiationneeded = null;
  8180. this.peerconnection.onnegotiationneeded = function (event) {
  8181. self.trace('onnegotiationneeded');
  8182. if (self.onnegotiationneeded !== null) {
  8183. self.onnegotiationneeded(event);
  8184. }
  8185. };
  8186. self.ondatachannel = null;
  8187. this.peerconnection.ondatachannel = function (event) {
  8188. self.trace('ondatachannel', event);
  8189. if (self.ondatachannel !== null) {
  8190. self.ondatachannel(event);
  8191. }
  8192. };
  8193. // XXX: do all non-firefox browsers which we support also support this?
  8194. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8195. this.statsinterval = window.setInterval(function() {
  8196. self.peerconnection.getStats(function(stats) {
  8197. var results = stats.result();
  8198. var now = new Date();
  8199. for (var i = 0; i < results.length; ++i) {
  8200. results[i].names().forEach(function (name) {
  8201. var id = results[i].id + '-' + name;
  8202. if (!self.stats[id]) {
  8203. self.stats[id] = {
  8204. startTime: now,
  8205. endTime: now,
  8206. values: [],
  8207. times: []
  8208. };
  8209. }
  8210. self.stats[id].values.push(results[i].stat(name));
  8211. self.stats[id].times.push(now.getTime());
  8212. if (self.stats[id].values.length > self.maxstats) {
  8213. self.stats[id].values.shift();
  8214. self.stats[id].times.shift();
  8215. }
  8216. self.stats[id].endTime = now;
  8217. });
  8218. }
  8219. });
  8220. }, 1000);
  8221. }
  8222. }
  8223. /**
  8224. * Returns a string representation of a SessionDescription object.
  8225. */
  8226. var dumpSDP = function(description) {
  8227. if (typeof description === 'undefined' || description == null) {
  8228. return '';
  8229. }
  8230. return 'type: ' + description.type + '\r\n' + description.sdp;
  8231. };
  8232. /**
  8233. * Takes a SessionDescription object and returns a "normalized" version.
  8234. * Currently it only takes care of ordering the a=ssrc lines.
  8235. */
  8236. var normalizePlanB = function(desc) {
  8237. if (typeof desc !== 'object' || desc === null ||
  8238. typeof desc.sdp !== 'string') {
  8239. logger.warn('An empty description was passed as an argument.');
  8240. return desc;
  8241. }
  8242. var transform = require('sdp-transform');
  8243. var session = transform.parse(desc.sdp);
  8244. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8245. Array.isArray(session.media)) {
  8246. session.media.forEach(function (mLine) {
  8247. // Chrome appears to be picky about the order in which a=ssrc lines
  8248. // are listed in an m-line when rtx is enabled (and thus there are
  8249. // a=ssrc-group lines with FID semantics). Specifically if we have
  8250. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8251. // the "a=ssrc:S1" lines, SRD fails.
  8252. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8253. // first.
  8254. var firstSsrcs = [];
  8255. var newSsrcLines = [];
  8256. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8257. mLine.ssrcGroups.forEach(function (group) {
  8258. if (typeof group.semantics !== 'undefined' &&
  8259. group.semantics === 'FID') {
  8260. if (typeof group.ssrcs !== 'undefined') {
  8261. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8262. }
  8263. }
  8264. });
  8265. }
  8266. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8267. for (var i = 0; i<mLine.ssrcs.length; i++){
  8268. if (typeof mLine.ssrcs[i] === 'object'
  8269. && typeof mLine.ssrcs[i].id !== 'undefined'
  8270. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  8271. newSsrcLines.push(mLine.ssrcs[i]);
  8272. delete mLine.ssrcs[i];
  8273. }
  8274. }
  8275. for (var i = 0; i<mLine.ssrcs.length; i++){
  8276. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8277. newSsrcLines.push(mLine.ssrcs[i]);
  8278. }
  8279. }
  8280. mLine.ssrcs = newSsrcLines;
  8281. }
  8282. });
  8283. }
  8284. var resStr = transform.write(session);
  8285. return new RTCSessionDescription({
  8286. type: desc.type,
  8287. sdp: resStr
  8288. });
  8289. };
  8290. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  8291. TraceablePeerConnection.prototype.__defineGetter__(
  8292. 'signalingState',
  8293. function() { return this.peerconnection.signalingState; });
  8294. TraceablePeerConnection.prototype.__defineGetter__(
  8295. 'iceConnectionState',
  8296. function() { return this.peerconnection.iceConnectionState; });
  8297. TraceablePeerConnection.prototype.__defineGetter__(
  8298. 'localDescription',
  8299. function() {
  8300. var desc = this.peerconnection.localDescription;
  8301. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8302. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8303. // if we're running on FF, transform to Plan B first.
  8304. if (RTCBrowserType.usesUnifiedPlan()) {
  8305. desc = this.interop.toPlanB(desc);
  8306. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8307. }
  8308. return desc;
  8309. });
  8310. TraceablePeerConnection.prototype.__defineGetter__(
  8311. 'remoteDescription',
  8312. function() {
  8313. var desc = this.peerconnection.remoteDescription;
  8314. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8315. // if we're running on FF, transform to Plan B first.
  8316. if (RTCBrowserType.usesUnifiedPlan()) {
  8317. desc = this.interop.toPlanB(desc);
  8318. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8319. }
  8320. return desc;
  8321. });
  8322. }
  8323. TraceablePeerConnection.prototype.addStream = function (stream) {
  8324. this.trace('addStream', stream.id);
  8325. try
  8326. {
  8327. this.peerconnection.addStream(stream);
  8328. }
  8329. catch (e)
  8330. {
  8331. logger.error(e);
  8332. }
  8333. };
  8334. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8335. this.trace('removeStream', stream.id);
  8336. if(stopStreams) {
  8337. stream.getAudioTracks().forEach(function (track) {
  8338. // stop() not supported with IE
  8339. if (track.stop) {
  8340. track.stop();
  8341. }
  8342. });
  8343. stream.getVideoTracks().forEach(function (track) {
  8344. // stop() not supported with IE
  8345. if (track.stop) {
  8346. track.stop();
  8347. }
  8348. });
  8349. if (stream.stop) {
  8350. stream.stop();
  8351. }
  8352. }
  8353. try {
  8354. // FF doesn't support this yet.
  8355. if (this.peerconnection.removeStream)
  8356. this.peerconnection.removeStream(stream);
  8357. } catch (e) {
  8358. logger.error(e);
  8359. }
  8360. };
  8361. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8362. this.trace('createDataChannel', label, opts);
  8363. return this.peerconnection.createDataChannel(label, opts);
  8364. };
  8365. TraceablePeerConnection.prototype.setLocalDescription
  8366. = function (description, successCallback, failureCallback) {
  8367. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8368. // if we're running on FF, transform to Plan A first.
  8369. if (RTCBrowserType.usesUnifiedPlan()) {
  8370. description = this.interop.toUnifiedPlan(description);
  8371. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8372. }
  8373. var self = this;
  8374. this.peerconnection.setLocalDescription(description,
  8375. function () {
  8376. self.trace('setLocalDescriptionOnSuccess');
  8377. successCallback();
  8378. },
  8379. function (err) {
  8380. self.trace('setLocalDescriptionOnFailure', err);
  8381. failureCallback(err);
  8382. }
  8383. );
  8384. /*
  8385. if (this.statsinterval === null && this.maxstats > 0) {
  8386. // start gathering stats
  8387. }
  8388. */
  8389. };
  8390. TraceablePeerConnection.prototype.setRemoteDescription
  8391. = function (description, successCallback, failureCallback) {
  8392. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  8393. // TODO the focus should squeze or explode the remote simulcast
  8394. description = this.simulcast.mungeRemoteDescription(description);
  8395. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  8396. // if we're running on FF, transform to Plan A first.
  8397. if (RTCBrowserType.usesUnifiedPlan()) {
  8398. description = this.interop.toUnifiedPlan(description);
  8399. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  8400. }
  8401. if (RTCBrowserType.usesPlanB()) {
  8402. description = normalizePlanB(description);
  8403. }
  8404. var self = this;
  8405. this.peerconnection.setRemoteDescription(description,
  8406. function () {
  8407. self.trace('setRemoteDescriptionOnSuccess');
  8408. successCallback();
  8409. },
  8410. function (err) {
  8411. self.trace('setRemoteDescriptionOnFailure', err);
  8412. failureCallback(err);
  8413. }
  8414. );
  8415. /*
  8416. if (this.statsinterval === null && this.maxstats > 0) {
  8417. // start gathering stats
  8418. }
  8419. */
  8420. };
  8421. TraceablePeerConnection.prototype.close = function () {
  8422. this.trace('stop');
  8423. if (this.statsinterval !== null) {
  8424. window.clearInterval(this.statsinterval);
  8425. this.statsinterval = null;
  8426. }
  8427. this.peerconnection.close();
  8428. };
  8429. TraceablePeerConnection.prototype.createOffer
  8430. = function (successCallback, failureCallback, constraints) {
  8431. var self = this;
  8432. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  8433. this.peerconnection.createOffer(
  8434. function (offer) {
  8435. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  8436. // NOTE this is not tested because in meet the focus generates the
  8437. // offer.
  8438. // if we're running on FF, transform to Plan B first.
  8439. if (RTCBrowserType.usesUnifiedPlan()) {
  8440. offer = self.interop.toPlanB(offer);
  8441. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  8442. }
  8443. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  8444. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8445. offer = self.simulcast.mungeLocalDescription(offer);
  8446. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  8447. }
  8448. successCallback(offer);
  8449. },
  8450. function(err) {
  8451. self.trace('createOfferOnFailure', err);
  8452. failureCallback(err);
  8453. },
  8454. constraints
  8455. );
  8456. };
  8457. TraceablePeerConnection.prototype.createAnswer
  8458. = function (successCallback, failureCallback, constraints) {
  8459. var self = this;
  8460. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  8461. this.peerconnection.createAnswer(
  8462. function (answer) {
  8463. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  8464. // if we're running on FF, transform to Plan A first.
  8465. if (RTCBrowserType.usesUnifiedPlan()) {
  8466. answer = self.interop.toPlanB(answer);
  8467. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  8468. }
  8469. // munge local video SSRC
  8470. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  8471. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8472. answer = self.simulcast.mungeLocalDescription(answer);
  8473. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  8474. }
  8475. successCallback(answer);
  8476. },
  8477. function(err) {
  8478. self.trace('createAnswerOnFailure', err);
  8479. failureCallback(err);
  8480. },
  8481. constraints
  8482. );
  8483. };
  8484. TraceablePeerConnection.prototype.addIceCandidate
  8485. = function (candidate, successCallback, failureCallback) {
  8486. //var self = this;
  8487. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  8488. this.peerconnection.addIceCandidate(candidate);
  8489. /* maybe later
  8490. this.peerconnection.addIceCandidate(candidate,
  8491. function () {
  8492. self.trace('addIceCandidateOnSuccess');
  8493. successCallback();
  8494. },
  8495. function (err) {
  8496. self.trace('addIceCandidateOnFailure', err);
  8497. failureCallback(err);
  8498. }
  8499. );
  8500. */
  8501. };
  8502. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  8503. // TODO: Is this the correct way to handle Opera, Temasys?
  8504. if (RTCBrowserType.isFirefox()) {
  8505. // ignore for now...
  8506. if(!errback)
  8507. errback = function () {};
  8508. this.peerconnection.getStats(null, callback, errback);
  8509. } else {
  8510. this.peerconnection.getStats(callback);
  8511. }
  8512. };
  8513. module.exports = TraceablePeerConnection;
  8514. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  8515. },{"../../service/xmpp/XMPPEvents":82,"../RTC/RTC":13,"../RTC/RTCBrowserType.js":14,"./LocalSSRCReplacement":26,"jitsi-meet-logger":44,"sdp-interop":62,"sdp-simulcast":65,"sdp-transform":72}],31:[function(require,module,exports){
  8516. (function (__filename){
  8517. /* global $, $iq, APP, config, messageHandler,
  8518. roomName, sessionTerminated, Strophe, Util */
  8519. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8520. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8521. var Settings = require("../settings/Settings");
  8522. var AuthenticationEvents
  8523. = require("../../service/authentication/AuthenticationEvents");
  8524. function createExpBackoffTimer(step) {
  8525. var count = 1;
  8526. return function (reset) {
  8527. // Reset call
  8528. if (reset) {
  8529. count = 1;
  8530. return;
  8531. }
  8532. // Calculate next timeout
  8533. var timeout = Math.pow(2, count - 1);
  8534. count += 1;
  8535. return timeout * step;
  8536. };
  8537. }
  8538. function Moderator(roomName, xmpp, emitter) {
  8539. this.roomName = roomName;
  8540. this.xmppService = xmpp;
  8541. this.getNextTimeout = createExpBackoffTimer(1000);
  8542. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  8543. // External authentication stuff
  8544. this.externalAuthEnabled = false;
  8545. this.settings = new Settings(roomName);
  8546. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  8547. // it will be enabled automatically if focus detects the component through
  8548. // service discovery.
  8549. this.sipGatewayEnabled =
  8550. this.xmppService.options.hosts.call_control !== undefined;
  8551. this.eventEmitter = emitter;
  8552. this.connection = this.xmppService.connection;
  8553. this.focusUserJid;
  8554. //FIXME:
  8555. // Message listener that talks to POPUP window
  8556. function listener(event) {
  8557. if (event.data && event.data.sessionId) {
  8558. if (event.origin !== window.location.origin) {
  8559. logger.warn("Ignoring sessionId from different origin: " +
  8560. event.origin);
  8561. return;
  8562. }
  8563. localStorage.setItem('sessionId', event.data.sessionId);
  8564. // After popup is closed we will authenticate
  8565. }
  8566. }
  8567. // Register
  8568. if (window.addEventListener) {
  8569. window.addEventListener("message", listener, false);
  8570. } else {
  8571. window.attachEvent("onmessage", listener);
  8572. }
  8573. }
  8574. Moderator.prototype.isExternalAuthEnabled = function () {
  8575. return this.externalAuthEnabled;
  8576. };
  8577. Moderator.prototype.isSipGatewayEnabled = function () {
  8578. return this.sipGatewayEnabled;
  8579. };
  8580. Moderator.prototype.onMucMemberLeft = function (jid) {
  8581. logger.info("Someone left is it focus ? " + jid);
  8582. var resource = Strophe.getResourceFromJid(jid);
  8583. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  8584. logger.info(
  8585. "Focus has left the room - leaving conference");
  8586. //hangUp();
  8587. // We'd rather reload to have everything re-initialized
  8588. //FIXME: show some message before reload
  8589. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  8590. }
  8591. };
  8592. Moderator.prototype.setFocusUserJid = function (focusJid) {
  8593. if (!this.focusUserJid) {
  8594. this.focusUserJid = focusJid;
  8595. logger.info("Focus jid set to: " + this.focusUserJid);
  8596. }
  8597. };
  8598. Moderator.prototype.getFocusUserJid = function () {
  8599. return this.focusUserJid;
  8600. };
  8601. Moderator.prototype.getFocusComponent = function () {
  8602. // Get focus component address
  8603. var focusComponent = this.xmppService.options.hosts.focus;
  8604. // If not specified use default: 'focus.domain'
  8605. if (!focusComponent) {
  8606. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  8607. }
  8608. return focusComponent;
  8609. };
  8610. Moderator.prototype.createConferenceIq = function () {
  8611. // Generate create conference IQ
  8612. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  8613. // Session Id used for authentication
  8614. var sessionId = localStorage.getItem('sessionId');
  8615. var machineUID = this.settings.getSettings().uid;
  8616. logger.info(
  8617. "Session ID: " + sessionId + " machine UID: " + machineUID);
  8618. elem.c('conference', {
  8619. xmlns: 'http://jitsi.org/protocol/focus',
  8620. room: this.roomName,
  8621. 'machine-uid': machineUID
  8622. });
  8623. if (sessionId) {
  8624. elem.attrs({ 'session-id': sessionId});
  8625. }
  8626. if (this.xmppService.options.hosts.bridge !== undefined) {
  8627. elem.c(
  8628. 'property', {
  8629. name: 'bridge',
  8630. value: this.xmppService.options.hosts.bridge
  8631. }).up();
  8632. }
  8633. // Tell the focus we have Jigasi configured
  8634. if (this.xmppService.options.hosts.call_control !== undefined) {
  8635. elem.c(
  8636. 'property', {
  8637. name: 'call_control',
  8638. value: this.xmppService.options.hosts.call_control
  8639. }).up();
  8640. }
  8641. if (this.xmppService.options.channelLastN !== undefined) {
  8642. elem.c(
  8643. 'property', {
  8644. name: 'channelLastN',
  8645. value: this.xmppService.options.channelLastN
  8646. }).up();
  8647. }
  8648. if (this.xmppService.options.adaptiveLastN !== undefined) {
  8649. elem.c(
  8650. 'property', {
  8651. name: 'adaptiveLastN',
  8652. value: this.xmppService.options.adaptiveLastN
  8653. }).up();
  8654. }
  8655. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  8656. elem.c(
  8657. 'property', {
  8658. name: 'adaptiveSimulcast',
  8659. value: this.xmppService.options.adaptiveSimulcast
  8660. }).up();
  8661. }
  8662. if (this.xmppService.options.openSctp !== undefined) {
  8663. elem.c(
  8664. 'property', {
  8665. name: 'openSctp',
  8666. value: this.xmppService.options.openSctp
  8667. }).up();
  8668. }
  8669. if (this.xmppService.options.startAudioMuted !== undefined)
  8670. {
  8671. elem.c(
  8672. 'property', {
  8673. name: 'startAudioMuted',
  8674. value: this.xmppService.options.startAudioMuted
  8675. }).up();
  8676. }
  8677. if (this.xmppService.options.startVideoMuted !== undefined)
  8678. {
  8679. elem.c(
  8680. 'property', {
  8681. name: 'startVideoMuted',
  8682. value: this.xmppService.options.startVideoMuted
  8683. }).up();
  8684. }
  8685. elem.c(
  8686. 'property', {
  8687. name: 'simulcastMode',
  8688. value: 'rewriting'
  8689. }).up();
  8690. elem.up();
  8691. return elem;
  8692. };
  8693. Moderator.prototype.parseSessionId = function (resultIq) {
  8694. var sessionId = $(resultIq).find('conference').attr('session-id');
  8695. if (sessionId) {
  8696. logger.info('Received sessionId: ' + sessionId);
  8697. localStorage.setItem('sessionId', sessionId);
  8698. }
  8699. };
  8700. Moderator.prototype.parseConfigOptions = function (resultIq) {
  8701. this.setFocusUserJid(
  8702. $(resultIq).find('conference').attr('focusjid'));
  8703. var authenticationEnabled
  8704. = $(resultIq).find(
  8705. '>conference>property' +
  8706. '[name=\'authentication\'][value=\'true\']').length > 0;
  8707. logger.info("Authentication enabled: " + authenticationEnabled);
  8708. this.externalAuthEnabled = $(resultIq).find(
  8709. '>conference>property' +
  8710. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  8711. console.info(
  8712. 'External authentication enabled: ' + this.externalAuthEnabled);
  8713. if (!this.externalAuthEnabled) {
  8714. // We expect to receive sessionId in 'internal' authentication mode
  8715. this.parseSessionId(resultIq);
  8716. }
  8717. var authIdentity = $(resultIq).find('>conference').attr('identity');
  8718. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  8719. authenticationEnabled, authIdentity);
  8720. // Check if focus has auto-detected Jigasi component(this will be also
  8721. // included if we have passed our host from the config)
  8722. if ($(resultIq).find(
  8723. '>conference>property' +
  8724. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  8725. this.sipGatewayEnabled = true;
  8726. }
  8727. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  8728. };
  8729. // FIXME = we need to show the fact that we're waiting for the focus
  8730. // to the user(or that focus is not available)
  8731. Moderator.prototype.allocateConferenceFocus = function (callback) {
  8732. // Try to use focus user JID from the config
  8733. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  8734. // Send create conference IQ
  8735. var iq = this.createConferenceIq();
  8736. var self = this;
  8737. this.connection.sendIQ(
  8738. iq,
  8739. function (result) {
  8740. // Setup config options
  8741. self.parseConfigOptions(result);
  8742. if ('true' === $(result).find('conference').attr('ready')) {
  8743. // Reset both timers
  8744. self.getNextTimeout(true);
  8745. self.getNextErrorTimeout(true);
  8746. // Exec callback
  8747. callback();
  8748. } else {
  8749. var waitMs = self.getNextTimeout();
  8750. logger.info("Waiting for the focus... " + waitMs);
  8751. // Reset error timeout
  8752. self.getNextErrorTimeout(true);
  8753. window.setTimeout(
  8754. function () {
  8755. self.allocateConferenceFocus(callback);
  8756. }, waitMs);
  8757. }
  8758. },
  8759. function (error) {
  8760. // Invalid session ? remove and try again
  8761. // without session ID to get a new one
  8762. var invalidSession
  8763. = $(error).find('>error>session-invalid').length;
  8764. if (invalidSession) {
  8765. logger.info("Session expired! - removing");
  8766. localStorage.removeItem("sessionId");
  8767. }
  8768. if ($(error).find('>error>graceful-shutdown').length) {
  8769. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  8770. return;
  8771. }
  8772. // Check for error returned by the reservation system
  8773. var reservationErr = $(error).find('>error>reservation-error');
  8774. if (reservationErr.length) {
  8775. // Trigger error event
  8776. var errorCode = reservationErr.attr('error-code');
  8777. var errorMsg;
  8778. if ($(error).find('>error>text')) {
  8779. errorMsg = $(error).find('>error>text').text();
  8780. }
  8781. self.eventEmitter.emit(
  8782. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  8783. return;
  8784. }
  8785. // Not authorized to create new room
  8786. if ($(error).find('>error>not-authorized').length) {
  8787. logger.warn("Unauthorized to start the conference", error);
  8788. var toDomain
  8789. = Strophe.getDomainFromJid(error.getAttribute('to'));
  8790. if (toDomain !==
  8791. this.xmppService.options.hosts.anonymousdomain) {
  8792. //FIXME: "is external" should come either from
  8793. // the focus or config.js
  8794. self.externalAuthEnabled = true;
  8795. }
  8796. self.eventEmitter.emit(
  8797. XMPPEvents.AUTHENTICATION_REQUIRED,
  8798. function () {
  8799. self.allocateConferenceFocus(
  8800. callback);
  8801. });
  8802. return;
  8803. }
  8804. var waitMs = self.getNextErrorTimeout();
  8805. logger.error("Focus error, retry after " + waitMs, error);
  8806. // Show message
  8807. var focusComponent = self.getFocusComponent();
  8808. var retrySec = waitMs / 1000;
  8809. //FIXME: message is duplicated ?
  8810. // Do not show in case of session invalid
  8811. // which means just a retry
  8812. if (!invalidSession) {
  8813. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  8814. focusComponent, retrySec);
  8815. }
  8816. // Reset response timeout
  8817. self.getNextTimeout(true);
  8818. window.setTimeout(
  8819. function () {
  8820. self.allocateConferenceFocus(callback);
  8821. }, waitMs);
  8822. }
  8823. );
  8824. };
  8825. Moderator.prototype.getLoginUrl = function (urlCallback) {
  8826. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  8827. iq.c('login-url', {
  8828. xmlns: 'http://jitsi.org/protocol/focus',
  8829. room: this.roomName,
  8830. 'machine-uid': this.settings.getSettings().uid
  8831. });
  8832. this.connection.sendIQ(
  8833. iq,
  8834. function (result) {
  8835. var url = $(result).find('login-url').attr('url');
  8836. url = url = decodeURIComponent(url);
  8837. if (url) {
  8838. logger.info("Got auth url: " + url);
  8839. urlCallback(url);
  8840. } else {
  8841. logger.error(
  8842. "Failed to get auth url from the focus", result);
  8843. }
  8844. },
  8845. function (error) {
  8846. logger.error("Get auth url error", error);
  8847. }
  8848. );
  8849. };
  8850. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  8851. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  8852. iq.c('login-url', {
  8853. xmlns: 'http://jitsi.org/protocol/focus',
  8854. room: this.roomName,
  8855. 'machine-uid': this.settings.getSettings().uid,
  8856. popup: true
  8857. });
  8858. this.connection.sendIQ(
  8859. iq,
  8860. function (result) {
  8861. var url = $(result).find('login-url').attr('url');
  8862. url = url = decodeURIComponent(url);
  8863. if (url) {
  8864. logger.info("Got POPUP auth url: " + url);
  8865. urlCallback(url);
  8866. } else {
  8867. logger.error(
  8868. "Failed to get POPUP auth url from the focus", result);
  8869. }
  8870. },
  8871. function (error) {
  8872. logger.error('Get POPUP auth url error', error);
  8873. }
  8874. );
  8875. };
  8876. Moderator.prototype.logout = function (callback) {
  8877. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  8878. var sessionId = localStorage.getItem('sessionId');
  8879. if (!sessionId) {
  8880. callback();
  8881. return;
  8882. }
  8883. iq.c('logout', {
  8884. xmlns: 'http://jitsi.org/protocol/focus',
  8885. 'session-id': sessionId
  8886. });
  8887. this.connection.sendIQ(
  8888. iq,
  8889. function (result) {
  8890. var logoutUrl = $(result).find('logout').attr('logout-url');
  8891. if (logoutUrl) {
  8892. logoutUrl = decodeURIComponent(logoutUrl);
  8893. }
  8894. logger.info("Log out OK, url: " + logoutUrl, result);
  8895. localStorage.removeItem('sessionId');
  8896. callback(logoutUrl);
  8897. },
  8898. function (error) {
  8899. logger.error("Logout error", error);
  8900. }
  8901. );
  8902. };
  8903. module.exports = Moderator;
  8904. }).call(this,"/modules/xmpp/moderator.js")
  8905. },{"../../service/authentication/AuthenticationEvents":79,"../../service/xmpp/XMPPEvents":82,"../settings/Settings":18,"jitsi-meet-logger":44}],32:[function(require,module,exports){
  8906. (function (__filename){
  8907. /* jshint -W117 */
  8908. /* a simple MUC connection plugin
  8909. * can only handle a single MUC room
  8910. */
  8911. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8912. var ChatRoom = require("./ChatRoom");
  8913. module.exports = function(XMPP) {
  8914. Strophe.addConnectionPlugin('emuc', {
  8915. connection: null,
  8916. rooms: {},//map with the rooms
  8917. init: function (conn) {
  8918. this.connection = conn;
  8919. // add handlers (just once)
  8920. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  8921. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  8922. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  8923. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  8924. },
  8925. createRoom: function (jid, password, options) {
  8926. var roomJid = Strophe.getBareJidFromJid(jid);
  8927. if (this.rooms[roomJid]) {
  8928. logger.error("You are already in the room!");
  8929. return;
  8930. }
  8931. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  8932. return this.rooms[roomJid];
  8933. },
  8934. doLeave: function (jid) {
  8935. this.rooms[jid].doLeave();
  8936. delete this.rooms[jid];
  8937. },
  8938. onPresence: function (pres) {
  8939. var from = pres.getAttribute('from');
  8940. // What is this for? A workaround for something?
  8941. if (pres.getAttribute('type')) {
  8942. return true;
  8943. }
  8944. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8945. if(!room)
  8946. return;
  8947. // Parse status.
  8948. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  8949. room.createNonAnonymousRoom();
  8950. }
  8951. room.onPresence(pres);
  8952. return true;
  8953. },
  8954. onPresenceUnavailable: function (pres) {
  8955. var from = pres.getAttribute('from');
  8956. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8957. if(!room)
  8958. return;
  8959. room.onPresenceUnavailable(pres, from);
  8960. return true;
  8961. },
  8962. onPresenceError: function (pres) {
  8963. var from = pres.getAttribute('from');
  8964. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8965. if(!room)
  8966. return;
  8967. room.onPresenceError(pres, from);
  8968. return true;
  8969. },
  8970. onMessage: function (msg) {
  8971. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  8972. var from = msg.getAttribute('from');
  8973. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8974. if(!room)
  8975. return;
  8976. room.onMessage(msg, from);
  8977. return true;
  8978. },
  8979. setJingleSession: function (from, session) {
  8980. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8981. if(!room)
  8982. return;
  8983. room.setJingleSession(session);
  8984. }
  8985. });
  8986. };
  8987. }).call(this,"/modules/xmpp/strophe.emuc.js")
  8988. },{"./ChatRoom":23,"jitsi-meet-logger":44}],33:[function(require,module,exports){
  8989. (function (__filename){
  8990. /* jshint -W117 */
  8991. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8992. var JingleSession = require("./JingleSessionPC");
  8993. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8994. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8995. module.exports = function(XMPP, eventEmitter) {
  8996. Strophe.addConnectionPlugin('jingle', {
  8997. connection: null,
  8998. sessions: {},
  8999. jid2session: {},
  9000. ice_config: {iceServers: []},
  9001. media_constraints: {
  9002. mandatory: {
  9003. 'OfferToReceiveAudio': true,
  9004. 'OfferToReceiveVideo': true
  9005. }
  9006. // MozDontOfferDataChannel: true when this is firefox
  9007. },
  9008. init: function (conn) {
  9009. this.connection = conn;
  9010. if (this.connection.disco) {
  9011. // http://xmpp.org/extensions/xep-0167.html#support
  9012. // http://xmpp.org/extensions/xep-0176.html#support
  9013. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9014. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9015. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9016. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9017. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9018. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9019. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9020. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9021. || RTCBrowserType.isTemasysPluginUsed()) {
  9022. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9023. }
  9024. // this is dealt with by SDP O/A so we don't need to announce this
  9025. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9026. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9027. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9028. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9029. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9030. }
  9031. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9032. },
  9033. onJingle: function (iq) {
  9034. var sid = $(iq).find('jingle').attr('sid');
  9035. var action = $(iq).find('jingle').attr('action');
  9036. var fromJid = iq.getAttribute('from');
  9037. // send ack first
  9038. var ack = $iq({type: 'result',
  9039. to: fromJid,
  9040. id: iq.getAttribute('id')
  9041. });
  9042. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9043. var sess = this.sessions[sid];
  9044. if ('session-initiate' != action) {
  9045. if (sess === null) {
  9046. ack.type = 'error';
  9047. ack.c('error', {type: 'cancel'})
  9048. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9049. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9050. this.connection.send(ack);
  9051. return true;
  9052. }
  9053. // local jid is not checked
  9054. if (fromJid != sess.peerjid) {
  9055. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9056. ack.type = 'error';
  9057. ack.c('error', {type: 'cancel'})
  9058. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9059. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9060. this.connection.send(ack);
  9061. return true;
  9062. }
  9063. } else if (sess !== undefined) {
  9064. // existing session with same session id
  9065. // this might be out-of-order if the sess.peerjid is the same as from
  9066. ack.type = 'error';
  9067. ack.c('error', {type: 'cancel'})
  9068. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9069. logger.warn('duplicate session id', sid);
  9070. this.connection.send(ack);
  9071. return true;
  9072. }
  9073. // FIXME: check for a defined action
  9074. this.connection.send(ack);
  9075. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9076. switch (action) {
  9077. case 'session-initiate':
  9078. var startMuted = $(iq).find('jingle>startmuted');
  9079. if (startMuted && startMuted.length > 0) {
  9080. var audioMuted = startMuted.attr("audio");
  9081. var videoMuted = startMuted.attr("video");
  9082. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9083. audioMuted === "true", videoMuted === "true");
  9084. }
  9085. sess = new JingleSession(
  9086. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9087. this.connection, XMPP);
  9088. // configure session
  9089. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9090. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9091. sess.media_constraints = this.media_constraints;
  9092. sess.ice_config = this.ice_config;
  9093. sess.initialize(fromJid, false);
  9094. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9095. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9096. sess.setOffer($(iq).find('>jingle'));
  9097. this.sessions[sess.sid] = sess;
  9098. this.jid2session[sess.peerjid] = sess;
  9099. // the callback should either
  9100. // .sendAnswer and .accept
  9101. // or .sendTerminate -- not necessarily synchronous
  9102. sess.sendAnswer();
  9103. sess.accept();
  9104. break;
  9105. case 'session-accept':
  9106. sess.setAnswer($(iq).find('>jingle'));
  9107. sess.accept();
  9108. break;
  9109. case 'session-terminate':
  9110. // If this is not the focus sending the terminate, we have
  9111. // nothing more to do here.
  9112. if (Object.keys(this.sessions).length < 1
  9113. || !(this.sessions[Object.keys(this.sessions)[0]]
  9114. instanceof JingleSession))
  9115. {
  9116. break;
  9117. }
  9118. logger.log('terminating...', sess.sid);
  9119. sess.terminate();
  9120. this.terminate(sess.sid);
  9121. if ($(iq).find('>jingle>reason').length) {
  9122. $(document).trigger('callterminated.jingle', [
  9123. sess.sid,
  9124. sess.peerjid,
  9125. $(iq).find('>jingle>reason>:first')[0].tagName,
  9126. $(iq).find('>jingle>reason>text').text()
  9127. ]);
  9128. } else {
  9129. $(document).trigger('callterminated.jingle',
  9130. [sess.sid, sess.peerjid]);
  9131. }
  9132. break;
  9133. case 'transport-info':
  9134. sess.addIceCandidate($(iq).find('>jingle>content'));
  9135. break;
  9136. case 'session-info':
  9137. var affected;
  9138. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9139. $(document).trigger('ringing.jingle', [sess.sid]);
  9140. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9141. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9142. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9143. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9144. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9145. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9146. }
  9147. break;
  9148. case 'addsource': // FIXME: proprietary, un-jingleish
  9149. case 'source-add': // FIXME: proprietary
  9150. sess.addSource($(iq).find('>jingle>content'), fromJid);
  9151. break;
  9152. case 'removesource': // FIXME: proprietary, un-jingleish
  9153. case 'source-remove': // FIXME: proprietary
  9154. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  9155. break;
  9156. default:
  9157. logger.warn('jingle action not implemented', action);
  9158. break;
  9159. }
  9160. return true;
  9161. },
  9162. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9163. if (sid === null || sid === undefined) {
  9164. for (sid in this.sessions) {
  9165. if (this.sessions[sid].state != 'ended') {
  9166. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9167. this.sessions[sid].terminate();
  9168. }
  9169. delete this.jid2session[this.sessions[sid].peerjid];
  9170. delete this.sessions[sid];
  9171. }
  9172. } else if (this.sessions.hasOwnProperty(sid)) {
  9173. if (this.sessions[sid].state != 'ended') {
  9174. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9175. this.sessions[sid].terminate();
  9176. }
  9177. delete this.jid2session[this.sessions[sid].peerjid];
  9178. delete this.sessions[sid];
  9179. }
  9180. },
  9181. getStunAndTurnCredentials: function () {
  9182. // get stun and turn configuration from server via xep-0215
  9183. // uses time-limited credentials as described in
  9184. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9185. //
  9186. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9187. // for a prosody module which implements this
  9188. //
  9189. // currently, this doesn't work with updateIce and therefore credentials with a long
  9190. // validity have to be fetched before creating the peerconnection
  9191. // TODO: implement refresh via updateIce as described in
  9192. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9193. var self = this;
  9194. this.connection.sendIQ(
  9195. $iq({type: 'get', to: this.connection.domain})
  9196. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9197. function (res) {
  9198. var iceservers = [];
  9199. $(res).find('>services>service').each(function (idx, el) {
  9200. el = $(el);
  9201. var dict = {};
  9202. var type = el.attr('type');
  9203. switch (type) {
  9204. case 'stun':
  9205. dict.url = 'stun:' + el.attr('host');
  9206. if (el.attr('port')) {
  9207. dict.url += ':' + el.attr('port');
  9208. }
  9209. iceservers.push(dict);
  9210. break;
  9211. case 'turn':
  9212. case 'turns':
  9213. dict.url = type + ':';
  9214. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  9215. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  9216. dict.url += el.attr('username') + '@';
  9217. } else {
  9218. dict.username = el.attr('username'); // only works in M28
  9219. }
  9220. }
  9221. dict.url += el.attr('host');
  9222. if (el.attr('port') && el.attr('port') != '3478') {
  9223. dict.url += ':' + el.attr('port');
  9224. }
  9225. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9226. dict.url += '?transport=' + el.attr('transport');
  9227. }
  9228. if (el.attr('password')) {
  9229. dict.credential = el.attr('password');
  9230. }
  9231. iceservers.push(dict);
  9232. break;
  9233. }
  9234. });
  9235. self.ice_config.iceServers = iceservers;
  9236. },
  9237. function (err) {
  9238. logger.warn('getting turn credentials failed', err);
  9239. logger.warn('is mod_turncredentials or similar installed?');
  9240. }
  9241. );
  9242. // implement push?
  9243. },
  9244. /**
  9245. * Returns the data saved in 'updateLog' in a format to be logged.
  9246. */
  9247. getLog: function () {
  9248. var data = {};
  9249. var self = this;
  9250. Object.keys(this.sessions).forEach(function (sid) {
  9251. var session = self.sessions[sid];
  9252. if (session.peerconnection && session.peerconnection.updateLog) {
  9253. // FIXME: should probably be a .dump call
  9254. data["jingle_" + session.sid] = {
  9255. updateLog: session.peerconnection.updateLog,
  9256. stats: session.peerconnection.stats,
  9257. url: window.location.href
  9258. };
  9259. }
  9260. });
  9261. return data;
  9262. }
  9263. });
  9264. };
  9265. }).call(this,"/modules/xmpp/strophe.jingle.js")
  9266. },{"../../service/xmpp/XMPPEvents":82,"../RTC/RTCBrowserType":14,"./JingleSessionPC":25,"jitsi-meet-logger":44}],34:[function(require,module,exports){
  9267. /* global Strophe */
  9268. module.exports = function () {
  9269. Strophe.addConnectionPlugin('logger', {
  9270. // logs raw stanzas and makes them available for download as JSON
  9271. connection: null,
  9272. log: [],
  9273. init: function (conn) {
  9274. this.connection = conn;
  9275. this.connection.rawInput = this.log_incoming.bind(this);
  9276. this.connection.rawOutput = this.log_outgoing.bind(this);
  9277. },
  9278. log_incoming: function (stanza) {
  9279. this.log.push([new Date().getTime(), 'incoming', stanza]);
  9280. },
  9281. log_outgoing: function (stanza) {
  9282. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  9283. }
  9284. });
  9285. };
  9286. },{}],35:[function(require,module,exports){
  9287. /* global $, $iq, Strophe */
  9288. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9289. /**
  9290. * Ping every 20 sec
  9291. */
  9292. var PING_INTERVAL = 20000;
  9293. /**
  9294. * Ping timeout error after 15 sec of waiting.
  9295. */
  9296. var PING_TIMEOUT = 15000;
  9297. /**
  9298. * Will close the connection after 3 consecutive ping errors.
  9299. */
  9300. var PING_THRESHOLD = 3;
  9301. /**
  9302. * XEP-0199 ping plugin.
  9303. *
  9304. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  9305. */
  9306. module.exports = function (XMPP, eventEmitter) {
  9307. Strophe.addConnectionPlugin('ping', {
  9308. connection: null,
  9309. failedPings: 0,
  9310. /**
  9311. * Initializes the plugin. Method called by Strophe.
  9312. * @param connection Strophe connection instance.
  9313. */
  9314. init: function (connection) {
  9315. this.connection = connection;
  9316. Strophe.addNamespace('PING', "urn:xmpp:ping");
  9317. },
  9318. /**
  9319. * Sends "ping" to given <tt>jid</tt>
  9320. * @param jid the JID to which ping request will be sent.
  9321. * @param success callback called on success.
  9322. * @param error callback called on error.
  9323. * @param timeout ms how long are we going to wait for the response. On
  9324. * timeout <tt>error<//t> callback is called with undefined error
  9325. * argument.
  9326. */
  9327. ping: function (jid, success, error, timeout) {
  9328. var iq = $iq({type: 'get', to: jid});
  9329. iq.c('ping', {xmlns: Strophe.NS.PING});
  9330. this.connection.sendIQ(iq, success, error, timeout);
  9331. },
  9332. /**
  9333. * Starts to send ping in given interval to specified remote JID.
  9334. * This plugin supports only one such task and <tt>stopInterval</tt>
  9335. * must be called before starting a new one.
  9336. * @param remoteJid remote JID to which ping requests will be sent to.
  9337. * @param interval task interval in ms.
  9338. */
  9339. startInterval: function (remoteJid, interval) {
  9340. if (this.intervalId) {
  9341. console.error("Ping task scheduled already");
  9342. return;
  9343. }
  9344. if (!interval)
  9345. interval = PING_INTERVAL;
  9346. var self = this;
  9347. this.intervalId = window.setInterval(function () {
  9348. self.ping(remoteJid,
  9349. function (result) {
  9350. // Ping OK
  9351. self.failedPings = 0;
  9352. },
  9353. function (error) {
  9354. self.failedPings += 1;
  9355. console.error(
  9356. "Ping " + (error ? "error" : "timeout"), error);
  9357. if (self.failedPings >= PING_THRESHOLD) {
  9358. self.connection.disconnect();
  9359. }
  9360. }, PING_TIMEOUT);
  9361. }, interval);
  9362. console.info("XMPP pings will be sent every " + interval + " ms");
  9363. },
  9364. /**
  9365. * Stops current "ping" interval task.
  9366. */
  9367. stopInterval: function () {
  9368. if (this.intervalId) {
  9369. window.clearInterval(this.intervalId);
  9370. this.intervalId = null;
  9371. this.failedPings = 0;
  9372. console.info("Ping interval cleared");
  9373. }
  9374. }
  9375. });
  9376. };
  9377. },{"../../service/xmpp/XMPPEvents":82}],36:[function(require,module,exports){
  9378. (function (__filename){
  9379. /* jshint -W117 */
  9380. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9381. module.exports = function() {
  9382. Strophe.addConnectionPlugin('rayo',
  9383. {
  9384. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  9385. connection: null,
  9386. init: function (conn) {
  9387. this.connection = conn;
  9388. if (this.connection.disco) {
  9389. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  9390. }
  9391. this.connection.addHandler(
  9392. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  9393. },
  9394. onRayo: function (iq) {
  9395. logger.info("Rayo IQ", iq);
  9396. },
  9397. dial: function (to, from, roomName, roomPass) {
  9398. var self = this;
  9399. var req = $iq(
  9400. {
  9401. type: 'set',
  9402. to: this.connection.emuc.focusMucJid
  9403. }
  9404. );
  9405. req.c('dial',
  9406. {
  9407. xmlns: this.RAYO_XMLNS,
  9408. to: to,
  9409. from: from
  9410. });
  9411. req.c('header',
  9412. {
  9413. name: 'JvbRoomName',
  9414. value: roomName
  9415. }).up();
  9416. if (roomPass !== null && roomPass.length) {
  9417. req.c('header',
  9418. {
  9419. name: 'JvbRoomPassword',
  9420. value: roomPass
  9421. }).up();
  9422. }
  9423. this.connection.sendIQ(
  9424. req,
  9425. function (result) {
  9426. logger.info('Dial result ', result);
  9427. var resource = $(result).find('ref').attr('uri');
  9428. this.call_resource = resource.substr('xmpp:'.length);
  9429. logger.info(
  9430. "Received call resource: " + this.call_resource);
  9431. },
  9432. function (error) {
  9433. logger.info('Dial error ', error);
  9434. }
  9435. );
  9436. },
  9437. hang_up: function () {
  9438. if (!this.call_resource) {
  9439. logger.warn("No call in progress");
  9440. return;
  9441. }
  9442. var self = this;
  9443. var req = $iq(
  9444. {
  9445. type: 'set',
  9446. to: this.call_resource
  9447. }
  9448. );
  9449. req.c('hangup',
  9450. {
  9451. xmlns: this.RAYO_XMLNS
  9452. });
  9453. this.connection.sendIQ(
  9454. req,
  9455. function (result) {
  9456. logger.info('Hangup result ', result);
  9457. self.call_resource = null;
  9458. },
  9459. function (error) {
  9460. logger.info('Hangup error ', error);
  9461. self.call_resource = null;
  9462. }
  9463. );
  9464. }
  9465. }
  9466. );
  9467. };
  9468. }).call(this,"/modules/xmpp/strophe.rayo.js")
  9469. },{"jitsi-meet-logger":44}],37:[function(require,module,exports){
  9470. (function (__filename){
  9471. /**
  9472. * Strophe logger implementation. Logs from level WARN and above.
  9473. */
  9474. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9475. module.exports = function () {
  9476. Strophe.log = function (level, msg) {
  9477. switch (level) {
  9478. case Strophe.LogLevel.WARN:
  9479. logger.warn("Strophe: " + msg);
  9480. break;
  9481. case Strophe.LogLevel.ERROR:
  9482. case Strophe.LogLevel.FATAL:
  9483. logger.error("Strophe: " + msg);
  9484. break;
  9485. }
  9486. };
  9487. Strophe.getStatusString = function (status) {
  9488. switch (status) {
  9489. case Strophe.Status.ERROR:
  9490. return "ERROR";
  9491. case Strophe.Status.CONNECTING:
  9492. return "CONNECTING";
  9493. case Strophe.Status.CONNFAIL:
  9494. return "CONNFAIL";
  9495. case Strophe.Status.AUTHENTICATING:
  9496. return "AUTHENTICATING";
  9497. case Strophe.Status.AUTHFAIL:
  9498. return "AUTHFAIL";
  9499. case Strophe.Status.CONNECTED:
  9500. return "CONNECTED";
  9501. case Strophe.Status.DISCONNECTED:
  9502. return "DISCONNECTED";
  9503. case Strophe.Status.DISCONNECTING:
  9504. return "DISCONNECTING";
  9505. case Strophe.Status.ATTACHED:
  9506. return "ATTACHED";
  9507. default:
  9508. return "unknown";
  9509. }
  9510. };
  9511. };
  9512. }).call(this,"/modules/xmpp/strophe.util.js")
  9513. },{"jitsi-meet-logger":44}],38:[function(require,module,exports){
  9514. (function (__filename){
  9515. /* global $, APP, config, Strophe*/
  9516. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9517. var EventEmitter = require("events");
  9518. var Pako = require("pako");
  9519. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9520. var RTCEvents = require("../../service/RTC/RTCEvents");
  9521. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9522. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  9523. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9524. var RTC = require("../RTC/RTC");
  9525. var authenticatedUser = false;
  9526. function createConnection(bosh) {
  9527. bosh = bosh || '/http-bind';
  9528. return new Strophe.Connection(bosh);
  9529. };
  9530. //!!!!!!!!!! FIXME: ...
  9531. function initStrophePlugins(XMPP)
  9532. {
  9533. require("./strophe.emuc")(XMPP);
  9534. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  9535. // require("./strophe.moderate")(XMPP, eventEmitter);
  9536. require("./strophe.util")();
  9537. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  9538. require("./strophe.rayo")();
  9539. require("./strophe.logger")();
  9540. }
  9541. //!!!!!!!!!! FIXME: ...
  9542. ///**
  9543. // * If given <tt>localStream</tt> is video one this method will advertise it's
  9544. // * video type in MUC presence.
  9545. // * @param localStream new or modified <tt>LocalStream</tt>.
  9546. // */
  9547. //function broadcastLocalVideoType(localStream) {
  9548. // if (localStream.videoType)
  9549. // XMPP.addToPresence('videoType', localStream.videoType);
  9550. //}
  9551. //
  9552. //function registerListeners() {
  9553. // RTC.addStreamListener(
  9554. // broadcastLocalVideoType,
  9555. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  9556. // );
  9557. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  9558. // XMPP.addToPresence("devices", devices);
  9559. // });
  9560. //}
  9561. function XMPP(options) {
  9562. this.eventEmitter = new EventEmitter();
  9563. this.connection = null;
  9564. this.disconnectInProgress = false;
  9565. this.forceMuted = false;
  9566. this.options = options;
  9567. initStrophePlugins(this);
  9568. // registerListeners();
  9569. this.connection = createConnection(options.bosh);
  9570. }
  9571. XMPP.prototype.getConnection = function(){ return connection; };
  9572. XMPP.prototype._connect = function (jid, password) {
  9573. var self = this;
  9574. // connection.connect() starts the connection process.
  9575. //
  9576. // As the connection process proceeds, the user supplied callback will
  9577. // be triggered multiple times with status updates. The callback should
  9578. // take two arguments - the status code and the error condition.
  9579. //
  9580. // The status code will be one of the values in the Strophe.Status
  9581. // constants. The error condition will be one of the conditions defined
  9582. // in RFC 3920 or the condition ‘strophe-parsererror’.
  9583. //
  9584. // The Parameters wait, hold and route are optional and only relevant
  9585. // for BOSH connections. Please see XEP 124 for a more detailed
  9586. // explanation of the optional parameters.
  9587. //
  9588. // Connection status constants for use by the connection handler
  9589. // callback.
  9590. //
  9591. // Status.ERROR - An error has occurred (websockets specific)
  9592. // Status.CONNECTING - The connection is currently being made
  9593. // Status.CONNFAIL - The connection attempt failed
  9594. // Status.AUTHENTICATING - The connection is authenticating
  9595. // Status.AUTHFAIL - The authentication attempt failed
  9596. // Status.CONNECTED - The connection has succeeded
  9597. // Status.DISCONNECTED - The connection has been terminated
  9598. // Status.DISCONNECTING - The connection is currently being terminated
  9599. // Status.ATTACHED - The connection has been attached
  9600. var anonymousConnectionFailed = false;
  9601. var connectionFailed = false;
  9602. var lastErrorMsg;
  9603. this.connection.connect(jid, password, function (status, msg) {
  9604. logger.log('Strophe status changed to',
  9605. Strophe.getStatusString(status), msg);
  9606. if (status === Strophe.Status.CONNECTED) {
  9607. if (self.options.useStunTurn) {
  9608. self.connection.jingle.getStunAndTurnCredentials();
  9609. }
  9610. logger.info("My Jabber ID: " + self.connection.jid);
  9611. self.connection.ping.startInterval(
  9612. Strophe.getDomainFromJid(self.connection.jid));
  9613. if (password)
  9614. authenticatedUser = true;
  9615. if (self.connection && self.connection.connected &&
  9616. Strophe.getResourceFromJid(self.connection.jid)) {
  9617. // .connected is true while connecting?
  9618. // self.connection.send($pres());
  9619. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  9620. Strophe.getResourceFromJid(self.connection.jid));
  9621. }
  9622. } else if (status === Strophe.Status.CONNFAIL) {
  9623. if (msg === 'x-strophe-bad-non-anon-jid') {
  9624. anonymousConnectionFailed = true;
  9625. }
  9626. else
  9627. {
  9628. connectionFailed = true;
  9629. }
  9630. lastErrorMsg = msg;
  9631. } else if (status === Strophe.Status.DISCONNECTED) {
  9632. // Stop ping interval
  9633. self.connection.ping.stopInterval();
  9634. self.disconnectInProgress = false;
  9635. if (anonymousConnectionFailed) {
  9636. // prompt user for username and password
  9637. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9638. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9639. } else if(connectionFailed) {
  9640. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9641. JitsiConnectionErrors.OTHER_ERROR,
  9642. msg ? msg : lastErrorMsg);
  9643. } else {
  9644. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  9645. msg ? msg : lastErrorMsg);
  9646. }
  9647. } else if (status === Strophe.Status.AUTHFAIL) {
  9648. // wrong password or username, prompt user
  9649. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9650. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9651. }
  9652. });
  9653. }
  9654. XMPP.prototype.connect = function (jid, password) {
  9655. if(!jid) {
  9656. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  9657. // Force authenticated domain if room is appended with '?login=true'
  9658. if (this.options.hosts.anonymousdomain &&
  9659. window.location.search.indexOf("login=true") !== -1) {
  9660. configDomain = this.options.hosts.domain;
  9661. }
  9662. jid = configDomain || window.location.hostname;
  9663. }
  9664. return this._connect(jid, password);
  9665. };
  9666. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  9667. var roomjid = roomName + '@' + this.options.hosts.muc;
  9668. if (useNicks) {
  9669. if (nick) {
  9670. roomjid += '/' + nick;
  9671. } else {
  9672. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  9673. }
  9674. } else {
  9675. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  9676. if(!authenticatedUser)
  9677. tmpJid = tmpJid.substr(0, 8);
  9678. roomjid += '/' + tmpJid;
  9679. }
  9680. return this.connection.emuc.createRoom(roomjid, null, options);
  9681. }
  9682. XMPP.prototype.addListener = function(type, listener) {
  9683. this.eventEmitter.on(type, listener);
  9684. };
  9685. XMPP.prototype.removeListener = function (type, listener) {
  9686. this.eventEmitter.removeListener(type, listener);
  9687. };
  9688. //FIXME: this should work with the room
  9689. XMPP.prototype.leaveRoom = function (jid) {
  9690. var handler = this.connection.jingle.jid2session[jid];
  9691. if (handler && handler.peerconnection) {
  9692. // FIXME: probably removing streams is not required and close() should
  9693. // be enough
  9694. if (RTC.localAudio) {
  9695. handler.peerconnection.removeStream(
  9696. RTC.localAudio.getOriginalStream(), true);
  9697. }
  9698. if (RTC.localVideo) {
  9699. handler.peerconnection.removeStream(
  9700. RTC.localVideo.getOriginalStream(), true);
  9701. }
  9702. handler.peerconnection.close();
  9703. }
  9704. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  9705. this.connection.emuc.doLeave(jid);
  9706. };
  9707. /**
  9708. * Sends 'data' as a log message to the focus. Returns true iff a message
  9709. * was sent.
  9710. * @param data
  9711. * @returns {boolean} true iff a message was sent.
  9712. */
  9713. XMPP.prototype.sendLogs = function (data) {
  9714. if(!this.connection.emuc.focusMucJid)
  9715. return false;
  9716. var deflate = true;
  9717. var content = JSON.stringify(data);
  9718. if (deflate) {
  9719. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  9720. }
  9721. content = Base64.encode(content);
  9722. // XEP-0337-ish
  9723. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  9724. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  9725. id: 'PeerConnectionStats'});
  9726. message.c('message').t(content).up();
  9727. if (deflate) {
  9728. message.c('tag', {name: "deflated", value: "true"}).up();
  9729. }
  9730. message.up();
  9731. this.connection.send(message);
  9732. return true;
  9733. };
  9734. // Gets the logs from strophe.jingle.
  9735. XMPP.prototype.getJingleLog = function () {
  9736. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  9737. };
  9738. // Gets the logs from strophe.
  9739. XMPP.prototype.getXmppLog = function () {
  9740. return this.connection.logger ? this.connection.logger.log : null;
  9741. };
  9742. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  9743. this.connection.rayo.dial(to, from, roomName,roomPass);
  9744. };
  9745. XMPP.prototype.setMute = function (jid, mute) {
  9746. this.connection.moderate.setMute(jid, mute);
  9747. };
  9748. XMPP.prototype.eject = function (jid) {
  9749. this.connection.moderate.eject(jid);
  9750. };
  9751. XMPP.prototype.getSessions = function () {
  9752. return this.connection.jingle.sessions;
  9753. };
  9754. XMPP.prototype.disconnect = function () {
  9755. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  9756. {
  9757. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  9758. return;
  9759. }
  9760. this.disconnectInProgress = true;
  9761. this.connection.disconnect();
  9762. };
  9763. module.exports = XMPP;
  9764. }).call(this,"/modules/xmpp/xmpp.js")
  9765. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":76,"../../service/RTC/StreamEventTypes":78,"../../service/xmpp/XMPPEvents":82,"../RTC/RTC":13,"./strophe.emuc":32,"./strophe.jingle":33,"./strophe.logger":34,"./strophe.ping":35,"./strophe.rayo":36,"./strophe.util":37,"events":40,"jitsi-meet-logger":44,"pako":45}],39:[function(require,module,exports){
  9766. (function (process){
  9767. /*!
  9768. * async
  9769. * https://github.com/caolan/async
  9770. *
  9771. * Copyright 2010-2014 Caolan McMahon
  9772. * Released under the MIT license
  9773. */
  9774. /*jshint onevar: false, indent:4 */
  9775. /*global setImmediate: false, setTimeout: false, console: false */
  9776. (function () {
  9777. var async = {};
  9778. // global on the server, window in the browser
  9779. var root, previous_async;
  9780. root = this;
  9781. if (root != null) {
  9782. previous_async = root.async;
  9783. }
  9784. async.noConflict = function () {
  9785. root.async = previous_async;
  9786. return async;
  9787. };
  9788. function only_once(fn) {
  9789. var called = false;
  9790. return function() {
  9791. if (called) throw new Error("Callback was already called.");
  9792. called = true;
  9793. fn.apply(root, arguments);
  9794. }
  9795. }
  9796. //// cross-browser compatiblity functions ////
  9797. var _toString = Object.prototype.toString;
  9798. var _isArray = Array.isArray || function (obj) {
  9799. return _toString.call(obj) === '[object Array]';
  9800. };
  9801. var _each = function (arr, iterator) {
  9802. if (arr.forEach) {
  9803. return arr.forEach(iterator);
  9804. }
  9805. for (var i = 0; i < arr.length; i += 1) {
  9806. iterator(arr[i], i, arr);
  9807. }
  9808. };
  9809. var _map = function (arr, iterator) {
  9810. if (arr.map) {
  9811. return arr.map(iterator);
  9812. }
  9813. var results = [];
  9814. _each(arr, function (x, i, a) {
  9815. results.push(iterator(x, i, a));
  9816. });
  9817. return results;
  9818. };
  9819. var _reduce = function (arr, iterator, memo) {
  9820. if (arr.reduce) {
  9821. return arr.reduce(iterator, memo);
  9822. }
  9823. _each(arr, function (x, i, a) {
  9824. memo = iterator(memo, x, i, a);
  9825. });
  9826. return memo;
  9827. };
  9828. var _keys = function (obj) {
  9829. if (Object.keys) {
  9830. return Object.keys(obj);
  9831. }
  9832. var keys = [];
  9833. for (var k in obj) {
  9834. if (obj.hasOwnProperty(k)) {
  9835. keys.push(k);
  9836. }
  9837. }
  9838. return keys;
  9839. };
  9840. //// exported async module functions ////
  9841. //// nextTick implementation with browser-compatible fallback ////
  9842. if (typeof process === 'undefined' || !(process.nextTick)) {
  9843. if (typeof setImmediate === 'function') {
  9844. async.nextTick = function (fn) {
  9845. // not a direct alias for IE10 compatibility
  9846. setImmediate(fn);
  9847. };
  9848. async.setImmediate = async.nextTick;
  9849. }
  9850. else {
  9851. async.nextTick = function (fn) {
  9852. setTimeout(fn, 0);
  9853. };
  9854. async.setImmediate = async.nextTick;
  9855. }
  9856. }
  9857. else {
  9858. async.nextTick = process.nextTick;
  9859. if (typeof setImmediate !== 'undefined') {
  9860. async.setImmediate = function (fn) {
  9861. // not a direct alias for IE10 compatibility
  9862. setImmediate(fn);
  9863. };
  9864. }
  9865. else {
  9866. async.setImmediate = async.nextTick;
  9867. }
  9868. }
  9869. async.each = function (arr, iterator, callback) {
  9870. callback = callback || function () {};
  9871. if (!arr.length) {
  9872. return callback();
  9873. }
  9874. var completed = 0;
  9875. _each(arr, function (x) {
  9876. iterator(x, only_once(done) );
  9877. });
  9878. function done(err) {
  9879. if (err) {
  9880. callback(err);
  9881. callback = function () {};
  9882. }
  9883. else {
  9884. completed += 1;
  9885. if (completed >= arr.length) {
  9886. callback();
  9887. }
  9888. }
  9889. }
  9890. };
  9891. async.forEach = async.each;
  9892. async.eachSeries = function (arr, iterator, callback) {
  9893. callback = callback || function () {};
  9894. if (!arr.length) {
  9895. return callback();
  9896. }
  9897. var completed = 0;
  9898. var iterate = function () {
  9899. iterator(arr[completed], function (err) {
  9900. if (err) {
  9901. callback(err);
  9902. callback = function () {};
  9903. }
  9904. else {
  9905. completed += 1;
  9906. if (completed >= arr.length) {
  9907. callback();
  9908. }
  9909. else {
  9910. iterate();
  9911. }
  9912. }
  9913. });
  9914. };
  9915. iterate();
  9916. };
  9917. async.forEachSeries = async.eachSeries;
  9918. async.eachLimit = function (arr, limit, iterator, callback) {
  9919. var fn = _eachLimit(limit);
  9920. fn.apply(null, [arr, iterator, callback]);
  9921. };
  9922. async.forEachLimit = async.eachLimit;
  9923. var _eachLimit = function (limit) {
  9924. return function (arr, iterator, callback) {
  9925. callback = callback || function () {};
  9926. if (!arr.length || limit <= 0) {
  9927. return callback();
  9928. }
  9929. var completed = 0;
  9930. var started = 0;
  9931. var running = 0;
  9932. (function replenish () {
  9933. if (completed >= arr.length) {
  9934. return callback();
  9935. }
  9936. while (running < limit && started < arr.length) {
  9937. started += 1;
  9938. running += 1;
  9939. iterator(arr[started - 1], function (err) {
  9940. if (err) {
  9941. callback(err);
  9942. callback = function () {};
  9943. }
  9944. else {
  9945. completed += 1;
  9946. running -= 1;
  9947. if (completed >= arr.length) {
  9948. callback();
  9949. }
  9950. else {
  9951. replenish();
  9952. }
  9953. }
  9954. });
  9955. }
  9956. })();
  9957. };
  9958. };
  9959. var doParallel = function (fn) {
  9960. return function () {
  9961. var args = Array.prototype.slice.call(arguments);
  9962. return fn.apply(null, [async.each].concat(args));
  9963. };
  9964. };
  9965. var doParallelLimit = function(limit, fn) {
  9966. return function () {
  9967. var args = Array.prototype.slice.call(arguments);
  9968. return fn.apply(null, [_eachLimit(limit)].concat(args));
  9969. };
  9970. };
  9971. var doSeries = function (fn) {
  9972. return function () {
  9973. var args = Array.prototype.slice.call(arguments);
  9974. return fn.apply(null, [async.eachSeries].concat(args));
  9975. };
  9976. };
  9977. var _asyncMap = function (eachfn, arr, iterator, callback) {
  9978. arr = _map(arr, function (x, i) {
  9979. return {index: i, value: x};
  9980. });
  9981. if (!callback) {
  9982. eachfn(arr, function (x, callback) {
  9983. iterator(x.value, function (err) {
  9984. callback(err);
  9985. });
  9986. });
  9987. } else {
  9988. var results = [];
  9989. eachfn(arr, function (x, callback) {
  9990. iterator(x.value, function (err, v) {
  9991. results[x.index] = v;
  9992. callback(err);
  9993. });
  9994. }, function (err) {
  9995. callback(err, results);
  9996. });
  9997. }
  9998. };
  9999. async.map = doParallel(_asyncMap);
  10000. async.mapSeries = doSeries(_asyncMap);
  10001. async.mapLimit = function (arr, limit, iterator, callback) {
  10002. return _mapLimit(limit)(arr, iterator, callback);
  10003. };
  10004. var _mapLimit = function(limit) {
  10005. return doParallelLimit(limit, _asyncMap);
  10006. };
  10007. // reduce only has a series version, as doing reduce in parallel won't
  10008. // work in many situations.
  10009. async.reduce = function (arr, memo, iterator, callback) {
  10010. async.eachSeries(arr, function (x, callback) {
  10011. iterator(memo, x, function (err, v) {
  10012. memo = v;
  10013. callback(err);
  10014. });
  10015. }, function (err) {
  10016. callback(err, memo);
  10017. });
  10018. };
  10019. // inject alias
  10020. async.inject = async.reduce;
  10021. // foldl alias
  10022. async.foldl = async.reduce;
  10023. async.reduceRight = function (arr, memo, iterator, callback) {
  10024. var reversed = _map(arr, function (x) {
  10025. return x;
  10026. }).reverse();
  10027. async.reduce(reversed, memo, iterator, callback);
  10028. };
  10029. // foldr alias
  10030. async.foldr = async.reduceRight;
  10031. var _filter = function (eachfn, arr, iterator, callback) {
  10032. var results = [];
  10033. arr = _map(arr, function (x, i) {
  10034. return {index: i, value: x};
  10035. });
  10036. eachfn(arr, function (x, callback) {
  10037. iterator(x.value, function (v) {
  10038. if (v) {
  10039. results.push(x);
  10040. }
  10041. callback();
  10042. });
  10043. }, function (err) {
  10044. callback(_map(results.sort(function (a, b) {
  10045. return a.index - b.index;
  10046. }), function (x) {
  10047. return x.value;
  10048. }));
  10049. });
  10050. };
  10051. async.filter = doParallel(_filter);
  10052. async.filterSeries = doSeries(_filter);
  10053. // select alias
  10054. async.select = async.filter;
  10055. async.selectSeries = async.filterSeries;
  10056. var _reject = function (eachfn, arr, iterator, callback) {
  10057. var results = [];
  10058. arr = _map(arr, function (x, i) {
  10059. return {index: i, value: x};
  10060. });
  10061. eachfn(arr, function (x, callback) {
  10062. iterator(x.value, function (v) {
  10063. if (!v) {
  10064. results.push(x);
  10065. }
  10066. callback();
  10067. });
  10068. }, function (err) {
  10069. callback(_map(results.sort(function (a, b) {
  10070. return a.index - b.index;
  10071. }), function (x) {
  10072. return x.value;
  10073. }));
  10074. });
  10075. };
  10076. async.reject = doParallel(_reject);
  10077. async.rejectSeries = doSeries(_reject);
  10078. var _detect = function (eachfn, arr, iterator, main_callback) {
  10079. eachfn(arr, function (x, callback) {
  10080. iterator(x, function (result) {
  10081. if (result) {
  10082. main_callback(x);
  10083. main_callback = function () {};
  10084. }
  10085. else {
  10086. callback();
  10087. }
  10088. });
  10089. }, function (err) {
  10090. main_callback();
  10091. });
  10092. };
  10093. async.detect = doParallel(_detect);
  10094. async.detectSeries = doSeries(_detect);
  10095. async.some = function (arr, iterator, main_callback) {
  10096. async.each(arr, function (x, callback) {
  10097. iterator(x, function (v) {
  10098. if (v) {
  10099. main_callback(true);
  10100. main_callback = function () {};
  10101. }
  10102. callback();
  10103. });
  10104. }, function (err) {
  10105. main_callback(false);
  10106. });
  10107. };
  10108. // any alias
  10109. async.any = async.some;
  10110. async.every = function (arr, iterator, main_callback) {
  10111. async.each(arr, function (x, callback) {
  10112. iterator(x, function (v) {
  10113. if (!v) {
  10114. main_callback(false);
  10115. main_callback = function () {};
  10116. }
  10117. callback();
  10118. });
  10119. }, function (err) {
  10120. main_callback(true);
  10121. });
  10122. };
  10123. // all alias
  10124. async.all = async.every;
  10125. async.sortBy = function (arr, iterator, callback) {
  10126. async.map(arr, function (x, callback) {
  10127. iterator(x, function (err, criteria) {
  10128. if (err) {
  10129. callback(err);
  10130. }
  10131. else {
  10132. callback(null, {value: x, criteria: criteria});
  10133. }
  10134. });
  10135. }, function (err, results) {
  10136. if (err) {
  10137. return callback(err);
  10138. }
  10139. else {
  10140. var fn = function (left, right) {
  10141. var a = left.criteria, b = right.criteria;
  10142. return a < b ? -1 : a > b ? 1 : 0;
  10143. };
  10144. callback(null, _map(results.sort(fn), function (x) {
  10145. return x.value;
  10146. }));
  10147. }
  10148. });
  10149. };
  10150. async.auto = function (tasks, callback) {
  10151. callback = callback || function () {};
  10152. var keys = _keys(tasks);
  10153. var remainingTasks = keys.length
  10154. if (!remainingTasks) {
  10155. return callback();
  10156. }
  10157. var results = {};
  10158. var listeners = [];
  10159. var addListener = function (fn) {
  10160. listeners.unshift(fn);
  10161. };
  10162. var removeListener = function (fn) {
  10163. for (var i = 0; i < listeners.length; i += 1) {
  10164. if (listeners[i] === fn) {
  10165. listeners.splice(i, 1);
  10166. return;
  10167. }
  10168. }
  10169. };
  10170. var taskComplete = function () {
  10171. remainingTasks--
  10172. _each(listeners.slice(0), function (fn) {
  10173. fn();
  10174. });
  10175. };
  10176. addListener(function () {
  10177. if (!remainingTasks) {
  10178. var theCallback = callback;
  10179. // prevent final callback from calling itself if it errors
  10180. callback = function () {};
  10181. theCallback(null, results);
  10182. }
  10183. });
  10184. _each(keys, function (k) {
  10185. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  10186. var taskCallback = function (err) {
  10187. var args = Array.prototype.slice.call(arguments, 1);
  10188. if (args.length <= 1) {
  10189. args = args[0];
  10190. }
  10191. if (err) {
  10192. var safeResults = {};
  10193. _each(_keys(results), function(rkey) {
  10194. safeResults[rkey] = results[rkey];
  10195. });
  10196. safeResults[k] = args;
  10197. callback(err, safeResults);
  10198. // stop subsequent errors hitting callback multiple times
  10199. callback = function () {};
  10200. }
  10201. else {
  10202. results[k] = args;
  10203. async.setImmediate(taskComplete);
  10204. }
  10205. };
  10206. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  10207. var ready = function () {
  10208. return _reduce(requires, function (a, x) {
  10209. return (a && results.hasOwnProperty(x));
  10210. }, true) && !results.hasOwnProperty(k);
  10211. };
  10212. if (ready()) {
  10213. task[task.length - 1](taskCallback, results);
  10214. }
  10215. else {
  10216. var listener = function () {
  10217. if (ready()) {
  10218. removeListener(listener);
  10219. task[task.length - 1](taskCallback, results);
  10220. }
  10221. };
  10222. addListener(listener);
  10223. }
  10224. });
  10225. };
  10226. async.retry = function(times, task, callback) {
  10227. var DEFAULT_TIMES = 5;
  10228. var attempts = [];
  10229. // Use defaults if times not passed
  10230. if (typeof times === 'function') {
  10231. callback = task;
  10232. task = times;
  10233. times = DEFAULT_TIMES;
  10234. }
  10235. // Make sure times is a number
  10236. times = parseInt(times, 10) || DEFAULT_TIMES;
  10237. var wrappedTask = function(wrappedCallback, wrappedResults) {
  10238. var retryAttempt = function(task, finalAttempt) {
  10239. return function(seriesCallback) {
  10240. task(function(err, result){
  10241. seriesCallback(!err || finalAttempt, {err: err, result: result});
  10242. }, wrappedResults);
  10243. };
  10244. };
  10245. while (times) {
  10246. attempts.push(retryAttempt(task, !(times-=1)));
  10247. }
  10248. async.series(attempts, function(done, data){
  10249. data = data[data.length - 1];
  10250. (wrappedCallback || callback)(data.err, data.result);
  10251. });
  10252. }
  10253. // If a callback is passed, run this as a controll flow
  10254. return callback ? wrappedTask() : wrappedTask
  10255. };
  10256. async.waterfall = function (tasks, callback) {
  10257. callback = callback || function () {};
  10258. if (!_isArray(tasks)) {
  10259. var err = new Error('First argument to waterfall must be an array of functions');
  10260. return callback(err);
  10261. }
  10262. if (!tasks.length) {
  10263. return callback();
  10264. }
  10265. var wrapIterator = function (iterator) {
  10266. return function (err) {
  10267. if (err) {
  10268. callback.apply(null, arguments);
  10269. callback = function () {};
  10270. }
  10271. else {
  10272. var args = Array.prototype.slice.call(arguments, 1);
  10273. var next = iterator.next();
  10274. if (next) {
  10275. args.push(wrapIterator(next));
  10276. }
  10277. else {
  10278. args.push(callback);
  10279. }
  10280. async.setImmediate(function () {
  10281. iterator.apply(null, args);
  10282. });
  10283. }
  10284. };
  10285. };
  10286. wrapIterator(async.iterator(tasks))();
  10287. };
  10288. var _parallel = function(eachfn, tasks, callback) {
  10289. callback = callback || function () {};
  10290. if (_isArray(tasks)) {
  10291. eachfn.map(tasks, function (fn, callback) {
  10292. if (fn) {
  10293. fn(function (err) {
  10294. var args = Array.prototype.slice.call(arguments, 1);
  10295. if (args.length <= 1) {
  10296. args = args[0];
  10297. }
  10298. callback.call(null, err, args);
  10299. });
  10300. }
  10301. }, callback);
  10302. }
  10303. else {
  10304. var results = {};
  10305. eachfn.each(_keys(tasks), function (k, callback) {
  10306. tasks[k](function (err) {
  10307. var args = Array.prototype.slice.call(arguments, 1);
  10308. if (args.length <= 1) {
  10309. args = args[0];
  10310. }
  10311. results[k] = args;
  10312. callback(err);
  10313. });
  10314. }, function (err) {
  10315. callback(err, results);
  10316. });
  10317. }
  10318. };
  10319. async.parallel = function (tasks, callback) {
  10320. _parallel({ map: async.map, each: async.each }, tasks, callback);
  10321. };
  10322. async.parallelLimit = function(tasks, limit, callback) {
  10323. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  10324. };
  10325. async.series = function (tasks, callback) {
  10326. callback = callback || function () {};
  10327. if (_isArray(tasks)) {
  10328. async.mapSeries(tasks, function (fn, callback) {
  10329. if (fn) {
  10330. fn(function (err) {
  10331. var args = Array.prototype.slice.call(arguments, 1);
  10332. if (args.length <= 1) {
  10333. args = args[0];
  10334. }
  10335. callback.call(null, err, args);
  10336. });
  10337. }
  10338. }, callback);
  10339. }
  10340. else {
  10341. var results = {};
  10342. async.eachSeries(_keys(tasks), function (k, callback) {
  10343. tasks[k](function (err) {
  10344. var args = Array.prototype.slice.call(arguments, 1);
  10345. if (args.length <= 1) {
  10346. args = args[0];
  10347. }
  10348. results[k] = args;
  10349. callback(err);
  10350. });
  10351. }, function (err) {
  10352. callback(err, results);
  10353. });
  10354. }
  10355. };
  10356. async.iterator = function (tasks) {
  10357. var makeCallback = function (index) {
  10358. var fn = function () {
  10359. if (tasks.length) {
  10360. tasks[index].apply(null, arguments);
  10361. }
  10362. return fn.next();
  10363. };
  10364. fn.next = function () {
  10365. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  10366. };
  10367. return fn;
  10368. };
  10369. return makeCallback(0);
  10370. };
  10371. async.apply = function (fn) {
  10372. var args = Array.prototype.slice.call(arguments, 1);
  10373. return function () {
  10374. return fn.apply(
  10375. null, args.concat(Array.prototype.slice.call(arguments))
  10376. );
  10377. };
  10378. };
  10379. var _concat = function (eachfn, arr, fn, callback) {
  10380. var r = [];
  10381. eachfn(arr, function (x, cb) {
  10382. fn(x, function (err, y) {
  10383. r = r.concat(y || []);
  10384. cb(err);
  10385. });
  10386. }, function (err) {
  10387. callback(err, r);
  10388. });
  10389. };
  10390. async.concat = doParallel(_concat);
  10391. async.concatSeries = doSeries(_concat);
  10392. async.whilst = function (test, iterator, callback) {
  10393. if (test()) {
  10394. iterator(function (err) {
  10395. if (err) {
  10396. return callback(err);
  10397. }
  10398. async.whilst(test, iterator, callback);
  10399. });
  10400. }
  10401. else {
  10402. callback();
  10403. }
  10404. };
  10405. async.doWhilst = function (iterator, test, callback) {
  10406. iterator(function (err) {
  10407. if (err) {
  10408. return callback(err);
  10409. }
  10410. var args = Array.prototype.slice.call(arguments, 1);
  10411. if (test.apply(null, args)) {
  10412. async.doWhilst(iterator, test, callback);
  10413. }
  10414. else {
  10415. callback();
  10416. }
  10417. });
  10418. };
  10419. async.until = function (test, iterator, callback) {
  10420. if (!test()) {
  10421. iterator(function (err) {
  10422. if (err) {
  10423. return callback(err);
  10424. }
  10425. async.until(test, iterator, callback);
  10426. });
  10427. }
  10428. else {
  10429. callback();
  10430. }
  10431. };
  10432. async.doUntil = function (iterator, test, callback) {
  10433. iterator(function (err) {
  10434. if (err) {
  10435. return callback(err);
  10436. }
  10437. var args = Array.prototype.slice.call(arguments, 1);
  10438. if (!test.apply(null, args)) {
  10439. async.doUntil(iterator, test, callback);
  10440. }
  10441. else {
  10442. callback();
  10443. }
  10444. });
  10445. };
  10446. async.queue = function (worker, concurrency) {
  10447. if (concurrency === undefined) {
  10448. concurrency = 1;
  10449. }
  10450. function _insert(q, data, pos, callback) {
  10451. if (!q.started){
  10452. q.started = true;
  10453. }
  10454. if (!_isArray(data)) {
  10455. data = [data];
  10456. }
  10457. if(data.length == 0) {
  10458. // call drain immediately if there are no tasks
  10459. return async.setImmediate(function() {
  10460. if (q.drain) {
  10461. q.drain();
  10462. }
  10463. });
  10464. }
  10465. _each(data, function(task) {
  10466. var item = {
  10467. data: task,
  10468. callback: typeof callback === 'function' ? callback : null
  10469. };
  10470. if (pos) {
  10471. q.tasks.unshift(item);
  10472. } else {
  10473. q.tasks.push(item);
  10474. }
  10475. if (q.saturated && q.tasks.length === q.concurrency) {
  10476. q.saturated();
  10477. }
  10478. async.setImmediate(q.process);
  10479. });
  10480. }
  10481. var workers = 0;
  10482. var q = {
  10483. tasks: [],
  10484. concurrency: concurrency,
  10485. saturated: null,
  10486. empty: null,
  10487. drain: null,
  10488. started: false,
  10489. paused: false,
  10490. push: function (data, callback) {
  10491. _insert(q, data, false, callback);
  10492. },
  10493. kill: function () {
  10494. q.drain = null;
  10495. q.tasks = [];
  10496. },
  10497. unshift: function (data, callback) {
  10498. _insert(q, data, true, callback);
  10499. },
  10500. process: function () {
  10501. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  10502. var task = q.tasks.shift();
  10503. if (q.empty && q.tasks.length === 0) {
  10504. q.empty();
  10505. }
  10506. workers += 1;
  10507. var next = function () {
  10508. workers -= 1;
  10509. if (task.callback) {
  10510. task.callback.apply(task, arguments);
  10511. }
  10512. if (q.drain && q.tasks.length + workers === 0) {
  10513. q.drain();
  10514. }
  10515. q.process();
  10516. };
  10517. var cb = only_once(next);
  10518. worker(task.data, cb);
  10519. }
  10520. },
  10521. length: function () {
  10522. return q.tasks.length;
  10523. },
  10524. running: function () {
  10525. return workers;
  10526. },
  10527. idle: function() {
  10528. return q.tasks.length + workers === 0;
  10529. },
  10530. pause: function () {
  10531. if (q.paused === true) { return; }
  10532. q.paused = true;
  10533. q.process();
  10534. },
  10535. resume: function () {
  10536. if (q.paused === false) { return; }
  10537. q.paused = false;
  10538. q.process();
  10539. }
  10540. };
  10541. return q;
  10542. };
  10543. async.priorityQueue = function (worker, concurrency) {
  10544. function _compareTasks(a, b){
  10545. return a.priority - b.priority;
  10546. };
  10547. function _binarySearch(sequence, item, compare) {
  10548. var beg = -1,
  10549. end = sequence.length - 1;
  10550. while (beg < end) {
  10551. var mid = beg + ((end - beg + 1) >>> 1);
  10552. if (compare(item, sequence[mid]) >= 0) {
  10553. beg = mid;
  10554. } else {
  10555. end = mid - 1;
  10556. }
  10557. }
  10558. return beg;
  10559. }
  10560. function _insert(q, data, priority, callback) {
  10561. if (!q.started){
  10562. q.started = true;
  10563. }
  10564. if (!_isArray(data)) {
  10565. data = [data];
  10566. }
  10567. if(data.length == 0) {
  10568. // call drain immediately if there are no tasks
  10569. return async.setImmediate(function() {
  10570. if (q.drain) {
  10571. q.drain();
  10572. }
  10573. });
  10574. }
  10575. _each(data, function(task) {
  10576. var item = {
  10577. data: task,
  10578. priority: priority,
  10579. callback: typeof callback === 'function' ? callback : null
  10580. };
  10581. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  10582. if (q.saturated && q.tasks.length === q.concurrency) {
  10583. q.saturated();
  10584. }
  10585. async.setImmediate(q.process);
  10586. });
  10587. }
  10588. // Start with a normal queue
  10589. var q = async.queue(worker, concurrency);
  10590. // Override push to accept second parameter representing priority
  10591. q.push = function (data, priority, callback) {
  10592. _insert(q, data, priority, callback);
  10593. };
  10594. // Remove unshift function
  10595. delete q.unshift;
  10596. return q;
  10597. };
  10598. async.cargo = function (worker, payload) {
  10599. var working = false,
  10600. tasks = [];
  10601. var cargo = {
  10602. tasks: tasks,
  10603. payload: payload,
  10604. saturated: null,
  10605. empty: null,
  10606. drain: null,
  10607. drained: true,
  10608. push: function (data, callback) {
  10609. if (!_isArray(data)) {
  10610. data = [data];
  10611. }
  10612. _each(data, function(task) {
  10613. tasks.push({
  10614. data: task,
  10615. callback: typeof callback === 'function' ? callback : null
  10616. });
  10617. cargo.drained = false;
  10618. if (cargo.saturated && tasks.length === payload) {
  10619. cargo.saturated();
  10620. }
  10621. });
  10622. async.setImmediate(cargo.process);
  10623. },
  10624. process: function process() {
  10625. if (working) return;
  10626. if (tasks.length === 0) {
  10627. if(cargo.drain && !cargo.drained) cargo.drain();
  10628. cargo.drained = true;
  10629. return;
  10630. }
  10631. var ts = typeof payload === 'number'
  10632. ? tasks.splice(0, payload)
  10633. : tasks.splice(0, tasks.length);
  10634. var ds = _map(ts, function (task) {
  10635. return task.data;
  10636. });
  10637. if(cargo.empty) cargo.empty();
  10638. working = true;
  10639. worker(ds, function () {
  10640. working = false;
  10641. var args = arguments;
  10642. _each(ts, function (data) {
  10643. if (data.callback) {
  10644. data.callback.apply(null, args);
  10645. }
  10646. });
  10647. process();
  10648. });
  10649. },
  10650. length: function () {
  10651. return tasks.length;
  10652. },
  10653. running: function () {
  10654. return working;
  10655. }
  10656. };
  10657. return cargo;
  10658. };
  10659. var _console_fn = function (name) {
  10660. return function (fn) {
  10661. var args = Array.prototype.slice.call(arguments, 1);
  10662. fn.apply(null, args.concat([function (err) {
  10663. var args = Array.prototype.slice.call(arguments, 1);
  10664. if (typeof console !== 'undefined') {
  10665. if (err) {
  10666. if (console.error) {
  10667. console.error(err);
  10668. }
  10669. }
  10670. else if (console[name]) {
  10671. _each(args, function (x) {
  10672. console[name](x);
  10673. });
  10674. }
  10675. }
  10676. }]));
  10677. };
  10678. };
  10679. async.log = _console_fn('log');
  10680. async.dir = _console_fn('dir');
  10681. /*async.info = _console_fn('info');
  10682. async.warn = _console_fn('warn');
  10683. async.error = _console_fn('error');*/
  10684. async.memoize = function (fn, hasher) {
  10685. var memo = {};
  10686. var queues = {};
  10687. hasher = hasher || function (x) {
  10688. return x;
  10689. };
  10690. var memoized = function () {
  10691. var args = Array.prototype.slice.call(arguments);
  10692. var callback = args.pop();
  10693. var key = hasher.apply(null, args);
  10694. if (key in memo) {
  10695. async.nextTick(function () {
  10696. callback.apply(null, memo[key]);
  10697. });
  10698. }
  10699. else if (key in queues) {
  10700. queues[key].push(callback);
  10701. }
  10702. else {
  10703. queues[key] = [callback];
  10704. fn.apply(null, args.concat([function () {
  10705. memo[key] = arguments;
  10706. var q = queues[key];
  10707. delete queues[key];
  10708. for (var i = 0, l = q.length; i < l; i++) {
  10709. q[i].apply(null, arguments);
  10710. }
  10711. }]));
  10712. }
  10713. };
  10714. memoized.memo = memo;
  10715. memoized.unmemoized = fn;
  10716. return memoized;
  10717. };
  10718. async.unmemoize = function (fn) {
  10719. return function () {
  10720. return (fn.unmemoized || fn).apply(null, arguments);
  10721. };
  10722. };
  10723. async.times = function (count, iterator, callback) {
  10724. var counter = [];
  10725. for (var i = 0; i < count; i++) {
  10726. counter.push(i);
  10727. }
  10728. return async.map(counter, iterator, callback);
  10729. };
  10730. async.timesSeries = function (count, iterator, callback) {
  10731. var counter = [];
  10732. for (var i = 0; i < count; i++) {
  10733. counter.push(i);
  10734. }
  10735. return async.mapSeries(counter, iterator, callback);
  10736. };
  10737. async.seq = function (/* functions... */) {
  10738. var fns = arguments;
  10739. return function () {
  10740. var that = this;
  10741. var args = Array.prototype.slice.call(arguments);
  10742. var callback = args.pop();
  10743. async.reduce(fns, args, function (newargs, fn, cb) {
  10744. fn.apply(that, newargs.concat([function () {
  10745. var err = arguments[0];
  10746. var nextargs = Array.prototype.slice.call(arguments, 1);
  10747. cb(err, nextargs);
  10748. }]))
  10749. },
  10750. function (err, results) {
  10751. callback.apply(that, [err].concat(results));
  10752. });
  10753. };
  10754. };
  10755. async.compose = function (/* functions... */) {
  10756. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  10757. };
  10758. var _applyEach = function (eachfn, fns /*args...*/) {
  10759. var go = function () {
  10760. var that = this;
  10761. var args = Array.prototype.slice.call(arguments);
  10762. var callback = args.pop();
  10763. return eachfn(fns, function (fn, cb) {
  10764. fn.apply(that, args.concat([cb]));
  10765. },
  10766. callback);
  10767. };
  10768. if (arguments.length > 2) {
  10769. var args = Array.prototype.slice.call(arguments, 2);
  10770. return go.apply(this, args);
  10771. }
  10772. else {
  10773. return go;
  10774. }
  10775. };
  10776. async.applyEach = doParallel(_applyEach);
  10777. async.applyEachSeries = doSeries(_applyEach);
  10778. async.forever = function (fn, callback) {
  10779. function next(err) {
  10780. if (err) {
  10781. if (callback) {
  10782. return callback(err);
  10783. }
  10784. throw err;
  10785. }
  10786. fn(next);
  10787. }
  10788. next();
  10789. };
  10790. // Node.js
  10791. if (typeof module !== 'undefined' && module.exports) {
  10792. module.exports = async;
  10793. }
  10794. // AMD / RequireJS
  10795. else if (typeof define !== 'undefined' && define.amd) {
  10796. define([], function () {
  10797. return async;
  10798. });
  10799. }
  10800. // included directly via <script> tag
  10801. else {
  10802. root.async = async;
  10803. }
  10804. }());
  10805. }).call(this,require('_process'))
  10806. },{"_process":41}],40:[function(require,module,exports){
  10807. // Copyright Joyent, Inc. and other Node contributors.
  10808. //
  10809. // Permission is hereby granted, free of charge, to any person obtaining a
  10810. // copy of this software and associated documentation files (the
  10811. // "Software"), to deal in the Software without restriction, including
  10812. // without limitation the rights to use, copy, modify, merge, publish,
  10813. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10814. // persons to whom the Software is furnished to do so, subject to the
  10815. // following conditions:
  10816. //
  10817. // The above copyright notice and this permission notice shall be included
  10818. // in all copies or substantial portions of the Software.
  10819. //
  10820. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10821. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10822. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10823. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10824. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10825. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10826. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10827. function EventEmitter() {
  10828. this._events = this._events || {};
  10829. this._maxListeners = this._maxListeners || undefined;
  10830. }
  10831. module.exports = EventEmitter;
  10832. // Backwards-compat with node 0.10.x
  10833. EventEmitter.EventEmitter = EventEmitter;
  10834. EventEmitter.prototype._events = undefined;
  10835. EventEmitter.prototype._maxListeners = undefined;
  10836. // By default EventEmitters will print a warning if more than 10 listeners are
  10837. // added to it. This is a useful default which helps finding memory leaks.
  10838. EventEmitter.defaultMaxListeners = 10;
  10839. // Obviously not all Emitters should be limited to 10. This function allows
  10840. // that to be increased. Set to zero for unlimited.
  10841. EventEmitter.prototype.setMaxListeners = function(n) {
  10842. if (!isNumber(n) || n < 0 || isNaN(n))
  10843. throw TypeError('n must be a positive number');
  10844. this._maxListeners = n;
  10845. return this;
  10846. };
  10847. EventEmitter.prototype.emit = function(type) {
  10848. var er, handler, len, args, i, listeners;
  10849. if (!this._events)
  10850. this._events = {};
  10851. // If there is no 'error' event listener then throw.
  10852. if (type === 'error') {
  10853. if (!this._events.error ||
  10854. (isObject(this._events.error) && !this._events.error.length)) {
  10855. er = arguments[1];
  10856. if (er instanceof Error) {
  10857. throw er; // Unhandled 'error' event
  10858. }
  10859. throw TypeError('Uncaught, unspecified "error" event.');
  10860. }
  10861. }
  10862. handler = this._events[type];
  10863. if (isUndefined(handler))
  10864. return false;
  10865. if (isFunction(handler)) {
  10866. switch (arguments.length) {
  10867. // fast cases
  10868. case 1:
  10869. handler.call(this);
  10870. break;
  10871. case 2:
  10872. handler.call(this, arguments[1]);
  10873. break;
  10874. case 3:
  10875. handler.call(this, arguments[1], arguments[2]);
  10876. break;
  10877. // slower
  10878. default:
  10879. len = arguments.length;
  10880. args = new Array(len - 1);
  10881. for (i = 1; i < len; i++)
  10882. args[i - 1] = arguments[i];
  10883. handler.apply(this, args);
  10884. }
  10885. } else if (isObject(handler)) {
  10886. len = arguments.length;
  10887. args = new Array(len - 1);
  10888. for (i = 1; i < len; i++)
  10889. args[i - 1] = arguments[i];
  10890. listeners = handler.slice();
  10891. len = listeners.length;
  10892. for (i = 0; i < len; i++)
  10893. listeners[i].apply(this, args);
  10894. }
  10895. return true;
  10896. };
  10897. EventEmitter.prototype.addListener = function(type, listener) {
  10898. var m;
  10899. if (!isFunction(listener))
  10900. throw TypeError('listener must be a function');
  10901. if (!this._events)
  10902. this._events = {};
  10903. // To avoid recursion in the case that type === "newListener"! Before
  10904. // adding it to the listeners, first emit "newListener".
  10905. if (this._events.newListener)
  10906. this.emit('newListener', type,
  10907. isFunction(listener.listener) ?
  10908. listener.listener : listener);
  10909. if (!this._events[type])
  10910. // Optimize the case of one listener. Don't need the extra array object.
  10911. this._events[type] = listener;
  10912. else if (isObject(this._events[type]))
  10913. // If we've already got an array, just append.
  10914. this._events[type].push(listener);
  10915. else
  10916. // Adding the second element, need to change to array.
  10917. this._events[type] = [this._events[type], listener];
  10918. // Check for listener leak
  10919. if (isObject(this._events[type]) && !this._events[type].warned) {
  10920. var m;
  10921. if (!isUndefined(this._maxListeners)) {
  10922. m = this._maxListeners;
  10923. } else {
  10924. m = EventEmitter.defaultMaxListeners;
  10925. }
  10926. if (m && m > 0 && this._events[type].length > m) {
  10927. this._events[type].warned = true;
  10928. console.error('(node) warning: possible EventEmitter memory ' +
  10929. 'leak detected. %d listeners added. ' +
  10930. 'Use emitter.setMaxListeners() to increase limit.',
  10931. this._events[type].length);
  10932. if (typeof console.trace === 'function') {
  10933. // not supported in IE 10
  10934. console.trace();
  10935. }
  10936. }
  10937. }
  10938. return this;
  10939. };
  10940. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  10941. EventEmitter.prototype.once = function(type, listener) {
  10942. if (!isFunction(listener))
  10943. throw TypeError('listener must be a function');
  10944. var fired = false;
  10945. function g() {
  10946. this.removeListener(type, g);
  10947. if (!fired) {
  10948. fired = true;
  10949. listener.apply(this, arguments);
  10950. }
  10951. }
  10952. g.listener = listener;
  10953. this.on(type, g);
  10954. return this;
  10955. };
  10956. // emits a 'removeListener' event iff the listener was removed
  10957. EventEmitter.prototype.removeListener = function(type, listener) {
  10958. var list, position, length, i;
  10959. if (!isFunction(listener))
  10960. throw TypeError('listener must be a function');
  10961. if (!this._events || !this._events[type])
  10962. return this;
  10963. list = this._events[type];
  10964. length = list.length;
  10965. position = -1;
  10966. if (list === listener ||
  10967. (isFunction(list.listener) && list.listener === listener)) {
  10968. delete this._events[type];
  10969. if (this._events.removeListener)
  10970. this.emit('removeListener', type, listener);
  10971. } else if (isObject(list)) {
  10972. for (i = length; i-- > 0;) {
  10973. if (list[i] === listener ||
  10974. (list[i].listener && list[i].listener === listener)) {
  10975. position = i;
  10976. break;
  10977. }
  10978. }
  10979. if (position < 0)
  10980. return this;
  10981. if (list.length === 1) {
  10982. list.length = 0;
  10983. delete this._events[type];
  10984. } else {
  10985. list.splice(position, 1);
  10986. }
  10987. if (this._events.removeListener)
  10988. this.emit('removeListener', type, listener);
  10989. }
  10990. return this;
  10991. };
  10992. EventEmitter.prototype.removeAllListeners = function(type) {
  10993. var key, listeners;
  10994. if (!this._events)
  10995. return this;
  10996. // not listening for removeListener, no need to emit
  10997. if (!this._events.removeListener) {
  10998. if (arguments.length === 0)
  10999. this._events = {};
  11000. else if (this._events[type])
  11001. delete this._events[type];
  11002. return this;
  11003. }
  11004. // emit removeListener for all listeners on all events
  11005. if (arguments.length === 0) {
  11006. for (key in this._events) {
  11007. if (key === 'removeListener') continue;
  11008. this.removeAllListeners(key);
  11009. }
  11010. this.removeAllListeners('removeListener');
  11011. this._events = {};
  11012. return this;
  11013. }
  11014. listeners = this._events[type];
  11015. if (isFunction(listeners)) {
  11016. this.removeListener(type, listeners);
  11017. } else {
  11018. // LIFO order
  11019. while (listeners.length)
  11020. this.removeListener(type, listeners[listeners.length - 1]);
  11021. }
  11022. delete this._events[type];
  11023. return this;
  11024. };
  11025. EventEmitter.prototype.listeners = function(type) {
  11026. var ret;
  11027. if (!this._events || !this._events[type])
  11028. ret = [];
  11029. else if (isFunction(this._events[type]))
  11030. ret = [this._events[type]];
  11031. else
  11032. ret = this._events[type].slice();
  11033. return ret;
  11034. };
  11035. EventEmitter.listenerCount = function(emitter, type) {
  11036. var ret;
  11037. if (!emitter._events || !emitter._events[type])
  11038. ret = 0;
  11039. else if (isFunction(emitter._events[type]))
  11040. ret = 1;
  11041. else
  11042. ret = emitter._events[type].length;
  11043. return ret;
  11044. };
  11045. function isFunction(arg) {
  11046. return typeof arg === 'function';
  11047. }
  11048. function isNumber(arg) {
  11049. return typeof arg === 'number';
  11050. }
  11051. function isObject(arg) {
  11052. return typeof arg === 'object' && arg !== null;
  11053. }
  11054. function isUndefined(arg) {
  11055. return arg === void 0;
  11056. }
  11057. },{}],41:[function(require,module,exports){
  11058. // shim for using process in browser
  11059. var process = module.exports = {};
  11060. var queue = [];
  11061. var draining = false;
  11062. var currentQueue;
  11063. var queueIndex = -1;
  11064. function cleanUpNextTick() {
  11065. draining = false;
  11066. if (currentQueue.length) {
  11067. queue = currentQueue.concat(queue);
  11068. } else {
  11069. queueIndex = -1;
  11070. }
  11071. if (queue.length) {
  11072. drainQueue();
  11073. }
  11074. }
  11075. function drainQueue() {
  11076. if (draining) {
  11077. return;
  11078. }
  11079. var timeout = setTimeout(cleanUpNextTick);
  11080. draining = true;
  11081. var len = queue.length;
  11082. while(len) {
  11083. currentQueue = queue;
  11084. queue = [];
  11085. while (++queueIndex < len) {
  11086. if (currentQueue) {
  11087. currentQueue[queueIndex].run();
  11088. }
  11089. }
  11090. queueIndex = -1;
  11091. len = queue.length;
  11092. }
  11093. currentQueue = null;
  11094. draining = false;
  11095. clearTimeout(timeout);
  11096. }
  11097. process.nextTick = function (fun) {
  11098. var args = new Array(arguments.length - 1);
  11099. if (arguments.length > 1) {
  11100. for (var i = 1; i < arguments.length; i++) {
  11101. args[i - 1] = arguments[i];
  11102. }
  11103. }
  11104. queue.push(new Item(fun, args));
  11105. if (queue.length === 1 && !draining) {
  11106. setTimeout(drainQueue, 0);
  11107. }
  11108. };
  11109. // v8 likes predictible objects
  11110. function Item(fun, array) {
  11111. this.fun = fun;
  11112. this.array = array;
  11113. }
  11114. Item.prototype.run = function () {
  11115. this.fun.apply(null, this.array);
  11116. };
  11117. process.title = 'browser';
  11118. process.browser = true;
  11119. process.env = {};
  11120. process.argv = [];
  11121. process.version = ''; // empty string to avoid regexp issues
  11122. process.versions = {};
  11123. function noop() {}
  11124. process.on = noop;
  11125. process.addListener = noop;
  11126. process.once = noop;
  11127. process.off = noop;
  11128. process.removeListener = noop;
  11129. process.removeAllListeners = noop;
  11130. process.emit = noop;
  11131. process.binding = function (name) {
  11132. throw new Error('process.binding is not supported');
  11133. };
  11134. process.cwd = function () { return '/' };
  11135. process.chdir = function (dir) {
  11136. throw new Error('process.chdir is not supported');
  11137. };
  11138. process.umask = function() { return 0; };
  11139. },{}],42:[function(require,module,exports){
  11140. (function (process,global){
  11141. /*!
  11142. * @overview es6-promise - a tiny implementation of Promises/A+.
  11143. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11144. * @license Licensed under MIT license
  11145. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  11146. * @version 3.0.2
  11147. */
  11148. (function() {
  11149. "use strict";
  11150. function lib$es6$promise$utils$$objectOrFunction(x) {
  11151. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  11152. }
  11153. function lib$es6$promise$utils$$isFunction(x) {
  11154. return typeof x === 'function';
  11155. }
  11156. function lib$es6$promise$utils$$isMaybeThenable(x) {
  11157. return typeof x === 'object' && x !== null;
  11158. }
  11159. var lib$es6$promise$utils$$_isArray;
  11160. if (!Array.isArray) {
  11161. lib$es6$promise$utils$$_isArray = function (x) {
  11162. return Object.prototype.toString.call(x) === '[object Array]';
  11163. };
  11164. } else {
  11165. lib$es6$promise$utils$$_isArray = Array.isArray;
  11166. }
  11167. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  11168. var lib$es6$promise$asap$$len = 0;
  11169. var lib$es6$promise$asap$$toString = {}.toString;
  11170. var lib$es6$promise$asap$$vertxNext;
  11171. var lib$es6$promise$asap$$customSchedulerFn;
  11172. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  11173. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  11174. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  11175. lib$es6$promise$asap$$len += 2;
  11176. if (lib$es6$promise$asap$$len === 2) {
  11177. // If len is 2, that means that we need to schedule an async flush.
  11178. // If additional callbacks are queued before the queue is flushed, they
  11179. // will be processed by this flush that we are scheduling.
  11180. if (lib$es6$promise$asap$$customSchedulerFn) {
  11181. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  11182. } else {
  11183. lib$es6$promise$asap$$scheduleFlush();
  11184. }
  11185. }
  11186. }
  11187. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  11188. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  11189. }
  11190. function lib$es6$promise$asap$$setAsap(asapFn) {
  11191. lib$es6$promise$asap$$asap = asapFn;
  11192. }
  11193. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  11194. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  11195. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  11196. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  11197. // test for web worker but not in IE10
  11198. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  11199. typeof importScripts !== 'undefined' &&
  11200. typeof MessageChannel !== 'undefined';
  11201. // node
  11202. function lib$es6$promise$asap$$useNextTick() {
  11203. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  11204. // see https://github.com/cujojs/when/issues/410 for details
  11205. return function() {
  11206. process.nextTick(lib$es6$promise$asap$$flush);
  11207. };
  11208. }
  11209. // vertx
  11210. function lib$es6$promise$asap$$useVertxTimer() {
  11211. return function() {
  11212. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  11213. };
  11214. }
  11215. function lib$es6$promise$asap$$useMutationObserver() {
  11216. var iterations = 0;
  11217. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  11218. var node = document.createTextNode('');
  11219. observer.observe(node, { characterData: true });
  11220. return function() {
  11221. node.data = (iterations = ++iterations % 2);
  11222. };
  11223. }
  11224. // web worker
  11225. function lib$es6$promise$asap$$useMessageChannel() {
  11226. var channel = new MessageChannel();
  11227. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  11228. return function () {
  11229. channel.port2.postMessage(0);
  11230. };
  11231. }
  11232. function lib$es6$promise$asap$$useSetTimeout() {
  11233. return function() {
  11234. setTimeout(lib$es6$promise$asap$$flush, 1);
  11235. };
  11236. }
  11237. var lib$es6$promise$asap$$queue = new Array(1000);
  11238. function lib$es6$promise$asap$$flush() {
  11239. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  11240. var callback = lib$es6$promise$asap$$queue[i];
  11241. var arg = lib$es6$promise$asap$$queue[i+1];
  11242. callback(arg);
  11243. lib$es6$promise$asap$$queue[i] = undefined;
  11244. lib$es6$promise$asap$$queue[i+1] = undefined;
  11245. }
  11246. lib$es6$promise$asap$$len = 0;
  11247. }
  11248. function lib$es6$promise$asap$$attemptVertx() {
  11249. try {
  11250. var r = require;
  11251. var vertx = r('vertx');
  11252. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  11253. return lib$es6$promise$asap$$useVertxTimer();
  11254. } catch(e) {
  11255. return lib$es6$promise$asap$$useSetTimeout();
  11256. }
  11257. }
  11258. var lib$es6$promise$asap$$scheduleFlush;
  11259. // Decide what async method to use to triggering processing of queued callbacks:
  11260. if (lib$es6$promise$asap$$isNode) {
  11261. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  11262. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  11263. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  11264. } else if (lib$es6$promise$asap$$isWorker) {
  11265. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  11266. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  11267. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  11268. } else {
  11269. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  11270. }
  11271. function lib$es6$promise$$internal$$noop() {}
  11272. var lib$es6$promise$$internal$$PENDING = void 0;
  11273. var lib$es6$promise$$internal$$FULFILLED = 1;
  11274. var lib$es6$promise$$internal$$REJECTED = 2;
  11275. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11276. function lib$es6$promise$$internal$$selfFulfillment() {
  11277. return new TypeError("You cannot resolve a promise with itself");
  11278. }
  11279. function lib$es6$promise$$internal$$cannotReturnOwn() {
  11280. return new TypeError('A promises callback cannot return that same promise.');
  11281. }
  11282. function lib$es6$promise$$internal$$getThen(promise) {
  11283. try {
  11284. return promise.then;
  11285. } catch(error) {
  11286. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  11287. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  11288. }
  11289. }
  11290. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  11291. try {
  11292. then.call(value, fulfillmentHandler, rejectionHandler);
  11293. } catch(e) {
  11294. return e;
  11295. }
  11296. }
  11297. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  11298. lib$es6$promise$asap$$asap(function(promise) {
  11299. var sealed = false;
  11300. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  11301. if (sealed) { return; }
  11302. sealed = true;
  11303. if (thenable !== value) {
  11304. lib$es6$promise$$internal$$resolve(promise, value);
  11305. } else {
  11306. lib$es6$promise$$internal$$fulfill(promise, value);
  11307. }
  11308. }, function(reason) {
  11309. if (sealed) { return; }
  11310. sealed = true;
  11311. lib$es6$promise$$internal$$reject(promise, reason);
  11312. }, 'Settle: ' + (promise._label || ' unknown promise'));
  11313. if (!sealed && error) {
  11314. sealed = true;
  11315. lib$es6$promise$$internal$$reject(promise, error);
  11316. }
  11317. }, promise);
  11318. }
  11319. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  11320. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  11321. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  11322. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  11323. lib$es6$promise$$internal$$reject(promise, thenable._result);
  11324. } else {
  11325. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  11326. lib$es6$promise$$internal$$resolve(promise, value);
  11327. }, function(reason) {
  11328. lib$es6$promise$$internal$$reject(promise, reason);
  11329. });
  11330. }
  11331. }
  11332. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  11333. if (maybeThenable.constructor === promise.constructor) {
  11334. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  11335. } else {
  11336. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  11337. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  11338. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  11339. } else if (then === undefined) {
  11340. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11341. } else if (lib$es6$promise$utils$$isFunction(then)) {
  11342. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  11343. } else {
  11344. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11345. }
  11346. }
  11347. }
  11348. function lib$es6$promise$$internal$$resolve(promise, value) {
  11349. if (promise === value) {
  11350. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  11351. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  11352. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  11353. } else {
  11354. lib$es6$promise$$internal$$fulfill(promise, value);
  11355. }
  11356. }
  11357. function lib$es6$promise$$internal$$publishRejection(promise) {
  11358. if (promise._onerror) {
  11359. promise._onerror(promise._result);
  11360. }
  11361. lib$es6$promise$$internal$$publish(promise);
  11362. }
  11363. function lib$es6$promise$$internal$$fulfill(promise, value) {
  11364. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11365. promise._result = value;
  11366. promise._state = lib$es6$promise$$internal$$FULFILLED;
  11367. if (promise._subscribers.length !== 0) {
  11368. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  11369. }
  11370. }
  11371. function lib$es6$promise$$internal$$reject(promise, reason) {
  11372. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11373. promise._state = lib$es6$promise$$internal$$REJECTED;
  11374. promise._result = reason;
  11375. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  11376. }
  11377. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  11378. var subscribers = parent._subscribers;
  11379. var length = subscribers.length;
  11380. parent._onerror = null;
  11381. subscribers[length] = child;
  11382. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  11383. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  11384. if (length === 0 && parent._state) {
  11385. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  11386. }
  11387. }
  11388. function lib$es6$promise$$internal$$publish(promise) {
  11389. var subscribers = promise._subscribers;
  11390. var settled = promise._state;
  11391. if (subscribers.length === 0) { return; }
  11392. var child, callback, detail = promise._result;
  11393. for (var i = 0; i < subscribers.length; i += 3) {
  11394. child = subscribers[i];
  11395. callback = subscribers[i + settled];
  11396. if (child) {
  11397. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  11398. } else {
  11399. callback(detail);
  11400. }
  11401. }
  11402. promise._subscribers.length = 0;
  11403. }
  11404. function lib$es6$promise$$internal$$ErrorObject() {
  11405. this.error = null;
  11406. }
  11407. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11408. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  11409. try {
  11410. return callback(detail);
  11411. } catch(e) {
  11412. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  11413. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  11414. }
  11415. }
  11416. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  11417. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  11418. value, error, succeeded, failed;
  11419. if (hasCallback) {
  11420. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  11421. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  11422. failed = true;
  11423. error = value.error;
  11424. value = null;
  11425. } else {
  11426. succeeded = true;
  11427. }
  11428. if (promise === value) {
  11429. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  11430. return;
  11431. }
  11432. } else {
  11433. value = detail;
  11434. succeeded = true;
  11435. }
  11436. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  11437. // noop
  11438. } else if (hasCallback && succeeded) {
  11439. lib$es6$promise$$internal$$resolve(promise, value);
  11440. } else if (failed) {
  11441. lib$es6$promise$$internal$$reject(promise, error);
  11442. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  11443. lib$es6$promise$$internal$$fulfill(promise, value);
  11444. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  11445. lib$es6$promise$$internal$$reject(promise, value);
  11446. }
  11447. }
  11448. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  11449. try {
  11450. resolver(function resolvePromise(value){
  11451. lib$es6$promise$$internal$$resolve(promise, value);
  11452. }, function rejectPromise(reason) {
  11453. lib$es6$promise$$internal$$reject(promise, reason);
  11454. });
  11455. } catch(e) {
  11456. lib$es6$promise$$internal$$reject(promise, e);
  11457. }
  11458. }
  11459. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  11460. var enumerator = this;
  11461. enumerator._instanceConstructor = Constructor;
  11462. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  11463. if (enumerator._validateInput(input)) {
  11464. enumerator._input = input;
  11465. enumerator.length = input.length;
  11466. enumerator._remaining = input.length;
  11467. enumerator._init();
  11468. if (enumerator.length === 0) {
  11469. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11470. } else {
  11471. enumerator.length = enumerator.length || 0;
  11472. enumerator._enumerate();
  11473. if (enumerator._remaining === 0) {
  11474. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11475. }
  11476. }
  11477. } else {
  11478. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  11479. }
  11480. }
  11481. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  11482. return lib$es6$promise$utils$$isArray(input);
  11483. };
  11484. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  11485. return new Error('Array Methods must be provided an Array');
  11486. };
  11487. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  11488. this._result = new Array(this.length);
  11489. };
  11490. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  11491. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  11492. var enumerator = this;
  11493. var length = enumerator.length;
  11494. var promise = enumerator.promise;
  11495. var input = enumerator._input;
  11496. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11497. enumerator._eachEntry(input[i], i);
  11498. }
  11499. };
  11500. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  11501. var enumerator = this;
  11502. var c = enumerator._instanceConstructor;
  11503. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  11504. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  11505. entry._onerror = null;
  11506. enumerator._settledAt(entry._state, i, entry._result);
  11507. } else {
  11508. enumerator._willSettleAt(c.resolve(entry), i);
  11509. }
  11510. } else {
  11511. enumerator._remaining--;
  11512. enumerator._result[i] = entry;
  11513. }
  11514. };
  11515. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  11516. var enumerator = this;
  11517. var promise = enumerator.promise;
  11518. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  11519. enumerator._remaining--;
  11520. if (state === lib$es6$promise$$internal$$REJECTED) {
  11521. lib$es6$promise$$internal$$reject(promise, value);
  11522. } else {
  11523. enumerator._result[i] = value;
  11524. }
  11525. }
  11526. if (enumerator._remaining === 0) {
  11527. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  11528. }
  11529. };
  11530. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  11531. var enumerator = this;
  11532. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  11533. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  11534. }, function(reason) {
  11535. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  11536. });
  11537. };
  11538. function lib$es6$promise$promise$all$$all(entries) {
  11539. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  11540. }
  11541. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  11542. function lib$es6$promise$promise$race$$race(entries) {
  11543. /*jshint validthis:true */
  11544. var Constructor = this;
  11545. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11546. if (!lib$es6$promise$utils$$isArray(entries)) {
  11547. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  11548. return promise;
  11549. }
  11550. var length = entries.length;
  11551. function onFulfillment(value) {
  11552. lib$es6$promise$$internal$$resolve(promise, value);
  11553. }
  11554. function onRejection(reason) {
  11555. lib$es6$promise$$internal$$reject(promise, reason);
  11556. }
  11557. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11558. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  11559. }
  11560. return promise;
  11561. }
  11562. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  11563. function lib$es6$promise$promise$resolve$$resolve(object) {
  11564. /*jshint validthis:true */
  11565. var Constructor = this;
  11566. if (object && typeof object === 'object' && object.constructor === Constructor) {
  11567. return object;
  11568. }
  11569. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11570. lib$es6$promise$$internal$$resolve(promise, object);
  11571. return promise;
  11572. }
  11573. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  11574. function lib$es6$promise$promise$reject$$reject(reason) {
  11575. /*jshint validthis:true */
  11576. var Constructor = this;
  11577. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11578. lib$es6$promise$$internal$$reject(promise, reason);
  11579. return promise;
  11580. }
  11581. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  11582. var lib$es6$promise$promise$$counter = 0;
  11583. function lib$es6$promise$promise$$needsResolver() {
  11584. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  11585. }
  11586. function lib$es6$promise$promise$$needsNew() {
  11587. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  11588. }
  11589. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  11590. /**
  11591. Promise objects represent the eventual result of an asynchronous operation. The
  11592. primary way of interacting with a promise is through its `then` method, which
  11593. registers callbacks to receive either a promise's eventual value or the reason
  11594. why the promise cannot be fulfilled.
  11595. Terminology
  11596. -----------
  11597. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  11598. - `thenable` is an object or function that defines a `then` method.
  11599. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  11600. - `exception` is a value that is thrown using the throw statement.
  11601. - `reason` is a value that indicates why a promise was rejected.
  11602. - `settled` the final resting state of a promise, fulfilled or rejected.
  11603. A promise can be in one of three states: pending, fulfilled, or rejected.
  11604. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  11605. state. Promises that are rejected have a rejection reason and are in the
  11606. rejected state. A fulfillment value is never a thenable.
  11607. Promises can also be said to *resolve* a value. If this value is also a
  11608. promise, then the original promise's settled state will match the value's
  11609. settled state. So a promise that *resolves* a promise that rejects will
  11610. itself reject, and a promise that *resolves* a promise that fulfills will
  11611. itself fulfill.
  11612. Basic Usage:
  11613. ------------
  11614. ```js
  11615. var promise = new Promise(function(resolve, reject) {
  11616. // on success
  11617. resolve(value);
  11618. // on failure
  11619. reject(reason);
  11620. });
  11621. promise.then(function(value) {
  11622. // on fulfillment
  11623. }, function(reason) {
  11624. // on rejection
  11625. });
  11626. ```
  11627. Advanced Usage:
  11628. ---------------
  11629. Promises shine when abstracting away asynchronous interactions such as
  11630. `XMLHttpRequest`s.
  11631. ```js
  11632. function getJSON(url) {
  11633. return new Promise(function(resolve, reject){
  11634. var xhr = new XMLHttpRequest();
  11635. xhr.open('GET', url);
  11636. xhr.onreadystatechange = handler;
  11637. xhr.responseType = 'json';
  11638. xhr.setRequestHeader('Accept', 'application/json');
  11639. xhr.send();
  11640. function handler() {
  11641. if (this.readyState === this.DONE) {
  11642. if (this.status === 200) {
  11643. resolve(this.response);
  11644. } else {
  11645. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  11646. }
  11647. }
  11648. };
  11649. });
  11650. }
  11651. getJSON('/posts.json').then(function(json) {
  11652. // on fulfillment
  11653. }, function(reason) {
  11654. // on rejection
  11655. });
  11656. ```
  11657. Unlike callbacks, promises are great composable primitives.
  11658. ```js
  11659. Promise.all([
  11660. getJSON('/posts'),
  11661. getJSON('/comments')
  11662. ]).then(function(values){
  11663. values[0] // => postsJSON
  11664. values[1] // => commentsJSON
  11665. return values;
  11666. });
  11667. ```
  11668. @class Promise
  11669. @param {function} resolver
  11670. Useful for tooling.
  11671. @constructor
  11672. */
  11673. function lib$es6$promise$promise$$Promise(resolver) {
  11674. this._id = lib$es6$promise$promise$$counter++;
  11675. this._state = undefined;
  11676. this._result = undefined;
  11677. this._subscribers = [];
  11678. if (lib$es6$promise$$internal$$noop !== resolver) {
  11679. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  11680. lib$es6$promise$promise$$needsResolver();
  11681. }
  11682. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  11683. lib$es6$promise$promise$$needsNew();
  11684. }
  11685. lib$es6$promise$$internal$$initializePromise(this, resolver);
  11686. }
  11687. }
  11688. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  11689. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  11690. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  11691. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  11692. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  11693. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  11694. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  11695. lib$es6$promise$promise$$Promise.prototype = {
  11696. constructor: lib$es6$promise$promise$$Promise,
  11697. /**
  11698. The primary way of interacting with a promise is through its `then` method,
  11699. which registers callbacks to receive either a promise's eventual value or the
  11700. reason why the promise cannot be fulfilled.
  11701. ```js
  11702. findUser().then(function(user){
  11703. // user is available
  11704. }, function(reason){
  11705. // user is unavailable, and you are given the reason why
  11706. });
  11707. ```
  11708. Chaining
  11709. --------
  11710. The return value of `then` is itself a promise. This second, 'downstream'
  11711. promise is resolved with the return value of the first promise's fulfillment
  11712. or rejection handler, or rejected if the handler throws an exception.
  11713. ```js
  11714. findUser().then(function (user) {
  11715. return user.name;
  11716. }, function (reason) {
  11717. return 'default name';
  11718. }).then(function (userName) {
  11719. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  11720. // will be `'default name'`
  11721. });
  11722. findUser().then(function (user) {
  11723. throw new Error('Found user, but still unhappy');
  11724. }, function (reason) {
  11725. throw new Error('`findUser` rejected and we're unhappy');
  11726. }).then(function (value) {
  11727. // never reached
  11728. }, function (reason) {
  11729. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  11730. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  11731. });
  11732. ```
  11733. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  11734. ```js
  11735. findUser().then(function (user) {
  11736. throw new PedagogicalException('Upstream error');
  11737. }).then(function (value) {
  11738. // never reached
  11739. }).then(function (value) {
  11740. // never reached
  11741. }, function (reason) {
  11742. // The `PedgagocialException` is propagated all the way down to here
  11743. });
  11744. ```
  11745. Assimilation
  11746. ------------
  11747. Sometimes the value you want to propagate to a downstream promise can only be
  11748. retrieved asynchronously. This can be achieved by returning a promise in the
  11749. fulfillment or rejection handler. The downstream promise will then be pending
  11750. until the returned promise is settled. This is called *assimilation*.
  11751. ```js
  11752. findUser().then(function (user) {
  11753. return findCommentsByAuthor(user);
  11754. }).then(function (comments) {
  11755. // The user's comments are now available
  11756. });
  11757. ```
  11758. If the assimliated promise rejects, then the downstream promise will also reject.
  11759. ```js
  11760. findUser().then(function (user) {
  11761. return findCommentsByAuthor(user);
  11762. }).then(function (comments) {
  11763. // If `findCommentsByAuthor` fulfills, we'll have the value here
  11764. }, function (reason) {
  11765. // If `findCommentsByAuthor` rejects, we'll have the reason here
  11766. });
  11767. ```
  11768. Simple Example
  11769. --------------
  11770. Synchronous Example
  11771. ```javascript
  11772. var result;
  11773. try {
  11774. result = findResult();
  11775. // success
  11776. } catch(reason) {
  11777. // failure
  11778. }
  11779. ```
  11780. Errback Example
  11781. ```js
  11782. findResult(function(result, err){
  11783. if (err) {
  11784. // failure
  11785. } else {
  11786. // success
  11787. }
  11788. });
  11789. ```
  11790. Promise Example;
  11791. ```javascript
  11792. findResult().then(function(result){
  11793. // success
  11794. }, function(reason){
  11795. // failure
  11796. });
  11797. ```
  11798. Advanced Example
  11799. --------------
  11800. Synchronous Example
  11801. ```javascript
  11802. var author, books;
  11803. try {
  11804. author = findAuthor();
  11805. books = findBooksByAuthor(author);
  11806. // success
  11807. } catch(reason) {
  11808. // failure
  11809. }
  11810. ```
  11811. Errback Example
  11812. ```js
  11813. function foundBooks(books) {
  11814. }
  11815. function failure(reason) {
  11816. }
  11817. findAuthor(function(author, err){
  11818. if (err) {
  11819. failure(err);
  11820. // failure
  11821. } else {
  11822. try {
  11823. findBoooksByAuthor(author, function(books, err) {
  11824. if (err) {
  11825. failure(err);
  11826. } else {
  11827. try {
  11828. foundBooks(books);
  11829. } catch(reason) {
  11830. failure(reason);
  11831. }
  11832. }
  11833. });
  11834. } catch(error) {
  11835. failure(err);
  11836. }
  11837. // success
  11838. }
  11839. });
  11840. ```
  11841. Promise Example;
  11842. ```javascript
  11843. findAuthor().
  11844. then(findBooksByAuthor).
  11845. then(function(books){
  11846. // found books
  11847. }).catch(function(reason){
  11848. // something went wrong
  11849. });
  11850. ```
  11851. @method then
  11852. @param {Function} onFulfilled
  11853. @param {Function} onRejected
  11854. Useful for tooling.
  11855. @return {Promise}
  11856. */
  11857. then: function(onFulfillment, onRejection) {
  11858. var parent = this;
  11859. var state = parent._state;
  11860. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  11861. return this;
  11862. }
  11863. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  11864. var result = parent._result;
  11865. if (state) {
  11866. var callback = arguments[state - 1];
  11867. lib$es6$promise$asap$$asap(function(){
  11868. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  11869. });
  11870. } else {
  11871. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  11872. }
  11873. return child;
  11874. },
  11875. /**
  11876. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  11877. as the catch block of a try/catch statement.
  11878. ```js
  11879. function findAuthor(){
  11880. throw new Error('couldn't find that author');
  11881. }
  11882. // synchronous
  11883. try {
  11884. findAuthor();
  11885. } catch(reason) {
  11886. // something went wrong
  11887. }
  11888. // async with promises
  11889. findAuthor().catch(function(reason){
  11890. // something went wrong
  11891. });
  11892. ```
  11893. @method catch
  11894. @param {Function} onRejection
  11895. Useful for tooling.
  11896. @return {Promise}
  11897. */
  11898. 'catch': function(onRejection) {
  11899. return this.then(null, onRejection);
  11900. }
  11901. };
  11902. function lib$es6$promise$polyfill$$polyfill() {
  11903. var local;
  11904. if (typeof global !== 'undefined') {
  11905. local = global;
  11906. } else if (typeof self !== 'undefined') {
  11907. local = self;
  11908. } else {
  11909. try {
  11910. local = Function('return this')();
  11911. } catch (e) {
  11912. throw new Error('polyfill failed because global object is unavailable in this environment');
  11913. }
  11914. }
  11915. var P = local.Promise;
  11916. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  11917. return;
  11918. }
  11919. local.Promise = lib$es6$promise$promise$$default;
  11920. }
  11921. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  11922. var lib$es6$promise$umd$$ES6Promise = {
  11923. 'Promise': lib$es6$promise$promise$$default,
  11924. 'polyfill': lib$es6$promise$polyfill$$default
  11925. };
  11926. /* global define:true module:true window: true */
  11927. if (typeof define === 'function' && define['amd']) {
  11928. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  11929. } else if (typeof module !== 'undefined' && module['exports']) {
  11930. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  11931. } else if (typeof this !== 'undefined') {
  11932. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  11933. }
  11934. lib$es6$promise$polyfill$$default();
  11935. }).call(this);
  11936. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11937. },{"_process":41}],43:[function(require,module,exports){
  11938. /* Copyright @ 2015 Atlassian Pty Ltd
  11939. *
  11940. * Licensed under the Apache License, Version 2.0 (the "License");
  11941. * you may not use this file except in compliance with the License.
  11942. * You may obtain a copy of the License at
  11943. *
  11944. * http://www.apache.org/licenses/LICENSE-2.0
  11945. *
  11946. * Unless required by applicable law or agreed to in writing, software
  11947. * distributed under the License is distributed on an "AS IS" BASIS,
  11948. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11949. * See the License for the specific language governing permissions and
  11950. * limitations under the License.
  11951. */
  11952. /**
  11953. * Ordered log levels.
  11954. */
  11955. var levels = {
  11956. "trace": 0,
  11957. "debug": 1,
  11958. "info": 2,
  11959. "log": 3,
  11960. "warn": 4,
  11961. "error": 5
  11962. };
  11963. /**
  11964. * Parses Error's object stack trace and extracts information about the last
  11965. * caller before the log method was called.
  11966. * @returns JS object with info about the caller - method name, file location,
  11967. * line and column.
  11968. */
  11969. function getCallerInfo() {
  11970. var callerInfo = {
  11971. methodName: "",
  11972. fileLocation: "",
  11973. line: null,
  11974. column: null
  11975. };
  11976. //gets the part of the stack without the logger wrappers
  11977. var error = new Error();
  11978. var stack = error.stack.split("\n");
  11979. if(!stack || stack.length < 1) {
  11980. return callerInfo;
  11981. }
  11982. var m = null;
  11983. if(stack[3]) {
  11984. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  11985. }
  11986. if(!m || m.length <= 4) {
  11987. //Firefox && Safari
  11988. if(stack[2].indexOf("log@") === 0){
  11989. //Safari
  11990. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  11991. } else {
  11992. //Firefox
  11993. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  11994. }
  11995. return callerInfo;
  11996. }
  11997. callerInfo.methodName = m[1];
  11998. callerInfo.fileLocation = m[2];
  11999. callerInfo.line = m[3];
  12000. callerInfo.column = m[4];
  12001. return callerInfo;
  12002. }
  12003. /**
  12004. * Logs messages using the transports and level from the logger.
  12005. * @param logger a logger instance.
  12006. * @param level the log level of the message. See the levels variable.
  12007. * @param arguments array with arguments that will be logged.
  12008. */
  12009. function log() {
  12010. var logger = arguments[0], level = arguments[1],
  12011. args = Array.prototype.slice.call(arguments, 2);
  12012. if(levels[level] <= logger.level) {
  12013. return;
  12014. }
  12015. var callerInfo = getCallerInfo();
  12016. for(var i = 0; i < logger.transports.length; i++) {
  12017. var t = logger.transports[i];
  12018. var l = t[level];
  12019. if(l && typeof(l) === "function") {
  12020. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12021. .apply(t, args);
  12022. }
  12023. }
  12024. }
  12025. /**
  12026. *
  12027. * Constructs new logger object.
  12028. * @param level the logging level for the new logger
  12029. * @param id optional identifier for the logger instance.
  12030. * @param transports optional list of handlers(objects) for the logs.
  12031. * The handlers must support - log, warn, error, debug, info, trace.
  12032. * @param format optional (NOT implemented) string.
  12033. */
  12034. function Logger(level, id, transports, format) {
  12035. this.id = id;
  12036. this.format = format;
  12037. if(!this.transports) {
  12038. this.transports = [];
  12039. this.transports.push(Logger.consoleTransport);
  12040. }
  12041. this.level = levels[level];
  12042. var methods = Object.keys(levels);
  12043. for(var i = 0; i < methods.length; i++){
  12044. this[methods[i]] =
  12045. log.bind(null, this, methods[i]);
  12046. }
  12047. }
  12048. /**
  12049. * Sets the log level for the logger.
  12050. * @param level the new log level.
  12051. */
  12052. Logger.prototype.setLevel = function (level) {
  12053. this.level = levels[level];
  12054. };
  12055. module.exports = Logger;
  12056. /**
  12057. * The default transport - console
  12058. */
  12059. Logger.consoleTransport = console;
  12060. /**
  12061. * Enum for the supported log levels.
  12062. */
  12063. Logger.levels = {
  12064. TRACE: "trace",
  12065. DEBUG: "debug",
  12066. INFO: "info",
  12067. LOG: "log",
  12068. WARN: "warn",
  12069. ERROR: "error"
  12070. };
  12071. },{}],44:[function(require,module,exports){
  12072. /* Copyright @ 2015 Atlassian Pty Ltd
  12073. *
  12074. * Licensed under the Apache License, Version 2.0 (the "License");
  12075. * you may not use this file except in compliance with the License.
  12076. * You may obtain a copy of the License at
  12077. *
  12078. * http://www.apache.org/licenses/LICENSE-2.0
  12079. *
  12080. * Unless required by applicable law or agreed to in writing, software
  12081. * distributed under the License is distributed on an "AS IS" BASIS,
  12082. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12083. * See the License for the specific language governing permissions and
  12084. * limitations under the License.
  12085. */
  12086. var Logger = require("./Logger");
  12087. /**
  12088. * Map with the created loggers with ID.
  12089. */
  12090. var idLoggers = {};
  12091. /**
  12092. * Array with the loggers without id.
  12093. */
  12094. var loggers = [];
  12095. /**
  12096. * Log level for the lbrary.
  12097. */
  12098. var curLevel = Logger.levels.TRACE;
  12099. module.exports = {
  12100. /**
  12101. * Creates new logger.
  12102. * @arguments the same as Logger constructor
  12103. */
  12104. getLogger: function(id, transports, format) {
  12105. var logger = new Logger(curLevel, id, transports, format);
  12106. if(id) {
  12107. idLoggers[id] = idLoggers[id] || [];
  12108. idLoggers[id].push(logger);
  12109. } else {
  12110. loggers.push(logger);
  12111. }
  12112. return logger;
  12113. },
  12114. /**
  12115. * Changes the log level for the existing loggers by id.
  12116. * @param level the new log level.
  12117. * @param id if specified the level will be changed only for loggers with the
  12118. * same id. Otherwise the operation will affect all loggers that don't
  12119. * have id.
  12120. */
  12121. setLogLevelById: function(level, id) {
  12122. var l = id? (idLoggers[id] || []) : loggers;
  12123. for(var i = 0; i < l.length; i++) {
  12124. l[i].setLevel(level);
  12125. }
  12126. },
  12127. /**
  12128. * Changes the log level for all existing loggers.
  12129. * @param level the new log level.
  12130. */
  12131. setLogLevel: function (level) {
  12132. curLevel = level;
  12133. var i = 0;
  12134. for(; i < loggers.length; i++) {
  12135. loggers[i].setLevel(level);
  12136. }
  12137. for(var id in idLoggers) {
  12138. var l = idLoggers[id] || [];
  12139. for(i = 0; i < l.length; i++) {
  12140. l[i].setLevel(level);
  12141. }
  12142. }
  12143. },
  12144. /**
  12145. * The supported log levels.
  12146. */
  12147. levels: Logger.levels
  12148. };
  12149. },{"./Logger":43}],45:[function(require,module,exports){
  12150. // Top level file is just a mixin of submodules & constants
  12151. 'use strict';
  12152. var assign = require('./lib/utils/common').assign;
  12153. var deflate = require('./lib/deflate');
  12154. var inflate = require('./lib/inflate');
  12155. var constants = require('./lib/zlib/constants');
  12156. var pako = {};
  12157. assign(pako, deflate, inflate, constants);
  12158. module.exports = pako;
  12159. },{"./lib/deflate":46,"./lib/inflate":47,"./lib/utils/common":48,"./lib/zlib/constants":51}],46:[function(require,module,exports){
  12160. 'use strict';
  12161. var zlib_deflate = require('./zlib/deflate.js');
  12162. var utils = require('./utils/common');
  12163. var strings = require('./utils/strings');
  12164. var msg = require('./zlib/messages');
  12165. var zstream = require('./zlib/zstream');
  12166. var toString = Object.prototype.toString;
  12167. /* Public constants ==========================================================*/
  12168. /* ===========================================================================*/
  12169. var Z_NO_FLUSH = 0;
  12170. var Z_FINISH = 4;
  12171. var Z_OK = 0;
  12172. var Z_STREAM_END = 1;
  12173. var Z_SYNC_FLUSH = 2;
  12174. var Z_DEFAULT_COMPRESSION = -1;
  12175. var Z_DEFAULT_STRATEGY = 0;
  12176. var Z_DEFLATED = 8;
  12177. /* ===========================================================================*/
  12178. /**
  12179. * class Deflate
  12180. *
  12181. * Generic JS-style wrapper for zlib calls. If you don't need
  12182. * streaming behaviour - use more simple functions: [[deflate]],
  12183. * [[deflateRaw]] and [[gzip]].
  12184. **/
  12185. /* internal
  12186. * Deflate.chunks -> Array
  12187. *
  12188. * Chunks of output data, if [[Deflate#onData]] not overriden.
  12189. **/
  12190. /**
  12191. * Deflate.result -> Uint8Array|Array
  12192. *
  12193. * Compressed result, generated by default [[Deflate#onData]]
  12194. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  12195. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  12196. * push a chunk with explicit flush (call [[Deflate#push]] with
  12197. * `Z_SYNC_FLUSH` param).
  12198. **/
  12199. /**
  12200. * Deflate.err -> Number
  12201. *
  12202. * Error code after deflate finished. 0 (Z_OK) on success.
  12203. * You will not need it in real life, because deflate errors
  12204. * are possible only on wrong options or bad `onData` / `onEnd`
  12205. * custom handlers.
  12206. **/
  12207. /**
  12208. * Deflate.msg -> String
  12209. *
  12210. * Error message, if [[Deflate.err]] != 0
  12211. **/
  12212. /**
  12213. * new Deflate(options)
  12214. * - options (Object): zlib deflate options.
  12215. *
  12216. * Creates new deflator instance with specified params. Throws exception
  12217. * on bad params. Supported options:
  12218. *
  12219. * - `level`
  12220. * - `windowBits`
  12221. * - `memLevel`
  12222. * - `strategy`
  12223. *
  12224. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12225. * for more information on these.
  12226. *
  12227. * Additional options, for internal needs:
  12228. *
  12229. * - `chunkSize` - size of generated data chunks (16K by default)
  12230. * - `raw` (Boolean) - do raw deflate
  12231. * - `gzip` (Boolean) - create gzip wrapper
  12232. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12233. * (each char code [0..255])
  12234. * - `header` (Object) - custom header for gzip
  12235. * - `text` (Boolean) - true if compressed data believed to be text
  12236. * - `time` (Number) - modification time, unix timestamp
  12237. * - `os` (Number) - operation system code
  12238. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12239. * - `name` (String) - file name (binary string)
  12240. * - `comment` (String) - comment (binary string)
  12241. * - `hcrc` (Boolean) - true if header crc should be added
  12242. *
  12243. * ##### Example:
  12244. *
  12245. * ```javascript
  12246. * var pako = require('pako')
  12247. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12248. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12249. *
  12250. * var deflate = new pako.Deflate({ level: 3});
  12251. *
  12252. * deflate.push(chunk1, false);
  12253. * deflate.push(chunk2, true); // true -> last chunk
  12254. *
  12255. * if (deflate.err) { throw new Error(deflate.err); }
  12256. *
  12257. * console.log(deflate.result);
  12258. * ```
  12259. **/
  12260. var Deflate = function(options) {
  12261. this.options = utils.assign({
  12262. level: Z_DEFAULT_COMPRESSION,
  12263. method: Z_DEFLATED,
  12264. chunkSize: 16384,
  12265. windowBits: 15,
  12266. memLevel: 8,
  12267. strategy: Z_DEFAULT_STRATEGY,
  12268. to: ''
  12269. }, options || {});
  12270. var opt = this.options;
  12271. if (opt.raw && (opt.windowBits > 0)) {
  12272. opt.windowBits = -opt.windowBits;
  12273. }
  12274. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12275. opt.windowBits += 16;
  12276. }
  12277. this.err = 0; // error code, if happens (0 = Z_OK)
  12278. this.msg = ''; // error message
  12279. this.ended = false; // used to avoid multiple onEnd() calls
  12280. this.chunks = []; // chunks of compressed data
  12281. this.strm = new zstream();
  12282. this.strm.avail_out = 0;
  12283. var status = zlib_deflate.deflateInit2(
  12284. this.strm,
  12285. opt.level,
  12286. opt.method,
  12287. opt.windowBits,
  12288. opt.memLevel,
  12289. opt.strategy
  12290. );
  12291. if (status !== Z_OK) {
  12292. throw new Error(msg[status]);
  12293. }
  12294. if (opt.header) {
  12295. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12296. }
  12297. };
  12298. /**
  12299. * Deflate#push(data[, mode]) -> Boolean
  12300. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12301. * converted to utf8 byte sequence.
  12302. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12303. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12304. *
  12305. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12306. * new compressed chunks. Returns `true` on success. The last data block must have
  12307. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12308. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12309. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12310. *
  12311. * On fail call [[Deflate#onEnd]] with error code and return false.
  12312. *
  12313. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12314. * array format is detected automatically). Also, don't skip last param and always
  12315. * use the same type in your code (boolean or number). That will improve JS speed.
  12316. *
  12317. * For regular `Array`-s make sure all elements are [0..255].
  12318. *
  12319. * ##### Example
  12320. *
  12321. * ```javascript
  12322. * push(chunk, false); // push one of data chunks
  12323. * ...
  12324. * push(chunk, true); // push last chunk
  12325. * ```
  12326. **/
  12327. Deflate.prototype.push = function(data, mode) {
  12328. var strm = this.strm;
  12329. var chunkSize = this.options.chunkSize;
  12330. var status, _mode;
  12331. if (this.ended) { return false; }
  12332. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  12333. // Convert data if needed
  12334. if (typeof data === 'string') {
  12335. // If we need to compress text, change encoding to utf8.
  12336. strm.input = strings.string2buf(data);
  12337. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12338. strm.input = new Uint8Array(data);
  12339. } else {
  12340. strm.input = data;
  12341. }
  12342. strm.next_in = 0;
  12343. strm.avail_in = strm.input.length;
  12344. do {
  12345. if (strm.avail_out === 0) {
  12346. strm.output = new utils.Buf8(chunkSize);
  12347. strm.next_out = 0;
  12348. strm.avail_out = chunkSize;
  12349. }
  12350. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  12351. if (status !== Z_STREAM_END && status !== Z_OK) {
  12352. this.onEnd(status);
  12353. this.ended = true;
  12354. return false;
  12355. }
  12356. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  12357. if (this.options.to === 'string') {
  12358. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  12359. } else {
  12360. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12361. }
  12362. }
  12363. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  12364. // Finalize on the last chunk.
  12365. if (_mode === Z_FINISH) {
  12366. status = zlib_deflate.deflateEnd(this.strm);
  12367. this.onEnd(status);
  12368. this.ended = true;
  12369. return status === Z_OK;
  12370. }
  12371. // callback interim results if Z_SYNC_FLUSH.
  12372. if (_mode === Z_SYNC_FLUSH) {
  12373. this.onEnd(Z_OK);
  12374. strm.avail_out = 0;
  12375. return true;
  12376. }
  12377. return true;
  12378. };
  12379. /**
  12380. * Deflate#onData(chunk) -> Void
  12381. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12382. * on js engine support. When string output requested, each chunk
  12383. * will be string.
  12384. *
  12385. * By default, stores data blocks in `chunks[]` property and glue
  12386. * those in `onEnd`. Override this handler, if you need another behaviour.
  12387. **/
  12388. Deflate.prototype.onData = function(chunk) {
  12389. this.chunks.push(chunk);
  12390. };
  12391. /**
  12392. * Deflate#onEnd(status) -> Void
  12393. * - status (Number): deflate status. 0 (Z_OK) on success,
  12394. * other if not.
  12395. *
  12396. * Called once after you tell deflate that the input stream is
  12397. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12398. * or if an error happened. By default - join collected chunks,
  12399. * free memory and fill `results` / `err` properties.
  12400. **/
  12401. Deflate.prototype.onEnd = function(status) {
  12402. // On success - join
  12403. if (status === Z_OK) {
  12404. if (this.options.to === 'string') {
  12405. this.result = this.chunks.join('');
  12406. } else {
  12407. this.result = utils.flattenChunks(this.chunks);
  12408. }
  12409. }
  12410. this.chunks = [];
  12411. this.err = status;
  12412. this.msg = this.strm.msg;
  12413. };
  12414. /**
  12415. * deflate(data[, options]) -> Uint8Array|Array|String
  12416. * - data (Uint8Array|Array|String): input data to compress.
  12417. * - options (Object): zlib deflate options.
  12418. *
  12419. * Compress `data` with deflate alrorythm and `options`.
  12420. *
  12421. * Supported options are:
  12422. *
  12423. * - level
  12424. * - windowBits
  12425. * - memLevel
  12426. * - strategy
  12427. *
  12428. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12429. * for more information on these.
  12430. *
  12431. * Sugar (options):
  12432. *
  12433. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12434. * negative windowBits implicitly.
  12435. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12436. * (each char code [0..255])
  12437. *
  12438. * ##### Example:
  12439. *
  12440. * ```javascript
  12441. * var pako = require('pako')
  12442. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  12443. *
  12444. * console.log(pako.deflate(data));
  12445. * ```
  12446. **/
  12447. function deflate(input, options) {
  12448. var deflator = new Deflate(options);
  12449. deflator.push(input, true);
  12450. // That will never happens, if you don't cheat with options :)
  12451. if (deflator.err) { throw deflator.msg; }
  12452. return deflator.result;
  12453. }
  12454. /**
  12455. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  12456. * - data (Uint8Array|Array|String): input data to compress.
  12457. * - options (Object): zlib deflate options.
  12458. *
  12459. * The same as [[deflate]], but creates raw data, without wrapper
  12460. * (header and adler32 crc).
  12461. **/
  12462. function deflateRaw(input, options) {
  12463. options = options || {};
  12464. options.raw = true;
  12465. return deflate(input, options);
  12466. }
  12467. /**
  12468. * gzip(data[, options]) -> Uint8Array|Array|String
  12469. * - data (Uint8Array|Array|String): input data to compress.
  12470. * - options (Object): zlib deflate options.
  12471. *
  12472. * The same as [[deflate]], but create gzip wrapper instead of
  12473. * deflate one.
  12474. **/
  12475. function gzip(input, options) {
  12476. options = options || {};
  12477. options.gzip = true;
  12478. return deflate(input, options);
  12479. }
  12480. exports.Deflate = Deflate;
  12481. exports.deflate = deflate;
  12482. exports.deflateRaw = deflateRaw;
  12483. exports.gzip = gzip;
  12484. },{"./utils/common":48,"./utils/strings":49,"./zlib/deflate.js":53,"./zlib/messages":58,"./zlib/zstream":60}],47:[function(require,module,exports){
  12485. 'use strict';
  12486. var zlib_inflate = require('./zlib/inflate.js');
  12487. var utils = require('./utils/common');
  12488. var strings = require('./utils/strings');
  12489. var c = require('./zlib/constants');
  12490. var msg = require('./zlib/messages');
  12491. var zstream = require('./zlib/zstream');
  12492. var gzheader = require('./zlib/gzheader');
  12493. var toString = Object.prototype.toString;
  12494. /**
  12495. * class Inflate
  12496. *
  12497. * Generic JS-style wrapper for zlib calls. If you don't need
  12498. * streaming behaviour - use more simple functions: [[inflate]]
  12499. * and [[inflateRaw]].
  12500. **/
  12501. /* internal
  12502. * inflate.chunks -> Array
  12503. *
  12504. * Chunks of output data, if [[Inflate#onData]] not overriden.
  12505. **/
  12506. /**
  12507. * Inflate.result -> Uint8Array|Array|String
  12508. *
  12509. * Uncompressed result, generated by default [[Inflate#onData]]
  12510. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  12511. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  12512. * push a chunk with explicit flush (call [[Inflate#push]] with
  12513. * `Z_SYNC_FLUSH` param).
  12514. **/
  12515. /**
  12516. * Inflate.err -> Number
  12517. *
  12518. * Error code after inflate finished. 0 (Z_OK) on success.
  12519. * Should be checked if broken data possible.
  12520. **/
  12521. /**
  12522. * Inflate.msg -> String
  12523. *
  12524. * Error message, if [[Inflate.err]] != 0
  12525. **/
  12526. /**
  12527. * new Inflate(options)
  12528. * - options (Object): zlib inflate options.
  12529. *
  12530. * Creates new inflator instance with specified params. Throws exception
  12531. * on bad params. Supported options:
  12532. *
  12533. * - `windowBits`
  12534. *
  12535. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12536. * for more information on these.
  12537. *
  12538. * Additional options, for internal needs:
  12539. *
  12540. * - `chunkSize` - size of generated data chunks (16K by default)
  12541. * - `raw` (Boolean) - do raw inflate
  12542. * - `to` (String) - if equal to 'string', then result will be converted
  12543. * from utf8 to utf16 (javascript) string. When string output requested,
  12544. * chunk length can differ from `chunkSize`, depending on content.
  12545. *
  12546. * By default, when no options set, autodetect deflate/gzip data format via
  12547. * wrapper header.
  12548. *
  12549. * ##### Example:
  12550. *
  12551. * ```javascript
  12552. * var pako = require('pako')
  12553. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12554. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12555. *
  12556. * var inflate = new pako.Inflate({ level: 3});
  12557. *
  12558. * inflate.push(chunk1, false);
  12559. * inflate.push(chunk2, true); // true -> last chunk
  12560. *
  12561. * if (inflate.err) { throw new Error(inflate.err); }
  12562. *
  12563. * console.log(inflate.result);
  12564. * ```
  12565. **/
  12566. var Inflate = function(options) {
  12567. this.options = utils.assign({
  12568. chunkSize: 16384,
  12569. windowBits: 0,
  12570. to: ''
  12571. }, options || {});
  12572. var opt = this.options;
  12573. // Force window size for `raw` data, if not set directly,
  12574. // because we have no header for autodetect.
  12575. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  12576. opt.windowBits = -opt.windowBits;
  12577. if (opt.windowBits === 0) { opt.windowBits = -15; }
  12578. }
  12579. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  12580. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  12581. !(options && options.windowBits)) {
  12582. opt.windowBits += 32;
  12583. }
  12584. // Gzip header has no info about windows size, we can do autodetect only
  12585. // for deflate. So, if window size not set, force it to max when gzip possible
  12586. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  12587. // bit 3 (16) -> gzipped data
  12588. // bit 4 (32) -> autodetect gzip/deflate
  12589. if ((opt.windowBits & 15) === 0) {
  12590. opt.windowBits |= 15;
  12591. }
  12592. }
  12593. this.err = 0; // error code, if happens (0 = Z_OK)
  12594. this.msg = ''; // error message
  12595. this.ended = false; // used to avoid multiple onEnd() calls
  12596. this.chunks = []; // chunks of compressed data
  12597. this.strm = new zstream();
  12598. this.strm.avail_out = 0;
  12599. var status = zlib_inflate.inflateInit2(
  12600. this.strm,
  12601. opt.windowBits
  12602. );
  12603. if (status !== c.Z_OK) {
  12604. throw new Error(msg[status]);
  12605. }
  12606. this.header = new gzheader();
  12607. zlib_inflate.inflateGetHeader(this.strm, this.header);
  12608. };
  12609. /**
  12610. * Inflate#push(data[, mode]) -> Boolean
  12611. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  12612. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12613. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12614. *
  12615. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  12616. * new output chunks. Returns `true` on success. The last data block must have
  12617. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12618. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12619. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  12620. *
  12621. * On fail call [[Inflate#onEnd]] with error code and return false.
  12622. *
  12623. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12624. * format is detected automatically). Also, don't skip last param and always
  12625. * use the same type in your code (boolean or number). That will improve JS speed.
  12626. *
  12627. * For regular `Array`-s make sure all elements are [0..255].
  12628. *
  12629. * ##### Example
  12630. *
  12631. * ```javascript
  12632. * push(chunk, false); // push one of data chunks
  12633. * ...
  12634. * push(chunk, true); // push last chunk
  12635. * ```
  12636. **/
  12637. Inflate.prototype.push = function(data, mode) {
  12638. var strm = this.strm;
  12639. var chunkSize = this.options.chunkSize;
  12640. var status, _mode;
  12641. var next_out_utf8, tail, utf8str;
  12642. // Flag to properly process Z_BUF_ERROR on testing inflate call
  12643. // when we check that all output data was flushed.
  12644. var allowBufError = false;
  12645. if (this.ended) { return false; }
  12646. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  12647. // Convert data if needed
  12648. if (typeof data === 'string') {
  12649. // Only binary strings can be decompressed on practice
  12650. strm.input = strings.binstring2buf(data);
  12651. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12652. strm.input = new Uint8Array(data);
  12653. } else {
  12654. strm.input = data;
  12655. }
  12656. strm.next_in = 0;
  12657. strm.avail_in = strm.input.length;
  12658. do {
  12659. if (strm.avail_out === 0) {
  12660. strm.output = new utils.Buf8(chunkSize);
  12661. strm.next_out = 0;
  12662. strm.avail_out = chunkSize;
  12663. }
  12664. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  12665. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  12666. status = c.Z_OK;
  12667. allowBufError = false;
  12668. }
  12669. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  12670. this.onEnd(status);
  12671. this.ended = true;
  12672. return false;
  12673. }
  12674. if (strm.next_out) {
  12675. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  12676. if (this.options.to === 'string') {
  12677. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  12678. tail = strm.next_out - next_out_utf8;
  12679. utf8str = strings.buf2string(strm.output, next_out_utf8);
  12680. // move tail
  12681. strm.next_out = tail;
  12682. strm.avail_out = chunkSize - tail;
  12683. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  12684. this.onData(utf8str);
  12685. } else {
  12686. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12687. }
  12688. }
  12689. }
  12690. // When no more input data, we should check that internal inflate buffers
  12691. // are flushed. The only way to do it when avail_out = 0 - run one more
  12692. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  12693. // Here we set flag to process this error properly.
  12694. //
  12695. // NOTE. Deflate does not return error in this case and does not needs such
  12696. // logic.
  12697. if (strm.avail_in === 0 && strm.avail_out === 0) {
  12698. allowBufError = true;
  12699. }
  12700. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  12701. if (status === c.Z_STREAM_END) {
  12702. _mode = c.Z_FINISH;
  12703. }
  12704. // Finalize on the last chunk.
  12705. if (_mode === c.Z_FINISH) {
  12706. status = zlib_inflate.inflateEnd(this.strm);
  12707. this.onEnd(status);
  12708. this.ended = true;
  12709. return status === c.Z_OK;
  12710. }
  12711. // callback interim results if Z_SYNC_FLUSH.
  12712. if (_mode === c.Z_SYNC_FLUSH) {
  12713. this.onEnd(c.Z_OK);
  12714. strm.avail_out = 0;
  12715. return true;
  12716. }
  12717. return true;
  12718. };
  12719. /**
  12720. * Inflate#onData(chunk) -> Void
  12721. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12722. * on js engine support. When string output requested, each chunk
  12723. * will be string.
  12724. *
  12725. * By default, stores data blocks in `chunks[]` property and glue
  12726. * those in `onEnd`. Override this handler, if you need another behaviour.
  12727. **/
  12728. Inflate.prototype.onData = function(chunk) {
  12729. this.chunks.push(chunk);
  12730. };
  12731. /**
  12732. * Inflate#onEnd(status) -> Void
  12733. * - status (Number): inflate status. 0 (Z_OK) on success,
  12734. * other if not.
  12735. *
  12736. * Called either after you tell inflate that the input stream is
  12737. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12738. * or if an error happened. By default - join collected chunks,
  12739. * free memory and fill `results` / `err` properties.
  12740. **/
  12741. Inflate.prototype.onEnd = function(status) {
  12742. // On success - join
  12743. if (status === c.Z_OK) {
  12744. if (this.options.to === 'string') {
  12745. // Glue & convert here, until we teach pako to send
  12746. // utf8 alligned strings to onData
  12747. this.result = this.chunks.join('');
  12748. } else {
  12749. this.result = utils.flattenChunks(this.chunks);
  12750. }
  12751. }
  12752. this.chunks = [];
  12753. this.err = status;
  12754. this.msg = this.strm.msg;
  12755. };
  12756. /**
  12757. * inflate(data[, options]) -> Uint8Array|Array|String
  12758. * - data (Uint8Array|Array|String): input data to decompress.
  12759. * - options (Object): zlib inflate options.
  12760. *
  12761. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  12762. * format via wrapper header by default. That's why we don't provide
  12763. * separate `ungzip` method.
  12764. *
  12765. * Supported options are:
  12766. *
  12767. * - windowBits
  12768. *
  12769. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12770. * for more information.
  12771. *
  12772. * Sugar (options):
  12773. *
  12774. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12775. * negative windowBits implicitly.
  12776. * - `to` (String) - if equal to 'string', then result will be converted
  12777. * from utf8 to utf16 (javascript) string. When string output requested,
  12778. * chunk length can differ from `chunkSize`, depending on content.
  12779. *
  12780. *
  12781. * ##### Example:
  12782. *
  12783. * ```javascript
  12784. * var pako = require('pako')
  12785. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  12786. * , output;
  12787. *
  12788. * try {
  12789. * output = pako.inflate(input);
  12790. * } catch (err)
  12791. * console.log(err);
  12792. * }
  12793. * ```
  12794. **/
  12795. function inflate(input, options) {
  12796. var inflator = new Inflate(options);
  12797. inflator.push(input, true);
  12798. // That will never happens, if you don't cheat with options :)
  12799. if (inflator.err) { throw inflator.msg; }
  12800. return inflator.result;
  12801. }
  12802. /**
  12803. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  12804. * - data (Uint8Array|Array|String): input data to decompress.
  12805. * - options (Object): zlib inflate options.
  12806. *
  12807. * The same as [[inflate]], but creates raw data, without wrapper
  12808. * (header and adler32 crc).
  12809. **/
  12810. function inflateRaw(input, options) {
  12811. options = options || {};
  12812. options.raw = true;
  12813. return inflate(input, options);
  12814. }
  12815. /**
  12816. * ungzip(data[, options]) -> Uint8Array|Array|String
  12817. * - data (Uint8Array|Array|String): input data to decompress.
  12818. * - options (Object): zlib inflate options.
  12819. *
  12820. * Just shortcut to [[inflate]], because it autodetects format
  12821. * by header.content. Done for convenience.
  12822. **/
  12823. exports.Inflate = Inflate;
  12824. exports.inflate = inflate;
  12825. exports.inflateRaw = inflateRaw;
  12826. exports.ungzip = inflate;
  12827. },{"./utils/common":48,"./utils/strings":49,"./zlib/constants":51,"./zlib/gzheader":54,"./zlib/inflate.js":56,"./zlib/messages":58,"./zlib/zstream":60}],48:[function(require,module,exports){
  12828. 'use strict';
  12829. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  12830. (typeof Uint16Array !== 'undefined') &&
  12831. (typeof Int32Array !== 'undefined');
  12832. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  12833. var sources = Array.prototype.slice.call(arguments, 1);
  12834. while (sources.length) {
  12835. var source = sources.shift();
  12836. if (!source) { continue; }
  12837. if (typeof source !== 'object') {
  12838. throw new TypeError(source + 'must be non-object');
  12839. }
  12840. for (var p in source) {
  12841. if (source.hasOwnProperty(p)) {
  12842. obj[p] = source[p];
  12843. }
  12844. }
  12845. }
  12846. return obj;
  12847. };
  12848. // reduce buffer size, avoiding mem copy
  12849. exports.shrinkBuf = function (buf, size) {
  12850. if (buf.length === size) { return buf; }
  12851. if (buf.subarray) { return buf.subarray(0, size); }
  12852. buf.length = size;
  12853. return buf;
  12854. };
  12855. var fnTyped = {
  12856. arraySet: function (dest, src, src_offs, len, dest_offs) {
  12857. if (src.subarray && dest.subarray) {
  12858. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  12859. return;
  12860. }
  12861. // Fallback to ordinary array
  12862. for (var i=0; i<len; i++) {
  12863. dest[dest_offs + i] = src[src_offs + i];
  12864. }
  12865. },
  12866. // Join array of chunks to single array.
  12867. flattenChunks: function(chunks) {
  12868. var i, l, len, pos, chunk, result;
  12869. // calculate data length
  12870. len = 0;
  12871. for (i=0, l=chunks.length; i<l; i++) {
  12872. len += chunks[i].length;
  12873. }
  12874. // join chunks
  12875. result = new Uint8Array(len);
  12876. pos = 0;
  12877. for (i=0, l=chunks.length; i<l; i++) {
  12878. chunk = chunks[i];
  12879. result.set(chunk, pos);
  12880. pos += chunk.length;
  12881. }
  12882. return result;
  12883. }
  12884. };
  12885. var fnUntyped = {
  12886. arraySet: function (dest, src, src_offs, len, dest_offs) {
  12887. for (var i=0; i<len; i++) {
  12888. dest[dest_offs + i] = src[src_offs + i];
  12889. }
  12890. },
  12891. // Join array of chunks to single array.
  12892. flattenChunks: function(chunks) {
  12893. return [].concat.apply([], chunks);
  12894. }
  12895. };
  12896. // Enable/Disable typed arrays use, for testing
  12897. //
  12898. exports.setTyped = function (on) {
  12899. if (on) {
  12900. exports.Buf8 = Uint8Array;
  12901. exports.Buf16 = Uint16Array;
  12902. exports.Buf32 = Int32Array;
  12903. exports.assign(exports, fnTyped);
  12904. } else {
  12905. exports.Buf8 = Array;
  12906. exports.Buf16 = Array;
  12907. exports.Buf32 = Array;
  12908. exports.assign(exports, fnUntyped);
  12909. }
  12910. };
  12911. exports.setTyped(TYPED_OK);
  12912. },{}],49:[function(require,module,exports){
  12913. // String encode/decode helpers
  12914. 'use strict';
  12915. var utils = require('./common');
  12916. // Quick check if we can use fast array to bin string conversion
  12917. //
  12918. // - apply(Array) can fail on Android 2.2
  12919. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  12920. //
  12921. var STR_APPLY_OK = true;
  12922. var STR_APPLY_UIA_OK = true;
  12923. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  12924. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  12925. // Table with utf8 lengths (calculated by first byte of sequence)
  12926. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  12927. // because max possible codepoint is 0x10ffff
  12928. var _utf8len = new utils.Buf8(256);
  12929. for (var q=0; q<256; q++) {
  12930. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  12931. }
  12932. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  12933. // convert string to array (typed, when possible)
  12934. exports.string2buf = function (str) {
  12935. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  12936. // count binary size
  12937. for (m_pos = 0; m_pos < str_len; m_pos++) {
  12938. c = str.charCodeAt(m_pos);
  12939. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  12940. c2 = str.charCodeAt(m_pos+1);
  12941. if ((c2 & 0xfc00) === 0xdc00) {
  12942. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  12943. m_pos++;
  12944. }
  12945. }
  12946. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  12947. }
  12948. // allocate buffer
  12949. buf = new utils.Buf8(buf_len);
  12950. // convert
  12951. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  12952. c = str.charCodeAt(m_pos);
  12953. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  12954. c2 = str.charCodeAt(m_pos+1);
  12955. if ((c2 & 0xfc00) === 0xdc00) {
  12956. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  12957. m_pos++;
  12958. }
  12959. }
  12960. if (c < 0x80) {
  12961. /* one byte */
  12962. buf[i++] = c;
  12963. } else if (c < 0x800) {
  12964. /* two bytes */
  12965. buf[i++] = 0xC0 | (c >>> 6);
  12966. buf[i++] = 0x80 | (c & 0x3f);
  12967. } else if (c < 0x10000) {
  12968. /* three bytes */
  12969. buf[i++] = 0xE0 | (c >>> 12);
  12970. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  12971. buf[i++] = 0x80 | (c & 0x3f);
  12972. } else {
  12973. /* four bytes */
  12974. buf[i++] = 0xf0 | (c >>> 18);
  12975. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  12976. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  12977. buf[i++] = 0x80 | (c & 0x3f);
  12978. }
  12979. }
  12980. return buf;
  12981. };
  12982. // Helper (used in 2 places)
  12983. function buf2binstring(buf, len) {
  12984. // use fallback for big arrays to avoid stack overflow
  12985. if (len < 65537) {
  12986. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  12987. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  12988. }
  12989. }
  12990. var result = '';
  12991. for (var i=0; i < len; i++) {
  12992. result += String.fromCharCode(buf[i]);
  12993. }
  12994. return result;
  12995. }
  12996. // Convert byte array to binary string
  12997. exports.buf2binstring = function(buf) {
  12998. return buf2binstring(buf, buf.length);
  12999. };
  13000. // Convert binary string (typed, when possible)
  13001. exports.binstring2buf = function(str) {
  13002. var buf = new utils.Buf8(str.length);
  13003. for (var i=0, len=buf.length; i < len; i++) {
  13004. buf[i] = str.charCodeAt(i);
  13005. }
  13006. return buf;
  13007. };
  13008. // convert array to string
  13009. exports.buf2string = function (buf, max) {
  13010. var i, out, c, c_len;
  13011. var len = max || buf.length;
  13012. // Reserve max possible length (2 words per char)
  13013. // NB: by unknown reasons, Array is significantly faster for
  13014. // String.fromCharCode.apply than Uint16Array.
  13015. var utf16buf = new Array(len*2);
  13016. for (out=0, i=0; i<len;) {
  13017. c = buf[i++];
  13018. // quick process ascii
  13019. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13020. c_len = _utf8len[c];
  13021. // skip 5 & 6 byte codes
  13022. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13023. // apply mask on first byte
  13024. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13025. // join the rest
  13026. while (c_len > 1 && i < len) {
  13027. c = (c << 6) | (buf[i++] & 0x3f);
  13028. c_len--;
  13029. }
  13030. // terminated by end of string?
  13031. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13032. if (c < 0x10000) {
  13033. utf16buf[out++] = c;
  13034. } else {
  13035. c -= 0x10000;
  13036. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13037. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13038. }
  13039. }
  13040. return buf2binstring(utf16buf, out);
  13041. };
  13042. // Calculate max possible position in utf8 buffer,
  13043. // that will not break sequence. If that's not possible
  13044. // - (very small limits) return max size as is.
  13045. //
  13046. // buf[] - utf8 bytes array
  13047. // max - length limit (mandatory);
  13048. exports.utf8border = function(buf, max) {
  13049. var pos;
  13050. max = max || buf.length;
  13051. if (max > buf.length) { max = buf.length; }
  13052. // go back from last position, until start of sequence found
  13053. pos = max-1;
  13054. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13055. // Fuckup - very small and broken sequence,
  13056. // return max, because we should return something anyway.
  13057. if (pos < 0) { return max; }
  13058. // If we came to start of buffer - that means vuffer is too small,
  13059. // return max too.
  13060. if (pos === 0) { return max; }
  13061. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13062. };
  13063. },{"./common":48}],50:[function(require,module,exports){
  13064. 'use strict';
  13065. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13066. // It doesn't worth to make additional optimizationa as in original.
  13067. // Small size is preferable.
  13068. function adler32(adler, buf, len, pos) {
  13069. var s1 = (adler & 0xffff) |0,
  13070. s2 = ((adler >>> 16) & 0xffff) |0,
  13071. n = 0;
  13072. while (len !== 0) {
  13073. // Set limit ~ twice less than 5552, to keep
  13074. // s2 in 31-bits, because we force signed ints.
  13075. // in other case %= will fail.
  13076. n = len > 2000 ? 2000 : len;
  13077. len -= n;
  13078. do {
  13079. s1 = (s1 + buf[pos++]) |0;
  13080. s2 = (s2 + s1) |0;
  13081. } while (--n);
  13082. s1 %= 65521;
  13083. s2 %= 65521;
  13084. }
  13085. return (s1 | (s2 << 16)) |0;
  13086. }
  13087. module.exports = adler32;
  13088. },{}],51:[function(require,module,exports){
  13089. module.exports = {
  13090. /* Allowed flush values; see deflate() and inflate() below for details */
  13091. Z_NO_FLUSH: 0,
  13092. Z_PARTIAL_FLUSH: 1,
  13093. Z_SYNC_FLUSH: 2,
  13094. Z_FULL_FLUSH: 3,
  13095. Z_FINISH: 4,
  13096. Z_BLOCK: 5,
  13097. Z_TREES: 6,
  13098. /* Return codes for the compression/decompression functions. Negative values
  13099. * are errors, positive values are used for special but normal events.
  13100. */
  13101. Z_OK: 0,
  13102. Z_STREAM_END: 1,
  13103. Z_NEED_DICT: 2,
  13104. Z_ERRNO: -1,
  13105. Z_STREAM_ERROR: -2,
  13106. Z_DATA_ERROR: -3,
  13107. //Z_MEM_ERROR: -4,
  13108. Z_BUF_ERROR: -5,
  13109. //Z_VERSION_ERROR: -6,
  13110. /* compression levels */
  13111. Z_NO_COMPRESSION: 0,
  13112. Z_BEST_SPEED: 1,
  13113. Z_BEST_COMPRESSION: 9,
  13114. Z_DEFAULT_COMPRESSION: -1,
  13115. Z_FILTERED: 1,
  13116. Z_HUFFMAN_ONLY: 2,
  13117. Z_RLE: 3,
  13118. Z_FIXED: 4,
  13119. Z_DEFAULT_STRATEGY: 0,
  13120. /* Possible values of the data_type field (though see inflate()) */
  13121. Z_BINARY: 0,
  13122. Z_TEXT: 1,
  13123. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13124. Z_UNKNOWN: 2,
  13125. /* The deflate compression method */
  13126. Z_DEFLATED: 8
  13127. //Z_NULL: null // Use -1 or null inline, depending on var type
  13128. };
  13129. },{}],52:[function(require,module,exports){
  13130. 'use strict';
  13131. // Note: we can't get significant speed boost here.
  13132. // So write code to minimize size - no pregenerated tables
  13133. // and array tools dependencies.
  13134. // Use ordinary array, since untyped makes no boost here
  13135. function makeTable() {
  13136. var c, table = [];
  13137. for (var n =0; n < 256; n++) {
  13138. c = n;
  13139. for (var k =0; k < 8; k++) {
  13140. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13141. }
  13142. table[n] = c;
  13143. }
  13144. return table;
  13145. }
  13146. // Create table on load. Just 255 signed longs. Not a problem.
  13147. var crcTable = makeTable();
  13148. function crc32(crc, buf, len, pos) {
  13149. var t = crcTable,
  13150. end = pos + len;
  13151. crc = crc ^ (-1);
  13152. for (var i = pos; i < end; i++) {
  13153. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13154. }
  13155. return (crc ^ (-1)); // >>> 0;
  13156. }
  13157. module.exports = crc32;
  13158. },{}],53:[function(require,module,exports){
  13159. 'use strict';
  13160. var utils = require('../utils/common');
  13161. var trees = require('./trees');
  13162. var adler32 = require('./adler32');
  13163. var crc32 = require('./crc32');
  13164. var msg = require('./messages');
  13165. /* Public constants ==========================================================*/
  13166. /* ===========================================================================*/
  13167. /* Allowed flush values; see deflate() and inflate() below for details */
  13168. var Z_NO_FLUSH = 0;
  13169. var Z_PARTIAL_FLUSH = 1;
  13170. //var Z_SYNC_FLUSH = 2;
  13171. var Z_FULL_FLUSH = 3;
  13172. var Z_FINISH = 4;
  13173. var Z_BLOCK = 5;
  13174. //var Z_TREES = 6;
  13175. /* Return codes for the compression/decompression functions. Negative values
  13176. * are errors, positive values are used for special but normal events.
  13177. */
  13178. var Z_OK = 0;
  13179. var Z_STREAM_END = 1;
  13180. //var Z_NEED_DICT = 2;
  13181. //var Z_ERRNO = -1;
  13182. var Z_STREAM_ERROR = -2;
  13183. var Z_DATA_ERROR = -3;
  13184. //var Z_MEM_ERROR = -4;
  13185. var Z_BUF_ERROR = -5;
  13186. //var Z_VERSION_ERROR = -6;
  13187. /* compression levels */
  13188. //var Z_NO_COMPRESSION = 0;
  13189. //var Z_BEST_SPEED = 1;
  13190. //var Z_BEST_COMPRESSION = 9;
  13191. var Z_DEFAULT_COMPRESSION = -1;
  13192. var Z_FILTERED = 1;
  13193. var Z_HUFFMAN_ONLY = 2;
  13194. var Z_RLE = 3;
  13195. var Z_FIXED = 4;
  13196. var Z_DEFAULT_STRATEGY = 0;
  13197. /* Possible values of the data_type field (though see inflate()) */
  13198. //var Z_BINARY = 0;
  13199. //var Z_TEXT = 1;
  13200. //var Z_ASCII = 1; // = Z_TEXT
  13201. var Z_UNKNOWN = 2;
  13202. /* The deflate compression method */
  13203. var Z_DEFLATED = 8;
  13204. /*============================================================================*/
  13205. var MAX_MEM_LEVEL = 9;
  13206. /* Maximum value for memLevel in deflateInit2 */
  13207. var MAX_WBITS = 15;
  13208. /* 32K LZ77 window */
  13209. var DEF_MEM_LEVEL = 8;
  13210. var LENGTH_CODES = 29;
  13211. /* number of length codes, not counting the special END_BLOCK code */
  13212. var LITERALS = 256;
  13213. /* number of literal bytes 0..255 */
  13214. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13215. /* number of Literal or Length codes, including the END_BLOCK code */
  13216. var D_CODES = 30;
  13217. /* number of distance codes */
  13218. var BL_CODES = 19;
  13219. /* number of codes used to transfer the bit lengths */
  13220. var HEAP_SIZE = 2*L_CODES + 1;
  13221. /* maximum heap size */
  13222. var MAX_BITS = 15;
  13223. /* All codes must not exceed MAX_BITS bits */
  13224. var MIN_MATCH = 3;
  13225. var MAX_MATCH = 258;
  13226. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13227. var PRESET_DICT = 0x20;
  13228. var INIT_STATE = 42;
  13229. var EXTRA_STATE = 69;
  13230. var NAME_STATE = 73;
  13231. var COMMENT_STATE = 91;
  13232. var HCRC_STATE = 103;
  13233. var BUSY_STATE = 113;
  13234. var FINISH_STATE = 666;
  13235. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13236. var BS_BLOCK_DONE = 2; /* block flush performed */
  13237. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13238. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13239. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13240. function err(strm, errorCode) {
  13241. strm.msg = msg[errorCode];
  13242. return errorCode;
  13243. }
  13244. function rank(f) {
  13245. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13246. }
  13247. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13248. /* =========================================================================
  13249. * Flush as much pending output as possible. All deflate() output goes
  13250. * through this function so some applications may wish to modify it
  13251. * to avoid allocating a large strm->output buffer and copying into it.
  13252. * (See also read_buf()).
  13253. */
  13254. function flush_pending(strm) {
  13255. var s = strm.state;
  13256. //_tr_flush_bits(s);
  13257. var len = s.pending;
  13258. if (len > strm.avail_out) {
  13259. len = strm.avail_out;
  13260. }
  13261. if (len === 0) { return; }
  13262. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13263. strm.next_out += len;
  13264. s.pending_out += len;
  13265. strm.total_out += len;
  13266. strm.avail_out -= len;
  13267. s.pending -= len;
  13268. if (s.pending === 0) {
  13269. s.pending_out = 0;
  13270. }
  13271. }
  13272. function flush_block_only (s, last) {
  13273. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13274. s.block_start = s.strstart;
  13275. flush_pending(s.strm);
  13276. }
  13277. function put_byte(s, b) {
  13278. s.pending_buf[s.pending++] = b;
  13279. }
  13280. /* =========================================================================
  13281. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13282. * IN assertion: the stream state is correct and there is enough room in
  13283. * pending_buf.
  13284. */
  13285. function putShortMSB(s, b) {
  13286. // put_byte(s, (Byte)(b >> 8));
  13287. // put_byte(s, (Byte)(b & 0xff));
  13288. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13289. s.pending_buf[s.pending++] = b & 0xff;
  13290. }
  13291. /* ===========================================================================
  13292. * Read a new buffer from the current input stream, update the adler32
  13293. * and total number of bytes read. All deflate() input goes through
  13294. * this function so some applications may wish to modify it to avoid
  13295. * allocating a large strm->input buffer and copying from it.
  13296. * (See also flush_pending()).
  13297. */
  13298. function read_buf(strm, buf, start, size) {
  13299. var len = strm.avail_in;
  13300. if (len > size) { len = size; }
  13301. if (len === 0) { return 0; }
  13302. strm.avail_in -= len;
  13303. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13304. if (strm.state.wrap === 1) {
  13305. strm.adler = adler32(strm.adler, buf, len, start);
  13306. }
  13307. else if (strm.state.wrap === 2) {
  13308. strm.adler = crc32(strm.adler, buf, len, start);
  13309. }
  13310. strm.next_in += len;
  13311. strm.total_in += len;
  13312. return len;
  13313. }
  13314. /* ===========================================================================
  13315. * Set match_start to the longest match starting at the given string and
  13316. * return its length. Matches shorter or equal to prev_length are discarded,
  13317. * in which case the result is equal to prev_length and match_start is
  13318. * garbage.
  13319. * IN assertions: cur_match is the head of the hash chain for the current
  13320. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13321. * OUT assertion: the match length is not greater than s->lookahead.
  13322. */
  13323. function longest_match(s, cur_match) {
  13324. var chain_length = s.max_chain_length; /* max hash chain length */
  13325. var scan = s.strstart; /* current string */
  13326. var match; /* matched string */
  13327. var len; /* length of current match */
  13328. var best_len = s.prev_length; /* best match length so far */
  13329. var nice_match = s.nice_match; /* stop if match long enough */
  13330. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  13331. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  13332. var _win = s.window; // shortcut
  13333. var wmask = s.w_mask;
  13334. var prev = s.prev;
  13335. /* Stop when cur_match becomes <= limit. To simplify the code,
  13336. * we prevent matches with the string of window index 0.
  13337. */
  13338. var strend = s.strstart + MAX_MATCH;
  13339. var scan_end1 = _win[scan + best_len - 1];
  13340. var scan_end = _win[scan + best_len];
  13341. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  13342. * It is easy to get rid of this optimization if necessary.
  13343. */
  13344. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  13345. /* Do not waste too much time if we already have a good match: */
  13346. if (s.prev_length >= s.good_match) {
  13347. chain_length >>= 2;
  13348. }
  13349. /* Do not look for matches beyond the end of the input. This is necessary
  13350. * to make deflate deterministic.
  13351. */
  13352. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  13353. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  13354. do {
  13355. // Assert(cur_match < s->strstart, "no future");
  13356. match = cur_match;
  13357. /* Skip to next match if the match length cannot increase
  13358. * or if the match length is less than 2. Note that the checks below
  13359. * for insufficient lookahead only occur occasionally for performance
  13360. * reasons. Therefore uninitialized memory will be accessed, and
  13361. * conditional jumps will be made that depend on those values.
  13362. * However the length of the match is limited to the lookahead, so
  13363. * the output of deflate is not affected by the uninitialized values.
  13364. */
  13365. if (_win[match + best_len] !== scan_end ||
  13366. _win[match + best_len - 1] !== scan_end1 ||
  13367. _win[match] !== _win[scan] ||
  13368. _win[++match] !== _win[scan + 1]) {
  13369. continue;
  13370. }
  13371. /* The check at best_len-1 can be removed because it will be made
  13372. * again later. (This heuristic is not always a win.)
  13373. * It is not necessary to compare scan[2] and match[2] since they
  13374. * are always equal when the other bytes match, given that
  13375. * the hash keys are equal and that HASH_BITS >= 8.
  13376. */
  13377. scan += 2;
  13378. match++;
  13379. // Assert(*scan == *match, "match[2]?");
  13380. /* We check for insufficient lookahead only every 8th comparison;
  13381. * the 256th check will be made at strstart+258.
  13382. */
  13383. do {
  13384. /*jshint noempty:false*/
  13385. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13386. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13387. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13388. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13389. scan < strend);
  13390. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  13391. len = MAX_MATCH - (strend - scan);
  13392. scan = strend - MAX_MATCH;
  13393. if (len > best_len) {
  13394. s.match_start = cur_match;
  13395. best_len = len;
  13396. if (len >= nice_match) {
  13397. break;
  13398. }
  13399. scan_end1 = _win[scan + best_len - 1];
  13400. scan_end = _win[scan + best_len];
  13401. }
  13402. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  13403. if (best_len <= s.lookahead) {
  13404. return best_len;
  13405. }
  13406. return s.lookahead;
  13407. }
  13408. /* ===========================================================================
  13409. * Fill the window when the lookahead becomes insufficient.
  13410. * Updates strstart and lookahead.
  13411. *
  13412. * IN assertion: lookahead < MIN_LOOKAHEAD
  13413. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  13414. * At least one byte has been read, or avail_in == 0; reads are
  13415. * performed for at least two bytes (required for the zip translate_eol
  13416. * option -- not supported here).
  13417. */
  13418. function fill_window(s) {
  13419. var _w_size = s.w_size;
  13420. var p, n, m, more, str;
  13421. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  13422. do {
  13423. more = s.window_size - s.lookahead - s.strstart;
  13424. // JS ints have 32 bit, block below not needed
  13425. /* Deal with !@#$% 64K limit: */
  13426. //if (sizeof(int) <= 2) {
  13427. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  13428. // more = wsize;
  13429. //
  13430. // } else if (more == (unsigned)(-1)) {
  13431. // /* Very unlikely, but possible on 16 bit machine if
  13432. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  13433. // */
  13434. // more--;
  13435. // }
  13436. //}
  13437. /* If the window is almost full and there is insufficient lookahead,
  13438. * move the upper half to the lower one to make room in the upper half.
  13439. */
  13440. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  13441. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  13442. s.match_start -= _w_size;
  13443. s.strstart -= _w_size;
  13444. /* we now have strstart >= MAX_DIST */
  13445. s.block_start -= _w_size;
  13446. /* Slide the hash table (could be avoided with 32 bit values
  13447. at the expense of memory usage). We slide even when level == 0
  13448. to keep the hash table consistent if we switch back to level > 0
  13449. later. (Using level 0 permanently is not an optimal usage of
  13450. zlib, so we don't care about this pathological case.)
  13451. */
  13452. n = s.hash_size;
  13453. p = n;
  13454. do {
  13455. m = s.head[--p];
  13456. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  13457. } while (--n);
  13458. n = _w_size;
  13459. p = n;
  13460. do {
  13461. m = s.prev[--p];
  13462. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  13463. /* If n is not on any hash chain, prev[n] is garbage but
  13464. * its value will never be used.
  13465. */
  13466. } while (--n);
  13467. more += _w_size;
  13468. }
  13469. if (s.strm.avail_in === 0) {
  13470. break;
  13471. }
  13472. /* If there was no sliding:
  13473. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  13474. * more == window_size - lookahead - strstart
  13475. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  13476. * => more >= window_size - 2*WSIZE + 2
  13477. * In the BIG_MEM or MMAP case (not yet supported),
  13478. * window_size == input_size + MIN_LOOKAHEAD &&
  13479. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  13480. * Otherwise, window_size == 2*WSIZE so more >= 2.
  13481. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  13482. */
  13483. //Assert(more >= 2, "more < 2");
  13484. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  13485. s.lookahead += n;
  13486. /* Initialize the hash value now that we have some input: */
  13487. if (s.lookahead + s.insert >= MIN_MATCH) {
  13488. str = s.strstart - s.insert;
  13489. s.ins_h = s.window[str];
  13490. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  13491. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  13492. //#if MIN_MATCH != 3
  13493. // Call update_hash() MIN_MATCH-3 more times
  13494. //#endif
  13495. while (s.insert) {
  13496. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  13497. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  13498. s.prev[str & s.w_mask] = s.head[s.ins_h];
  13499. s.head[s.ins_h] = str;
  13500. str++;
  13501. s.insert--;
  13502. if (s.lookahead + s.insert < MIN_MATCH) {
  13503. break;
  13504. }
  13505. }
  13506. }
  13507. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  13508. * but this is not important since only literal bytes will be emitted.
  13509. */
  13510. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  13511. /* If the WIN_INIT bytes after the end of the current data have never been
  13512. * written, then zero those bytes in order to avoid memory check reports of
  13513. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  13514. * the longest match routines. Update the high water mark for the next
  13515. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  13516. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  13517. */
  13518. // if (s.high_water < s.window_size) {
  13519. // var curr = s.strstart + s.lookahead;
  13520. // var init = 0;
  13521. //
  13522. // if (s.high_water < curr) {
  13523. // /* Previous high water mark below current data -- zero WIN_INIT
  13524. // * bytes or up to end of window, whichever is less.
  13525. // */
  13526. // init = s.window_size - curr;
  13527. // if (init > WIN_INIT)
  13528. // init = WIN_INIT;
  13529. // zmemzero(s->window + curr, (unsigned)init);
  13530. // s->high_water = curr + init;
  13531. // }
  13532. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  13533. // /* High water mark at or above current data, but below current data
  13534. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  13535. // * to end of window, whichever is less.
  13536. // */
  13537. // init = (ulg)curr + WIN_INIT - s->high_water;
  13538. // if (init > s->window_size - s->high_water)
  13539. // init = s->window_size - s->high_water;
  13540. // zmemzero(s->window + s->high_water, (unsigned)init);
  13541. // s->high_water += init;
  13542. // }
  13543. // }
  13544. //
  13545. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  13546. // "not enough room for search");
  13547. }
  13548. /* ===========================================================================
  13549. * Copy without compression as much as possible from the input stream, return
  13550. * the current block state.
  13551. * This function does not insert new strings in the dictionary since
  13552. * uncompressible data is probably not useful. This function is used
  13553. * only for the level=0 compression option.
  13554. * NOTE: this function should be optimized to avoid extra copying from
  13555. * window to pending_buf.
  13556. */
  13557. function deflate_stored(s, flush) {
  13558. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  13559. * to pending_buf_size, and each stored block has a 5 byte header:
  13560. */
  13561. var max_block_size = 0xffff;
  13562. if (max_block_size > s.pending_buf_size - 5) {
  13563. max_block_size = s.pending_buf_size - 5;
  13564. }
  13565. /* Copy as much as possible from input to output: */
  13566. for (;;) {
  13567. /* Fill the window as much as possible: */
  13568. if (s.lookahead <= 1) {
  13569. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  13570. // s->block_start >= (long)s->w_size, "slide too late");
  13571. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  13572. // s.block_start >= s.w_size)) {
  13573. // throw new Error("slide too late");
  13574. // }
  13575. fill_window(s);
  13576. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  13577. return BS_NEED_MORE;
  13578. }
  13579. if (s.lookahead === 0) {
  13580. break;
  13581. }
  13582. /* flush the current block */
  13583. }
  13584. //Assert(s->block_start >= 0L, "block gone");
  13585. // if (s.block_start < 0) throw new Error("block gone");
  13586. s.strstart += s.lookahead;
  13587. s.lookahead = 0;
  13588. /* Emit a stored block if pending_buf will be full: */
  13589. var max_start = s.block_start + max_block_size;
  13590. if (s.strstart === 0 || s.strstart >= max_start) {
  13591. /* strstart == 0 is possible when wraparound on 16-bit machine */
  13592. s.lookahead = s.strstart - max_start;
  13593. s.strstart = max_start;
  13594. /*** FLUSH_BLOCK(s, 0); ***/
  13595. flush_block_only(s, false);
  13596. if (s.strm.avail_out === 0) {
  13597. return BS_NEED_MORE;
  13598. }
  13599. /***/
  13600. }
  13601. /* Flush if we may have to slide, otherwise block_start may become
  13602. * negative and the data will be gone:
  13603. */
  13604. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  13605. /*** FLUSH_BLOCK(s, 0); ***/
  13606. flush_block_only(s, false);
  13607. if (s.strm.avail_out === 0) {
  13608. return BS_NEED_MORE;
  13609. }
  13610. /***/
  13611. }
  13612. }
  13613. s.insert = 0;
  13614. if (flush === Z_FINISH) {
  13615. /*** FLUSH_BLOCK(s, 1); ***/
  13616. flush_block_only(s, true);
  13617. if (s.strm.avail_out === 0) {
  13618. return BS_FINISH_STARTED;
  13619. }
  13620. /***/
  13621. return BS_FINISH_DONE;
  13622. }
  13623. if (s.strstart > s.block_start) {
  13624. /*** FLUSH_BLOCK(s, 0); ***/
  13625. flush_block_only(s, false);
  13626. if (s.strm.avail_out === 0) {
  13627. return BS_NEED_MORE;
  13628. }
  13629. /***/
  13630. }
  13631. return BS_NEED_MORE;
  13632. }
  13633. /* ===========================================================================
  13634. * Compress as much as possible from the input stream, return the current
  13635. * block state.
  13636. * This function does not perform lazy evaluation of matches and inserts
  13637. * new strings in the dictionary only for unmatched strings or for short
  13638. * matches. It is used only for the fast compression options.
  13639. */
  13640. function deflate_fast(s, flush) {
  13641. var hash_head; /* head of the hash chain */
  13642. var bflush; /* set if current block must be flushed */
  13643. for (;;) {
  13644. /* Make sure that we always have enough lookahead, except
  13645. * at the end of the input file. We need MAX_MATCH bytes
  13646. * for the next match, plus MIN_MATCH bytes to insert the
  13647. * string following the next match.
  13648. */
  13649. if (s.lookahead < MIN_LOOKAHEAD) {
  13650. fill_window(s);
  13651. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  13652. return BS_NEED_MORE;
  13653. }
  13654. if (s.lookahead === 0) {
  13655. break; /* flush the current block */
  13656. }
  13657. }
  13658. /* Insert the string window[strstart .. strstart+2] in the
  13659. * dictionary, and set hash_head to the head of the hash chain:
  13660. */
  13661. hash_head = 0/*NIL*/;
  13662. if (s.lookahead >= MIN_MATCH) {
  13663. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13664. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13665. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13666. s.head[s.ins_h] = s.strstart;
  13667. /***/
  13668. }
  13669. /* Find the longest match, discarding those <= prev_length.
  13670. * At this point we have always match_length < MIN_MATCH
  13671. */
  13672. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  13673. /* To simplify the code, we prevent matches with the string
  13674. * of window index 0 (in particular we have to avoid a match
  13675. * of the string with itself at the start of the input file).
  13676. */
  13677. s.match_length = longest_match(s, hash_head);
  13678. /* longest_match() sets match_start */
  13679. }
  13680. if (s.match_length >= MIN_MATCH) {
  13681. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  13682. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  13683. s.match_length - MIN_MATCH, bflush); ***/
  13684. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  13685. s.lookahead -= s.match_length;
  13686. /* Insert new strings in the hash table only if the match length
  13687. * is not too large. This saves time but degrades compression.
  13688. */
  13689. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  13690. s.match_length--; /* string at strstart already in table */
  13691. do {
  13692. s.strstart++;
  13693. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13694. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13695. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13696. s.head[s.ins_h] = s.strstart;
  13697. /***/
  13698. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  13699. * always MIN_MATCH bytes ahead.
  13700. */
  13701. } while (--s.match_length !== 0);
  13702. s.strstart++;
  13703. } else
  13704. {
  13705. s.strstart += s.match_length;
  13706. s.match_length = 0;
  13707. s.ins_h = s.window[s.strstart];
  13708. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  13709. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  13710. //#if MIN_MATCH != 3
  13711. // Call UPDATE_HASH() MIN_MATCH-3 more times
  13712. //#endif
  13713. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  13714. * matter since it will be recomputed at next deflate call.
  13715. */
  13716. }
  13717. } else {
  13718. /* No match, output a literal byte */
  13719. //Tracevv((stderr,"%c", s.window[s.strstart]));
  13720. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  13721. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  13722. s.lookahead--;
  13723. s.strstart++;
  13724. }
  13725. if (bflush) {
  13726. /*** FLUSH_BLOCK(s, 0); ***/
  13727. flush_block_only(s, false);
  13728. if (s.strm.avail_out === 0) {
  13729. return BS_NEED_MORE;
  13730. }
  13731. /***/
  13732. }
  13733. }
  13734. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  13735. if (flush === Z_FINISH) {
  13736. /*** FLUSH_BLOCK(s, 1); ***/
  13737. flush_block_only(s, true);
  13738. if (s.strm.avail_out === 0) {
  13739. return BS_FINISH_STARTED;
  13740. }
  13741. /***/
  13742. return BS_FINISH_DONE;
  13743. }
  13744. if (s.last_lit) {
  13745. /*** FLUSH_BLOCK(s, 0); ***/
  13746. flush_block_only(s, false);
  13747. if (s.strm.avail_out === 0) {
  13748. return BS_NEED_MORE;
  13749. }
  13750. /***/
  13751. }
  13752. return BS_BLOCK_DONE;
  13753. }
  13754. /* ===========================================================================
  13755. * Same as above, but achieves better compression. We use a lazy
  13756. * evaluation for matches: a match is finally adopted only if there is
  13757. * no better match at the next window position.
  13758. */
  13759. function deflate_slow(s, flush) {
  13760. var hash_head; /* head of hash chain */
  13761. var bflush; /* set if current block must be flushed */
  13762. var max_insert;
  13763. /* Process the input block. */
  13764. for (;;) {
  13765. /* Make sure that we always have enough lookahead, except
  13766. * at the end of the input file. We need MAX_MATCH bytes
  13767. * for the next match, plus MIN_MATCH bytes to insert the
  13768. * string following the next match.
  13769. */
  13770. if (s.lookahead < MIN_LOOKAHEAD) {
  13771. fill_window(s);
  13772. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  13773. return BS_NEED_MORE;
  13774. }
  13775. if (s.lookahead === 0) { break; } /* flush the current block */
  13776. }
  13777. /* Insert the string window[strstart .. strstart+2] in the
  13778. * dictionary, and set hash_head to the head of the hash chain:
  13779. */
  13780. hash_head = 0/*NIL*/;
  13781. if (s.lookahead >= MIN_MATCH) {
  13782. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13783. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13784. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13785. s.head[s.ins_h] = s.strstart;
  13786. /***/
  13787. }
  13788. /* Find the longest match, discarding those <= prev_length.
  13789. */
  13790. s.prev_length = s.match_length;
  13791. s.prev_match = s.match_start;
  13792. s.match_length = MIN_MATCH-1;
  13793. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  13794. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  13795. /* To simplify the code, we prevent matches with the string
  13796. * of window index 0 (in particular we have to avoid a match
  13797. * of the string with itself at the start of the input file).
  13798. */
  13799. s.match_length = longest_match(s, hash_head);
  13800. /* longest_match() sets match_start */
  13801. if (s.match_length <= 5 &&
  13802. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  13803. /* If prev_match is also MIN_MATCH, match_start is garbage
  13804. * but we will ignore the current match anyway.
  13805. */
  13806. s.match_length = MIN_MATCH-1;
  13807. }
  13808. }
  13809. /* If there was a match at the previous step and the current
  13810. * match is not better, output the previous match:
  13811. */
  13812. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  13813. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  13814. /* Do not insert strings in hash table beyond this. */
  13815. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  13816. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  13817. s.prev_length - MIN_MATCH, bflush);***/
  13818. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  13819. /* Insert in hash table all strings up to the end of the match.
  13820. * strstart-1 and strstart are already inserted. If there is not
  13821. * enough lookahead, the last two strings are not inserted in
  13822. * the hash table.
  13823. */
  13824. s.lookahead -= s.prev_length-1;
  13825. s.prev_length -= 2;
  13826. do {
  13827. if (++s.strstart <= max_insert) {
  13828. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13829. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13830. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13831. s.head[s.ins_h] = s.strstart;
  13832. /***/
  13833. }
  13834. } while (--s.prev_length !== 0);
  13835. s.match_available = 0;
  13836. s.match_length = MIN_MATCH-1;
  13837. s.strstart++;
  13838. if (bflush) {
  13839. /*** FLUSH_BLOCK(s, 0); ***/
  13840. flush_block_only(s, false);
  13841. if (s.strm.avail_out === 0) {
  13842. return BS_NEED_MORE;
  13843. }
  13844. /***/
  13845. }
  13846. } else if (s.match_available) {
  13847. /* If there was no match at the previous position, output a
  13848. * single literal. If there was a match but the current match
  13849. * is longer, truncate the previous match to a single literal.
  13850. */
  13851. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  13852. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  13853. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  13854. if (bflush) {
  13855. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  13856. flush_block_only(s, false);
  13857. /***/
  13858. }
  13859. s.strstart++;
  13860. s.lookahead--;
  13861. if (s.strm.avail_out === 0) {
  13862. return BS_NEED_MORE;
  13863. }
  13864. } else {
  13865. /* There is no previous match to compare with, wait for
  13866. * the next step to decide.
  13867. */
  13868. s.match_available = 1;
  13869. s.strstart++;
  13870. s.lookahead--;
  13871. }
  13872. }
  13873. //Assert (flush != Z_NO_FLUSH, "no flush?");
  13874. if (s.match_available) {
  13875. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  13876. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  13877. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  13878. s.match_available = 0;
  13879. }
  13880. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  13881. if (flush === Z_FINISH) {
  13882. /*** FLUSH_BLOCK(s, 1); ***/
  13883. flush_block_only(s, true);
  13884. if (s.strm.avail_out === 0) {
  13885. return BS_FINISH_STARTED;
  13886. }
  13887. /***/
  13888. return BS_FINISH_DONE;
  13889. }
  13890. if (s.last_lit) {
  13891. /*** FLUSH_BLOCK(s, 0); ***/
  13892. flush_block_only(s, false);
  13893. if (s.strm.avail_out === 0) {
  13894. return BS_NEED_MORE;
  13895. }
  13896. /***/
  13897. }
  13898. return BS_BLOCK_DONE;
  13899. }
  13900. /* ===========================================================================
  13901. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  13902. * one. Do not maintain a hash table. (It will be regenerated if this run of
  13903. * deflate switches away from Z_RLE.)
  13904. */
  13905. function deflate_rle(s, flush) {
  13906. var bflush; /* set if current block must be flushed */
  13907. var prev; /* byte at distance one to match */
  13908. var scan, strend; /* scan goes up to strend for length of run */
  13909. var _win = s.window;
  13910. for (;;) {
  13911. /* Make sure that we always have enough lookahead, except
  13912. * at the end of the input file. We need MAX_MATCH bytes
  13913. * for the longest run, plus one for the unrolled loop.
  13914. */
  13915. if (s.lookahead <= MAX_MATCH) {
  13916. fill_window(s);
  13917. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  13918. return BS_NEED_MORE;
  13919. }
  13920. if (s.lookahead === 0) { break; } /* flush the current block */
  13921. }
  13922. /* See how many times the previous byte repeats */
  13923. s.match_length = 0;
  13924. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  13925. scan = s.strstart - 1;
  13926. prev = _win[scan];
  13927. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  13928. strend = s.strstart + MAX_MATCH;
  13929. do {
  13930. /*jshint noempty:false*/
  13931. } while (prev === _win[++scan] && prev === _win[++scan] &&
  13932. prev === _win[++scan] && prev === _win[++scan] &&
  13933. prev === _win[++scan] && prev === _win[++scan] &&
  13934. prev === _win[++scan] && prev === _win[++scan] &&
  13935. scan < strend);
  13936. s.match_length = MAX_MATCH - (strend - scan);
  13937. if (s.match_length > s.lookahead) {
  13938. s.match_length = s.lookahead;
  13939. }
  13940. }
  13941. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  13942. }
  13943. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  13944. if (s.match_length >= MIN_MATCH) {
  13945. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  13946. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  13947. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  13948. s.lookahead -= s.match_length;
  13949. s.strstart += s.match_length;
  13950. s.match_length = 0;
  13951. } else {
  13952. /* No match, output a literal byte */
  13953. //Tracevv((stderr,"%c", s->window[s->strstart]));
  13954. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  13955. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  13956. s.lookahead--;
  13957. s.strstart++;
  13958. }
  13959. if (bflush) {
  13960. /*** FLUSH_BLOCK(s, 0); ***/
  13961. flush_block_only(s, false);
  13962. if (s.strm.avail_out === 0) {
  13963. return BS_NEED_MORE;
  13964. }
  13965. /***/
  13966. }
  13967. }
  13968. s.insert = 0;
  13969. if (flush === Z_FINISH) {
  13970. /*** FLUSH_BLOCK(s, 1); ***/
  13971. flush_block_only(s, true);
  13972. if (s.strm.avail_out === 0) {
  13973. return BS_FINISH_STARTED;
  13974. }
  13975. /***/
  13976. return BS_FINISH_DONE;
  13977. }
  13978. if (s.last_lit) {
  13979. /*** FLUSH_BLOCK(s, 0); ***/
  13980. flush_block_only(s, false);
  13981. if (s.strm.avail_out === 0) {
  13982. return BS_NEED_MORE;
  13983. }
  13984. /***/
  13985. }
  13986. return BS_BLOCK_DONE;
  13987. }
  13988. /* ===========================================================================
  13989. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  13990. * (It will be regenerated if this run of deflate switches away from Huffman.)
  13991. */
  13992. function deflate_huff(s, flush) {
  13993. var bflush; /* set if current block must be flushed */
  13994. for (;;) {
  13995. /* Make sure that we have a literal to write. */
  13996. if (s.lookahead === 0) {
  13997. fill_window(s);
  13998. if (s.lookahead === 0) {
  13999. if (flush === Z_NO_FLUSH) {
  14000. return BS_NEED_MORE;
  14001. }
  14002. break; /* flush the current block */
  14003. }
  14004. }
  14005. /* Output a literal byte */
  14006. s.match_length = 0;
  14007. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14008. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14009. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14010. s.lookahead--;
  14011. s.strstart++;
  14012. if (bflush) {
  14013. /*** FLUSH_BLOCK(s, 0); ***/
  14014. flush_block_only(s, false);
  14015. if (s.strm.avail_out === 0) {
  14016. return BS_NEED_MORE;
  14017. }
  14018. /***/
  14019. }
  14020. }
  14021. s.insert = 0;
  14022. if (flush === Z_FINISH) {
  14023. /*** FLUSH_BLOCK(s, 1); ***/
  14024. flush_block_only(s, true);
  14025. if (s.strm.avail_out === 0) {
  14026. return BS_FINISH_STARTED;
  14027. }
  14028. /***/
  14029. return BS_FINISH_DONE;
  14030. }
  14031. if (s.last_lit) {
  14032. /*** FLUSH_BLOCK(s, 0); ***/
  14033. flush_block_only(s, false);
  14034. if (s.strm.avail_out === 0) {
  14035. return BS_NEED_MORE;
  14036. }
  14037. /***/
  14038. }
  14039. return BS_BLOCK_DONE;
  14040. }
  14041. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14042. * the desired pack level (0..9). The values given below have been tuned to
  14043. * exclude worst case performance for pathological files. Better values may be
  14044. * found for specific files.
  14045. */
  14046. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14047. this.good_length = good_length;
  14048. this.max_lazy = max_lazy;
  14049. this.nice_length = nice_length;
  14050. this.max_chain = max_chain;
  14051. this.func = func;
  14052. };
  14053. var configuration_table;
  14054. configuration_table = [
  14055. /* good lazy nice chain */
  14056. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14057. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14058. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14059. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14060. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14061. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14062. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14063. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14064. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14065. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14066. ];
  14067. /* ===========================================================================
  14068. * Initialize the "longest match" routines for a new zlib stream
  14069. */
  14070. function lm_init(s) {
  14071. s.window_size = 2 * s.w_size;
  14072. /*** CLEAR_HASH(s); ***/
  14073. zero(s.head); // Fill with NIL (= 0);
  14074. /* Set the default configuration parameters:
  14075. */
  14076. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14077. s.good_match = configuration_table[s.level].good_length;
  14078. s.nice_match = configuration_table[s.level].nice_length;
  14079. s.max_chain_length = configuration_table[s.level].max_chain;
  14080. s.strstart = 0;
  14081. s.block_start = 0;
  14082. s.lookahead = 0;
  14083. s.insert = 0;
  14084. s.match_length = s.prev_length = MIN_MATCH - 1;
  14085. s.match_available = 0;
  14086. s.ins_h = 0;
  14087. }
  14088. function DeflateState() {
  14089. this.strm = null; /* pointer back to this zlib stream */
  14090. this.status = 0; /* as the name implies */
  14091. this.pending_buf = null; /* output still pending */
  14092. this.pending_buf_size = 0; /* size of pending_buf */
  14093. this.pending_out = 0; /* next pending byte to output to the stream */
  14094. this.pending = 0; /* nb of bytes in the pending buffer */
  14095. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14096. this.gzhead = null; /* gzip header information to write */
  14097. this.gzindex = 0; /* where in extra, name, or comment */
  14098. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14099. this.last_flush = -1; /* value of flush param for previous deflate call */
  14100. this.w_size = 0; /* LZ77 window size (32K by default) */
  14101. this.w_bits = 0; /* log2(w_size) (8..16) */
  14102. this.w_mask = 0; /* w_size - 1 */
  14103. this.window = null;
  14104. /* Sliding window. Input bytes are read into the second half of the window,
  14105. * and move to the first half later to keep a dictionary of at least wSize
  14106. * bytes. With this organization, matches are limited to a distance of
  14107. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14108. * performed with a length multiple of the block size.
  14109. */
  14110. this.window_size = 0;
  14111. /* Actual size of window: 2*wSize, except when the user input buffer
  14112. * is directly used as sliding window.
  14113. */
  14114. this.prev = null;
  14115. /* Link to older string with same hash index. To limit the size of this
  14116. * array to 64K, this link is maintained only for the last 32K strings.
  14117. * An index in this array is thus a window index modulo 32K.
  14118. */
  14119. this.head = null; /* Heads of the hash chains or NIL. */
  14120. this.ins_h = 0; /* hash index of string to be inserted */
  14121. this.hash_size = 0; /* number of elements in hash table */
  14122. this.hash_bits = 0; /* log2(hash_size) */
  14123. this.hash_mask = 0; /* hash_size-1 */
  14124. this.hash_shift = 0;
  14125. /* Number of bits by which ins_h must be shifted at each input
  14126. * step. It must be such that after MIN_MATCH steps, the oldest
  14127. * byte no longer takes part in the hash key, that is:
  14128. * hash_shift * MIN_MATCH >= hash_bits
  14129. */
  14130. this.block_start = 0;
  14131. /* Window position at the beginning of the current output block. Gets
  14132. * negative when the window is moved backwards.
  14133. */
  14134. this.match_length = 0; /* length of best match */
  14135. this.prev_match = 0; /* previous match */
  14136. this.match_available = 0; /* set if previous match exists */
  14137. this.strstart = 0; /* start of string to insert */
  14138. this.match_start = 0; /* start of matching string */
  14139. this.lookahead = 0; /* number of valid bytes ahead in window */
  14140. this.prev_length = 0;
  14141. /* Length of the best match at previous step. Matches not greater than this
  14142. * are discarded. This is used in the lazy match evaluation.
  14143. */
  14144. this.max_chain_length = 0;
  14145. /* To speed up deflation, hash chains are never searched beyond this
  14146. * length. A higher limit improves compression ratio but degrades the
  14147. * speed.
  14148. */
  14149. this.max_lazy_match = 0;
  14150. /* Attempt to find a better match only when the current match is strictly
  14151. * smaller than this value. This mechanism is used only for compression
  14152. * levels >= 4.
  14153. */
  14154. // That's alias to max_lazy_match, don't use directly
  14155. //this.max_insert_length = 0;
  14156. /* Insert new strings in the hash table only if the match length is not
  14157. * greater than this length. This saves time but degrades compression.
  14158. * max_insert_length is used only for compression levels <= 3.
  14159. */
  14160. this.level = 0; /* compression level (1..9) */
  14161. this.strategy = 0; /* favor or force Huffman coding*/
  14162. this.good_match = 0;
  14163. /* Use a faster search when the previous match is longer than this */
  14164. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14165. /* used by trees.c: */
  14166. /* Didn't use ct_data typedef below to suppress compiler warning */
  14167. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  14168. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  14169. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  14170. // Use flat array of DOUBLE size, with interleaved fata,
  14171. // because JS does not support effective
  14172. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  14173. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  14174. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  14175. zero(this.dyn_ltree);
  14176. zero(this.dyn_dtree);
  14177. zero(this.bl_tree);
  14178. this.l_desc = null; /* desc. for literal tree */
  14179. this.d_desc = null; /* desc. for distance tree */
  14180. this.bl_desc = null; /* desc. for bit length tree */
  14181. //ush bl_count[MAX_BITS+1];
  14182. this.bl_count = new utils.Buf16(MAX_BITS+1);
  14183. /* number of codes at each bit length for an optimal tree */
  14184. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  14185. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  14186. zero(this.heap);
  14187. this.heap_len = 0; /* number of elements in the heap */
  14188. this.heap_max = 0; /* element of largest frequency */
  14189. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  14190. * The same heap array is used to build all trees.
  14191. */
  14192. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  14193. zero(this.depth);
  14194. /* Depth of each subtree used as tie breaker for trees of equal frequency
  14195. */
  14196. this.l_buf = 0; /* buffer index for literals or lengths */
  14197. this.lit_bufsize = 0;
  14198. /* Size of match buffer for literals/lengths. There are 4 reasons for
  14199. * limiting lit_bufsize to 64K:
  14200. * - frequencies can be kept in 16 bit counters
  14201. * - if compression is not successful for the first block, all input
  14202. * data is still in the window so we can still emit a stored block even
  14203. * when input comes from standard input. (This can also be done for
  14204. * all blocks if lit_bufsize is not greater than 32K.)
  14205. * - if compression is not successful for a file smaller than 64K, we can
  14206. * even emit a stored file instead of a stored block (saving 5 bytes).
  14207. * This is applicable only for zip (not gzip or zlib).
  14208. * - creating new Huffman trees less frequently may not provide fast
  14209. * adaptation to changes in the input data statistics. (Take for
  14210. * example a binary file with poorly compressible code followed by
  14211. * a highly compressible string table.) Smaller buffer sizes give
  14212. * fast adaptation but have of course the overhead of transmitting
  14213. * trees more frequently.
  14214. * - I can't count above 4
  14215. */
  14216. this.last_lit = 0; /* running index in l_buf */
  14217. this.d_buf = 0;
  14218. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14219. * the same number of elements. To use different lengths, an extra flag
  14220. * array would be necessary.
  14221. */
  14222. this.opt_len = 0; /* bit length of current block with optimal trees */
  14223. this.static_len = 0; /* bit length of current block with static trees */
  14224. this.matches = 0; /* number of string matches in current block */
  14225. this.insert = 0; /* bytes at end of window left to insert */
  14226. this.bi_buf = 0;
  14227. /* Output buffer. bits are inserted starting at the bottom (least
  14228. * significant bits).
  14229. */
  14230. this.bi_valid = 0;
  14231. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14232. * are always zero.
  14233. */
  14234. // Used for window memory init. We safely ignore it for JS. That makes
  14235. // sense only for pointers and memory check tools.
  14236. //this.high_water = 0;
  14237. /* High water mark offset in window for initialized bytes -- bytes above
  14238. * this are set to zero in order to avoid memory check warnings when
  14239. * longest match routines access bytes past the input. This is then
  14240. * updated to the new high water mark.
  14241. */
  14242. }
  14243. function deflateResetKeep(strm) {
  14244. var s;
  14245. if (!strm || !strm.state) {
  14246. return err(strm, Z_STREAM_ERROR);
  14247. }
  14248. strm.total_in = strm.total_out = 0;
  14249. strm.data_type = Z_UNKNOWN;
  14250. s = strm.state;
  14251. s.pending = 0;
  14252. s.pending_out = 0;
  14253. if (s.wrap < 0) {
  14254. s.wrap = -s.wrap;
  14255. /* was made negative by deflate(..., Z_FINISH); */
  14256. }
  14257. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14258. strm.adler = (s.wrap === 2) ?
  14259. 0 // crc32(0, Z_NULL, 0)
  14260. :
  14261. 1; // adler32(0, Z_NULL, 0)
  14262. s.last_flush = Z_NO_FLUSH;
  14263. trees._tr_init(s);
  14264. return Z_OK;
  14265. }
  14266. function deflateReset(strm) {
  14267. var ret = deflateResetKeep(strm);
  14268. if (ret === Z_OK) {
  14269. lm_init(strm.state);
  14270. }
  14271. return ret;
  14272. }
  14273. function deflateSetHeader(strm, head) {
  14274. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14275. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14276. strm.state.gzhead = head;
  14277. return Z_OK;
  14278. }
  14279. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14280. if (!strm) { // === Z_NULL
  14281. return Z_STREAM_ERROR;
  14282. }
  14283. var wrap = 1;
  14284. if (level === Z_DEFAULT_COMPRESSION) {
  14285. level = 6;
  14286. }
  14287. if (windowBits < 0) { /* suppress zlib wrapper */
  14288. wrap = 0;
  14289. windowBits = -windowBits;
  14290. }
  14291. else if (windowBits > 15) {
  14292. wrap = 2; /* write gzip wrapper instead */
  14293. windowBits -= 16;
  14294. }
  14295. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14296. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14297. strategy < 0 || strategy > Z_FIXED) {
  14298. return err(strm, Z_STREAM_ERROR);
  14299. }
  14300. if (windowBits === 8) {
  14301. windowBits = 9;
  14302. }
  14303. /* until 256-byte window bug fixed */
  14304. var s = new DeflateState();
  14305. strm.state = s;
  14306. s.strm = strm;
  14307. s.wrap = wrap;
  14308. s.gzhead = null;
  14309. s.w_bits = windowBits;
  14310. s.w_size = 1 << s.w_bits;
  14311. s.w_mask = s.w_size - 1;
  14312. s.hash_bits = memLevel + 7;
  14313. s.hash_size = 1 << s.hash_bits;
  14314. s.hash_mask = s.hash_size - 1;
  14315. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14316. s.window = new utils.Buf8(s.w_size * 2);
  14317. s.head = new utils.Buf16(s.hash_size);
  14318. s.prev = new utils.Buf16(s.w_size);
  14319. // Don't need mem init magic for JS.
  14320. //s.high_water = 0; /* nothing written to s->window yet */
  14321. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14322. s.pending_buf_size = s.lit_bufsize * 4;
  14323. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14324. s.d_buf = s.lit_bufsize >> 1;
  14325. s.l_buf = (1 + 2) * s.lit_bufsize;
  14326. s.level = level;
  14327. s.strategy = strategy;
  14328. s.method = method;
  14329. return deflateReset(strm);
  14330. }
  14331. function deflateInit(strm, level) {
  14332. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  14333. }
  14334. function deflate(strm, flush) {
  14335. var old_flush, s;
  14336. var beg, val; // for gzip header write only
  14337. if (!strm || !strm.state ||
  14338. flush > Z_BLOCK || flush < 0) {
  14339. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  14340. }
  14341. s = strm.state;
  14342. if (!strm.output ||
  14343. (!strm.input && strm.avail_in !== 0) ||
  14344. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  14345. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  14346. }
  14347. s.strm = strm; /* just in case */
  14348. old_flush = s.last_flush;
  14349. s.last_flush = flush;
  14350. /* Write the header */
  14351. if (s.status === INIT_STATE) {
  14352. if (s.wrap === 2) { // GZIP header
  14353. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14354. put_byte(s, 31);
  14355. put_byte(s, 139);
  14356. put_byte(s, 8);
  14357. if (!s.gzhead) { // s->gzhead == Z_NULL
  14358. put_byte(s, 0);
  14359. put_byte(s, 0);
  14360. put_byte(s, 0);
  14361. put_byte(s, 0);
  14362. put_byte(s, 0);
  14363. put_byte(s, s.level === 9 ? 2 :
  14364. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14365. 4 : 0));
  14366. put_byte(s, OS_CODE);
  14367. s.status = BUSY_STATE;
  14368. }
  14369. else {
  14370. put_byte(s, (s.gzhead.text ? 1 : 0) +
  14371. (s.gzhead.hcrc ? 2 : 0) +
  14372. (!s.gzhead.extra ? 0 : 4) +
  14373. (!s.gzhead.name ? 0 : 8) +
  14374. (!s.gzhead.comment ? 0 : 16)
  14375. );
  14376. put_byte(s, s.gzhead.time & 0xff);
  14377. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  14378. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  14379. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  14380. put_byte(s, s.level === 9 ? 2 :
  14381. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14382. 4 : 0));
  14383. put_byte(s, s.gzhead.os & 0xff);
  14384. if (s.gzhead.extra && s.gzhead.extra.length) {
  14385. put_byte(s, s.gzhead.extra.length & 0xff);
  14386. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  14387. }
  14388. if (s.gzhead.hcrc) {
  14389. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  14390. }
  14391. s.gzindex = 0;
  14392. s.status = EXTRA_STATE;
  14393. }
  14394. }
  14395. else // DEFLATE header
  14396. {
  14397. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  14398. var level_flags = -1;
  14399. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  14400. level_flags = 0;
  14401. } else if (s.level < 6) {
  14402. level_flags = 1;
  14403. } else if (s.level === 6) {
  14404. level_flags = 2;
  14405. } else {
  14406. level_flags = 3;
  14407. }
  14408. header |= (level_flags << 6);
  14409. if (s.strstart !== 0) { header |= PRESET_DICT; }
  14410. header += 31 - (header % 31);
  14411. s.status = BUSY_STATE;
  14412. putShortMSB(s, header);
  14413. /* Save the adler32 of the preset dictionary: */
  14414. if (s.strstart !== 0) {
  14415. putShortMSB(s, strm.adler >>> 16);
  14416. putShortMSB(s, strm.adler & 0xffff);
  14417. }
  14418. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  14419. }
  14420. }
  14421. //#ifdef GZIP
  14422. if (s.status === EXTRA_STATE) {
  14423. if (s.gzhead.extra/* != Z_NULL*/) {
  14424. beg = s.pending; /* start of bytes to update crc */
  14425. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  14426. if (s.pending === s.pending_buf_size) {
  14427. if (s.gzhead.hcrc && s.pending > beg) {
  14428. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14429. }
  14430. flush_pending(strm);
  14431. beg = s.pending;
  14432. if (s.pending === s.pending_buf_size) {
  14433. break;
  14434. }
  14435. }
  14436. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  14437. s.gzindex++;
  14438. }
  14439. if (s.gzhead.hcrc && s.pending > beg) {
  14440. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14441. }
  14442. if (s.gzindex === s.gzhead.extra.length) {
  14443. s.gzindex = 0;
  14444. s.status = NAME_STATE;
  14445. }
  14446. }
  14447. else {
  14448. s.status = NAME_STATE;
  14449. }
  14450. }
  14451. if (s.status === NAME_STATE) {
  14452. if (s.gzhead.name/* != Z_NULL*/) {
  14453. beg = s.pending; /* start of bytes to update crc */
  14454. //int val;
  14455. do {
  14456. if (s.pending === s.pending_buf_size) {
  14457. if (s.gzhead.hcrc && s.pending > beg) {
  14458. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14459. }
  14460. flush_pending(strm);
  14461. beg = s.pending;
  14462. if (s.pending === s.pending_buf_size) {
  14463. val = 1;
  14464. break;
  14465. }
  14466. }
  14467. // JS specific: little magic to add zero terminator to end of string
  14468. if (s.gzindex < s.gzhead.name.length) {
  14469. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  14470. } else {
  14471. val = 0;
  14472. }
  14473. put_byte(s, val);
  14474. } while (val !== 0);
  14475. if (s.gzhead.hcrc && s.pending > beg) {
  14476. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14477. }
  14478. if (val === 0) {
  14479. s.gzindex = 0;
  14480. s.status = COMMENT_STATE;
  14481. }
  14482. }
  14483. else {
  14484. s.status = COMMENT_STATE;
  14485. }
  14486. }
  14487. if (s.status === COMMENT_STATE) {
  14488. if (s.gzhead.comment/* != Z_NULL*/) {
  14489. beg = s.pending; /* start of bytes to update crc */
  14490. //int val;
  14491. do {
  14492. if (s.pending === s.pending_buf_size) {
  14493. if (s.gzhead.hcrc && s.pending > beg) {
  14494. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14495. }
  14496. flush_pending(strm);
  14497. beg = s.pending;
  14498. if (s.pending === s.pending_buf_size) {
  14499. val = 1;
  14500. break;
  14501. }
  14502. }
  14503. // JS specific: little magic to add zero terminator to end of string
  14504. if (s.gzindex < s.gzhead.comment.length) {
  14505. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  14506. } else {
  14507. val = 0;
  14508. }
  14509. put_byte(s, val);
  14510. } while (val !== 0);
  14511. if (s.gzhead.hcrc && s.pending > beg) {
  14512. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14513. }
  14514. if (val === 0) {
  14515. s.status = HCRC_STATE;
  14516. }
  14517. }
  14518. else {
  14519. s.status = HCRC_STATE;
  14520. }
  14521. }
  14522. if (s.status === HCRC_STATE) {
  14523. if (s.gzhead.hcrc) {
  14524. if (s.pending + 2 > s.pending_buf_size) {
  14525. flush_pending(strm);
  14526. }
  14527. if (s.pending + 2 <= s.pending_buf_size) {
  14528. put_byte(s, strm.adler & 0xff);
  14529. put_byte(s, (strm.adler >> 8) & 0xff);
  14530. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14531. s.status = BUSY_STATE;
  14532. }
  14533. }
  14534. else {
  14535. s.status = BUSY_STATE;
  14536. }
  14537. }
  14538. //#endif
  14539. /* Flush as much pending output as possible */
  14540. if (s.pending !== 0) {
  14541. flush_pending(strm);
  14542. if (strm.avail_out === 0) {
  14543. /* Since avail_out is 0, deflate will be called again with
  14544. * more output space, but possibly with both pending and
  14545. * avail_in equal to zero. There won't be anything to do,
  14546. * but this is not an error situation so make sure we
  14547. * return OK instead of BUF_ERROR at next call of deflate:
  14548. */
  14549. s.last_flush = -1;
  14550. return Z_OK;
  14551. }
  14552. /* Make sure there is something to do and avoid duplicate consecutive
  14553. * flushes. For repeated and useless calls with Z_FINISH, we keep
  14554. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  14555. */
  14556. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  14557. flush !== Z_FINISH) {
  14558. return err(strm, Z_BUF_ERROR);
  14559. }
  14560. /* User must not provide more input after the first FINISH: */
  14561. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  14562. return err(strm, Z_BUF_ERROR);
  14563. }
  14564. /* Start a new block or continue the current one.
  14565. */
  14566. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  14567. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  14568. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  14569. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  14570. configuration_table[s.level].func(s, flush));
  14571. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  14572. s.status = FINISH_STATE;
  14573. }
  14574. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  14575. if (strm.avail_out === 0) {
  14576. s.last_flush = -1;
  14577. /* avoid BUF_ERROR next call, see above */
  14578. }
  14579. return Z_OK;
  14580. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  14581. * of deflate should use the same flush parameter to make sure
  14582. * that the flush is complete. So we don't have to output an
  14583. * empty block here, this will be done at next call. This also
  14584. * ensures that for a very small output buffer, we emit at most
  14585. * one empty block.
  14586. */
  14587. }
  14588. if (bstate === BS_BLOCK_DONE) {
  14589. if (flush === Z_PARTIAL_FLUSH) {
  14590. trees._tr_align(s);
  14591. }
  14592. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  14593. trees._tr_stored_block(s, 0, 0, false);
  14594. /* For a full flush, this empty block will be recognized
  14595. * as a special marker by inflate_sync().
  14596. */
  14597. if (flush === Z_FULL_FLUSH) {
  14598. /*** CLEAR_HASH(s); ***/ /* forget history */
  14599. zero(s.head); // Fill with NIL (= 0);
  14600. if (s.lookahead === 0) {
  14601. s.strstart = 0;
  14602. s.block_start = 0;
  14603. s.insert = 0;
  14604. }
  14605. }
  14606. }
  14607. flush_pending(strm);
  14608. if (strm.avail_out === 0) {
  14609. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  14610. return Z_OK;
  14611. }
  14612. }
  14613. }
  14614. //Assert(strm->avail_out > 0, "bug2");
  14615. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  14616. if (flush !== Z_FINISH) { return Z_OK; }
  14617. if (s.wrap <= 0) { return Z_STREAM_END; }
  14618. /* Write the trailer */
  14619. if (s.wrap === 2) {
  14620. put_byte(s, strm.adler & 0xff);
  14621. put_byte(s, (strm.adler >> 8) & 0xff);
  14622. put_byte(s, (strm.adler >> 16) & 0xff);
  14623. put_byte(s, (strm.adler >> 24) & 0xff);
  14624. put_byte(s, strm.total_in & 0xff);
  14625. put_byte(s, (strm.total_in >> 8) & 0xff);
  14626. put_byte(s, (strm.total_in >> 16) & 0xff);
  14627. put_byte(s, (strm.total_in >> 24) & 0xff);
  14628. }
  14629. else
  14630. {
  14631. putShortMSB(s, strm.adler >>> 16);
  14632. putShortMSB(s, strm.adler & 0xffff);
  14633. }
  14634. flush_pending(strm);
  14635. /* If avail_out is zero, the application will call deflate again
  14636. * to flush the rest.
  14637. */
  14638. if (s.wrap > 0) { s.wrap = -s.wrap; }
  14639. /* write the trailer only once! */
  14640. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  14641. }
  14642. function deflateEnd(strm) {
  14643. var status;
  14644. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  14645. return Z_STREAM_ERROR;
  14646. }
  14647. status = strm.state.status;
  14648. if (status !== INIT_STATE &&
  14649. status !== EXTRA_STATE &&
  14650. status !== NAME_STATE &&
  14651. status !== COMMENT_STATE &&
  14652. status !== HCRC_STATE &&
  14653. status !== BUSY_STATE &&
  14654. status !== FINISH_STATE
  14655. ) {
  14656. return err(strm, Z_STREAM_ERROR);
  14657. }
  14658. strm.state = null;
  14659. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  14660. }
  14661. /* =========================================================================
  14662. * Copy the source state to the destination state
  14663. */
  14664. //function deflateCopy(dest, source) {
  14665. //
  14666. //}
  14667. exports.deflateInit = deflateInit;
  14668. exports.deflateInit2 = deflateInit2;
  14669. exports.deflateReset = deflateReset;
  14670. exports.deflateResetKeep = deflateResetKeep;
  14671. exports.deflateSetHeader = deflateSetHeader;
  14672. exports.deflate = deflate;
  14673. exports.deflateEnd = deflateEnd;
  14674. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  14675. /* Not implemented
  14676. exports.deflateBound = deflateBound;
  14677. exports.deflateCopy = deflateCopy;
  14678. exports.deflateSetDictionary = deflateSetDictionary;
  14679. exports.deflateParams = deflateParams;
  14680. exports.deflatePending = deflatePending;
  14681. exports.deflatePrime = deflatePrime;
  14682. exports.deflateTune = deflateTune;
  14683. */
  14684. },{"../utils/common":48,"./adler32":50,"./crc32":52,"./messages":58,"./trees":59}],54:[function(require,module,exports){
  14685. 'use strict';
  14686. function GZheader() {
  14687. /* true if compressed data believed to be text */
  14688. this.text = 0;
  14689. /* modification time */
  14690. this.time = 0;
  14691. /* extra flags (not used when writing a gzip file) */
  14692. this.xflags = 0;
  14693. /* operating system */
  14694. this.os = 0;
  14695. /* pointer to extra field or Z_NULL if none */
  14696. this.extra = null;
  14697. /* extra field length (valid if extra != Z_NULL) */
  14698. this.extra_len = 0; // Actually, we don't need it in JS,
  14699. // but leave for few code modifications
  14700. //
  14701. // Setup limits is not necessary because in js we should not preallocate memory
  14702. // for inflate use constant limit in 65536 bytes
  14703. //
  14704. /* space at extra (only when reading header) */
  14705. // this.extra_max = 0;
  14706. /* pointer to zero-terminated file name or Z_NULL */
  14707. this.name = '';
  14708. /* space at name (only when reading header) */
  14709. // this.name_max = 0;
  14710. /* pointer to zero-terminated comment or Z_NULL */
  14711. this.comment = '';
  14712. /* space at comment (only when reading header) */
  14713. // this.comm_max = 0;
  14714. /* true if there was or will be a header crc */
  14715. this.hcrc = 0;
  14716. /* true when done reading gzip header (not used when writing a gzip file) */
  14717. this.done = false;
  14718. }
  14719. module.exports = GZheader;
  14720. },{}],55:[function(require,module,exports){
  14721. 'use strict';
  14722. // See state defs from inflate.js
  14723. var BAD = 30; /* got a data error -- remain here until reset */
  14724. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  14725. /*
  14726. Decode literal, length, and distance codes and write out the resulting
  14727. literal and match bytes until either not enough input or output is
  14728. available, an end-of-block is encountered, or a data error is encountered.
  14729. When large enough input and output buffers are supplied to inflate(), for
  14730. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  14731. inflate execution time is spent in this routine.
  14732. Entry assumptions:
  14733. state.mode === LEN
  14734. strm.avail_in >= 6
  14735. strm.avail_out >= 258
  14736. start >= strm.avail_out
  14737. state.bits < 8
  14738. On return, state.mode is one of:
  14739. LEN -- ran out of enough output space or enough available input
  14740. TYPE -- reached end of block code, inflate() to interpret next block
  14741. BAD -- error in block data
  14742. Notes:
  14743. - The maximum input bits used by a length/distance pair is 15 bits for the
  14744. length code, 5 bits for the length extra, 15 bits for the distance code,
  14745. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  14746. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  14747. checking for available input while decoding.
  14748. - The maximum bytes that a single length/distance pair can output is 258
  14749. bytes, which is the maximum length that can be coded. inflate_fast()
  14750. requires strm.avail_out >= 258 for each loop to avoid checking for
  14751. output space.
  14752. */
  14753. module.exports = function inflate_fast(strm, start) {
  14754. var state;
  14755. var _in; /* local strm.input */
  14756. var last; /* have enough input while in < last */
  14757. var _out; /* local strm.output */
  14758. var beg; /* inflate()'s initial strm.output */
  14759. var end; /* while out < end, enough space available */
  14760. //#ifdef INFLATE_STRICT
  14761. var dmax; /* maximum distance from zlib header */
  14762. //#endif
  14763. var wsize; /* window size or zero if not using window */
  14764. var whave; /* valid bytes in the window */
  14765. var wnext; /* window write index */
  14766. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  14767. var s_window; /* allocated sliding window, if wsize != 0 */
  14768. var hold; /* local strm.hold */
  14769. var bits; /* local strm.bits */
  14770. var lcode; /* local strm.lencode */
  14771. var dcode; /* local strm.distcode */
  14772. var lmask; /* mask for first level of length codes */
  14773. var dmask; /* mask for first level of distance codes */
  14774. var here; /* retrieved table entry */
  14775. var op; /* code bits, operation, extra bits, or */
  14776. /* window position, window bytes to copy */
  14777. var len; /* match length, unused bytes */
  14778. var dist; /* match distance */
  14779. var from; /* where to copy match from */
  14780. var from_source;
  14781. var input, output; // JS specific, because we have no pointers
  14782. /* copy state to local variables */
  14783. state = strm.state;
  14784. //here = state.here;
  14785. _in = strm.next_in;
  14786. input = strm.input;
  14787. last = _in + (strm.avail_in - 5);
  14788. _out = strm.next_out;
  14789. output = strm.output;
  14790. beg = _out - (start - strm.avail_out);
  14791. end = _out + (strm.avail_out - 257);
  14792. //#ifdef INFLATE_STRICT
  14793. dmax = state.dmax;
  14794. //#endif
  14795. wsize = state.wsize;
  14796. whave = state.whave;
  14797. wnext = state.wnext;
  14798. s_window = state.window;
  14799. hold = state.hold;
  14800. bits = state.bits;
  14801. lcode = state.lencode;
  14802. dcode = state.distcode;
  14803. lmask = (1 << state.lenbits) - 1;
  14804. dmask = (1 << state.distbits) - 1;
  14805. /* decode literals and length/distances until end-of-block or not enough
  14806. input data or output space */
  14807. top:
  14808. do {
  14809. if (bits < 15) {
  14810. hold += input[_in++] << bits;
  14811. bits += 8;
  14812. hold += input[_in++] << bits;
  14813. bits += 8;
  14814. }
  14815. here = lcode[hold & lmask];
  14816. dolen:
  14817. for (;;) { // Goto emulation
  14818. op = here >>> 24/*here.bits*/;
  14819. hold >>>= op;
  14820. bits -= op;
  14821. op = (here >>> 16) & 0xff/*here.op*/;
  14822. if (op === 0) { /* literal */
  14823. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  14824. // "inflate: literal '%c'\n" :
  14825. // "inflate: literal 0x%02x\n", here.val));
  14826. output[_out++] = here & 0xffff/*here.val*/;
  14827. }
  14828. else if (op & 16) { /* length base */
  14829. len = here & 0xffff/*here.val*/;
  14830. op &= 15; /* number of extra bits */
  14831. if (op) {
  14832. if (bits < op) {
  14833. hold += input[_in++] << bits;
  14834. bits += 8;
  14835. }
  14836. len += hold & ((1 << op) - 1);
  14837. hold >>>= op;
  14838. bits -= op;
  14839. }
  14840. //Tracevv((stderr, "inflate: length %u\n", len));
  14841. if (bits < 15) {
  14842. hold += input[_in++] << bits;
  14843. bits += 8;
  14844. hold += input[_in++] << bits;
  14845. bits += 8;
  14846. }
  14847. here = dcode[hold & dmask];
  14848. dodist:
  14849. for (;;) { // goto emulation
  14850. op = here >>> 24/*here.bits*/;
  14851. hold >>>= op;
  14852. bits -= op;
  14853. op = (here >>> 16) & 0xff/*here.op*/;
  14854. if (op & 16) { /* distance base */
  14855. dist = here & 0xffff/*here.val*/;
  14856. op &= 15; /* number of extra bits */
  14857. if (bits < op) {
  14858. hold += input[_in++] << bits;
  14859. bits += 8;
  14860. if (bits < op) {
  14861. hold += input[_in++] << bits;
  14862. bits += 8;
  14863. }
  14864. }
  14865. dist += hold & ((1 << op) - 1);
  14866. //#ifdef INFLATE_STRICT
  14867. if (dist > dmax) {
  14868. strm.msg = 'invalid distance too far back';
  14869. state.mode = BAD;
  14870. break top;
  14871. }
  14872. //#endif
  14873. hold >>>= op;
  14874. bits -= op;
  14875. //Tracevv((stderr, "inflate: distance %u\n", dist));
  14876. op = _out - beg; /* max distance in output */
  14877. if (dist > op) { /* see if copy from window */
  14878. op = dist - op; /* distance back in window */
  14879. if (op > whave) {
  14880. if (state.sane) {
  14881. strm.msg = 'invalid distance too far back';
  14882. state.mode = BAD;
  14883. break top;
  14884. }
  14885. // (!) This block is disabled in zlib defailts,
  14886. // don't enable it for binary compatibility
  14887. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  14888. // if (len <= op - whave) {
  14889. // do {
  14890. // output[_out++] = 0;
  14891. // } while (--len);
  14892. // continue top;
  14893. // }
  14894. // len -= op - whave;
  14895. // do {
  14896. // output[_out++] = 0;
  14897. // } while (--op > whave);
  14898. // if (op === 0) {
  14899. // from = _out - dist;
  14900. // do {
  14901. // output[_out++] = output[from++];
  14902. // } while (--len);
  14903. // continue top;
  14904. // }
  14905. //#endif
  14906. }
  14907. from = 0; // window index
  14908. from_source = s_window;
  14909. if (wnext === 0) { /* very common case */
  14910. from += wsize - op;
  14911. if (op < len) { /* some from window */
  14912. len -= op;
  14913. do {
  14914. output[_out++] = s_window[from++];
  14915. } while (--op);
  14916. from = _out - dist; /* rest from output */
  14917. from_source = output;
  14918. }
  14919. }
  14920. else if (wnext < op) { /* wrap around window */
  14921. from += wsize + wnext - op;
  14922. op -= wnext;
  14923. if (op < len) { /* some from end of window */
  14924. len -= op;
  14925. do {
  14926. output[_out++] = s_window[from++];
  14927. } while (--op);
  14928. from = 0;
  14929. if (wnext < len) { /* some from start of window */
  14930. op = wnext;
  14931. len -= op;
  14932. do {
  14933. output[_out++] = s_window[from++];
  14934. } while (--op);
  14935. from = _out - dist; /* rest from output */
  14936. from_source = output;
  14937. }
  14938. }
  14939. }
  14940. else { /* contiguous in window */
  14941. from += wnext - op;
  14942. if (op < len) { /* some from window */
  14943. len -= op;
  14944. do {
  14945. output[_out++] = s_window[from++];
  14946. } while (--op);
  14947. from = _out - dist; /* rest from output */
  14948. from_source = output;
  14949. }
  14950. }
  14951. while (len > 2) {
  14952. output[_out++] = from_source[from++];
  14953. output[_out++] = from_source[from++];
  14954. output[_out++] = from_source[from++];
  14955. len -= 3;
  14956. }
  14957. if (len) {
  14958. output[_out++] = from_source[from++];
  14959. if (len > 1) {
  14960. output[_out++] = from_source[from++];
  14961. }
  14962. }
  14963. }
  14964. else {
  14965. from = _out - dist; /* copy direct from output */
  14966. do { /* minimum length is three */
  14967. output[_out++] = output[from++];
  14968. output[_out++] = output[from++];
  14969. output[_out++] = output[from++];
  14970. len -= 3;
  14971. } while (len > 2);
  14972. if (len) {
  14973. output[_out++] = output[from++];
  14974. if (len > 1) {
  14975. output[_out++] = output[from++];
  14976. }
  14977. }
  14978. }
  14979. }
  14980. else if ((op & 64) === 0) { /* 2nd level distance code */
  14981. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  14982. continue dodist;
  14983. }
  14984. else {
  14985. strm.msg = 'invalid distance code';
  14986. state.mode = BAD;
  14987. break top;
  14988. }
  14989. break; // need to emulate goto via "continue"
  14990. }
  14991. }
  14992. else if ((op & 64) === 0) { /* 2nd level length code */
  14993. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  14994. continue dolen;
  14995. }
  14996. else if (op & 32) { /* end-of-block */
  14997. //Tracevv((stderr, "inflate: end of block\n"));
  14998. state.mode = TYPE;
  14999. break top;
  15000. }
  15001. else {
  15002. strm.msg = 'invalid literal/length code';
  15003. state.mode = BAD;
  15004. break top;
  15005. }
  15006. break; // need to emulate goto via "continue"
  15007. }
  15008. } while (_in < last && _out < end);
  15009. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15010. len = bits >> 3;
  15011. _in -= len;
  15012. bits -= len << 3;
  15013. hold &= (1 << bits) - 1;
  15014. /* update state and return */
  15015. strm.next_in = _in;
  15016. strm.next_out = _out;
  15017. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15018. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15019. state.hold = hold;
  15020. state.bits = bits;
  15021. return;
  15022. };
  15023. },{}],56:[function(require,module,exports){
  15024. 'use strict';
  15025. var utils = require('../utils/common');
  15026. var adler32 = require('./adler32');
  15027. var crc32 = require('./crc32');
  15028. var inflate_fast = require('./inffast');
  15029. var inflate_table = require('./inftrees');
  15030. var CODES = 0;
  15031. var LENS = 1;
  15032. var DISTS = 2;
  15033. /* Public constants ==========================================================*/
  15034. /* ===========================================================================*/
  15035. /* Allowed flush values; see deflate() and inflate() below for details */
  15036. //var Z_NO_FLUSH = 0;
  15037. //var Z_PARTIAL_FLUSH = 1;
  15038. //var Z_SYNC_FLUSH = 2;
  15039. //var Z_FULL_FLUSH = 3;
  15040. var Z_FINISH = 4;
  15041. var Z_BLOCK = 5;
  15042. var Z_TREES = 6;
  15043. /* Return codes for the compression/decompression functions. Negative values
  15044. * are errors, positive values are used for special but normal events.
  15045. */
  15046. var Z_OK = 0;
  15047. var Z_STREAM_END = 1;
  15048. var Z_NEED_DICT = 2;
  15049. //var Z_ERRNO = -1;
  15050. var Z_STREAM_ERROR = -2;
  15051. var Z_DATA_ERROR = -3;
  15052. var Z_MEM_ERROR = -4;
  15053. var Z_BUF_ERROR = -5;
  15054. //var Z_VERSION_ERROR = -6;
  15055. /* The deflate compression method */
  15056. var Z_DEFLATED = 8;
  15057. /* STATES ====================================================================*/
  15058. /* ===========================================================================*/
  15059. var HEAD = 1; /* i: waiting for magic header */
  15060. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15061. var TIME = 3; /* i: waiting for modification time (gzip) */
  15062. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15063. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15064. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15065. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15066. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15067. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15068. var DICTID = 10; /* i: waiting for dictionary check value */
  15069. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15070. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15071. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15072. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15073. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15074. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15075. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15076. var LENLENS = 18; /* i: waiting for code length code lengths */
  15077. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15078. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15079. var LEN = 21; /* i: waiting for length/lit/eob code */
  15080. var LENEXT = 22; /* i: waiting for length extra bits */
  15081. var DIST = 23; /* i: waiting for distance code */
  15082. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15083. var MATCH = 25; /* o: waiting for output space to copy string */
  15084. var LIT = 26; /* o: waiting for output space to write literal */
  15085. var CHECK = 27; /* i: waiting for 32-bit check value */
  15086. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15087. var DONE = 29; /* finished check, done -- remain here until reset */
  15088. var BAD = 30; /* got a data error -- remain here until reset */
  15089. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15090. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15091. /* ===========================================================================*/
  15092. var ENOUGH_LENS = 852;
  15093. var ENOUGH_DISTS = 592;
  15094. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15095. var MAX_WBITS = 15;
  15096. /* 32K LZ77 window */
  15097. var DEF_WBITS = MAX_WBITS;
  15098. function ZSWAP32(q) {
  15099. return (((q >>> 24) & 0xff) +
  15100. ((q >>> 8) & 0xff00) +
  15101. ((q & 0xff00) << 8) +
  15102. ((q & 0xff) << 24));
  15103. }
  15104. function InflateState() {
  15105. this.mode = 0; /* current inflate mode */
  15106. this.last = false; /* true if processing last block */
  15107. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15108. this.havedict = false; /* true if dictionary provided */
  15109. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15110. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15111. this.check = 0; /* protected copy of check value */
  15112. this.total = 0; /* protected copy of output count */
  15113. // TODO: may be {}
  15114. this.head = null; /* where to save gzip header information */
  15115. /* sliding window */
  15116. this.wbits = 0; /* log base 2 of requested window size */
  15117. this.wsize = 0; /* window size or zero if not using window */
  15118. this.whave = 0; /* valid bytes in the window */
  15119. this.wnext = 0; /* window write index */
  15120. this.window = null; /* allocated sliding window, if needed */
  15121. /* bit accumulator */
  15122. this.hold = 0; /* input bit accumulator */
  15123. this.bits = 0; /* number of bits in "in" */
  15124. /* for string and stored block copying */
  15125. this.length = 0; /* literal or length of data to copy */
  15126. this.offset = 0; /* distance back to copy string from */
  15127. /* for table and code decoding */
  15128. this.extra = 0; /* extra bits needed */
  15129. /* fixed and dynamic code tables */
  15130. this.lencode = null; /* starting table for length/literal codes */
  15131. this.distcode = null; /* starting table for distance codes */
  15132. this.lenbits = 0; /* index bits for lencode */
  15133. this.distbits = 0; /* index bits for distcode */
  15134. /* dynamic table building */
  15135. this.ncode = 0; /* number of code length code lengths */
  15136. this.nlen = 0; /* number of length code lengths */
  15137. this.ndist = 0; /* number of distance code lengths */
  15138. this.have = 0; /* number of code lengths in lens[] */
  15139. this.next = null; /* next available space in codes[] */
  15140. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15141. this.work = new utils.Buf16(288); /* work area for code table building */
  15142. /*
  15143. because we don't have pointers in js, we use lencode and distcode directly
  15144. as buffers so we don't need codes
  15145. */
  15146. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15147. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15148. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15149. this.sane = 0; /* if false, allow invalid distance too far */
  15150. this.back = 0; /* bits back of last unprocessed length/lit */
  15151. this.was = 0; /* initial length of match */
  15152. }
  15153. function inflateResetKeep(strm) {
  15154. var state;
  15155. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15156. state = strm.state;
  15157. strm.total_in = strm.total_out = state.total = 0;
  15158. strm.msg = ''; /*Z_NULL*/
  15159. if (state.wrap) { /* to support ill-conceived Java test suite */
  15160. strm.adler = state.wrap & 1;
  15161. }
  15162. state.mode = HEAD;
  15163. state.last = 0;
  15164. state.havedict = 0;
  15165. state.dmax = 32768;
  15166. state.head = null/*Z_NULL*/;
  15167. state.hold = 0;
  15168. state.bits = 0;
  15169. //state.lencode = state.distcode = state.next = state.codes;
  15170. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  15171. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  15172. state.sane = 1;
  15173. state.back = -1;
  15174. //Tracev((stderr, "inflate: reset\n"));
  15175. return Z_OK;
  15176. }
  15177. function inflateReset(strm) {
  15178. var state;
  15179. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15180. state = strm.state;
  15181. state.wsize = 0;
  15182. state.whave = 0;
  15183. state.wnext = 0;
  15184. return inflateResetKeep(strm);
  15185. }
  15186. function inflateReset2(strm, windowBits) {
  15187. var wrap;
  15188. var state;
  15189. /* get the state */
  15190. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15191. state = strm.state;
  15192. /* extract wrap request from windowBits parameter */
  15193. if (windowBits < 0) {
  15194. wrap = 0;
  15195. windowBits = -windowBits;
  15196. }
  15197. else {
  15198. wrap = (windowBits >> 4) + 1;
  15199. if (windowBits < 48) {
  15200. windowBits &= 15;
  15201. }
  15202. }
  15203. /* set number of window bits, free window if different */
  15204. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  15205. return Z_STREAM_ERROR;
  15206. }
  15207. if (state.window !== null && state.wbits !== windowBits) {
  15208. state.window = null;
  15209. }
  15210. /* update state and reset the rest of it */
  15211. state.wrap = wrap;
  15212. state.wbits = windowBits;
  15213. return inflateReset(strm);
  15214. }
  15215. function inflateInit2(strm, windowBits) {
  15216. var ret;
  15217. var state;
  15218. if (!strm) { return Z_STREAM_ERROR; }
  15219. //strm.msg = Z_NULL; /* in case we return an error */
  15220. state = new InflateState();
  15221. //if (state === Z_NULL) return Z_MEM_ERROR;
  15222. //Tracev((stderr, "inflate: allocated\n"));
  15223. strm.state = state;
  15224. state.window = null/*Z_NULL*/;
  15225. ret = inflateReset2(strm, windowBits);
  15226. if (ret !== Z_OK) {
  15227. strm.state = null/*Z_NULL*/;
  15228. }
  15229. return ret;
  15230. }
  15231. function inflateInit(strm) {
  15232. return inflateInit2(strm, DEF_WBITS);
  15233. }
  15234. /*
  15235. Return state with length and distance decoding tables and index sizes set to
  15236. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15237. If BUILDFIXED is defined, then instead this routine builds the tables the
  15238. first time it's called, and returns those tables the first time and
  15239. thereafter. This reduces the size of the code by about 2K bytes, in
  15240. exchange for a little execution time. However, BUILDFIXED should not be
  15241. used for threaded applications, since the rewriting of the tables and virgin
  15242. may not be thread-safe.
  15243. */
  15244. var virgin = true;
  15245. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15246. function fixedtables(state) {
  15247. /* build fixed huffman tables if first call (may not be thread safe) */
  15248. if (virgin) {
  15249. var sym;
  15250. lenfix = new utils.Buf32(512);
  15251. distfix = new utils.Buf32(32);
  15252. /* literal/length table */
  15253. sym = 0;
  15254. while (sym < 144) { state.lens[sym++] = 8; }
  15255. while (sym < 256) { state.lens[sym++] = 9; }
  15256. while (sym < 280) { state.lens[sym++] = 7; }
  15257. while (sym < 288) { state.lens[sym++] = 8; }
  15258. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  15259. /* distance table */
  15260. sym = 0;
  15261. while (sym < 32) { state.lens[sym++] = 5; }
  15262. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  15263. /* do this just once */
  15264. virgin = false;
  15265. }
  15266. state.lencode = lenfix;
  15267. state.lenbits = 9;
  15268. state.distcode = distfix;
  15269. state.distbits = 5;
  15270. }
  15271. /*
  15272. Update the window with the last wsize (normally 32K) bytes written before
  15273. returning. If window does not exist yet, create it. This is only called
  15274. when a window is already in use, or when output has been written during this
  15275. inflate call, but the end of the deflate stream has not been reached yet.
  15276. It is also called to create a window for dictionary data when a dictionary
  15277. is loaded.
  15278. Providing output buffers larger than 32K to inflate() should provide a speed
  15279. advantage, since only the last 32K of output is copied to the sliding window
  15280. upon return from inflate(), and since all distances after the first 32K of
  15281. output will fall in the output data, making match copies simpler and faster.
  15282. The advantage may be dependent on the size of the processor's data caches.
  15283. */
  15284. function updatewindow(strm, src, end, copy) {
  15285. var dist;
  15286. var state = strm.state;
  15287. /* if it hasn't been done already, allocate space for the window */
  15288. if (state.window === null) {
  15289. state.wsize = 1 << state.wbits;
  15290. state.wnext = 0;
  15291. state.whave = 0;
  15292. state.window = new utils.Buf8(state.wsize);
  15293. }
  15294. /* copy state->wsize or less output bytes into the circular window */
  15295. if (copy >= state.wsize) {
  15296. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  15297. state.wnext = 0;
  15298. state.whave = state.wsize;
  15299. }
  15300. else {
  15301. dist = state.wsize - state.wnext;
  15302. if (dist > copy) {
  15303. dist = copy;
  15304. }
  15305. //zmemcpy(state->window + state->wnext, end - copy, dist);
  15306. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  15307. copy -= dist;
  15308. if (copy) {
  15309. //zmemcpy(state->window, end - copy, copy);
  15310. utils.arraySet(state.window,src, end - copy, copy, 0);
  15311. state.wnext = copy;
  15312. state.whave = state.wsize;
  15313. }
  15314. else {
  15315. state.wnext += dist;
  15316. if (state.wnext === state.wsize) { state.wnext = 0; }
  15317. if (state.whave < state.wsize) { state.whave += dist; }
  15318. }
  15319. }
  15320. return 0;
  15321. }
  15322. function inflate(strm, flush) {
  15323. var state;
  15324. var input, output; // input/output buffers
  15325. var next; /* next input INDEX */
  15326. var put; /* next output INDEX */
  15327. var have, left; /* available input and output */
  15328. var hold; /* bit buffer */
  15329. var bits; /* bits in bit buffer */
  15330. var _in, _out; /* save starting available input and output */
  15331. var copy; /* number of stored or match bytes to copy */
  15332. var from; /* where to copy match bytes from */
  15333. var from_source;
  15334. var here = 0; /* current decoding table entry */
  15335. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  15336. //var last; /* parent table entry */
  15337. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  15338. var len; /* length to copy for repeats, bits to drop */
  15339. var ret; /* return code */
  15340. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  15341. var opts;
  15342. var n; // temporary var for NEED_BITS
  15343. var order = /* permutation of code lengths */
  15344. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  15345. if (!strm || !strm.state || !strm.output ||
  15346. (!strm.input && strm.avail_in !== 0)) {
  15347. return Z_STREAM_ERROR;
  15348. }
  15349. state = strm.state;
  15350. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  15351. //--- LOAD() ---
  15352. put = strm.next_out;
  15353. output = strm.output;
  15354. left = strm.avail_out;
  15355. next = strm.next_in;
  15356. input = strm.input;
  15357. have = strm.avail_in;
  15358. hold = state.hold;
  15359. bits = state.bits;
  15360. //---
  15361. _in = have;
  15362. _out = left;
  15363. ret = Z_OK;
  15364. inf_leave: // goto emulation
  15365. for (;;) {
  15366. switch (state.mode) {
  15367. case HEAD:
  15368. if (state.wrap === 0) {
  15369. state.mode = TYPEDO;
  15370. break;
  15371. }
  15372. //=== NEEDBITS(16);
  15373. while (bits < 16) {
  15374. if (have === 0) { break inf_leave; }
  15375. have--;
  15376. hold += input[next++] << bits;
  15377. bits += 8;
  15378. }
  15379. //===//
  15380. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  15381. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  15382. //=== CRC2(state.check, hold);
  15383. hbuf[0] = hold & 0xff;
  15384. hbuf[1] = (hold >>> 8) & 0xff;
  15385. state.check = crc32(state.check, hbuf, 2, 0);
  15386. //===//
  15387. //=== INITBITS();
  15388. hold = 0;
  15389. bits = 0;
  15390. //===//
  15391. state.mode = FLAGS;
  15392. break;
  15393. }
  15394. state.flags = 0; /* expect zlib header */
  15395. if (state.head) {
  15396. state.head.done = false;
  15397. }
  15398. if (!(state.wrap & 1) || /* check if zlib header allowed */
  15399. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  15400. strm.msg = 'incorrect header check';
  15401. state.mode = BAD;
  15402. break;
  15403. }
  15404. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  15405. strm.msg = 'unknown compression method';
  15406. state.mode = BAD;
  15407. break;
  15408. }
  15409. //--- DROPBITS(4) ---//
  15410. hold >>>= 4;
  15411. bits -= 4;
  15412. //---//
  15413. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  15414. if (state.wbits === 0) {
  15415. state.wbits = len;
  15416. }
  15417. else if (len > state.wbits) {
  15418. strm.msg = 'invalid window size';
  15419. state.mode = BAD;
  15420. break;
  15421. }
  15422. state.dmax = 1 << len;
  15423. //Tracev((stderr, "inflate: zlib header ok\n"));
  15424. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15425. state.mode = hold & 0x200 ? DICTID : TYPE;
  15426. //=== INITBITS();
  15427. hold = 0;
  15428. bits = 0;
  15429. //===//
  15430. break;
  15431. case FLAGS:
  15432. //=== NEEDBITS(16); */
  15433. while (bits < 16) {
  15434. if (have === 0) { break inf_leave; }
  15435. have--;
  15436. hold += input[next++] << bits;
  15437. bits += 8;
  15438. }
  15439. //===//
  15440. state.flags = hold;
  15441. if ((state.flags & 0xff) !== Z_DEFLATED) {
  15442. strm.msg = 'unknown compression method';
  15443. state.mode = BAD;
  15444. break;
  15445. }
  15446. if (state.flags & 0xe000) {
  15447. strm.msg = 'unknown header flags set';
  15448. state.mode = BAD;
  15449. break;
  15450. }
  15451. if (state.head) {
  15452. state.head.text = ((hold >> 8) & 1);
  15453. }
  15454. if (state.flags & 0x0200) {
  15455. //=== CRC2(state.check, hold);
  15456. hbuf[0] = hold & 0xff;
  15457. hbuf[1] = (hold >>> 8) & 0xff;
  15458. state.check = crc32(state.check, hbuf, 2, 0);
  15459. //===//
  15460. }
  15461. //=== INITBITS();
  15462. hold = 0;
  15463. bits = 0;
  15464. //===//
  15465. state.mode = TIME;
  15466. /* falls through */
  15467. case TIME:
  15468. //=== NEEDBITS(32); */
  15469. while (bits < 32) {
  15470. if (have === 0) { break inf_leave; }
  15471. have--;
  15472. hold += input[next++] << bits;
  15473. bits += 8;
  15474. }
  15475. //===//
  15476. if (state.head) {
  15477. state.head.time = hold;
  15478. }
  15479. if (state.flags & 0x0200) {
  15480. //=== CRC4(state.check, hold)
  15481. hbuf[0] = hold & 0xff;
  15482. hbuf[1] = (hold >>> 8) & 0xff;
  15483. hbuf[2] = (hold >>> 16) & 0xff;
  15484. hbuf[3] = (hold >>> 24) & 0xff;
  15485. state.check = crc32(state.check, hbuf, 4, 0);
  15486. //===
  15487. }
  15488. //=== INITBITS();
  15489. hold = 0;
  15490. bits = 0;
  15491. //===//
  15492. state.mode = OS;
  15493. /* falls through */
  15494. case OS:
  15495. //=== NEEDBITS(16); */
  15496. while (bits < 16) {
  15497. if (have === 0) { break inf_leave; }
  15498. have--;
  15499. hold += input[next++] << bits;
  15500. bits += 8;
  15501. }
  15502. //===//
  15503. if (state.head) {
  15504. state.head.xflags = (hold & 0xff);
  15505. state.head.os = (hold >> 8);
  15506. }
  15507. if (state.flags & 0x0200) {
  15508. //=== CRC2(state.check, hold);
  15509. hbuf[0] = hold & 0xff;
  15510. hbuf[1] = (hold >>> 8) & 0xff;
  15511. state.check = crc32(state.check, hbuf, 2, 0);
  15512. //===//
  15513. }
  15514. //=== INITBITS();
  15515. hold = 0;
  15516. bits = 0;
  15517. //===//
  15518. state.mode = EXLEN;
  15519. /* falls through */
  15520. case EXLEN:
  15521. if (state.flags & 0x0400) {
  15522. //=== NEEDBITS(16); */
  15523. while (bits < 16) {
  15524. if (have === 0) { break inf_leave; }
  15525. have--;
  15526. hold += input[next++] << bits;
  15527. bits += 8;
  15528. }
  15529. //===//
  15530. state.length = hold;
  15531. if (state.head) {
  15532. state.head.extra_len = hold;
  15533. }
  15534. if (state.flags & 0x0200) {
  15535. //=== CRC2(state.check, hold);
  15536. hbuf[0] = hold & 0xff;
  15537. hbuf[1] = (hold >>> 8) & 0xff;
  15538. state.check = crc32(state.check, hbuf, 2, 0);
  15539. //===//
  15540. }
  15541. //=== INITBITS();
  15542. hold = 0;
  15543. bits = 0;
  15544. //===//
  15545. }
  15546. else if (state.head) {
  15547. state.head.extra = null/*Z_NULL*/;
  15548. }
  15549. state.mode = EXTRA;
  15550. /* falls through */
  15551. case EXTRA:
  15552. if (state.flags & 0x0400) {
  15553. copy = state.length;
  15554. if (copy > have) { copy = have; }
  15555. if (copy) {
  15556. if (state.head) {
  15557. len = state.head.extra_len - state.length;
  15558. if (!state.head.extra) {
  15559. // Use untyped array for more conveniend processing later
  15560. state.head.extra = new Array(state.head.extra_len);
  15561. }
  15562. utils.arraySet(
  15563. state.head.extra,
  15564. input,
  15565. next,
  15566. // extra field is limited to 65536 bytes
  15567. // - no need for additional size check
  15568. copy,
  15569. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  15570. len
  15571. );
  15572. //zmemcpy(state.head.extra + len, next,
  15573. // len + copy > state.head.extra_max ?
  15574. // state.head.extra_max - len : copy);
  15575. }
  15576. if (state.flags & 0x0200) {
  15577. state.check = crc32(state.check, input, copy, next);
  15578. }
  15579. have -= copy;
  15580. next += copy;
  15581. state.length -= copy;
  15582. }
  15583. if (state.length) { break inf_leave; }
  15584. }
  15585. state.length = 0;
  15586. state.mode = NAME;
  15587. /* falls through */
  15588. case NAME:
  15589. if (state.flags & 0x0800) {
  15590. if (have === 0) { break inf_leave; }
  15591. copy = 0;
  15592. do {
  15593. // TODO: 2 or 1 bytes?
  15594. len = input[next + copy++];
  15595. /* use constant limit because in js we should not preallocate memory */
  15596. if (state.head && len &&
  15597. (state.length < 65536 /*state.head.name_max*/)) {
  15598. state.head.name += String.fromCharCode(len);
  15599. }
  15600. } while (len && copy < have);
  15601. if (state.flags & 0x0200) {
  15602. state.check = crc32(state.check, input, copy, next);
  15603. }
  15604. have -= copy;
  15605. next += copy;
  15606. if (len) { break inf_leave; }
  15607. }
  15608. else if (state.head) {
  15609. state.head.name = null;
  15610. }
  15611. state.length = 0;
  15612. state.mode = COMMENT;
  15613. /* falls through */
  15614. case COMMENT:
  15615. if (state.flags & 0x1000) {
  15616. if (have === 0) { break inf_leave; }
  15617. copy = 0;
  15618. do {
  15619. len = input[next + copy++];
  15620. /* use constant limit because in js we should not preallocate memory */
  15621. if (state.head && len &&
  15622. (state.length < 65536 /*state.head.comm_max*/)) {
  15623. state.head.comment += String.fromCharCode(len);
  15624. }
  15625. } while (len && copy < have);
  15626. if (state.flags & 0x0200) {
  15627. state.check = crc32(state.check, input, copy, next);
  15628. }
  15629. have -= copy;
  15630. next += copy;
  15631. if (len) { break inf_leave; }
  15632. }
  15633. else if (state.head) {
  15634. state.head.comment = null;
  15635. }
  15636. state.mode = HCRC;
  15637. /* falls through */
  15638. case HCRC:
  15639. if (state.flags & 0x0200) {
  15640. //=== NEEDBITS(16); */
  15641. while (bits < 16) {
  15642. if (have === 0) { break inf_leave; }
  15643. have--;
  15644. hold += input[next++] << bits;
  15645. bits += 8;
  15646. }
  15647. //===//
  15648. if (hold !== (state.check & 0xffff)) {
  15649. strm.msg = 'header crc mismatch';
  15650. state.mode = BAD;
  15651. break;
  15652. }
  15653. //=== INITBITS();
  15654. hold = 0;
  15655. bits = 0;
  15656. //===//
  15657. }
  15658. if (state.head) {
  15659. state.head.hcrc = ((state.flags >> 9) & 1);
  15660. state.head.done = true;
  15661. }
  15662. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  15663. state.mode = TYPE;
  15664. break;
  15665. case DICTID:
  15666. //=== NEEDBITS(32); */
  15667. while (bits < 32) {
  15668. if (have === 0) { break inf_leave; }
  15669. have--;
  15670. hold += input[next++] << bits;
  15671. bits += 8;
  15672. }
  15673. //===//
  15674. strm.adler = state.check = ZSWAP32(hold);
  15675. //=== INITBITS();
  15676. hold = 0;
  15677. bits = 0;
  15678. //===//
  15679. state.mode = DICT;
  15680. /* falls through */
  15681. case DICT:
  15682. if (state.havedict === 0) {
  15683. //--- RESTORE() ---
  15684. strm.next_out = put;
  15685. strm.avail_out = left;
  15686. strm.next_in = next;
  15687. strm.avail_in = have;
  15688. state.hold = hold;
  15689. state.bits = bits;
  15690. //---
  15691. return Z_NEED_DICT;
  15692. }
  15693. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15694. state.mode = TYPE;
  15695. /* falls through */
  15696. case TYPE:
  15697. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  15698. /* falls through */
  15699. case TYPEDO:
  15700. if (state.last) {
  15701. //--- BYTEBITS() ---//
  15702. hold >>>= bits & 7;
  15703. bits -= bits & 7;
  15704. //---//
  15705. state.mode = CHECK;
  15706. break;
  15707. }
  15708. //=== NEEDBITS(3); */
  15709. while (bits < 3) {
  15710. if (have === 0) { break inf_leave; }
  15711. have--;
  15712. hold += input[next++] << bits;
  15713. bits += 8;
  15714. }
  15715. //===//
  15716. state.last = (hold & 0x01)/*BITS(1)*/;
  15717. //--- DROPBITS(1) ---//
  15718. hold >>>= 1;
  15719. bits -= 1;
  15720. //---//
  15721. switch ((hold & 0x03)/*BITS(2)*/) {
  15722. case 0: /* stored block */
  15723. //Tracev((stderr, "inflate: stored block%s\n",
  15724. // state.last ? " (last)" : ""));
  15725. state.mode = STORED;
  15726. break;
  15727. case 1: /* fixed block */
  15728. fixedtables(state);
  15729. //Tracev((stderr, "inflate: fixed codes block%s\n",
  15730. // state.last ? " (last)" : ""));
  15731. state.mode = LEN_; /* decode codes */
  15732. if (flush === Z_TREES) {
  15733. //--- DROPBITS(2) ---//
  15734. hold >>>= 2;
  15735. bits -= 2;
  15736. //---//
  15737. break inf_leave;
  15738. }
  15739. break;
  15740. case 2: /* dynamic block */
  15741. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  15742. // state.last ? " (last)" : ""));
  15743. state.mode = TABLE;
  15744. break;
  15745. case 3:
  15746. strm.msg = 'invalid block type';
  15747. state.mode = BAD;
  15748. }
  15749. //--- DROPBITS(2) ---//
  15750. hold >>>= 2;
  15751. bits -= 2;
  15752. //---//
  15753. break;
  15754. case STORED:
  15755. //--- BYTEBITS() ---// /* go to byte boundary */
  15756. hold >>>= bits & 7;
  15757. bits -= bits & 7;
  15758. //---//
  15759. //=== NEEDBITS(32); */
  15760. while (bits < 32) {
  15761. if (have === 0) { break inf_leave; }
  15762. have--;
  15763. hold += input[next++] << bits;
  15764. bits += 8;
  15765. }
  15766. //===//
  15767. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  15768. strm.msg = 'invalid stored block lengths';
  15769. state.mode = BAD;
  15770. break;
  15771. }
  15772. state.length = hold & 0xffff;
  15773. //Tracev((stderr, "inflate: stored length %u\n",
  15774. // state.length));
  15775. //=== INITBITS();
  15776. hold = 0;
  15777. bits = 0;
  15778. //===//
  15779. state.mode = COPY_;
  15780. if (flush === Z_TREES) { break inf_leave; }
  15781. /* falls through */
  15782. case COPY_:
  15783. state.mode = COPY;
  15784. /* falls through */
  15785. case COPY:
  15786. copy = state.length;
  15787. if (copy) {
  15788. if (copy > have) { copy = have; }
  15789. if (copy > left) { copy = left; }
  15790. if (copy === 0) { break inf_leave; }
  15791. //--- zmemcpy(put, next, copy); ---
  15792. utils.arraySet(output, input, next, copy, put);
  15793. //---//
  15794. have -= copy;
  15795. next += copy;
  15796. left -= copy;
  15797. put += copy;
  15798. state.length -= copy;
  15799. break;
  15800. }
  15801. //Tracev((stderr, "inflate: stored end\n"));
  15802. state.mode = TYPE;
  15803. break;
  15804. case TABLE:
  15805. //=== NEEDBITS(14); */
  15806. while (bits < 14) {
  15807. if (have === 0) { break inf_leave; }
  15808. have--;
  15809. hold += input[next++] << bits;
  15810. bits += 8;
  15811. }
  15812. //===//
  15813. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  15814. //--- DROPBITS(5) ---//
  15815. hold >>>= 5;
  15816. bits -= 5;
  15817. //---//
  15818. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  15819. //--- DROPBITS(5) ---//
  15820. hold >>>= 5;
  15821. bits -= 5;
  15822. //---//
  15823. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  15824. //--- DROPBITS(4) ---//
  15825. hold >>>= 4;
  15826. bits -= 4;
  15827. //---//
  15828. //#ifndef PKZIP_BUG_WORKAROUND
  15829. if (state.nlen > 286 || state.ndist > 30) {
  15830. strm.msg = 'too many length or distance symbols';
  15831. state.mode = BAD;
  15832. break;
  15833. }
  15834. //#endif
  15835. //Tracev((stderr, "inflate: table sizes ok\n"));
  15836. state.have = 0;
  15837. state.mode = LENLENS;
  15838. /* falls through */
  15839. case LENLENS:
  15840. while (state.have < state.ncode) {
  15841. //=== NEEDBITS(3);
  15842. while (bits < 3) {
  15843. if (have === 0) { break inf_leave; }
  15844. have--;
  15845. hold += input[next++] << bits;
  15846. bits += 8;
  15847. }
  15848. //===//
  15849. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  15850. //--- DROPBITS(3) ---//
  15851. hold >>>= 3;
  15852. bits -= 3;
  15853. //---//
  15854. }
  15855. while (state.have < 19) {
  15856. state.lens[order[state.have++]] = 0;
  15857. }
  15858. // We have separate tables & no pointers. 2 commented lines below not needed.
  15859. //state.next = state.codes;
  15860. //state.lencode = state.next;
  15861. // Switch to use dynamic table
  15862. state.lencode = state.lendyn;
  15863. state.lenbits = 7;
  15864. opts = {bits: state.lenbits};
  15865. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  15866. state.lenbits = opts.bits;
  15867. if (ret) {
  15868. strm.msg = 'invalid code lengths set';
  15869. state.mode = BAD;
  15870. break;
  15871. }
  15872. //Tracev((stderr, "inflate: code lengths ok\n"));
  15873. state.have = 0;
  15874. state.mode = CODELENS;
  15875. /* falls through */
  15876. case CODELENS:
  15877. while (state.have < state.nlen + state.ndist) {
  15878. for (;;) {
  15879. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  15880. here_bits = here >>> 24;
  15881. here_op = (here >>> 16) & 0xff;
  15882. here_val = here & 0xffff;
  15883. if ((here_bits) <= bits) { break; }
  15884. //--- PULLBYTE() ---//
  15885. if (have === 0) { break inf_leave; }
  15886. have--;
  15887. hold += input[next++] << bits;
  15888. bits += 8;
  15889. //---//
  15890. }
  15891. if (here_val < 16) {
  15892. //--- DROPBITS(here.bits) ---//
  15893. hold >>>= here_bits;
  15894. bits -= here_bits;
  15895. //---//
  15896. state.lens[state.have++] = here_val;
  15897. }
  15898. else {
  15899. if (here_val === 16) {
  15900. //=== NEEDBITS(here.bits + 2);
  15901. n = here_bits + 2;
  15902. while (bits < n) {
  15903. if (have === 0) { break inf_leave; }
  15904. have--;
  15905. hold += input[next++] << bits;
  15906. bits += 8;
  15907. }
  15908. //===//
  15909. //--- DROPBITS(here.bits) ---//
  15910. hold >>>= here_bits;
  15911. bits -= here_bits;
  15912. //---//
  15913. if (state.have === 0) {
  15914. strm.msg = 'invalid bit length repeat';
  15915. state.mode = BAD;
  15916. break;
  15917. }
  15918. len = state.lens[state.have - 1];
  15919. copy = 3 + (hold & 0x03);//BITS(2);
  15920. //--- DROPBITS(2) ---//
  15921. hold >>>= 2;
  15922. bits -= 2;
  15923. //---//
  15924. }
  15925. else if (here_val === 17) {
  15926. //=== NEEDBITS(here.bits + 3);
  15927. n = here_bits + 3;
  15928. while (bits < n) {
  15929. if (have === 0) { break inf_leave; }
  15930. have--;
  15931. hold += input[next++] << bits;
  15932. bits += 8;
  15933. }
  15934. //===//
  15935. //--- DROPBITS(here.bits) ---//
  15936. hold >>>= here_bits;
  15937. bits -= here_bits;
  15938. //---//
  15939. len = 0;
  15940. copy = 3 + (hold & 0x07);//BITS(3);
  15941. //--- DROPBITS(3) ---//
  15942. hold >>>= 3;
  15943. bits -= 3;
  15944. //---//
  15945. }
  15946. else {
  15947. //=== NEEDBITS(here.bits + 7);
  15948. n = here_bits + 7;
  15949. while (bits < n) {
  15950. if (have === 0) { break inf_leave; }
  15951. have--;
  15952. hold += input[next++] << bits;
  15953. bits += 8;
  15954. }
  15955. //===//
  15956. //--- DROPBITS(here.bits) ---//
  15957. hold >>>= here_bits;
  15958. bits -= here_bits;
  15959. //---//
  15960. len = 0;
  15961. copy = 11 + (hold & 0x7f);//BITS(7);
  15962. //--- DROPBITS(7) ---//
  15963. hold >>>= 7;
  15964. bits -= 7;
  15965. //---//
  15966. }
  15967. if (state.have + copy > state.nlen + state.ndist) {
  15968. strm.msg = 'invalid bit length repeat';
  15969. state.mode = BAD;
  15970. break;
  15971. }
  15972. while (copy--) {
  15973. state.lens[state.have++] = len;
  15974. }
  15975. }
  15976. }
  15977. /* handle error breaks in while */
  15978. if (state.mode === BAD) { break; }
  15979. /* check for end-of-block code (better have one) */
  15980. if (state.lens[256] === 0) {
  15981. strm.msg = 'invalid code -- missing end-of-block';
  15982. state.mode = BAD;
  15983. break;
  15984. }
  15985. /* build code tables -- note: do not change the lenbits or distbits
  15986. values here (9 and 6) without reading the comments in inftrees.h
  15987. concerning the ENOUGH constants, which depend on those values */
  15988. state.lenbits = 9;
  15989. opts = {bits: state.lenbits};
  15990. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  15991. // We have separate tables & no pointers. 2 commented lines below not needed.
  15992. // state.next_index = opts.table_index;
  15993. state.lenbits = opts.bits;
  15994. // state.lencode = state.next;
  15995. if (ret) {
  15996. strm.msg = 'invalid literal/lengths set';
  15997. state.mode = BAD;
  15998. break;
  15999. }
  16000. state.distbits = 6;
  16001. //state.distcode.copy(state.codes);
  16002. // Switch to use dynamic table
  16003. state.distcode = state.distdyn;
  16004. opts = {bits: state.distbits};
  16005. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16006. // We have separate tables & no pointers. 2 commented lines below not needed.
  16007. // state.next_index = opts.table_index;
  16008. state.distbits = opts.bits;
  16009. // state.distcode = state.next;
  16010. if (ret) {
  16011. strm.msg = 'invalid distances set';
  16012. state.mode = BAD;
  16013. break;
  16014. }
  16015. //Tracev((stderr, 'inflate: codes ok\n'));
  16016. state.mode = LEN_;
  16017. if (flush === Z_TREES) { break inf_leave; }
  16018. /* falls through */
  16019. case LEN_:
  16020. state.mode = LEN;
  16021. /* falls through */
  16022. case LEN:
  16023. if (have >= 6 && left >= 258) {
  16024. //--- RESTORE() ---
  16025. strm.next_out = put;
  16026. strm.avail_out = left;
  16027. strm.next_in = next;
  16028. strm.avail_in = have;
  16029. state.hold = hold;
  16030. state.bits = bits;
  16031. //---
  16032. inflate_fast(strm, _out);
  16033. //--- LOAD() ---
  16034. put = strm.next_out;
  16035. output = strm.output;
  16036. left = strm.avail_out;
  16037. next = strm.next_in;
  16038. input = strm.input;
  16039. have = strm.avail_in;
  16040. hold = state.hold;
  16041. bits = state.bits;
  16042. //---
  16043. if (state.mode === TYPE) {
  16044. state.back = -1;
  16045. }
  16046. break;
  16047. }
  16048. state.back = 0;
  16049. for (;;) {
  16050. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16051. here_bits = here >>> 24;
  16052. here_op = (here >>> 16) & 0xff;
  16053. here_val = here & 0xffff;
  16054. if (here_bits <= bits) { break; }
  16055. //--- PULLBYTE() ---//
  16056. if (have === 0) { break inf_leave; }
  16057. have--;
  16058. hold += input[next++] << bits;
  16059. bits += 8;
  16060. //---//
  16061. }
  16062. if (here_op && (here_op & 0xf0) === 0) {
  16063. last_bits = here_bits;
  16064. last_op = here_op;
  16065. last_val = here_val;
  16066. for (;;) {
  16067. here = state.lencode[last_val +
  16068. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16069. here_bits = here >>> 24;
  16070. here_op = (here >>> 16) & 0xff;
  16071. here_val = here & 0xffff;
  16072. if ((last_bits + here_bits) <= bits) { break; }
  16073. //--- PULLBYTE() ---//
  16074. if (have === 0) { break inf_leave; }
  16075. have--;
  16076. hold += input[next++] << bits;
  16077. bits += 8;
  16078. //---//
  16079. }
  16080. //--- DROPBITS(last.bits) ---//
  16081. hold >>>= last_bits;
  16082. bits -= last_bits;
  16083. //---//
  16084. state.back += last_bits;
  16085. }
  16086. //--- DROPBITS(here.bits) ---//
  16087. hold >>>= here_bits;
  16088. bits -= here_bits;
  16089. //---//
  16090. state.back += here_bits;
  16091. state.length = here_val;
  16092. if (here_op === 0) {
  16093. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16094. // "inflate: literal '%c'\n" :
  16095. // "inflate: literal 0x%02x\n", here.val));
  16096. state.mode = LIT;
  16097. break;
  16098. }
  16099. if (here_op & 32) {
  16100. //Tracevv((stderr, "inflate: end of block\n"));
  16101. state.back = -1;
  16102. state.mode = TYPE;
  16103. break;
  16104. }
  16105. if (here_op & 64) {
  16106. strm.msg = 'invalid literal/length code';
  16107. state.mode = BAD;
  16108. break;
  16109. }
  16110. state.extra = here_op & 15;
  16111. state.mode = LENEXT;
  16112. /* falls through */
  16113. case LENEXT:
  16114. if (state.extra) {
  16115. //=== NEEDBITS(state.extra);
  16116. n = state.extra;
  16117. while (bits < n) {
  16118. if (have === 0) { break inf_leave; }
  16119. have--;
  16120. hold += input[next++] << bits;
  16121. bits += 8;
  16122. }
  16123. //===//
  16124. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16125. //--- DROPBITS(state.extra) ---//
  16126. hold >>>= state.extra;
  16127. bits -= state.extra;
  16128. //---//
  16129. state.back += state.extra;
  16130. }
  16131. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16132. state.was = state.length;
  16133. state.mode = DIST;
  16134. /* falls through */
  16135. case DIST:
  16136. for (;;) {
  16137. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16138. here_bits = here >>> 24;
  16139. here_op = (here >>> 16) & 0xff;
  16140. here_val = here & 0xffff;
  16141. if ((here_bits) <= bits) { break; }
  16142. //--- PULLBYTE() ---//
  16143. if (have === 0) { break inf_leave; }
  16144. have--;
  16145. hold += input[next++] << bits;
  16146. bits += 8;
  16147. //---//
  16148. }
  16149. if ((here_op & 0xf0) === 0) {
  16150. last_bits = here_bits;
  16151. last_op = here_op;
  16152. last_val = here_val;
  16153. for (;;) {
  16154. here = state.distcode[last_val +
  16155. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16156. here_bits = here >>> 24;
  16157. here_op = (here >>> 16) & 0xff;
  16158. here_val = here & 0xffff;
  16159. if ((last_bits + here_bits) <= bits) { break; }
  16160. //--- PULLBYTE() ---//
  16161. if (have === 0) { break inf_leave; }
  16162. have--;
  16163. hold += input[next++] << bits;
  16164. bits += 8;
  16165. //---//
  16166. }
  16167. //--- DROPBITS(last.bits) ---//
  16168. hold >>>= last_bits;
  16169. bits -= last_bits;
  16170. //---//
  16171. state.back += last_bits;
  16172. }
  16173. //--- DROPBITS(here.bits) ---//
  16174. hold >>>= here_bits;
  16175. bits -= here_bits;
  16176. //---//
  16177. state.back += here_bits;
  16178. if (here_op & 64) {
  16179. strm.msg = 'invalid distance code';
  16180. state.mode = BAD;
  16181. break;
  16182. }
  16183. state.offset = here_val;
  16184. state.extra = (here_op) & 15;
  16185. state.mode = DISTEXT;
  16186. /* falls through */
  16187. case DISTEXT:
  16188. if (state.extra) {
  16189. //=== NEEDBITS(state.extra);
  16190. n = state.extra;
  16191. while (bits < n) {
  16192. if (have === 0) { break inf_leave; }
  16193. have--;
  16194. hold += input[next++] << bits;
  16195. bits += 8;
  16196. }
  16197. //===//
  16198. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16199. //--- DROPBITS(state.extra) ---//
  16200. hold >>>= state.extra;
  16201. bits -= state.extra;
  16202. //---//
  16203. state.back += state.extra;
  16204. }
  16205. //#ifdef INFLATE_STRICT
  16206. if (state.offset > state.dmax) {
  16207. strm.msg = 'invalid distance too far back';
  16208. state.mode = BAD;
  16209. break;
  16210. }
  16211. //#endif
  16212. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  16213. state.mode = MATCH;
  16214. /* falls through */
  16215. case MATCH:
  16216. if (left === 0) { break inf_leave; }
  16217. copy = _out - left;
  16218. if (state.offset > copy) { /* copy from window */
  16219. copy = state.offset - copy;
  16220. if (copy > state.whave) {
  16221. if (state.sane) {
  16222. strm.msg = 'invalid distance too far back';
  16223. state.mode = BAD;
  16224. break;
  16225. }
  16226. // (!) This block is disabled in zlib defailts,
  16227. // don't enable it for binary compatibility
  16228. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16229. // Trace((stderr, "inflate.c too far\n"));
  16230. // copy -= state.whave;
  16231. // if (copy > state.length) { copy = state.length; }
  16232. // if (copy > left) { copy = left; }
  16233. // left -= copy;
  16234. // state.length -= copy;
  16235. // do {
  16236. // output[put++] = 0;
  16237. // } while (--copy);
  16238. // if (state.length === 0) { state.mode = LEN; }
  16239. // break;
  16240. //#endif
  16241. }
  16242. if (copy > state.wnext) {
  16243. copy -= state.wnext;
  16244. from = state.wsize - copy;
  16245. }
  16246. else {
  16247. from = state.wnext - copy;
  16248. }
  16249. if (copy > state.length) { copy = state.length; }
  16250. from_source = state.window;
  16251. }
  16252. else { /* copy from output */
  16253. from_source = output;
  16254. from = put - state.offset;
  16255. copy = state.length;
  16256. }
  16257. if (copy > left) { copy = left; }
  16258. left -= copy;
  16259. state.length -= copy;
  16260. do {
  16261. output[put++] = from_source[from++];
  16262. } while (--copy);
  16263. if (state.length === 0) { state.mode = LEN; }
  16264. break;
  16265. case LIT:
  16266. if (left === 0) { break inf_leave; }
  16267. output[put++] = state.length;
  16268. left--;
  16269. state.mode = LEN;
  16270. break;
  16271. case CHECK:
  16272. if (state.wrap) {
  16273. //=== NEEDBITS(32);
  16274. while (bits < 32) {
  16275. if (have === 0) { break inf_leave; }
  16276. have--;
  16277. // Use '|' insdead of '+' to make sure that result is signed
  16278. hold |= input[next++] << bits;
  16279. bits += 8;
  16280. }
  16281. //===//
  16282. _out -= left;
  16283. strm.total_out += _out;
  16284. state.total += _out;
  16285. if (_out) {
  16286. strm.adler = state.check =
  16287. /*UPDATE(state.check, put - _out, _out);*/
  16288. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  16289. }
  16290. _out = left;
  16291. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  16292. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  16293. strm.msg = 'incorrect data check';
  16294. state.mode = BAD;
  16295. break;
  16296. }
  16297. //=== INITBITS();
  16298. hold = 0;
  16299. bits = 0;
  16300. //===//
  16301. //Tracev((stderr, "inflate: check matches trailer\n"));
  16302. }
  16303. state.mode = LENGTH;
  16304. /* falls through */
  16305. case LENGTH:
  16306. if (state.wrap && state.flags) {
  16307. //=== NEEDBITS(32);
  16308. while (bits < 32) {
  16309. if (have === 0) { break inf_leave; }
  16310. have--;
  16311. hold += input[next++] << bits;
  16312. bits += 8;
  16313. }
  16314. //===//
  16315. if (hold !== (state.total & 0xffffffff)) {
  16316. strm.msg = 'incorrect length check';
  16317. state.mode = BAD;
  16318. break;
  16319. }
  16320. //=== INITBITS();
  16321. hold = 0;
  16322. bits = 0;
  16323. //===//
  16324. //Tracev((stderr, "inflate: length matches trailer\n"));
  16325. }
  16326. state.mode = DONE;
  16327. /* falls through */
  16328. case DONE:
  16329. ret = Z_STREAM_END;
  16330. break inf_leave;
  16331. case BAD:
  16332. ret = Z_DATA_ERROR;
  16333. break inf_leave;
  16334. case MEM:
  16335. return Z_MEM_ERROR;
  16336. case SYNC:
  16337. /* falls through */
  16338. default:
  16339. return Z_STREAM_ERROR;
  16340. }
  16341. }
  16342. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  16343. /*
  16344. Return from inflate(), updating the total counts and the check value.
  16345. If there was no progress during the inflate() call, return a buffer
  16346. error. Call updatewindow() to create and/or update the window state.
  16347. Note: a memory error from inflate() is non-recoverable.
  16348. */
  16349. //--- RESTORE() ---
  16350. strm.next_out = put;
  16351. strm.avail_out = left;
  16352. strm.next_in = next;
  16353. strm.avail_in = have;
  16354. state.hold = hold;
  16355. state.bits = bits;
  16356. //---
  16357. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  16358. (state.mode < CHECK || flush !== Z_FINISH))) {
  16359. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  16360. state.mode = MEM;
  16361. return Z_MEM_ERROR;
  16362. }
  16363. }
  16364. _in -= strm.avail_in;
  16365. _out -= strm.avail_out;
  16366. strm.total_in += _in;
  16367. strm.total_out += _out;
  16368. state.total += _out;
  16369. if (state.wrap && _out) {
  16370. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  16371. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  16372. }
  16373. strm.data_type = state.bits + (state.last ? 64 : 0) +
  16374. (state.mode === TYPE ? 128 : 0) +
  16375. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  16376. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  16377. ret = Z_BUF_ERROR;
  16378. }
  16379. return ret;
  16380. }
  16381. function inflateEnd(strm) {
  16382. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  16383. return Z_STREAM_ERROR;
  16384. }
  16385. var state = strm.state;
  16386. if (state.window) {
  16387. state.window = null;
  16388. }
  16389. strm.state = null;
  16390. return Z_OK;
  16391. }
  16392. function inflateGetHeader(strm, head) {
  16393. var state;
  16394. /* check state */
  16395. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16396. state = strm.state;
  16397. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  16398. /* save header structure */
  16399. state.head = head;
  16400. head.done = false;
  16401. return Z_OK;
  16402. }
  16403. exports.inflateReset = inflateReset;
  16404. exports.inflateReset2 = inflateReset2;
  16405. exports.inflateResetKeep = inflateResetKeep;
  16406. exports.inflateInit = inflateInit;
  16407. exports.inflateInit2 = inflateInit2;
  16408. exports.inflate = inflate;
  16409. exports.inflateEnd = inflateEnd;
  16410. exports.inflateGetHeader = inflateGetHeader;
  16411. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  16412. /* Not implemented
  16413. exports.inflateCopy = inflateCopy;
  16414. exports.inflateGetDictionary = inflateGetDictionary;
  16415. exports.inflateMark = inflateMark;
  16416. exports.inflatePrime = inflatePrime;
  16417. exports.inflateSetDictionary = inflateSetDictionary;
  16418. exports.inflateSync = inflateSync;
  16419. exports.inflateSyncPoint = inflateSyncPoint;
  16420. exports.inflateUndermine = inflateUndermine;
  16421. */
  16422. },{"../utils/common":48,"./adler32":50,"./crc32":52,"./inffast":55,"./inftrees":57}],57:[function(require,module,exports){
  16423. 'use strict';
  16424. var utils = require('../utils/common');
  16425. var MAXBITS = 15;
  16426. var ENOUGH_LENS = 852;
  16427. var ENOUGH_DISTS = 592;
  16428. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16429. var CODES = 0;
  16430. var LENS = 1;
  16431. var DISTS = 2;
  16432. var lbase = [ /* Length codes 257..285 base */
  16433. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  16434. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  16435. ];
  16436. var lext = [ /* Length codes 257..285 extra */
  16437. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  16438. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  16439. ];
  16440. var dbase = [ /* Distance codes 0..29 base */
  16441. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  16442. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  16443. 8193, 12289, 16385, 24577, 0, 0
  16444. ];
  16445. var dext = [ /* Distance codes 0..29 extra */
  16446. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  16447. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  16448. 28, 28, 29, 29, 64, 64
  16449. ];
  16450. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  16451. {
  16452. var bits = opts.bits;
  16453. //here = opts.here; /* table entry for duplication */
  16454. var len = 0; /* a code's length in bits */
  16455. var sym = 0; /* index of code symbols */
  16456. var min = 0, max = 0; /* minimum and maximum code lengths */
  16457. var root = 0; /* number of index bits for root table */
  16458. var curr = 0; /* number of index bits for current table */
  16459. var drop = 0; /* code bits to drop for sub-table */
  16460. var left = 0; /* number of prefix codes available */
  16461. var used = 0; /* code entries in table used */
  16462. var huff = 0; /* Huffman code */
  16463. var incr; /* for incrementing code, index */
  16464. var fill; /* index for replicating entries */
  16465. var low; /* low bits for current root entry */
  16466. var mask; /* mask for low root bits */
  16467. var next; /* next available space in table */
  16468. var base = null; /* base value table to use */
  16469. var base_index = 0;
  16470. // var shoextra; /* extra bits table to use */
  16471. var end; /* use base and extra for symbol > end */
  16472. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  16473. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  16474. var extra = null;
  16475. var extra_index = 0;
  16476. var here_bits, here_op, here_val;
  16477. /*
  16478. Process a set of code lengths to create a canonical Huffman code. The
  16479. code lengths are lens[0..codes-1]. Each length corresponds to the
  16480. symbols 0..codes-1. The Huffman code is generated by first sorting the
  16481. symbols by length from short to long, and retaining the symbol order
  16482. for codes with equal lengths. Then the code starts with all zero bits
  16483. for the first code of the shortest length, and the codes are integer
  16484. increments for the same length, and zeros are appended as the length
  16485. increases. For the deflate format, these bits are stored backwards
  16486. from their more natural integer increment ordering, and so when the
  16487. decoding tables are built in the large loop below, the integer codes
  16488. are incremented backwards.
  16489. This routine assumes, but does not check, that all of the entries in
  16490. lens[] are in the range 0..MAXBITS. The caller must assure this.
  16491. 1..MAXBITS is interpreted as that code length. zero means that that
  16492. symbol does not occur in this code.
  16493. The codes are sorted by computing a count of codes for each length,
  16494. creating from that a table of starting indices for each length in the
  16495. sorted table, and then entering the symbols in order in the sorted
  16496. table. The sorted table is work[], with that space being provided by
  16497. the caller.
  16498. The length counts are used for other purposes as well, i.e. finding
  16499. the minimum and maximum length codes, determining if there are any
  16500. codes at all, checking for a valid set of lengths, and looking ahead
  16501. at length counts to determine sub-table sizes when building the
  16502. decoding tables.
  16503. */
  16504. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  16505. for (len = 0; len <= MAXBITS; len++) {
  16506. count[len] = 0;
  16507. }
  16508. for (sym = 0; sym < codes; sym++) {
  16509. count[lens[lens_index + sym]]++;
  16510. }
  16511. /* bound code lengths, force root to be within code lengths */
  16512. root = bits;
  16513. for (max = MAXBITS; max >= 1; max--) {
  16514. if (count[max] !== 0) { break; }
  16515. }
  16516. if (root > max) {
  16517. root = max;
  16518. }
  16519. if (max === 0) { /* no symbols to code at all */
  16520. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  16521. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  16522. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  16523. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16524. //table.op[opts.table_index] = 64;
  16525. //table.bits[opts.table_index] = 1;
  16526. //table.val[opts.table_index++] = 0;
  16527. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16528. opts.bits = 1;
  16529. return 0; /* no symbols, but wait for decoding to report error */
  16530. }
  16531. for (min = 1; min < max; min++) {
  16532. if (count[min] !== 0) { break; }
  16533. }
  16534. if (root < min) {
  16535. root = min;
  16536. }
  16537. /* check for an over-subscribed or incomplete set of lengths */
  16538. left = 1;
  16539. for (len = 1; len <= MAXBITS; len++) {
  16540. left <<= 1;
  16541. left -= count[len];
  16542. if (left < 0) {
  16543. return -1;
  16544. } /* over-subscribed */
  16545. }
  16546. if (left > 0 && (type === CODES || max !== 1)) {
  16547. return -1; /* incomplete set */
  16548. }
  16549. /* generate offsets into symbol table for each length for sorting */
  16550. offs[1] = 0;
  16551. for (len = 1; len < MAXBITS; len++) {
  16552. offs[len + 1] = offs[len] + count[len];
  16553. }
  16554. /* sort symbols by length, by symbol order within each length */
  16555. for (sym = 0; sym < codes; sym++) {
  16556. if (lens[lens_index + sym] !== 0) {
  16557. work[offs[lens[lens_index + sym]]++] = sym;
  16558. }
  16559. }
  16560. /*
  16561. Create and fill in decoding tables. In this loop, the table being
  16562. filled is at next and has curr index bits. The code being used is huff
  16563. with length len. That code is converted to an index by dropping drop
  16564. bits off of the bottom. For codes where len is less than drop + curr,
  16565. those top drop + curr - len bits are incremented through all values to
  16566. fill the table with replicated entries.
  16567. root is the number of index bits for the root table. When len exceeds
  16568. root, sub-tables are created pointed to by the root entry with an index
  16569. of the low root bits of huff. This is saved in low to check for when a
  16570. new sub-table should be started. drop is zero when the root table is
  16571. being filled, and drop is root when sub-tables are being filled.
  16572. When a new sub-table is needed, it is necessary to look ahead in the
  16573. code lengths to determine what size sub-table is needed. The length
  16574. counts are used for this, and so count[] is decremented as codes are
  16575. entered in the tables.
  16576. used keeps track of how many table entries have been allocated from the
  16577. provided *table space. It is checked for LENS and DIST tables against
  16578. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  16579. the initial root table size constants. See the comments in inftrees.h
  16580. for more information.
  16581. sym increments through all symbols, and the loop terminates when
  16582. all codes of length max, i.e. all codes, have been processed. This
  16583. routine permits incomplete codes, so another loop after this one fills
  16584. in the rest of the decoding tables with invalid code markers.
  16585. */
  16586. /* set up for code type */
  16587. // poor man optimization - use if-else instead of switch,
  16588. // to avoid deopts in old v8
  16589. if (type === CODES) {
  16590. base = extra = work; /* dummy value--not used */
  16591. end = 19;
  16592. } else if (type === LENS) {
  16593. base = lbase;
  16594. base_index -= 257;
  16595. extra = lext;
  16596. extra_index -= 257;
  16597. end = 256;
  16598. } else { /* DISTS */
  16599. base = dbase;
  16600. extra = dext;
  16601. end = -1;
  16602. }
  16603. /* initialize opts for loop */
  16604. huff = 0; /* starting code */
  16605. sym = 0; /* starting code symbol */
  16606. len = min; /* starting code length */
  16607. next = table_index; /* current table to fill in */
  16608. curr = root; /* current table index bits */
  16609. drop = 0; /* current bits to drop from code for index */
  16610. low = -1; /* trigger new sub-table when len > root */
  16611. used = 1 << root; /* use root table entries */
  16612. mask = used - 1; /* mask for comparing low */
  16613. /* check available table space */
  16614. if ((type === LENS && used > ENOUGH_LENS) ||
  16615. (type === DISTS && used > ENOUGH_DISTS)) {
  16616. return 1;
  16617. }
  16618. var i=0;
  16619. /* process all codes and make table entries */
  16620. for (;;) {
  16621. i++;
  16622. /* create table entry */
  16623. here_bits = len - drop;
  16624. if (work[sym] < end) {
  16625. here_op = 0;
  16626. here_val = work[sym];
  16627. }
  16628. else if (work[sym] > end) {
  16629. here_op = extra[extra_index + work[sym]];
  16630. here_val = base[base_index + work[sym]];
  16631. }
  16632. else {
  16633. here_op = 32 + 64; /* end of block */
  16634. here_val = 0;
  16635. }
  16636. /* replicate for those indices with low len bits equal to huff */
  16637. incr = 1 << (len - drop);
  16638. fill = 1 << curr;
  16639. min = fill; /* save offset to next table */
  16640. do {
  16641. fill -= incr;
  16642. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  16643. } while (fill !== 0);
  16644. /* backwards increment the len-bit code huff */
  16645. incr = 1 << (len - 1);
  16646. while (huff & incr) {
  16647. incr >>= 1;
  16648. }
  16649. if (incr !== 0) {
  16650. huff &= incr - 1;
  16651. huff += incr;
  16652. } else {
  16653. huff = 0;
  16654. }
  16655. /* go to next symbol, update count, len */
  16656. sym++;
  16657. if (--count[len] === 0) {
  16658. if (len === max) { break; }
  16659. len = lens[lens_index + work[sym]];
  16660. }
  16661. /* create new sub-table if needed */
  16662. if (len > root && (huff & mask) !== low) {
  16663. /* if first time, transition to sub-tables */
  16664. if (drop === 0) {
  16665. drop = root;
  16666. }
  16667. /* increment past last table */
  16668. next += min; /* here min is 1 << curr */
  16669. /* determine length of next table */
  16670. curr = len - drop;
  16671. left = 1 << curr;
  16672. while (curr + drop < max) {
  16673. left -= count[curr + drop];
  16674. if (left <= 0) { break; }
  16675. curr++;
  16676. left <<= 1;
  16677. }
  16678. /* check for enough space */
  16679. used += 1 << curr;
  16680. if ((type === LENS && used > ENOUGH_LENS) ||
  16681. (type === DISTS && used > ENOUGH_DISTS)) {
  16682. return 1;
  16683. }
  16684. /* point entry in root table to sub-table */
  16685. low = huff & mask;
  16686. /*table.op[low] = curr;
  16687. table.bits[low] = root;
  16688. table.val[low] = next - opts.table_index;*/
  16689. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  16690. }
  16691. }
  16692. /* fill in remaining table entry if code is incomplete (guaranteed to have
  16693. at most one remaining entry, since if the code is incomplete, the
  16694. maximum code length that was allowed to get this far is one bit) */
  16695. if (huff !== 0) {
  16696. //table.op[next + huff] = 64; /* invalid code marker */
  16697. //table.bits[next + huff] = len - drop;
  16698. //table.val[next + huff] = 0;
  16699. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  16700. }
  16701. /* set return parameters */
  16702. //opts.table_index += used;
  16703. opts.bits = root;
  16704. return 0;
  16705. };
  16706. },{"../utils/common":48}],58:[function(require,module,exports){
  16707. 'use strict';
  16708. module.exports = {
  16709. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  16710. '1': 'stream end', /* Z_STREAM_END 1 */
  16711. '0': '', /* Z_OK 0 */
  16712. '-1': 'file error', /* Z_ERRNO (-1) */
  16713. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  16714. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  16715. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  16716. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  16717. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  16718. };
  16719. },{}],59:[function(require,module,exports){
  16720. 'use strict';
  16721. var utils = require('../utils/common');
  16722. /* Public constants ==========================================================*/
  16723. /* ===========================================================================*/
  16724. //var Z_FILTERED = 1;
  16725. //var Z_HUFFMAN_ONLY = 2;
  16726. //var Z_RLE = 3;
  16727. var Z_FIXED = 4;
  16728. //var Z_DEFAULT_STRATEGY = 0;
  16729. /* Possible values of the data_type field (though see inflate()) */
  16730. var Z_BINARY = 0;
  16731. var Z_TEXT = 1;
  16732. //var Z_ASCII = 1; // = Z_TEXT
  16733. var Z_UNKNOWN = 2;
  16734. /*============================================================================*/
  16735. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  16736. // From zutil.h
  16737. var STORED_BLOCK = 0;
  16738. var STATIC_TREES = 1;
  16739. var DYN_TREES = 2;
  16740. /* The three kinds of block type */
  16741. var MIN_MATCH = 3;
  16742. var MAX_MATCH = 258;
  16743. /* The minimum and maximum match lengths */
  16744. // From deflate.h
  16745. /* ===========================================================================
  16746. * Internal compression state.
  16747. */
  16748. var LENGTH_CODES = 29;
  16749. /* number of length codes, not counting the special END_BLOCK code */
  16750. var LITERALS = 256;
  16751. /* number of literal bytes 0..255 */
  16752. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  16753. /* number of Literal or Length codes, including the END_BLOCK code */
  16754. var D_CODES = 30;
  16755. /* number of distance codes */
  16756. var BL_CODES = 19;
  16757. /* number of codes used to transfer the bit lengths */
  16758. var HEAP_SIZE = 2*L_CODES + 1;
  16759. /* maximum heap size */
  16760. var MAX_BITS = 15;
  16761. /* All codes must not exceed MAX_BITS bits */
  16762. var Buf_size = 16;
  16763. /* size of bit buffer in bi_buf */
  16764. /* ===========================================================================
  16765. * Constants
  16766. */
  16767. var MAX_BL_BITS = 7;
  16768. /* Bit length codes must not exceed MAX_BL_BITS bits */
  16769. var END_BLOCK = 256;
  16770. /* end of block literal code */
  16771. var REP_3_6 = 16;
  16772. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  16773. var REPZ_3_10 = 17;
  16774. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  16775. var REPZ_11_138 = 18;
  16776. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  16777. var extra_lbits = /* extra bits for each length code */
  16778. [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];
  16779. var extra_dbits = /* extra bits for each distance code */
  16780. [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];
  16781. var extra_blbits = /* extra bits for each bit length code */
  16782. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  16783. var bl_order =
  16784. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  16785. /* The lengths of the bit length codes are sent in order of decreasing
  16786. * probability, to avoid transmitting the lengths for unused bit length codes.
  16787. */
  16788. /* ===========================================================================
  16789. * Local data. These are initialized only once.
  16790. */
  16791. // We pre-fill arrays with 0 to avoid uninitialized gaps
  16792. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  16793. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  16794. var static_ltree = new Array((L_CODES+2) * 2);
  16795. zero(static_ltree);
  16796. /* The static literal tree. Since the bit lengths are imposed, there is no
  16797. * need for the L_CODES extra codes used during heap construction. However
  16798. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  16799. * below).
  16800. */
  16801. var static_dtree = new Array(D_CODES * 2);
  16802. zero(static_dtree);
  16803. /* The static distance tree. (Actually a trivial tree since all codes use
  16804. * 5 bits.)
  16805. */
  16806. var _dist_code = new Array(DIST_CODE_LEN);
  16807. zero(_dist_code);
  16808. /* Distance codes. The first 256 values correspond to the distances
  16809. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  16810. * the 15 bit distances.
  16811. */
  16812. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  16813. zero(_length_code);
  16814. /* length code for each normalized match length (0 == MIN_MATCH) */
  16815. var base_length = new Array(LENGTH_CODES);
  16816. zero(base_length);
  16817. /* First normalized length for each code (0 = MIN_MATCH) */
  16818. var base_dist = new Array(D_CODES);
  16819. zero(base_dist);
  16820. /* First normalized distance for each code (0 = distance of 1) */
  16821. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  16822. this.static_tree = static_tree; /* static tree or NULL */
  16823. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  16824. this.extra_base = extra_base; /* base index for extra_bits */
  16825. this.elems = elems; /* max number of elements in the tree */
  16826. this.max_length = max_length; /* max bit length for the codes */
  16827. // show if `static_tree` has data or dummy - needed for monomorphic objects
  16828. this.has_stree = static_tree && static_tree.length;
  16829. };
  16830. var static_l_desc;
  16831. var static_d_desc;
  16832. var static_bl_desc;
  16833. var TreeDesc = function(dyn_tree, stat_desc) {
  16834. this.dyn_tree = dyn_tree; /* the dynamic tree */
  16835. this.max_code = 0; /* largest code with non zero frequency */
  16836. this.stat_desc = stat_desc; /* the corresponding static tree */
  16837. };
  16838. function d_code(dist) {
  16839. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  16840. }
  16841. /* ===========================================================================
  16842. * Output a short LSB first on the stream.
  16843. * IN assertion: there is enough room in pendingBuf.
  16844. */
  16845. function put_short (s, w) {
  16846. // put_byte(s, (uch)((w) & 0xff));
  16847. // put_byte(s, (uch)((ush)(w) >> 8));
  16848. s.pending_buf[s.pending++] = (w) & 0xff;
  16849. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  16850. }
  16851. /* ===========================================================================
  16852. * Send a value on a given number of bits.
  16853. * IN assertion: length <= 16 and value fits in length bits.
  16854. */
  16855. function send_bits(s, value, length) {
  16856. if (s.bi_valid > (Buf_size - length)) {
  16857. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  16858. put_short(s, s.bi_buf);
  16859. s.bi_buf = value >> (Buf_size - s.bi_valid);
  16860. s.bi_valid += length - Buf_size;
  16861. } else {
  16862. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  16863. s.bi_valid += length;
  16864. }
  16865. }
  16866. function send_code(s, c, tree) {
  16867. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  16868. }
  16869. /* ===========================================================================
  16870. * Reverse the first len bits of a code, using straightforward code (a faster
  16871. * method would use a table)
  16872. * IN assertion: 1 <= len <= 15
  16873. */
  16874. function bi_reverse(code, len) {
  16875. var res = 0;
  16876. do {
  16877. res |= code & 1;
  16878. code >>>= 1;
  16879. res <<= 1;
  16880. } while (--len > 0);
  16881. return res >>> 1;
  16882. }
  16883. /* ===========================================================================
  16884. * Flush the bit buffer, keeping at most 7 bits in it.
  16885. */
  16886. function bi_flush(s) {
  16887. if (s.bi_valid === 16) {
  16888. put_short(s, s.bi_buf);
  16889. s.bi_buf = 0;
  16890. s.bi_valid = 0;
  16891. } else if (s.bi_valid >= 8) {
  16892. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  16893. s.bi_buf >>= 8;
  16894. s.bi_valid -= 8;
  16895. }
  16896. }
  16897. /* ===========================================================================
  16898. * Compute the optimal bit lengths for a tree and update the total bit length
  16899. * for the current block.
  16900. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  16901. * above are the tree nodes sorted by increasing frequency.
  16902. * OUT assertions: the field len is set to the optimal bit length, the
  16903. * array bl_count contains the frequencies for each bit length.
  16904. * The length opt_len is updated; static_len is also updated if stree is
  16905. * not null.
  16906. */
  16907. function gen_bitlen(s, desc)
  16908. // deflate_state *s;
  16909. // tree_desc *desc; /* the tree descriptor */
  16910. {
  16911. var tree = desc.dyn_tree;
  16912. var max_code = desc.max_code;
  16913. var stree = desc.stat_desc.static_tree;
  16914. var has_stree = desc.stat_desc.has_stree;
  16915. var extra = desc.stat_desc.extra_bits;
  16916. var base = desc.stat_desc.extra_base;
  16917. var max_length = desc.stat_desc.max_length;
  16918. var h; /* heap index */
  16919. var n, m; /* iterate over the tree elements */
  16920. var bits; /* bit length */
  16921. var xbits; /* extra bits */
  16922. var f; /* frequency */
  16923. var overflow = 0; /* number of elements with bit length too large */
  16924. for (bits = 0; bits <= MAX_BITS; bits++) {
  16925. s.bl_count[bits] = 0;
  16926. }
  16927. /* In a first pass, compute the optimal bit lengths (which may
  16928. * overflow in the case of the bit length tree).
  16929. */
  16930. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  16931. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  16932. n = s.heap[h];
  16933. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  16934. if (bits > max_length) {
  16935. bits = max_length;
  16936. overflow++;
  16937. }
  16938. tree[n*2 + 1]/*.Len*/ = bits;
  16939. /* We overwrite tree[n].Dad which is no longer needed */
  16940. if (n > max_code) { continue; } /* not a leaf node */
  16941. s.bl_count[bits]++;
  16942. xbits = 0;
  16943. if (n >= base) {
  16944. xbits = extra[n-base];
  16945. }
  16946. f = tree[n * 2]/*.Freq*/;
  16947. s.opt_len += f * (bits + xbits);
  16948. if (has_stree) {
  16949. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  16950. }
  16951. }
  16952. if (overflow === 0) { return; }
  16953. // Trace((stderr,"\nbit length overflow\n"));
  16954. /* This happens for example on obj2 and pic of the Calgary corpus */
  16955. /* Find the first bit length which could increase: */
  16956. do {
  16957. bits = max_length-1;
  16958. while (s.bl_count[bits] === 0) { bits--; }
  16959. s.bl_count[bits]--; /* move one leaf down the tree */
  16960. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  16961. s.bl_count[max_length]--;
  16962. /* The brother of the overflow item also moves one step up,
  16963. * but this does not affect bl_count[max_length]
  16964. */
  16965. overflow -= 2;
  16966. } while (overflow > 0);
  16967. /* Now recompute all bit lengths, scanning in increasing frequency.
  16968. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  16969. * lengths instead of fixing only the wrong ones. This idea is taken
  16970. * from 'ar' written by Haruhiko Okumura.)
  16971. */
  16972. for (bits = max_length; bits !== 0; bits--) {
  16973. n = s.bl_count[bits];
  16974. while (n !== 0) {
  16975. m = s.heap[--h];
  16976. if (m > max_code) { continue; }
  16977. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  16978. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  16979. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  16980. tree[m*2 + 1]/*.Len*/ = bits;
  16981. }
  16982. n--;
  16983. }
  16984. }
  16985. }
  16986. /* ===========================================================================
  16987. * Generate the codes for a given tree and bit counts (which need not be
  16988. * optimal).
  16989. * IN assertion: the array bl_count contains the bit length statistics for
  16990. * the given tree and the field len is set for all tree elements.
  16991. * OUT assertion: the field code is set for all tree elements of non
  16992. * zero code length.
  16993. */
  16994. function gen_codes(tree, max_code, bl_count)
  16995. // ct_data *tree; /* the tree to decorate */
  16996. // int max_code; /* largest code with non zero frequency */
  16997. // ushf *bl_count; /* number of codes at each bit length */
  16998. {
  16999. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17000. var code = 0; /* running code value */
  17001. var bits; /* bit index */
  17002. var n; /* code index */
  17003. /* The distribution counts are first used to generate the code values
  17004. * without bit reversal.
  17005. */
  17006. for (bits = 1; bits <= MAX_BITS; bits++) {
  17007. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17008. }
  17009. /* Check that the bit counts in bl_count are consistent. The last code
  17010. * must be all ones.
  17011. */
  17012. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17013. // "inconsistent bit counts");
  17014. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17015. for (n = 0; n <= max_code; n++) {
  17016. var len = tree[n*2 + 1]/*.Len*/;
  17017. if (len === 0) { continue; }
  17018. /* Now reverse the bits */
  17019. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17020. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17021. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17022. }
  17023. }
  17024. /* ===========================================================================
  17025. * Initialize the various 'constant' tables.
  17026. */
  17027. function tr_static_init() {
  17028. var n; /* iterates over tree elements */
  17029. var bits; /* bit counter */
  17030. var length; /* length value */
  17031. var code; /* code value */
  17032. var dist; /* distance index */
  17033. var bl_count = new Array(MAX_BITS+1);
  17034. /* number of codes at each bit length for an optimal tree */
  17035. // do check in _tr_init()
  17036. //if (static_init_done) return;
  17037. /* For some embedded targets, global variables are not initialized: */
  17038. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17039. static_l_desc.static_tree = static_ltree;
  17040. static_l_desc.extra_bits = extra_lbits;
  17041. static_d_desc.static_tree = static_dtree;
  17042. static_d_desc.extra_bits = extra_dbits;
  17043. static_bl_desc.extra_bits = extra_blbits;
  17044. #endif*/
  17045. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17046. length = 0;
  17047. for (code = 0; code < LENGTH_CODES-1; code++) {
  17048. base_length[code] = length;
  17049. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17050. _length_code[length++] = code;
  17051. }
  17052. }
  17053. //Assert (length == 256, "tr_static_init: length != 256");
  17054. /* Note that the length 255 (match length 258) can be represented
  17055. * in two different ways: code 284 + 5 bits or code 285, so we
  17056. * overwrite length_code[255] to use the best encoding:
  17057. */
  17058. _length_code[length-1] = code;
  17059. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17060. dist = 0;
  17061. for (code = 0 ; code < 16; code++) {
  17062. base_dist[code] = dist;
  17063. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17064. _dist_code[dist++] = code;
  17065. }
  17066. }
  17067. //Assert (dist == 256, "tr_static_init: dist != 256");
  17068. dist >>= 7; /* from now on, all distances are divided by 128 */
  17069. for (; code < D_CODES; code++) {
  17070. base_dist[code] = dist << 7;
  17071. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17072. _dist_code[256 + dist++] = code;
  17073. }
  17074. }
  17075. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17076. /* Construct the codes of the static literal tree */
  17077. for (bits = 0; bits <= MAX_BITS; bits++) {
  17078. bl_count[bits] = 0;
  17079. }
  17080. n = 0;
  17081. while (n <= 143) {
  17082. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17083. n++;
  17084. bl_count[8]++;
  17085. }
  17086. while (n <= 255) {
  17087. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17088. n++;
  17089. bl_count[9]++;
  17090. }
  17091. while (n <= 279) {
  17092. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17093. n++;
  17094. bl_count[7]++;
  17095. }
  17096. while (n <= 287) {
  17097. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17098. n++;
  17099. bl_count[8]++;
  17100. }
  17101. /* Codes 286 and 287 do not exist, but we must include them in the
  17102. * tree construction to get a canonical Huffman tree (longest code
  17103. * all ones)
  17104. */
  17105. gen_codes(static_ltree, L_CODES+1, bl_count);
  17106. /* The static distance tree is trivial: */
  17107. for (n = 0; n < D_CODES; n++) {
  17108. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17109. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17110. }
  17111. // Now data ready and we can init static trees
  17112. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17113. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17114. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17115. //static_init_done = true;
  17116. }
  17117. /* ===========================================================================
  17118. * Initialize a new block.
  17119. */
  17120. function init_block(s) {
  17121. var n; /* iterates over tree elements */
  17122. /* Initialize the trees. */
  17123. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17124. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17125. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17126. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17127. s.opt_len = s.static_len = 0;
  17128. s.last_lit = s.matches = 0;
  17129. }
  17130. /* ===========================================================================
  17131. * Flush the bit buffer and align the output on a byte boundary
  17132. */
  17133. function bi_windup(s)
  17134. {
  17135. if (s.bi_valid > 8) {
  17136. put_short(s, s.bi_buf);
  17137. } else if (s.bi_valid > 0) {
  17138. //put_byte(s, (Byte)s->bi_buf);
  17139. s.pending_buf[s.pending++] = s.bi_buf;
  17140. }
  17141. s.bi_buf = 0;
  17142. s.bi_valid = 0;
  17143. }
  17144. /* ===========================================================================
  17145. * Copy a stored block, storing first the length and its
  17146. * one's complement if requested.
  17147. */
  17148. function copy_block(s, buf, len, header)
  17149. //DeflateState *s;
  17150. //charf *buf; /* the input data */
  17151. //unsigned len; /* its length */
  17152. //int header; /* true if block header must be written */
  17153. {
  17154. bi_windup(s); /* align on byte boundary */
  17155. if (header) {
  17156. put_short(s, len);
  17157. put_short(s, ~len);
  17158. }
  17159. // while (len--) {
  17160. // put_byte(s, *buf++);
  17161. // }
  17162. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17163. s.pending += len;
  17164. }
  17165. /* ===========================================================================
  17166. * Compares to subtrees, using the tree depth as tie breaker when
  17167. * the subtrees have equal frequency. This minimizes the worst case length.
  17168. */
  17169. function smaller(tree, n, m, depth) {
  17170. var _n2 = n*2;
  17171. var _m2 = m*2;
  17172. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  17173. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  17174. }
  17175. /* ===========================================================================
  17176. * Restore the heap property by moving down the tree starting at node k,
  17177. * exchanging a node with the smallest of its two sons if necessary, stopping
  17178. * when the heap property is re-established (each father smaller than its
  17179. * two sons).
  17180. */
  17181. function pqdownheap(s, tree, k)
  17182. // deflate_state *s;
  17183. // ct_data *tree; /* the tree to restore */
  17184. // int k; /* node to move down */
  17185. {
  17186. var v = s.heap[k];
  17187. var j = k << 1; /* left son of k */
  17188. while (j <= s.heap_len) {
  17189. /* Set j to the smallest of the two sons: */
  17190. if (j < s.heap_len &&
  17191. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  17192. j++;
  17193. }
  17194. /* Exit if v is smaller than both sons */
  17195. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  17196. /* Exchange v with the smallest son */
  17197. s.heap[k] = s.heap[j];
  17198. k = j;
  17199. /* And continue down the tree, setting j to the left son of k */
  17200. j <<= 1;
  17201. }
  17202. s.heap[k] = v;
  17203. }
  17204. // inlined manually
  17205. // var SMALLEST = 1;
  17206. /* ===========================================================================
  17207. * Send the block data compressed using the given Huffman trees
  17208. */
  17209. function compress_block(s, ltree, dtree)
  17210. // deflate_state *s;
  17211. // const ct_data *ltree; /* literal tree */
  17212. // const ct_data *dtree; /* distance tree */
  17213. {
  17214. var dist; /* distance of matched string */
  17215. var lc; /* match length or unmatched char (if dist == 0) */
  17216. var lx = 0; /* running index in l_buf */
  17217. var code; /* the code to send */
  17218. var extra; /* number of extra bits to send */
  17219. if (s.last_lit !== 0) {
  17220. do {
  17221. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  17222. lc = s.pending_buf[s.l_buf + lx];
  17223. lx++;
  17224. if (dist === 0) {
  17225. send_code(s, lc, ltree); /* send a literal byte */
  17226. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  17227. } else {
  17228. /* Here, lc is the match length - MIN_MATCH */
  17229. code = _length_code[lc];
  17230. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  17231. extra = extra_lbits[code];
  17232. if (extra !== 0) {
  17233. lc -= base_length[code];
  17234. send_bits(s, lc, extra); /* send the extra length bits */
  17235. }
  17236. dist--; /* dist is now the match distance - 1 */
  17237. code = d_code(dist);
  17238. //Assert (code < D_CODES, "bad d_code");
  17239. send_code(s, code, dtree); /* send the distance code */
  17240. extra = extra_dbits[code];
  17241. if (extra !== 0) {
  17242. dist -= base_dist[code];
  17243. send_bits(s, dist, extra); /* send the extra distance bits */
  17244. }
  17245. } /* literal or match pair ? */
  17246. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  17247. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  17248. // "pendingBuf overflow");
  17249. } while (lx < s.last_lit);
  17250. }
  17251. send_code(s, END_BLOCK, ltree);
  17252. }
  17253. /* ===========================================================================
  17254. * Construct one Huffman tree and assigns the code bit strings and lengths.
  17255. * Update the total bit length for the current block.
  17256. * IN assertion: the field freq is set for all tree elements.
  17257. * OUT assertions: the fields len and code are set to the optimal bit length
  17258. * and corresponding code. The length opt_len is updated; static_len is
  17259. * also updated if stree is not null. The field max_code is set.
  17260. */
  17261. function build_tree(s, desc)
  17262. // deflate_state *s;
  17263. // tree_desc *desc; /* the tree descriptor */
  17264. {
  17265. var tree = desc.dyn_tree;
  17266. var stree = desc.stat_desc.static_tree;
  17267. var has_stree = desc.stat_desc.has_stree;
  17268. var elems = desc.stat_desc.elems;
  17269. var n, m; /* iterate over heap elements */
  17270. var max_code = -1; /* largest code with non zero frequency */
  17271. var node; /* new node being created */
  17272. /* Construct the initial heap, with least frequent element in
  17273. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17274. * heap[0] is not used.
  17275. */
  17276. s.heap_len = 0;
  17277. s.heap_max = HEAP_SIZE;
  17278. for (n = 0; n < elems; n++) {
  17279. if (tree[n * 2]/*.Freq*/ !== 0) {
  17280. s.heap[++s.heap_len] = max_code = n;
  17281. s.depth[n] = 0;
  17282. } else {
  17283. tree[n*2 + 1]/*.Len*/ = 0;
  17284. }
  17285. }
  17286. /* The pkzip format requires that at least one distance code exists,
  17287. * and that at least one bit should be sent even if there is only one
  17288. * possible code. So to avoid special checks later on we force at least
  17289. * two codes of non zero frequency.
  17290. */
  17291. while (s.heap_len < 2) {
  17292. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  17293. tree[node * 2]/*.Freq*/ = 1;
  17294. s.depth[node] = 0;
  17295. s.opt_len--;
  17296. if (has_stree) {
  17297. s.static_len -= stree[node*2 + 1]/*.Len*/;
  17298. }
  17299. /* node is 0 or 1 so it does not have extra bits */
  17300. }
  17301. desc.max_code = max_code;
  17302. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17303. * establish sub-heaps of increasing lengths:
  17304. */
  17305. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  17306. /* Construct the Huffman tree by repeatedly combining the least two
  17307. * frequent nodes.
  17308. */
  17309. node = elems; /* next internal node of the tree */
  17310. do {
  17311. //pqremove(s, tree, n); /* n = node of least frequency */
  17312. /*** pqremove ***/
  17313. n = s.heap[1/*SMALLEST*/];
  17314. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  17315. pqdownheap(s, tree, 1/*SMALLEST*/);
  17316. /***/
  17317. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  17318. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  17319. s.heap[--s.heap_max] = m;
  17320. /* Create a new node father of n and m */
  17321. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  17322. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  17323. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  17324. /* and insert the new node in the heap */
  17325. s.heap[1/*SMALLEST*/] = node++;
  17326. pqdownheap(s, tree, 1/*SMALLEST*/);
  17327. } while (s.heap_len >= 2);
  17328. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  17329. /* At this point, the fields freq and dad are set. We can now
  17330. * generate the bit lengths.
  17331. */
  17332. gen_bitlen(s, desc);
  17333. /* The field len is now set, we can generate the bit codes */
  17334. gen_codes(tree, max_code, s.bl_count);
  17335. }
  17336. /* ===========================================================================
  17337. * Scan a literal or distance tree to determine the frequencies of the codes
  17338. * in the bit length tree.
  17339. */
  17340. function scan_tree(s, tree, max_code)
  17341. // deflate_state *s;
  17342. // ct_data *tree; /* the tree to be scanned */
  17343. // int max_code; /* and its largest code of non zero frequency */
  17344. {
  17345. var n; /* iterates over all tree elements */
  17346. var prevlen = -1; /* last emitted length */
  17347. var curlen; /* length of current code */
  17348. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17349. var count = 0; /* repeat count of the current code */
  17350. var max_count = 7; /* max repeat count */
  17351. var min_count = 4; /* min repeat count */
  17352. if (nextlen === 0) {
  17353. max_count = 138;
  17354. min_count = 3;
  17355. }
  17356. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  17357. for (n = 0; n <= max_code; n++) {
  17358. curlen = nextlen;
  17359. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17360. if (++count < max_count && curlen === nextlen) {
  17361. continue;
  17362. } else if (count < min_count) {
  17363. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  17364. } else if (curlen !== 0) {
  17365. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  17366. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  17367. } else if (count <= 10) {
  17368. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  17369. } else {
  17370. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  17371. }
  17372. count = 0;
  17373. prevlen = curlen;
  17374. if (nextlen === 0) {
  17375. max_count = 138;
  17376. min_count = 3;
  17377. } else if (curlen === nextlen) {
  17378. max_count = 6;
  17379. min_count = 3;
  17380. } else {
  17381. max_count = 7;
  17382. min_count = 4;
  17383. }
  17384. }
  17385. }
  17386. /* ===========================================================================
  17387. * Send a literal or distance tree in compressed form, using the codes in
  17388. * bl_tree.
  17389. */
  17390. function send_tree(s, tree, max_code)
  17391. // deflate_state *s;
  17392. // ct_data *tree; /* the tree to be scanned */
  17393. // int max_code; /* and its largest code of non zero frequency */
  17394. {
  17395. var n; /* iterates over all tree elements */
  17396. var prevlen = -1; /* last emitted length */
  17397. var curlen; /* length of current code */
  17398. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17399. var count = 0; /* repeat count of the current code */
  17400. var max_count = 7; /* max repeat count */
  17401. var min_count = 4; /* min repeat count */
  17402. /* tree[max_code+1].Len = -1; */ /* guard already set */
  17403. if (nextlen === 0) {
  17404. max_count = 138;
  17405. min_count = 3;
  17406. }
  17407. for (n = 0; n <= max_code; n++) {
  17408. curlen = nextlen;
  17409. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17410. if (++count < max_count && curlen === nextlen) {
  17411. continue;
  17412. } else if (count < min_count) {
  17413. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  17414. } else if (curlen !== 0) {
  17415. if (curlen !== prevlen) {
  17416. send_code(s, curlen, s.bl_tree);
  17417. count--;
  17418. }
  17419. //Assert(count >= 3 && count <= 6, " 3_6?");
  17420. send_code(s, REP_3_6, s.bl_tree);
  17421. send_bits(s, count-3, 2);
  17422. } else if (count <= 10) {
  17423. send_code(s, REPZ_3_10, s.bl_tree);
  17424. send_bits(s, count-3, 3);
  17425. } else {
  17426. send_code(s, REPZ_11_138, s.bl_tree);
  17427. send_bits(s, count-11, 7);
  17428. }
  17429. count = 0;
  17430. prevlen = curlen;
  17431. if (nextlen === 0) {
  17432. max_count = 138;
  17433. min_count = 3;
  17434. } else if (curlen === nextlen) {
  17435. max_count = 6;
  17436. min_count = 3;
  17437. } else {
  17438. max_count = 7;
  17439. min_count = 4;
  17440. }
  17441. }
  17442. }
  17443. /* ===========================================================================
  17444. * Construct the Huffman tree for the bit lengths and return the index in
  17445. * bl_order of the last bit length code to send.
  17446. */
  17447. function build_bl_tree(s) {
  17448. var max_blindex; /* index of last bit length code of non zero freq */
  17449. /* Determine the bit length frequencies for literal and distance trees */
  17450. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  17451. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  17452. /* Build the bit length tree: */
  17453. build_tree(s, s.bl_desc);
  17454. /* opt_len now includes the length of the tree representations, except
  17455. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  17456. */
  17457. /* Determine the number of bit length codes to send. The pkzip format
  17458. * requires that at least 4 bit length codes be sent. (appnote.txt says
  17459. * 3 but the actual value used is 4.)
  17460. */
  17461. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  17462. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  17463. break;
  17464. }
  17465. }
  17466. /* Update opt_len to include the bit length tree and counts */
  17467. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  17468. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  17469. // s->opt_len, s->static_len));
  17470. return max_blindex;
  17471. }
  17472. /* ===========================================================================
  17473. * Send the header for a block using dynamic Huffman trees: the counts, the
  17474. * lengths of the bit length codes, the literal tree and the distance tree.
  17475. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  17476. */
  17477. function send_all_trees(s, lcodes, dcodes, blcodes)
  17478. // deflate_state *s;
  17479. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  17480. {
  17481. var rank; /* index in bl_order */
  17482. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  17483. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  17484. // "too many codes");
  17485. //Tracev((stderr, "\nbl counts: "));
  17486. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  17487. send_bits(s, dcodes-1, 5);
  17488. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  17489. for (rank = 0; rank < blcodes; rank++) {
  17490. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  17491. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  17492. }
  17493. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  17494. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  17495. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  17496. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  17497. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  17498. }
  17499. /* ===========================================================================
  17500. * Check if the data type is TEXT or BINARY, using the following algorithm:
  17501. * - TEXT if the two conditions below are satisfied:
  17502. * a) There are no non-portable control characters belonging to the
  17503. * "black list" (0..6, 14..25, 28..31).
  17504. * b) There is at least one printable character belonging to the
  17505. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  17506. * - BINARY otherwise.
  17507. * - The following partially-portable control characters form a
  17508. * "gray list" that is ignored in this detection algorithm:
  17509. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  17510. * IN assertion: the fields Freq of dyn_ltree are set.
  17511. */
  17512. function detect_data_type(s) {
  17513. /* black_mask is the bit mask of black-listed bytes
  17514. * set bits 0..6, 14..25, and 28..31
  17515. * 0xf3ffc07f = binary 11110011111111111100000001111111
  17516. */
  17517. var black_mask = 0xf3ffc07f;
  17518. var n;
  17519. /* Check for non-textual ("black-listed") bytes. */
  17520. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  17521. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  17522. return Z_BINARY;
  17523. }
  17524. }
  17525. /* Check for textual ("white-listed") bytes. */
  17526. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  17527. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  17528. return Z_TEXT;
  17529. }
  17530. for (n = 32; n < LITERALS; n++) {
  17531. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  17532. return Z_TEXT;
  17533. }
  17534. }
  17535. /* There are no "black-listed" or "white-listed" bytes:
  17536. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  17537. */
  17538. return Z_BINARY;
  17539. }
  17540. var static_init_done = false;
  17541. /* ===========================================================================
  17542. * Initialize the tree data structures for a new zlib stream.
  17543. */
  17544. function _tr_init(s)
  17545. {
  17546. if (!static_init_done) {
  17547. tr_static_init();
  17548. static_init_done = true;
  17549. }
  17550. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  17551. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  17552. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  17553. s.bi_buf = 0;
  17554. s.bi_valid = 0;
  17555. /* Initialize the first block of the first file: */
  17556. init_block(s);
  17557. }
  17558. /* ===========================================================================
  17559. * Send a stored block
  17560. */
  17561. function _tr_stored_block(s, buf, stored_len, last)
  17562. //DeflateState *s;
  17563. //charf *buf; /* input block */
  17564. //ulg stored_len; /* length of input block */
  17565. //int last; /* one if this is the last block for a file */
  17566. {
  17567. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  17568. copy_block(s, buf, stored_len, true); /* with header */
  17569. }
  17570. /* ===========================================================================
  17571. * Send one empty static block to give enough lookahead for inflate.
  17572. * This takes 10 bits, of which 7 may remain in the bit buffer.
  17573. */
  17574. function _tr_align(s) {
  17575. send_bits(s, STATIC_TREES<<1, 3);
  17576. send_code(s, END_BLOCK, static_ltree);
  17577. bi_flush(s);
  17578. }
  17579. /* ===========================================================================
  17580. * Determine the best encoding for the current block: dynamic trees, static
  17581. * trees or store, and output the encoded block to the zip file.
  17582. */
  17583. function _tr_flush_block(s, buf, stored_len, last)
  17584. //DeflateState *s;
  17585. //charf *buf; /* input block, or NULL if too old */
  17586. //ulg stored_len; /* length of input block */
  17587. //int last; /* one if this is the last block for a file */
  17588. {
  17589. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  17590. var max_blindex = 0; /* index of last bit length code of non zero freq */
  17591. /* Build the Huffman trees unless a stored block is forced */
  17592. if (s.level > 0) {
  17593. /* Check if the file is binary or text */
  17594. if (s.strm.data_type === Z_UNKNOWN) {
  17595. s.strm.data_type = detect_data_type(s);
  17596. }
  17597. /* Construct the literal and distance trees */
  17598. build_tree(s, s.l_desc);
  17599. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  17600. // s->static_len));
  17601. build_tree(s, s.d_desc);
  17602. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  17603. // s->static_len));
  17604. /* At this point, opt_len and static_len are the total bit lengths of
  17605. * the compressed block data, excluding the tree representations.
  17606. */
  17607. /* Build the bit length tree for the above two trees, and get the index
  17608. * in bl_order of the last bit length code to send.
  17609. */
  17610. max_blindex = build_bl_tree(s);
  17611. /* Determine the best encoding. Compute the block lengths in bytes. */
  17612. opt_lenb = (s.opt_len+3+7) >>> 3;
  17613. static_lenb = (s.static_len+3+7) >>> 3;
  17614. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  17615. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  17616. // s->last_lit));
  17617. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  17618. } else {
  17619. // Assert(buf != (char*)0, "lost buf");
  17620. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  17621. }
  17622. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  17623. /* 4: two words for the lengths */
  17624. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  17625. * Otherwise we can't have processed more than WSIZE input bytes since
  17626. * the last block flush, because compression would have been
  17627. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  17628. * transform a block into a stored block.
  17629. */
  17630. _tr_stored_block(s, buf, stored_len, last);
  17631. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  17632. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  17633. compress_block(s, static_ltree, static_dtree);
  17634. } else {
  17635. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  17636. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  17637. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  17638. }
  17639. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  17640. /* The above check is made mod 2^32, for files larger than 512 MB
  17641. * and uLong implemented on 32 bits.
  17642. */
  17643. init_block(s);
  17644. if (last) {
  17645. bi_windup(s);
  17646. }
  17647. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  17648. // s->compressed_len-7*last));
  17649. }
  17650. /* ===========================================================================
  17651. * Save the match info and tally the frequency counts. Return true if
  17652. * the current block must be flushed.
  17653. */
  17654. function _tr_tally(s, dist, lc)
  17655. // deflate_state *s;
  17656. // unsigned dist; /* distance of matched string */
  17657. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  17658. {
  17659. //var out_length, in_length, dcode;
  17660. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  17661. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  17662. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  17663. s.last_lit++;
  17664. if (dist === 0) {
  17665. /* lc is the unmatched char */
  17666. s.dyn_ltree[lc*2]/*.Freq*/++;
  17667. } else {
  17668. s.matches++;
  17669. /* Here, lc is the match length - MIN_MATCH */
  17670. dist--; /* dist = match distance - 1 */
  17671. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  17672. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  17673. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  17674. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  17675. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  17676. }
  17677. // (!) This block is disabled in zlib defailts,
  17678. // don't enable it for binary compatibility
  17679. //#ifdef TRUNCATE_BLOCK
  17680. // /* Try to guess if it is profitable to stop the current block here */
  17681. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  17682. // /* Compute an upper bound for the compressed length */
  17683. // out_length = s.last_lit*8;
  17684. // in_length = s.strstart - s.block_start;
  17685. //
  17686. // for (dcode = 0; dcode < D_CODES; dcode++) {
  17687. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  17688. // }
  17689. // out_length >>>= 3;
  17690. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  17691. // // s->last_lit, in_length, out_length,
  17692. // // 100L - out_length*100L/in_length));
  17693. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  17694. // return true;
  17695. // }
  17696. // }
  17697. //#endif
  17698. return (s.last_lit === s.lit_bufsize-1);
  17699. /* We avoid equality with lit_bufsize because of wraparound at 64K
  17700. * on 16 bit machines and because stored blocks are restricted to
  17701. * 64K-1 bytes.
  17702. */
  17703. }
  17704. exports._tr_init = _tr_init;
  17705. exports._tr_stored_block = _tr_stored_block;
  17706. exports._tr_flush_block = _tr_flush_block;
  17707. exports._tr_tally = _tr_tally;
  17708. exports._tr_align = _tr_align;
  17709. },{"../utils/common":48}],60:[function(require,module,exports){
  17710. 'use strict';
  17711. function ZStream() {
  17712. /* next input byte */
  17713. this.input = null; // JS specific, because we have no pointers
  17714. this.next_in = 0;
  17715. /* number of bytes available at input */
  17716. this.avail_in = 0;
  17717. /* total number of input bytes read so far */
  17718. this.total_in = 0;
  17719. /* next output byte should be put there */
  17720. this.output = null; // JS specific, because we have no pointers
  17721. this.next_out = 0;
  17722. /* remaining free space at output */
  17723. this.avail_out = 0;
  17724. /* total number of bytes output so far */
  17725. this.total_out = 0;
  17726. /* last error message, NULL if no error */
  17727. this.msg = ''/*Z_NULL*/;
  17728. /* not visible by applications */
  17729. this.state = null;
  17730. /* best guess about the data type: binary or text */
  17731. this.data_type = 2/*Z_UNKNOWN*/;
  17732. /* adler32 value of the uncompressed data */
  17733. this.adler = 0;
  17734. }
  17735. module.exports = ZStream;
  17736. },{}],61:[function(require,module,exports){
  17737. /* Copyright @ 2015 Atlassian Pty Ltd
  17738. *
  17739. * Licensed under the Apache License, Version 2.0 (the "License");
  17740. * you may not use this file except in compliance with the License.
  17741. * You may obtain a copy of the License at
  17742. *
  17743. * http://www.apache.org/licenses/LICENSE-2.0
  17744. *
  17745. * Unless required by applicable law or agreed to in writing, software
  17746. * distributed under the License is distributed on an "AS IS" BASIS,
  17747. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17748. * See the License for the specific language governing permissions and
  17749. * limitations under the License.
  17750. */
  17751. module.exports = function arrayEquals(array) {
  17752. // if the other array is a falsy value, return
  17753. if (!array)
  17754. return false;
  17755. // compare lengths - can save a lot of time
  17756. if (this.length != array.length)
  17757. return false;
  17758. for (var i = 0, l = this.length; i < l; i++) {
  17759. // Check if we have nested arrays
  17760. if (this[i] instanceof Array && array[i] instanceof Array) {
  17761. // recurse into the nested arrays
  17762. if (!arrayEquals.apply(this[i], [array[i]]))
  17763. return false;
  17764. } else if (this[i] != array[i]) {
  17765. // Warning - two different object instances will never be equal:
  17766. // {x:20} != {x:20}
  17767. return false;
  17768. }
  17769. }
  17770. return true;
  17771. };
  17772. },{}],62:[function(require,module,exports){
  17773. /* Copyright @ 2015 Atlassian Pty Ltd
  17774. *
  17775. * Licensed under the Apache License, Version 2.0 (the "License");
  17776. * you may not use this file except in compliance with the License.
  17777. * You may obtain a copy of the License at
  17778. *
  17779. * http://www.apache.org/licenses/LICENSE-2.0
  17780. *
  17781. * Unless required by applicable law or agreed to in writing, software
  17782. * distributed under the License is distributed on an "AS IS" BASIS,
  17783. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17784. * See the License for the specific language governing permissions and
  17785. * limitations under the License.
  17786. */
  17787. exports.Interop = require('./interop');
  17788. },{"./interop":63}],63:[function(require,module,exports){
  17789. /* Copyright @ 2015 Atlassian Pty Ltd
  17790. *
  17791. * Licensed under the Apache License, Version 2.0 (the "License");
  17792. * you may not use this file except in compliance with the License.
  17793. * You may obtain a copy of the License at
  17794. *
  17795. * http://www.apache.org/licenses/LICENSE-2.0
  17796. *
  17797. * Unless required by applicable law or agreed to in writing, software
  17798. * distributed under the License is distributed on an "AS IS" BASIS,
  17799. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17800. * See the License for the specific language governing permissions and
  17801. * limitations under the License.
  17802. */
  17803. /* global RTCSessionDescription */
  17804. /* jshint -W097 */
  17805. "use strict";
  17806. var transform = require('./transform');
  17807. var arrayEquals = require('./array-equals');
  17808. function Interop() {
  17809. /**
  17810. * This map holds the most recent Unified Plan offer/answer SDP that was
  17811. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  17812. * the SDP string as values.
  17813. *
  17814. * @type {{}}
  17815. */
  17816. this.cache = {};
  17817. }
  17818. module.exports = Interop;
  17819. /**
  17820. * Returns the index of the first m-line with the given media type and with a
  17821. * direction which allows sending, in the last Unified Plan description with
  17822. * type "answer" converted to Plan B. Returns {null} if there is no saved
  17823. * answer, or if none of its m-lines with the given type allow sending.
  17824. * @param type the media type ("audio" or "video").
  17825. * @returns {*}
  17826. */
  17827. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  17828. if (!this.cache.answer) {
  17829. return null;
  17830. }
  17831. var session = transform.parse(this.cache.answer);
  17832. if (session && session.media && Array.isArray(session.media)){
  17833. for (var i = 0; i < session.media.length; i++) {
  17834. if (session.media[i].type == type &&
  17835. (!session.media[i].direction /* default to sendrecv */ ||
  17836. session.media[i].direction === 'sendrecv' ||
  17837. session.media[i].direction === 'sendonly')){
  17838. return i;
  17839. }
  17840. }
  17841. }
  17842. return null;
  17843. };
  17844. /**
  17845. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  17846. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  17847. * application.
  17848. *
  17849. * @param desc
  17850. * @returns {*}
  17851. */
  17852. Interop.prototype.toPlanB = function(desc) {
  17853. var self = this;
  17854. //#region Preliminary input validation.
  17855. if (typeof desc !== 'object' || desc === null ||
  17856. typeof desc.sdp !== 'string') {
  17857. console.warn('An empty description was passed as an argument.');
  17858. return desc;
  17859. }
  17860. // Objectify the SDP for easier manipulation.
  17861. var session = transform.parse(desc.sdp);
  17862. // If the SDP contains no media, there's nothing to transform.
  17863. if (typeof session.media === 'undefined' ||
  17864. !Array.isArray(session.media) || session.media.length === 0) {
  17865. console.warn('The description has no media.');
  17866. return desc;
  17867. }
  17868. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  17869. // SDP has a video, an audio and a data "channel" at most.
  17870. if (session.media.length <= 3 && session.media.every(function(m) {
  17871. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  17872. })) {
  17873. console.warn('This description does not look like Unified Plan.');
  17874. return desc;
  17875. }
  17876. //#endregion
  17877. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  17878. var sdp = desc.sdp;
  17879. var rewrite = false;
  17880. for (var i = 0; i < session.media.length; i++) {
  17881. var uLine = session.media[i];
  17882. uLine.rtp.forEach(function(rtp) {
  17883. if (rtp.codec === 'NULL')
  17884. {
  17885. rewrite = true;
  17886. var offer = transform.parse(self.cache['offer']);
  17887. rtp.codec = offer.media[i].rtp[0].codec;
  17888. }
  17889. });
  17890. };
  17891. if (rewrite) {
  17892. sdp = transform.write(session);
  17893. }
  17894. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  17895. // -> Unified Plan transformation.
  17896. this.cache[desc.type] = sdp;
  17897. //#region Convert from Unified Plan to Plan B.
  17898. // We rebuild the session.media array.
  17899. var media = session.media;
  17900. session.media = [];
  17901. // Associative array that maps channel types to channel objects for fast
  17902. // access to channel objects by their type, e.g. type2bl['audio']->channel
  17903. // obj.
  17904. var type2bl = {};
  17905. // Used to build the group:BUNDLE value after the channels construction
  17906. // loop.
  17907. var types = [];
  17908. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  17909. media.forEach(function(uLine) {
  17910. // rtcp-mux is required in the Plan B SDP.
  17911. if ((typeof uLine.rtcpMux !== 'string' ||
  17912. uLine.rtcpMux !== 'rtcp-mux') &&
  17913. uLine.direction !== 'inactive') {
  17914. throw new Error('Cannot convert to Plan B because m-lines ' +
  17915. 'without the rtcp-mux attribute were found.');
  17916. }
  17917. if (uLine.type === 'application') {
  17918. session.media.push(uLine);
  17919. types.push(uLine.mid);
  17920. return;
  17921. }
  17922. // If we don't have a channel for this uLine.type, then use this
  17923. // uLine as the channel basis.
  17924. if (typeof type2bl[uLine.type] === 'undefined') {
  17925. type2bl[uLine.type] = uLine;
  17926. }
  17927. // Add sources to the channel and handle a=msid.
  17928. if (typeof uLine.sources === 'object') {
  17929. Object.keys(uLine.sources).forEach(function(ssrc) {
  17930. if (typeof type2bl[uLine.type].sources !== 'object')
  17931. type2bl[uLine.type].sources = {};
  17932. // Assign the sources to the channel.
  17933. type2bl[uLine.type].sources[ssrc] =
  17934. uLine.sources[ssrc];
  17935. if (typeof uLine.msid !== 'undefined') {
  17936. // In Plan B the msid is an SSRC attribute. Also, we don't
  17937. // care about the obsolete label and mslabel attributes.
  17938. //
  17939. // Note that it is not guaranteed that the uLine will
  17940. // have an msid. recvonly channels in particular don't have
  17941. // one.
  17942. type2bl[uLine.type].sources[ssrc].msid =
  17943. uLine.msid;
  17944. }
  17945. // NOTE ssrcs in ssrc groups will share msids, as
  17946. // draft-uberti-rtcweb-plan-00 mandates.
  17947. });
  17948. }
  17949. // Add ssrc groups to the channel.
  17950. if (typeof uLine.ssrcGroups !== 'undefined' &&
  17951. Array.isArray(uLine.ssrcGroups)) {
  17952. // Create the ssrcGroups array, if it's not defined.
  17953. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  17954. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  17955. type2bl[uLine.type].ssrcGroups = [];
  17956. }
  17957. type2bl[uLine.type].ssrcGroups =
  17958. type2bl[uLine.type].ssrcGroups.concat(
  17959. uLine.ssrcGroups);
  17960. }
  17961. if (type2bl[uLine.type] === uLine) {
  17962. // Copy ICE related stuff from the principal media line.
  17963. uLine.candidates = media[0].candidates;
  17964. uLine.iceUfrag = media[0].iceUfrag;
  17965. uLine.icePwd = media[0].icePwd;
  17966. uLine.fingerprint = media[0].fingerprint;
  17967. // Plan B mids are in ['audio', 'video', 'data']
  17968. uLine.mid = uLine.type;
  17969. // Plan B doesn't support/need the bundle-only attribute.
  17970. delete uLine.bundleOnly;
  17971. // In Plan B the msid is an SSRC attribute.
  17972. delete uLine.msid;
  17973. // Used to build the group:BUNDLE value after this loop.
  17974. types.push(uLine.type);
  17975. // Add the channel to the new media array.
  17976. session.media.push(uLine);
  17977. }
  17978. });
  17979. // We regenerate the BUNDLE group with the new mids.
  17980. session.groups.some(function(group) {
  17981. if (group.type === 'BUNDLE') {
  17982. group.mids = types.join(' ');
  17983. return true;
  17984. }
  17985. });
  17986. // msid semantic
  17987. session.msidSemantic = {
  17988. semantic: 'WMS',
  17989. token: '*'
  17990. };
  17991. var resStr = transform.write(session);
  17992. return new RTCSessionDescription({
  17993. type: desc.type,
  17994. sdp: resStr
  17995. });
  17996. //#endregion
  17997. };
  17998. /**
  17999. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18000. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18001. * to FF.
  18002. *
  18003. * @param desc
  18004. * @returns {*}
  18005. */
  18006. Interop.prototype.toUnifiedPlan = function(desc) {
  18007. var self = this;
  18008. //#region Preliminary input validation.
  18009. if (typeof desc !== 'object' || desc === null ||
  18010. typeof desc.sdp !== 'string') {
  18011. console.warn('An empty description was passed as an argument.');
  18012. return desc;
  18013. }
  18014. var session = transform.parse(desc.sdp);
  18015. // If the SDP contains no media, there's nothing to transform.
  18016. if (typeof session.media === 'undefined' ||
  18017. !Array.isArray(session.media) || session.media.length === 0) {
  18018. console.warn('The description has no media.');
  18019. return desc;
  18020. }
  18021. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18022. // a video, an audio and a data "channel" at most.
  18023. if (session.media.length > 3 || !session.media.every(function(m) {
  18024. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18025. })) {
  18026. console.warn('This description does not look like Plan B.');
  18027. return desc;
  18028. }
  18029. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18030. var mids = [];
  18031. session.media.forEach(function(m) {
  18032. mids.push(m.mid);
  18033. });
  18034. var hasBundle = false;
  18035. if (typeof session.groups !== 'undefined' &&
  18036. Array.isArray(session.groups)) {
  18037. hasBundle = session.groups.every(function(g) {
  18038. return g.type !== 'BUNDLE' ||
  18039. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18040. });
  18041. }
  18042. if (!hasBundle) {
  18043. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18044. " are not bundled were found.");
  18045. }
  18046. //#endregion
  18047. //#region Convert from Plan B to Unified Plan.
  18048. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18049. // rebuild an equivalent Unified Plan offer/answer.
  18050. //
  18051. // For example, if this is a local answer (in Unified Plan style) that we
  18052. // convert to Plan B prior to handing it over to the application (the
  18053. // PeerConnection wrapper called us, for instance, after a successful
  18054. // createAnswer), we want to remember the m-line at which we've seen the
  18055. // (local) SSRC. That's because when the application wants to do call the
  18056. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18057. // Unified Plan), we need to know to which m-line to assign the (local)
  18058. // SSRC. We also need to know all the other m-lines that the original
  18059. // answer had and include them in the transformed answer as well.
  18060. //
  18061. // Another example is if this is a remote offer that we convert to Plan B
  18062. // prior to giving it to the application, we want to remember the mid at
  18063. // which we've seen the (remote) SSRC.
  18064. //
  18065. // In the iteration that follows, we use the cached Unified Plan (if it
  18066. // exists) to assign mids to ssrcs.
  18067. var cached;
  18068. if (typeof this.cache[desc.type] !== 'undefined') {
  18069. cached = transform.parse(this.cache[desc.type]);
  18070. }
  18071. var recvonlySsrcs = {
  18072. audio: {},
  18073. video: {}
  18074. };
  18075. // A helper map that sends mids to m-line objects. We use it later to
  18076. // rebuild the Unified Plan style session.media array.
  18077. var mid2ul = {};
  18078. session.media.forEach(function(bLine) {
  18079. if ((typeof bLine.rtcpMux !== 'string' ||
  18080. bLine.rtcpMux !== 'rtcp-mux') &&
  18081. bLine.direction !== 'inactive') {
  18082. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18083. "without the rtcp-mux attribute were found.");
  18084. }
  18085. if (bLine.type === 'application') {
  18086. mid2ul[bLine.mid] = bLine;
  18087. return;
  18088. }
  18089. // With rtcp-mux and bundle all the channels should have the same ICE
  18090. // stuff.
  18091. var sources = bLine.sources;
  18092. var ssrcGroups = bLine.ssrcGroups;
  18093. var candidates = bLine.candidates;
  18094. var iceUfrag = bLine.iceUfrag;
  18095. var icePwd = bLine.icePwd;
  18096. var fingerprint = bLine.fingerprint;
  18097. var port = bLine.port;
  18098. // We'll use the "bLine" object as a prototype for each new "mLine"
  18099. // that we create, but first we need to clean it up a bit.
  18100. delete bLine.sources;
  18101. delete bLine.ssrcGroups;
  18102. delete bLine.candidates;
  18103. delete bLine.iceUfrag;
  18104. delete bLine.icePwd;
  18105. delete bLine.fingerprint;
  18106. delete bLine.port;
  18107. delete bLine.mid;
  18108. // inverted ssrc group map
  18109. var ssrc2group = {};
  18110. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18111. ssrcGroups.forEach(function (ssrcGroup) {
  18112. // TODO(gp) find out how to receive simulcast with FF. For the
  18113. // time being, hide it.
  18114. if (ssrcGroup.semantics === 'SIM') {
  18115. return;
  18116. }
  18117. // XXX This might brake if an SSRC is in more than one group
  18118. // for some reason.
  18119. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18120. Array.isArray(ssrcGroup.ssrcs)) {
  18121. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18122. if (typeof ssrc2group[ssrc] === 'undefined') {
  18123. ssrc2group[ssrc] = [];
  18124. }
  18125. ssrc2group[ssrc].push(ssrcGroup);
  18126. });
  18127. }
  18128. });
  18129. }
  18130. // ssrc to m-line index.
  18131. var ssrc2ml = {};
  18132. if (typeof sources === 'object') {
  18133. // Explode the Plan B channel sources with one m-line per source.
  18134. Object.keys(sources).forEach(function(ssrc) {
  18135. // The (unified) m-line for this SSRC. We either create it from
  18136. // scratch or, if it's a grouped SSRC, we re-use a related
  18137. // mline. In other words, if the source is grouped with another
  18138. // source, put the two together in the same m-line.
  18139. var uLine;
  18140. // We assume here that we are the answerer in the O/A, so any
  18141. // offers which we translate come from the remote side, while
  18142. // answers are local. So the check below is to make that we
  18143. // handle receive-only SSRCs in a special way only if they come
  18144. // from the remote side.
  18145. if (desc.type==='offer') {
  18146. // We want to detect SSRCs which are used by a remote peer
  18147. // in an m-line with direction=recvonly (i.e. they are
  18148. // being used for RTCP only).
  18149. // This information would have gotten lost if the remote
  18150. // peer used Unified Plan and their local description was
  18151. // translated to Plan B. So we use the lack of an MSID
  18152. // attribute to deduce a "receive only" SSRC.
  18153. if (!sources[ssrc].msid) {
  18154. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  18155. // Receive-only SSRCs must not create new m-lines. We
  18156. // will assign them to an existing m-line later.
  18157. return;
  18158. }
  18159. }
  18160. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  18161. Array.isArray(ssrc2group[ssrc])) {
  18162. ssrc2group[ssrc].some(function (ssrcGroup) {
  18163. // ssrcGroup.ssrcs *is* an Array, no need to check
  18164. // again here.
  18165. return ssrcGroup.ssrcs.some(function (related) {
  18166. if (typeof ssrc2ml[related] === 'object') {
  18167. uLine = ssrc2ml[related];
  18168. return true;
  18169. }
  18170. });
  18171. });
  18172. }
  18173. if (typeof uLine === 'object') {
  18174. // the m-line already exists. Just add the source.
  18175. uLine.sources[ssrc] = sources[ssrc];
  18176. delete sources[ssrc].msid;
  18177. } else {
  18178. // Use the "bLine" as a prototype for the "uLine".
  18179. uLine = Object.create(bLine);
  18180. ssrc2ml[ssrc] = uLine;
  18181. if (typeof sources[ssrc].msid !== 'undefined') {
  18182. // Assign the msid of the source to the m-line. Note
  18183. // that it is not guaranteed that the source will have
  18184. // msid. In particular "recvonly" sources don't have an
  18185. // msid. Note that "recvonly" is a term only defined
  18186. // for m-lines.
  18187. uLine.msid = sources[ssrc].msid;
  18188. uLine.direction = 'sendrecv';
  18189. delete sources[ssrc].msid;
  18190. }
  18191. // We assign one SSRC per media line.
  18192. uLine.sources = {};
  18193. uLine.sources[ssrc] = sources[ssrc];
  18194. uLine.ssrcGroups = ssrc2group[ssrc];
  18195. // Use the cached Unified Plan SDP (if it exists) to assign
  18196. // SSRCs to mids.
  18197. if (typeof cached !== 'undefined' &&
  18198. typeof cached.media !== 'undefined' &&
  18199. Array.isArray(cached.media)) {
  18200. cached.media.forEach(function (m) {
  18201. if (typeof m.sources === 'object') {
  18202. Object.keys(m.sources).forEach(function (s) {
  18203. if (s === ssrc) {
  18204. uLine.mid = m.mid;
  18205. }
  18206. });
  18207. }
  18208. });
  18209. }
  18210. if (typeof uLine.mid === 'undefined') {
  18211. // If this is an SSRC that we see for the first time
  18212. // assign it a new mid. This is typically the case when
  18213. // this method is called to transform a remote
  18214. // description for the first time or when there is a
  18215. // new SSRC in the remote description because a new
  18216. // peer has joined the conference. Local SSRCs should
  18217. // have already been added to the map in the toPlanB
  18218. // method.
  18219. //
  18220. // Because FF generates answers in Unified Plan style,
  18221. // we MUST already have a cached answer with all the
  18222. // local SSRCs mapped to some m-line/mid.
  18223. if (desc.type === 'answer') {
  18224. throw new Error("An unmapped SSRC was found.");
  18225. }
  18226. uLine.mid = [bLine.type, '-', ssrc].join('');
  18227. }
  18228. // Include the candidates in the 1st media line.
  18229. uLine.candidates = candidates;
  18230. uLine.iceUfrag = iceUfrag;
  18231. uLine.icePwd = icePwd;
  18232. uLine.fingerprint = fingerprint;
  18233. uLine.port = port;
  18234. mid2ul[uLine.mid] = uLine;
  18235. }
  18236. });
  18237. }
  18238. });
  18239. // Rebuild the media array in the right order and add the missing mLines
  18240. // (missing from the Plan B SDP).
  18241. session.media = [];
  18242. mids = []; // reuse
  18243. if (desc.type === 'answer') {
  18244. // The media lines in the answer must match the media lines in the
  18245. // offer. The order is important too. Here we assume that Firefox is
  18246. // the answerer, so we merely have to use the reconstructed (unified)
  18247. // answer to update the cached (unified) answer accordingly.
  18248. //
  18249. // In the general case, one would have to use the cached (unified)
  18250. // offer to find the m-lines that are missing from the reconstructed
  18251. // answer, potentially grabbing them from the cached (unified) answer.
  18252. // One has to be careful with this approach because inactive m-lines do
  18253. // not always have an mid, making it tricky (impossible?) to find where
  18254. // exactly and which m-lines are missing from the reconstructed answer.
  18255. for (var i = 0; i < cached.media.length; i++) {
  18256. var uLine = cached.media[i];
  18257. if (typeof mid2ul[uLine.mid] === 'undefined') {
  18258. // The mid isn't in the reconstructed (unified) answer.
  18259. // This is either a (unified) m-line containing a remote
  18260. // track only, or a (unified) m-line containing a remote
  18261. // track and a local track that has been removed.
  18262. // In either case, it MUST exist in the cached
  18263. // (unified) answer.
  18264. //
  18265. // In case this is a removed local track, clean-up
  18266. // the (unified) m-line and make sure it's 'recvonly' or
  18267. // 'inactive'.
  18268. delete uLine.msid;
  18269. delete uLine.sources;
  18270. delete uLine.ssrcGroups;
  18271. if (!uLine.direction
  18272. || uLine.direction === 'sendrecv')
  18273. uLine.direction = 'recvonly';
  18274. else if (uLine.direction === 'sendonly')
  18275. uLine.direction = 'inactive';
  18276. } else {
  18277. // This is an (unified) m-line/channel that contains a local
  18278. // track (sendrecv or sendonly channel) or it's a unified
  18279. // recvonly m-line/channel. In either case, since we're
  18280. // going from PlanB -> Unified Plan this m-line MUST
  18281. // exist in the cached answer.
  18282. }
  18283. session.media.push(uLine);
  18284. if (typeof uLine.mid === 'string') {
  18285. // inactive lines don't/may not have an mid.
  18286. mids.push(uLine.mid);
  18287. }
  18288. }
  18289. } else {
  18290. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  18291. // under any circumstances. If we are no longer interested in sending a
  18292. // track, we just remove the msid and ssrc attributes and set it to
  18293. // either a=recvonly (as the reofferer, we must use recvonly if the
  18294. // other side was previously sending on the m-section, but we can also
  18295. // leave the possibility open if it wasn't previously in use), or
  18296. // a=inactive.
  18297. if (typeof cached !== 'undefined' &&
  18298. typeof cached.media !== 'undefined' &&
  18299. Array.isArray(cached.media)) {
  18300. cached.media.forEach(function(uLine) {
  18301. mids.push(uLine.mid);
  18302. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  18303. session.media.push(mid2ul[uLine.mid]);
  18304. } else {
  18305. delete uLine.msid;
  18306. delete uLine.sources;
  18307. delete uLine.ssrcGroups;
  18308. if (!uLine.direction
  18309. || uLine.direction === 'sendrecv')
  18310. uLine.direction = 'recvonly';
  18311. if (!uLine.direction
  18312. || uLine.direction === 'sendonly')
  18313. uLine.direction = 'inactive';
  18314. session.media.push(uLine);
  18315. }
  18316. });
  18317. }
  18318. // Add all the remaining (new) m-lines of the transformed SDP.
  18319. Object.keys(mid2ul).forEach(function(mid) {
  18320. if (mids.indexOf(mid) === -1) {
  18321. mids.push(mid);
  18322. if (mid2ul[mid].direction === 'recvonly') {
  18323. // This is a remote recvonly channel. Add its SSRC to the
  18324. // appropriate sendrecv or sendonly channel.
  18325. // TODO(gp) what if we don't have sendrecv/sendonly
  18326. // channel?
  18327. session.media.some(function (uLine) {
  18328. if ((uLine.direction === 'sendrecv' ||
  18329. uLine.direction === 'sendonly') &&
  18330. uLine.type === mid2ul[mid].type) {
  18331. // mid2ul[mid] shouldn't have any ssrc-groups
  18332. Object.keys(mid2ul[mid].sources).forEach(
  18333. function (ssrc) {
  18334. uLine.sources[ssrc] =
  18335. mid2ul[mid].sources[ssrc];
  18336. });
  18337. return true;
  18338. }
  18339. });
  18340. } else {
  18341. session.media.push(mid2ul[mid]);
  18342. }
  18343. }
  18344. });
  18345. }
  18346. // After we have constructed the Plan Unified m-lines we can figure out
  18347. // where (in which m-line) to place the 'recvonly SSRCs'.
  18348. // Note: we assume here that we are the answerer in the O/A, so any offers
  18349. // which we translate come from the remote side, while answers are local
  18350. // (and so our last local description is cached as an 'answer').
  18351. ["audio", "video"].forEach(function (type) {
  18352. if (!session || !session.media || !Array.isArray(session.media))
  18353. return;
  18354. var idx = null;
  18355. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  18356. idx = self.getFirstSendingIndexFromAnswer(type);
  18357. if (idx === null){
  18358. // If this is the first offer we receive, we don't have a
  18359. // cached answer. Assume that we will be sending media using
  18360. // the first m-line for each media type.
  18361. for (var i = 0; i < session.media.length; i++) {
  18362. if (session.media[i].type === type) {
  18363. idx = i;
  18364. break;
  18365. }
  18366. }
  18367. }
  18368. }
  18369. if (idx && session.media.length > idx) {
  18370. var mLine = session.media[idx];
  18371. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  18372. if (mLine.sources && mLine.sources[ssrc]) {
  18373. console.warn("Replacing an existing SSRC.");
  18374. }
  18375. if (!mLine.sources) {
  18376. mLine.sources = {};
  18377. }
  18378. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  18379. });
  18380. }
  18381. });
  18382. // We regenerate the BUNDLE group (since we regenerated the mids)
  18383. session.groups.some(function(group) {
  18384. if (group.type === 'BUNDLE') {
  18385. group.mids = mids.join(' ');
  18386. return true;
  18387. }
  18388. });
  18389. // msid semantic
  18390. session.msidSemantic = {
  18391. semantic: 'WMS',
  18392. token: '*'
  18393. };
  18394. var resStr = transform.write(session);
  18395. // Cache the transformed SDP (Unified Plan) for later re-use in this
  18396. // function.
  18397. this.cache[desc.type] = resStr;
  18398. return new RTCSessionDescription({
  18399. type: desc.type,
  18400. sdp: resStr
  18401. });
  18402. //#endregion
  18403. };
  18404. },{"./array-equals":61,"./transform":64}],64:[function(require,module,exports){
  18405. /* Copyright @ 2015 Atlassian Pty Ltd
  18406. *
  18407. * Licensed under the Apache License, Version 2.0 (the "License");
  18408. * you may not use this file except in compliance with the License.
  18409. * You may obtain a copy of the License at
  18410. *
  18411. * http://www.apache.org/licenses/LICENSE-2.0
  18412. *
  18413. * Unless required by applicable law or agreed to in writing, software
  18414. * distributed under the License is distributed on an "AS IS" BASIS,
  18415. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18416. * See the License for the specific language governing permissions and
  18417. * limitations under the License.
  18418. */
  18419. var transform = require('sdp-transform');
  18420. exports.write = function(session, opts) {
  18421. if (typeof session !== 'undefined' &&
  18422. typeof session.media !== 'undefined' &&
  18423. Array.isArray(session.media)) {
  18424. session.media.forEach(function (mLine) {
  18425. // expand sources to ssrcs
  18426. if (typeof mLine.sources !== 'undefined' &&
  18427. Object.keys(mLine.sources).length !== 0) {
  18428. mLine.ssrcs = [];
  18429. Object.keys(mLine.sources).forEach(function (ssrc) {
  18430. var source = mLine.sources[ssrc];
  18431. Object.keys(source).forEach(function (attribute) {
  18432. mLine.ssrcs.push({
  18433. id: ssrc,
  18434. attribute: attribute,
  18435. value: source[attribute]
  18436. });
  18437. });
  18438. });
  18439. delete mLine.sources;
  18440. }
  18441. // join ssrcs in ssrc groups
  18442. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18443. Array.isArray(mLine.ssrcGroups)) {
  18444. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18445. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18446. Array.isArray(ssrcGroup.ssrcs)) {
  18447. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  18448. }
  18449. });
  18450. }
  18451. });
  18452. }
  18453. // join group mids
  18454. if (typeof session !== 'undefined' &&
  18455. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18456. session.groups.forEach(function (g) {
  18457. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  18458. g.mids = g.mids.join(' ');
  18459. }
  18460. });
  18461. }
  18462. return transform.write(session, opts);
  18463. };
  18464. exports.parse = function(sdp) {
  18465. var session = transform.parse(sdp);
  18466. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  18467. Array.isArray(session.media)) {
  18468. session.media.forEach(function (mLine) {
  18469. // group sources attributes by ssrc
  18470. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  18471. mLine.sources = {};
  18472. mLine.ssrcs.forEach(function (ssrc) {
  18473. if (!mLine.sources[ssrc.id])
  18474. mLine.sources[ssrc.id] = {};
  18475. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  18476. });
  18477. delete mLine.ssrcs;
  18478. }
  18479. // split ssrcs in ssrc groups
  18480. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18481. Array.isArray(mLine.ssrcGroups)) {
  18482. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18483. if (typeof ssrcGroup.ssrcs === 'string') {
  18484. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  18485. }
  18486. });
  18487. }
  18488. });
  18489. }
  18490. // split group mids
  18491. if (typeof session !== 'undefined' &&
  18492. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18493. session.groups.forEach(function (g) {
  18494. if (typeof g.mids === 'string') {
  18495. g.mids = g.mids.split(' ');
  18496. }
  18497. });
  18498. }
  18499. return session;
  18500. };
  18501. },{"sdp-transform":72}],65:[function(require,module,exports){
  18502. var transform = require('sdp-transform');
  18503. var transformUtils = require('./transform-utils');
  18504. var parseSsrcs = transformUtils.parseSsrcs;
  18505. var writeSsrcs = transformUtils.writeSsrcs;
  18506. //region Constants
  18507. var DEFAULT_NUM_OF_LAYERS = 3;
  18508. //endregion
  18509. //region Ctor
  18510. function Simulcast(options) {
  18511. this.options = options ? options : {};
  18512. if (!this.options.numOfLayers) {
  18513. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  18514. }
  18515. this.layers = [];
  18516. }
  18517. //endregion
  18518. //region Stateless private utility functions
  18519. /**
  18520. * Returns a random integer between min (included) and max (excluded)
  18521. * Using Math.round() gives a non-uniform distribution!
  18522. * @returns {number}
  18523. */
  18524. function generateSSRC() {
  18525. var min = 0, max = 0xffffffff;
  18526. return Math.floor(Math.random() * (max - min)) + min;
  18527. };
  18528. function processVideo(session, action) {
  18529. if (session == null || !Array.isArray(session.media)) {
  18530. return;
  18531. }
  18532. session.media.forEach(function (mLine) {
  18533. if (mLine.type === 'video') {
  18534. action(mLine);
  18535. }
  18536. });
  18537. }
  18538. function validateDescription(desc)
  18539. {
  18540. return desc && desc != null
  18541. && desc.type && desc.type != ''
  18542. && desc.sdp && desc.sdp != '';
  18543. }
  18544. function explodeRemoteSimulcast(mLine) {
  18545. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18546. return;
  18547. }
  18548. var sources = parseSsrcs(mLine);
  18549. var order = [];
  18550. // Find the SIM group and explode its sources.
  18551. var j = mLine.ssrcGroups.length;
  18552. while (j--) {
  18553. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  18554. continue;
  18555. }
  18556. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  18557. for (var i = 0; i < simulcastSsrcs.length; i++) {
  18558. var ssrc = simulcastSsrcs[i];
  18559. order.push(ssrc);
  18560. var parts = sources[ssrc].msid.split(' ');
  18561. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  18562. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  18563. // Remove all the groups that this SSRC participates in.
  18564. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18565. if (relatedGroup.semantics === 'SIM') {
  18566. return;
  18567. }
  18568. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18569. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18570. return;
  18571. }
  18572. // Nuke all the related SSRCs.
  18573. relatedSsrcs.forEach(function (relatedSSRC) {
  18574. sources[relatedSSRC].msid = sources[ssrc].msid;
  18575. sources[relatedSSRC].cname = sources[ssrc].cname;
  18576. if (relatedSSRC !== ssrc) {
  18577. order.push(relatedSSRC);
  18578. }
  18579. });
  18580. // Schedule the related group for nuking.
  18581. })
  18582. }
  18583. mLine.ssrcs = writeSsrcs(sources, order);
  18584. mLine.ssrcGroups.splice(j, 1);
  18585. };
  18586. }
  18587. function squeezeRemoteSimulcast(mLine) {
  18588. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18589. return;
  18590. }
  18591. var sources = parseSsrcs(mLine);
  18592. // Find the SIM group and nuke it.
  18593. mLine.ssrcGroups.some(function (simulcastGroup) {
  18594. if (simulcastGroup.semantics !== 'SIM') {
  18595. return false;
  18596. }
  18597. // Schedule the SIM group for nuking.
  18598. simulcastGroup.nuke = true;
  18599. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  18600. // Nuke all the higher layer SSRCs.
  18601. for (var i = 1; i < simulcastSsrcs.length; i++) {
  18602. var ssrc = simulcastSsrcs[i];
  18603. delete sources[ssrc];
  18604. // Remove all the groups that this SSRC participates in.
  18605. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18606. if (relatedGroup.semantics === 'SIM') {
  18607. return;
  18608. }
  18609. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18610. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18611. return;
  18612. }
  18613. // Nuke all the related SSRCs.
  18614. relatedSsrcs.forEach(function (relatedSSRC) {
  18615. delete sources[relatedSSRC];
  18616. });
  18617. // Schedule the related group for nuking.
  18618. relatedGroup.nuke = true;
  18619. })
  18620. }
  18621. return true;
  18622. });
  18623. mLine.ssrcs = writeSsrcs(sources);
  18624. // Nuke all the scheduled groups.
  18625. var i = mLine.ssrcGroups.length;
  18626. while (i--) {
  18627. if (mLine.ssrcGroups[i].nuke) {
  18628. mLine.ssrcGroups.splice(i, 1);
  18629. }
  18630. }
  18631. }
  18632. function removeGoogConference(mLine) {
  18633. if (!mLine || !Array.isArray(mLine.invalid)) {
  18634. return;
  18635. }
  18636. var i = mLine.invalid.length;
  18637. while (i--) {
  18638. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  18639. mLine.invalid.splice(i, 1);
  18640. }
  18641. }
  18642. }
  18643. function assertGoogConference(mLine) {
  18644. if (!mLine) {
  18645. return;
  18646. }
  18647. if (!Array.isArray(mLine.invalid)) {
  18648. mLine.invalid = [];
  18649. }
  18650. if (!mLine.invalid.some(
  18651. function (i) { return i.value === 'x-google-flag:conference' })) {
  18652. mLine.invalid.push({'value': 'x-google-flag:conference'});
  18653. }
  18654. }
  18655. //endregion
  18656. //region "Private" functions
  18657. /**
  18658. *
  18659. * @param mLine
  18660. * @private
  18661. */
  18662. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  18663. if (!mLine || mLine.type !== 'video') {
  18664. return;
  18665. }
  18666. var sources = parseSsrcs(mLine);
  18667. if (Object.keys(sources).length === 0) {
  18668. // no sources, disable simulcast.
  18669. if (this.layers.length !== 0) {
  18670. this.layers = [];
  18671. }
  18672. return;
  18673. }
  18674. // find the base layer (we'll reuse its msid and cname).
  18675. var baseLayerSSRC = Object.keys(sources)[0];
  18676. var baseLayer = sources[baseLayerSSRC];
  18677. // todo(gp) handle screen sharing.
  18678. // check if base CNAME has changed and reinitialise layers.
  18679. if (this.layers.length > 0
  18680. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  18681. this.layers = [];
  18682. }
  18683. // (re)initialise layers
  18684. if (this.layers.length < 1) {
  18685. // first push the base layer.
  18686. this.layers.push({
  18687. ssrc: baseLayerSSRC,
  18688. msid: baseLayer.msid,
  18689. cname: baseLayer.cname
  18690. });
  18691. var rtx = false; // RFC 4588
  18692. if (Array.isArray(mLine.rtp)) {
  18693. rtx = mLine.rtp.some(
  18694. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  18695. }
  18696. if (rtx) {
  18697. this.layers[0].rtx = generateSSRC();
  18698. }
  18699. // now push additional layers.
  18700. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  18701. var layer = { ssrc: generateSSRC() };
  18702. if (rtx) {
  18703. layer.rtx = generateSSRC();
  18704. }
  18705. this.layers.push(layer);
  18706. }
  18707. }
  18708. };
  18709. /**
  18710. *
  18711. * @param mLine
  18712. * @private
  18713. */
  18714. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  18715. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  18716. var sources = {};
  18717. var msid = this.layers[0].msid;
  18718. var cname = this.layers[0].cname;
  18719. var simulcastSsrcs = [];
  18720. var ssrcGroups = [];
  18721. for (var i = 0; i < this.layers.length; i++) {
  18722. var layer = this.layers[i];
  18723. sources[layer.ssrc] = { msid: msid, cname: cname };
  18724. simulcastSsrcs.push(layer.ssrc);
  18725. if (layer.rtx) {
  18726. sources[layer.rtx] = {
  18727. msid: msid,
  18728. cname: cname
  18729. }
  18730. ssrcGroups.push({
  18731. semantics: 'FID',
  18732. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  18733. });
  18734. }
  18735. }
  18736. ssrcGroups.push({
  18737. semantics: 'SIM',
  18738. ssrcs: simulcastSsrcs.join(' ')
  18739. });
  18740. mLine.ssrcGroups = ssrcGroups;
  18741. mLine.ssrcs = writeSsrcs(sources);
  18742. }
  18743. }
  18744. //endregion
  18745. //region "Public" functions
  18746. Simulcast.prototype.isSupported = function () {
  18747. return window.chrome;
  18748. // TODO this needs improvements. For example I doubt that Chrome in Android
  18749. // has simulcast support. Also, only recent versions of Chromium have native
  18750. // simulcast support.
  18751. }
  18752. /**
  18753. *
  18754. * @param desc
  18755. * @returns {RTCSessionDescription}
  18756. */
  18757. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  18758. if (!validateDescription(desc)) {
  18759. return desc;
  18760. }
  18761. var session = transform.parse(desc.sdp);
  18762. var self = this;
  18763. processVideo(session, function (mLine) {
  18764. // Handle simulcast reception.
  18765. if (self.options.explodeRemoteSimulcast) {
  18766. explodeRemoteSimulcast(mLine);
  18767. } else {
  18768. squeezeRemoteSimulcast(mLine);
  18769. }
  18770. // If native simulcast is enabled, we must append the x-goog-conference
  18771. // attribute to the SDP.
  18772. if (self.layers.length < 1) {
  18773. removeGoogConference(mLine);
  18774. } else {
  18775. assertGoogConference(mLine);
  18776. }
  18777. });
  18778. return new RTCSessionDescription({
  18779. type: desc.type,
  18780. sdp: transform.write(session)
  18781. });
  18782. };
  18783. /**
  18784. *
  18785. * @param desc
  18786. * @returns {RTCSessionDescription}
  18787. */
  18788. Simulcast.prototype.mungeLocalDescription = function (desc) {
  18789. if (!validateDescription(desc) || !this.isSupported()) {
  18790. return desc;
  18791. }
  18792. var session = transform.parse(desc.sdp);
  18793. var self = this;
  18794. processVideo(session, function (mLine) {
  18795. // Initialize native simulcast layers, if not already done.
  18796. self._maybeInitializeLayers(mLine);
  18797. // Update the SDP with the simulcast layers.
  18798. self._restoreSimulcastView(mLine);
  18799. });
  18800. return new RTCSessionDescription({
  18801. type: desc.type,
  18802. sdp: transform.write(session)
  18803. });
  18804. };
  18805. //endregion
  18806. module.exports = Simulcast;
  18807. },{"./transform-utils":66,"sdp-transform":68}],66:[function(require,module,exports){
  18808. exports.writeSsrcs = function(sources, order) {
  18809. var ssrcs = [];
  18810. // expand sources to ssrcs
  18811. if (typeof sources !== 'undefined' &&
  18812. Object.keys(sources).length !== 0) {
  18813. if (Array.isArray(order)) {
  18814. for (var i = 0; i < order.length; i++) {
  18815. var ssrc = order[i];
  18816. var source = sources[ssrc];
  18817. Object.keys(source).forEach(function (attribute) {
  18818. ssrcs.push({
  18819. id: ssrc,
  18820. attribute: attribute,
  18821. value: source[attribute]
  18822. });
  18823. });
  18824. }
  18825. } else {
  18826. Object.keys(sources).forEach(function (ssrc) {
  18827. var source = sources[ssrc];
  18828. Object.keys(source).forEach(function (attribute) {
  18829. ssrcs.push({
  18830. id: ssrc,
  18831. attribute: attribute,
  18832. value: source[attribute]
  18833. });
  18834. });
  18835. });
  18836. }
  18837. }
  18838. return ssrcs;
  18839. };
  18840. exports.parseSsrcs = function (mLine) {
  18841. var sources = {};
  18842. // group sources attributes by ssrc.
  18843. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  18844. mLine.ssrcs.forEach(function (ssrc) {
  18845. if (!sources[ssrc.id])
  18846. sources[ssrc.id] = {};
  18847. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  18848. });
  18849. }
  18850. return sources;
  18851. };
  18852. },{}],67:[function(require,module,exports){
  18853. var grammar = module.exports = {
  18854. v: [{
  18855. name: 'version',
  18856. reg: /^(\d*)$/
  18857. }],
  18858. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  18859. // NB: sessionId will be a String in most cases because it is huge
  18860. name: 'origin',
  18861. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  18862. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  18863. format: "%s %s %d %s IP%d %s"
  18864. }],
  18865. // default parsing of these only (though some of these feel outdated)
  18866. s: [{ name: 'name' }],
  18867. i: [{ name: 'description' }],
  18868. u: [{ name: 'uri' }],
  18869. e: [{ name: 'email' }],
  18870. p: [{ name: 'phone' }],
  18871. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  18872. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  18873. //k: [{}], // outdated thing ignored
  18874. t: [{ //t=0 0
  18875. name: 'timing',
  18876. reg: /^(\d*) (\d*)/,
  18877. names: ['start', 'stop'],
  18878. format: "%d %d"
  18879. }],
  18880. c: [{ //c=IN IP4 10.47.197.26
  18881. name: 'connection',
  18882. reg: /^IN IP(\d) (\S*)/,
  18883. names: ['version', 'ip'],
  18884. format: "IN IP%d %s"
  18885. }],
  18886. b: [{ //b=AS:4000
  18887. push: 'bandwidth',
  18888. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  18889. names: ['type', 'limit'],
  18890. format: "%s:%s"
  18891. }],
  18892. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  18893. // NB: special - pushes to session
  18894. // TODO: rtp/fmtp should be filtered by the payloads found here?
  18895. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  18896. names: ['type', 'port', 'protocol', 'payloads'],
  18897. format: "%s %d %s %s"
  18898. }],
  18899. a: [
  18900. { //a=rtpmap:110 opus/48000/2
  18901. push: 'rtp',
  18902. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  18903. names: ['payload', 'codec', 'rate', 'encoding'],
  18904. format: function (o) {
  18905. return (o.encoding) ?
  18906. "rtpmap:%d %s/%s/%s":
  18907. "rtpmap:%d %s/%s";
  18908. }
  18909. },
  18910. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  18911. push: 'fmtp',
  18912. reg: /^fmtp:(\d*) (\S*)/,
  18913. names: ['payload', 'config'],
  18914. format: "fmtp:%d %s"
  18915. },
  18916. { //a=control:streamid=0
  18917. name: 'control',
  18918. reg: /^control:(.*)/,
  18919. format: "control:%s"
  18920. },
  18921. { //a=rtcp:65179 IN IP4 193.84.77.194
  18922. name: 'rtcp',
  18923. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  18924. names: ['port', 'netType', 'ipVer', 'address'],
  18925. format: function (o) {
  18926. return (o.address != null) ?
  18927. "rtcp:%d %s IP%d %s":
  18928. "rtcp:%d";
  18929. }
  18930. },
  18931. { //a=rtcp-fb:98 trr-int 100
  18932. push: 'rtcpFbTrrInt',
  18933. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  18934. names: ['payload', 'value'],
  18935. format: "rtcp-fb:%d trr-int %d"
  18936. },
  18937. { //a=rtcp-fb:98 nack rpsi
  18938. push: 'rtcpFb',
  18939. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  18940. names: ['payload', 'type', 'subtype'],
  18941. format: function (o) {
  18942. return (o.subtype != null) ?
  18943. "rtcp-fb:%s %s %s":
  18944. "rtcp-fb:%s %s";
  18945. }
  18946. },
  18947. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  18948. //a=extmap:1/recvonly URI-gps-string
  18949. push: 'ext',
  18950. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  18951. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  18952. format: function (o) {
  18953. return (o.config != null) ?
  18954. "extmap:%s %s %s":
  18955. "extmap:%s %s";
  18956. }
  18957. },
  18958. {
  18959. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  18960. push: 'crypto',
  18961. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  18962. names: ['id', 'suite', 'config', 'sessionConfig'],
  18963. format: function (o) {
  18964. return (o.sessionConfig != null) ?
  18965. "crypto:%d %s %s %s":
  18966. "crypto:%d %s %s";
  18967. }
  18968. },
  18969. { //a=setup:actpass
  18970. name: 'setup',
  18971. reg: /^setup:(\w*)/,
  18972. format: "setup:%s"
  18973. },
  18974. { //a=mid:1
  18975. name: 'mid',
  18976. reg: /^mid:([^\s]*)/,
  18977. format: "mid:%s"
  18978. },
  18979. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  18980. name: 'msid',
  18981. reg: /^msid:(.*)/,
  18982. format: "msid:%s"
  18983. },
  18984. { //a=ptime:20
  18985. name: 'ptime',
  18986. reg: /^ptime:(\d*)/,
  18987. format: "ptime:%d"
  18988. },
  18989. { //a=maxptime:60
  18990. name: 'maxptime',
  18991. reg: /^maxptime:(\d*)/,
  18992. format: "maxptime:%d"
  18993. },
  18994. { //a=sendrecv
  18995. name: 'direction',
  18996. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  18997. },
  18998. { //a=ice-lite
  18999. name: 'icelite',
  19000. reg: /^(ice-lite)/
  19001. },
  19002. { //a=ice-ufrag:F7gI
  19003. name: 'iceUfrag',
  19004. reg: /^ice-ufrag:(\S*)/,
  19005. format: "ice-ufrag:%s"
  19006. },
  19007. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19008. name: 'icePwd',
  19009. reg: /^ice-pwd:(\S*)/,
  19010. format: "ice-pwd:%s"
  19011. },
  19012. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19013. name: 'fingerprint',
  19014. reg: /^fingerprint:(\S*) (\S*)/,
  19015. names: ['type', 'hash'],
  19016. format: "fingerprint:%s %s"
  19017. },
  19018. {
  19019. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19020. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19021. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19022. push:'candidates',
  19023. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19024. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19025. format: function (o) {
  19026. var str = "candidate:%s %d %s %d %s %d typ %s";
  19027. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19028. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19029. if (o.generation != null) {
  19030. str += " generation %d";
  19031. }
  19032. return str;
  19033. }
  19034. },
  19035. { //a=end-of-candidates (keep after the candidates line for readability)
  19036. name: 'endOfCandidates',
  19037. reg: /^(end-of-candidates)/
  19038. },
  19039. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19040. name: 'remoteCandidates',
  19041. reg: /^remote-candidates:(.*)/,
  19042. format: "remote-candidates:%s"
  19043. },
  19044. { //a=ice-options:google-ice
  19045. name: 'iceOptions',
  19046. reg: /^ice-options:(\S*)/,
  19047. format: "ice-options:%s"
  19048. },
  19049. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19050. push: "ssrcs",
  19051. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19052. names: ['id', 'attribute', 'value'],
  19053. format: "ssrc:%d %s:%s"
  19054. },
  19055. { //a=ssrc-group:FEC 1 2
  19056. push: "ssrcGroups",
  19057. reg: /^ssrc-group:(\w*) (.*)/,
  19058. names: ['semantics', 'ssrcs'],
  19059. format: "ssrc-group:%s %s"
  19060. },
  19061. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19062. name: "msidSemantic",
  19063. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19064. names: ['semantic', 'token'],
  19065. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19066. },
  19067. { //a=group:BUNDLE audio video
  19068. push: 'groups',
  19069. reg: /^group:(\w*) (.*)/,
  19070. names: ['type', 'mids'],
  19071. format: "group:%s %s"
  19072. },
  19073. { //a=rtcp-mux
  19074. name: 'rtcpMux',
  19075. reg: /^(rtcp-mux)/
  19076. },
  19077. { //a=rtcp-rsize
  19078. name: 'rtcpRsize',
  19079. reg: /^(rtcp-rsize)/
  19080. },
  19081. { // any a= that we don't understand is kepts verbatim on media.invalid
  19082. push: 'invalid',
  19083. names: ["value"]
  19084. }
  19085. ]
  19086. };
  19087. // set sensible defaults to avoid polluting the grammar with boring details
  19088. Object.keys(grammar).forEach(function (key) {
  19089. var objs = grammar[key];
  19090. objs.forEach(function (obj) {
  19091. if (!obj.reg) {
  19092. obj.reg = /(.*)/;
  19093. }
  19094. if (!obj.format) {
  19095. obj.format = "%s";
  19096. }
  19097. });
  19098. });
  19099. },{}],68:[function(require,module,exports){
  19100. var parser = require('./parser');
  19101. var writer = require('./writer');
  19102. exports.write = writer;
  19103. exports.parse = parser.parse;
  19104. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19105. exports.parsePayloads = parser.parsePayloads;
  19106. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19107. },{"./parser":69,"./writer":70}],69:[function(require,module,exports){
  19108. var toIntIfInt = function (v) {
  19109. return String(Number(v)) === v ? Number(v) : v;
  19110. };
  19111. var attachProperties = function (match, location, names, rawName) {
  19112. if (rawName && !names) {
  19113. location[rawName] = toIntIfInt(match[1]);
  19114. }
  19115. else {
  19116. for (var i = 0; i < names.length; i += 1) {
  19117. if (match[i+1] != null) {
  19118. location[names[i]] = toIntIfInt(match[i+1]);
  19119. }
  19120. }
  19121. }
  19122. };
  19123. var parseReg = function (obj, location, content) {
  19124. var needsBlank = obj.name && obj.names;
  19125. if (obj.push && !location[obj.push]) {
  19126. location[obj.push] = [];
  19127. }
  19128. else if (needsBlank && !location[obj.name]) {
  19129. location[obj.name] = {};
  19130. }
  19131. var keyLocation = obj.push ?
  19132. {} : // blank object that will be pushed
  19133. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19134. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19135. if (obj.push) {
  19136. location[obj.push].push(keyLocation);
  19137. }
  19138. };
  19139. var grammar = require('./grammar');
  19140. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19141. exports.parse = function (sdp) {
  19142. var session = {}
  19143. , media = []
  19144. , location = session; // points at where properties go under (one of the above)
  19145. // parse lines we understand
  19146. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19147. var type = l[0];
  19148. var content = l.slice(2);
  19149. if (type === 'm') {
  19150. media.push({rtp: [], fmtp: []});
  19151. location = media[media.length-1]; // point at latest media line
  19152. }
  19153. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19154. var obj = grammar[type][j];
  19155. if (obj.reg.test(content)) {
  19156. return parseReg(obj, location, content);
  19157. }
  19158. }
  19159. });
  19160. session.media = media; // link it up
  19161. return session;
  19162. };
  19163. var fmtpReducer = function (acc, expr) {
  19164. var s = expr.split('=');
  19165. if (s.length === 2) {
  19166. acc[s[0]] = toIntIfInt(s[1]);
  19167. }
  19168. return acc;
  19169. };
  19170. exports.parseFmtpConfig = function (str) {
  19171. return str.split(';').reduce(fmtpReducer, {});
  19172. };
  19173. exports.parsePayloads = function (str) {
  19174. return str.split(' ').map(Number);
  19175. };
  19176. exports.parseRemoteCandidates = function (str) {
  19177. var candidates = [];
  19178. var parts = str.split(' ').map(toIntIfInt);
  19179. for (var i = 0; i < parts.length; i += 3) {
  19180. candidates.push({
  19181. component: parts[i],
  19182. ip: parts[i + 1],
  19183. port: parts[i + 2]
  19184. });
  19185. }
  19186. return candidates;
  19187. };
  19188. },{"./grammar":67}],70:[function(require,module,exports){
  19189. var grammar = require('./grammar');
  19190. // customized util.format - discards excess arguments and can void middle ones
  19191. var formatRegExp = /%[sdv%]/g;
  19192. var format = function (formatStr) {
  19193. var i = 1;
  19194. var args = arguments;
  19195. var len = args.length;
  19196. return formatStr.replace(formatRegExp, function (x) {
  19197. if (i >= len) {
  19198. return x; // missing argument
  19199. }
  19200. var arg = args[i];
  19201. i += 1;
  19202. switch (x) {
  19203. case '%%':
  19204. return '%';
  19205. case '%s':
  19206. return String(arg);
  19207. case '%d':
  19208. return Number(arg);
  19209. case '%v':
  19210. return '';
  19211. }
  19212. });
  19213. // NB: we discard excess arguments - they are typically undefined from makeLine
  19214. };
  19215. var makeLine = function (type, obj, location) {
  19216. var str = obj.format instanceof Function ?
  19217. (obj.format(obj.push ? location : location[obj.name])) :
  19218. obj.format;
  19219. var args = [type + '=' + str];
  19220. if (obj.names) {
  19221. for (var i = 0; i < obj.names.length; i += 1) {
  19222. var n = obj.names[i];
  19223. if (obj.name) {
  19224. args.push(location[obj.name][n]);
  19225. }
  19226. else { // for mLine and push attributes
  19227. args.push(location[obj.names[i]]);
  19228. }
  19229. }
  19230. }
  19231. else {
  19232. args.push(location[obj.name]);
  19233. }
  19234. return format.apply(null, args);
  19235. };
  19236. // RFC specified order
  19237. // TODO: extend this with all the rest
  19238. var defaultOuterOrder = [
  19239. 'v', 'o', 's', 'i',
  19240. 'u', 'e', 'p', 'c',
  19241. 'b', 't', 'r', 'z', 'a'
  19242. ];
  19243. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19244. module.exports = function (session, opts) {
  19245. opts = opts || {};
  19246. // ensure certain properties exist
  19247. if (session.version == null) {
  19248. session.version = 0; // "v=0" must be there (only defined version atm)
  19249. }
  19250. if (session.name == null) {
  19251. session.name = " "; // "s= " must be there if no meaningful name set
  19252. }
  19253. session.media.forEach(function (mLine) {
  19254. if (mLine.payloads == null) {
  19255. mLine.payloads = "";
  19256. }
  19257. });
  19258. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19259. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19260. var sdp = [];
  19261. // loop through outerOrder for matching properties on session
  19262. outerOrder.forEach(function (type) {
  19263. grammar[type].forEach(function (obj) {
  19264. if (obj.name in session && session[obj.name] != null) {
  19265. sdp.push(makeLine(type, obj, session));
  19266. }
  19267. else if (obj.push in session && session[obj.push] != null) {
  19268. session[obj.push].forEach(function (el) {
  19269. sdp.push(makeLine(type, obj, el));
  19270. });
  19271. }
  19272. });
  19273. });
  19274. // then for each media line, follow the innerOrder
  19275. session.media.forEach(function (mLine) {
  19276. sdp.push(makeLine('m', grammar.m[0], mLine));
  19277. innerOrder.forEach(function (type) {
  19278. grammar[type].forEach(function (obj) {
  19279. if (obj.name in mLine && mLine[obj.name] != null) {
  19280. sdp.push(makeLine(type, obj, mLine));
  19281. }
  19282. else if (obj.push in mLine && mLine[obj.push] != null) {
  19283. mLine[obj.push].forEach(function (el) {
  19284. sdp.push(makeLine(type, obj, el));
  19285. });
  19286. }
  19287. });
  19288. });
  19289. });
  19290. return sdp.join('\r\n') + '\r\n';
  19291. };
  19292. },{"./grammar":67}],71:[function(require,module,exports){
  19293. var grammar = module.exports = {
  19294. v: [{
  19295. name: 'version',
  19296. reg: /^(\d*)$/
  19297. }],
  19298. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19299. // NB: sessionId will be a String in most cases because it is huge
  19300. name: 'origin',
  19301. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19302. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19303. format: "%s %s %d %s IP%d %s"
  19304. }],
  19305. // default parsing of these only (though some of these feel outdated)
  19306. s: [{ name: 'name' }],
  19307. i: [{ name: 'description' }],
  19308. u: [{ name: 'uri' }],
  19309. e: [{ name: 'email' }],
  19310. p: [{ name: 'phone' }],
  19311. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19312. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19313. //k: [{}], // outdated thing ignored
  19314. t: [{ //t=0 0
  19315. name: 'timing',
  19316. reg: /^(\d*) (\d*)/,
  19317. names: ['start', 'stop'],
  19318. format: "%d %d"
  19319. }],
  19320. c: [{ //c=IN IP4 10.47.197.26
  19321. name: 'connection',
  19322. reg: /^IN IP(\d) (\S*)/,
  19323. names: ['version', 'ip'],
  19324. format: "IN IP%d %s"
  19325. }],
  19326. b: [{ //b=AS:4000
  19327. push: 'bandwidth',
  19328. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19329. names: ['type', 'limit'],
  19330. format: "%s:%s"
  19331. }],
  19332. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19333. // NB: special - pushes to session
  19334. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19335. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19336. names: ['type', 'port', 'protocol', 'payloads'],
  19337. format: "%s %d %s %s"
  19338. }],
  19339. a: [
  19340. { //a=rtpmap:110 opus/48000/2
  19341. push: 'rtp',
  19342. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19343. names: ['payload', 'codec', 'rate', 'encoding'],
  19344. format: function (o) {
  19345. return (o.encoding) ?
  19346. "rtpmap:%d %s/%s/%s":
  19347. "rtpmap:%d %s/%s";
  19348. }
  19349. },
  19350. {
  19351. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19352. //a=fmtp:111 minptime=10; useinbandfec=1
  19353. push: 'fmtp',
  19354. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19355. names: ['payload', 'config'],
  19356. format: "fmtp:%d %s"
  19357. },
  19358. { //a=control:streamid=0
  19359. name: 'control',
  19360. reg: /^control:(.*)/,
  19361. format: "control:%s"
  19362. },
  19363. { //a=rtcp:65179 IN IP4 193.84.77.194
  19364. name: 'rtcp',
  19365. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19366. names: ['port', 'netType', 'ipVer', 'address'],
  19367. format: function (o) {
  19368. return (o.address != null) ?
  19369. "rtcp:%d %s IP%d %s":
  19370. "rtcp:%d";
  19371. }
  19372. },
  19373. { //a=rtcp-fb:98 trr-int 100
  19374. push: 'rtcpFbTrrInt',
  19375. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19376. names: ['payload', 'value'],
  19377. format: "rtcp-fb:%d trr-int %d"
  19378. },
  19379. { //a=rtcp-fb:98 nack rpsi
  19380. push: 'rtcpFb',
  19381. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19382. names: ['payload', 'type', 'subtype'],
  19383. format: function (o) {
  19384. return (o.subtype != null) ?
  19385. "rtcp-fb:%s %s %s":
  19386. "rtcp-fb:%s %s";
  19387. }
  19388. },
  19389. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19390. //a=extmap:1/recvonly URI-gps-string
  19391. push: 'ext',
  19392. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19393. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19394. format: function (o) {
  19395. return (o.config != null) ?
  19396. "extmap:%s %s %s":
  19397. "extmap:%s %s";
  19398. }
  19399. },
  19400. {
  19401. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19402. push: 'crypto',
  19403. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19404. names: ['id', 'suite', 'config', 'sessionConfig'],
  19405. format: function (o) {
  19406. return (o.sessionConfig != null) ?
  19407. "crypto:%d %s %s %s":
  19408. "crypto:%d %s %s";
  19409. }
  19410. },
  19411. { //a=setup:actpass
  19412. name: 'setup',
  19413. reg: /^setup:(\w*)/,
  19414. format: "setup:%s"
  19415. },
  19416. { //a=mid:1
  19417. name: 'mid',
  19418. reg: /^mid:([^\s]*)/,
  19419. format: "mid:%s"
  19420. },
  19421. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19422. name: 'msid',
  19423. reg: /^msid:(.*)/,
  19424. format: "msid:%s"
  19425. },
  19426. { //a=ptime:20
  19427. name: 'ptime',
  19428. reg: /^ptime:(\d*)/,
  19429. format: "ptime:%d"
  19430. },
  19431. { //a=maxptime:60
  19432. name: 'maxptime',
  19433. reg: /^maxptime:(\d*)/,
  19434. format: "maxptime:%d"
  19435. },
  19436. { //a=sendrecv
  19437. name: 'direction',
  19438. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19439. },
  19440. { //a=ice-lite
  19441. name: 'icelite',
  19442. reg: /^(ice-lite)/
  19443. },
  19444. { //a=ice-ufrag:F7gI
  19445. name: 'iceUfrag',
  19446. reg: /^ice-ufrag:(\S*)/,
  19447. format: "ice-ufrag:%s"
  19448. },
  19449. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19450. name: 'icePwd',
  19451. reg: /^ice-pwd:(\S*)/,
  19452. format: "ice-pwd:%s"
  19453. },
  19454. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19455. name: 'fingerprint',
  19456. reg: /^fingerprint:(\S*) (\S*)/,
  19457. names: ['type', 'hash'],
  19458. format: "fingerprint:%s %s"
  19459. },
  19460. {
  19461. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19462. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19463. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19464. push:'candidates',
  19465. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19466. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19467. format: function (o) {
  19468. var str = "candidate:%s %d %s %d %s %d typ %s";
  19469. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19470. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19471. if (o.generation != null) {
  19472. str += " generation %d";
  19473. }
  19474. return str;
  19475. }
  19476. },
  19477. { //a=end-of-candidates (keep after the candidates line for readability)
  19478. name: 'endOfCandidates',
  19479. reg: /^(end-of-candidates)/
  19480. },
  19481. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19482. name: 'remoteCandidates',
  19483. reg: /^remote-candidates:(.*)/,
  19484. format: "remote-candidates:%s"
  19485. },
  19486. { //a=ice-options:google-ice
  19487. name: 'iceOptions',
  19488. reg: /^ice-options:(\S*)/,
  19489. format: "ice-options:%s"
  19490. },
  19491. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19492. push: "ssrcs",
  19493. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19494. names: ['id', 'attribute', 'value'],
  19495. format: "ssrc:%d %s:%s"
  19496. },
  19497. { //a=ssrc-group:FEC 1 2
  19498. push: "ssrcGroups",
  19499. reg: /^ssrc-group:(\w*) (.*)/,
  19500. names: ['semantics', 'ssrcs'],
  19501. format: "ssrc-group:%s %s"
  19502. },
  19503. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19504. name: "msidSemantic",
  19505. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19506. names: ['semantic', 'token'],
  19507. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19508. },
  19509. { //a=group:BUNDLE audio video
  19510. push: 'groups',
  19511. reg: /^group:(\w*) (.*)/,
  19512. names: ['type', 'mids'],
  19513. format: "group:%s %s"
  19514. },
  19515. { //a=rtcp-mux
  19516. name: 'rtcpMux',
  19517. reg: /^(rtcp-mux)/
  19518. },
  19519. { //a=rtcp-rsize
  19520. name: 'rtcpRsize',
  19521. reg: /^(rtcp-rsize)/
  19522. },
  19523. { // any a= that we don't understand is kepts verbatim on media.invalid
  19524. push: 'invalid',
  19525. names: ["value"]
  19526. }
  19527. ]
  19528. };
  19529. // set sensible defaults to avoid polluting the grammar with boring details
  19530. Object.keys(grammar).forEach(function (key) {
  19531. var objs = grammar[key];
  19532. objs.forEach(function (obj) {
  19533. if (!obj.reg) {
  19534. obj.reg = /(.*)/;
  19535. }
  19536. if (!obj.format) {
  19537. obj.format = "%s";
  19538. }
  19539. });
  19540. });
  19541. },{}],72:[function(require,module,exports){
  19542. arguments[4][68][0].apply(exports,arguments)
  19543. },{"./parser":73,"./writer":74,"dup":68}],73:[function(require,module,exports){
  19544. var toIntIfInt = function (v) {
  19545. return String(Number(v)) === v ? Number(v) : v;
  19546. };
  19547. var attachProperties = function (match, location, names, rawName) {
  19548. if (rawName && !names) {
  19549. location[rawName] = toIntIfInt(match[1]);
  19550. }
  19551. else {
  19552. for (var i = 0; i < names.length; i += 1) {
  19553. if (match[i+1] != null) {
  19554. location[names[i]] = toIntIfInt(match[i+1]);
  19555. }
  19556. }
  19557. }
  19558. };
  19559. var parseReg = function (obj, location, content) {
  19560. var needsBlank = obj.name && obj.names;
  19561. if (obj.push && !location[obj.push]) {
  19562. location[obj.push] = [];
  19563. }
  19564. else if (needsBlank && !location[obj.name]) {
  19565. location[obj.name] = {};
  19566. }
  19567. var keyLocation = obj.push ?
  19568. {} : // blank object that will be pushed
  19569. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19570. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19571. if (obj.push) {
  19572. location[obj.push].push(keyLocation);
  19573. }
  19574. };
  19575. var grammar = require('./grammar');
  19576. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19577. exports.parse = function (sdp) {
  19578. var session = {}
  19579. , media = []
  19580. , location = session; // points at where properties go under (one of the above)
  19581. // parse lines we understand
  19582. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19583. var type = l[0];
  19584. var content = l.slice(2);
  19585. if (type === 'm') {
  19586. media.push({rtp: [], fmtp: []});
  19587. location = media[media.length-1]; // point at latest media line
  19588. }
  19589. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19590. var obj = grammar[type][j];
  19591. if (obj.reg.test(content)) {
  19592. return parseReg(obj, location, content);
  19593. }
  19594. }
  19595. });
  19596. session.media = media; // link it up
  19597. return session;
  19598. };
  19599. var fmtpReducer = function (acc, expr) {
  19600. var s = expr.split('=');
  19601. if (s.length === 2) {
  19602. acc[s[0]] = toIntIfInt(s[1]);
  19603. }
  19604. return acc;
  19605. };
  19606. exports.parseFmtpConfig = function (str) {
  19607. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  19608. };
  19609. exports.parsePayloads = function (str) {
  19610. return str.split(' ').map(Number);
  19611. };
  19612. exports.parseRemoteCandidates = function (str) {
  19613. var candidates = [];
  19614. var parts = str.split(' ').map(toIntIfInt);
  19615. for (var i = 0; i < parts.length; i += 3) {
  19616. candidates.push({
  19617. component: parts[i],
  19618. ip: parts[i + 1],
  19619. port: parts[i + 2]
  19620. });
  19621. }
  19622. return candidates;
  19623. };
  19624. },{"./grammar":71}],74:[function(require,module,exports){
  19625. arguments[4][70][0].apply(exports,arguments)
  19626. },{"./grammar":71,"dup":70}],75:[function(require,module,exports){
  19627. var MediaStreamType = {
  19628. VIDEO_TYPE: "Video",
  19629. AUDIO_TYPE: "Audio"
  19630. };
  19631. module.exports = MediaStreamType;
  19632. },{}],76:[function(require,module,exports){
  19633. var RTCEvents = {
  19634. RTC_READY: "rtc.ready",
  19635. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  19636. LASTN_CHANGED: "rtc.lastn_changed",
  19637. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  19638. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  19639. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  19640. };
  19641. module.exports = RTCEvents;
  19642. },{}],77:[function(require,module,exports){
  19643. var Resolutions = {
  19644. "1080": {
  19645. width: 1920,
  19646. height: 1080,
  19647. order: 7
  19648. },
  19649. "fullhd": {
  19650. width: 1920,
  19651. height: 1080,
  19652. order: 7
  19653. },
  19654. "720": {
  19655. width: 1280,
  19656. height: 720,
  19657. order: 6
  19658. },
  19659. "hd": {
  19660. width: 1280,
  19661. height: 720,
  19662. order: 6
  19663. },
  19664. "960": {
  19665. width: 960,
  19666. height: 720,
  19667. order: 5
  19668. },
  19669. "640": {
  19670. width: 640,
  19671. height: 480,
  19672. order: 4
  19673. },
  19674. "vga": {
  19675. width: 640,
  19676. height: 480,
  19677. order: 4
  19678. },
  19679. "360": {
  19680. width: 640,
  19681. height: 360,
  19682. order: 3
  19683. },
  19684. "320": {
  19685. width: 320,
  19686. height: 240,
  19687. order: 2
  19688. },
  19689. "180": {
  19690. width: 320,
  19691. height: 180,
  19692. order: 1
  19693. }
  19694. };
  19695. module.exports = Resolutions;
  19696. },{}],78:[function(require,module,exports){
  19697. var StreamEventTypes = {
  19698. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  19699. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  19700. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  19701. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  19702. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  19703. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  19704. };
  19705. module.exports = StreamEventTypes;
  19706. },{}],79:[function(require,module,exports){
  19707. var AuthenticationEvents = {
  19708. /**
  19709. * Event callback arguments:
  19710. * function(authenticationEnabled, userIdentity)
  19711. * authenticationEnabled - indicates whether authentication has been enabled
  19712. * in this session
  19713. * userIdentity - if user has been logged in then it contains user name. If
  19714. * contains 'null' or 'undefined' then user is not logged in.
  19715. */
  19716. IDENTITY_UPDATED: "authentication.identity_updated"
  19717. };
  19718. module.exports = AuthenticationEvents;
  19719. },{}],80:[function(require,module,exports){
  19720. var DesktopSharingEventTypes = {
  19721. INIT: "ds.init",
  19722. SWITCHING_DONE: "ds.switching_done",
  19723. NEW_STREAM_CREATED: "ds.new_stream_created"
  19724. };
  19725. module.exports = DesktopSharingEventTypes;
  19726. },{}],81:[function(require,module,exports){
  19727. var Constants = {
  19728. LOCAL_JID: 'local'
  19729. };
  19730. module.exports = Constants;
  19731. },{}],82:[function(require,module,exports){
  19732. var XMPPEvents = {
  19733. // Designates an event indicating that the connection to the XMPP server
  19734. // failed.
  19735. CONNECTION_FAILED: "xmpp.connection.failed",
  19736. // Designates an event indicating that the media (ICE) connection was
  19737. // interrupted. This should go to the RTC module.
  19738. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  19739. // Designates an event indicating that the media (ICE) connection was
  19740. // restored. This should go to the RTC module.
  19741. CONNECTION_RESTORED: "xmpp.connection.restored",
  19742. // Designates an event indicating that an offer (e.g. Jingle
  19743. // session-initiate) was received.
  19744. CALL_INCOMING: "xmpp.callincoming.jingle",
  19745. // Designates an event indicating that we were kicked from the XMPP MUC.
  19746. KICKED: "xmpp.kicked",
  19747. // Designates an event indicating that the userID for a specific JID has
  19748. // changed.
  19749. USER_ID_CHANGED: "xmpp.user_id_changed",
  19750. // Designates an event indicating that we have joined the XMPP MUC.
  19751. MUC_JOINED: "xmpp.muc_joined",
  19752. // Designates an event indicating that a participant joined the XMPP MUC.
  19753. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  19754. // Designates an event indicating that a participant left the XMPP MUC.
  19755. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  19756. // Designates an event indicating that the MUC role of a participant has
  19757. // changed.
  19758. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  19759. // Designates an event indicating that the XMPP MUC was destroyed.
  19760. MUC_DESTROYED: "xmpp.muc_destroyed",
  19761. // Designates an event indicating that the display name of a participant
  19762. // has changed.
  19763. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  19764. // Designates an event indicating that we received statistics from a
  19765. // participant in the MUC.
  19766. REMOTE_STATS: "xmpp.remote_stats",
  19767. // Designates an event indicating that our role in the XMPP MUC has changed.
  19768. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  19769. // Designates an event indicating that the subject of the XMPP MUC has
  19770. // changed.
  19771. SUBJECT_CHANGED: "xmpp.subject_changed",
  19772. // Designates an event indicating that an XMPP message in the MUC was
  19773. // received.
  19774. MESSAGE_RECEIVED: "xmpp.message_received",
  19775. // Designates an event indicating that we sent an XMPP message to the MUC.
  19776. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  19777. // Designates an event indicating that the video type (e.g. 'camera' or
  19778. // 'screen') for a participant has changed.
  19779. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  19780. // Designates an event indicating that a participant in the XMPP MUC has
  19781. // advertised that they have audio muted (or unmuted).
  19782. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  19783. // Designates an event indicating that a participant in the XMPP MUC has
  19784. // advertised that they have video muted (or unmuted).
  19785. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  19786. // Designates an event indicating that the focus has asked us to mute our
  19787. // audio.
  19788. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  19789. // Designates an event indicating that a moderator in the room changed the
  19790. // "start muted" settings for the conference.
  19791. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  19792. // Designates an event indicating that we should join the conference with
  19793. // audio and/or video muted.
  19794. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  19795. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  19796. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  19797. PASSWORD_REQUIRED: "xmpp.password_required",
  19798. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  19799. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  19800. ETHERPAD: "xmpp.etherpad",
  19801. DEVICE_AVAILABLE: "xmpp.device_available",
  19802. BRIDGE_DOWN: "xmpp.bridge_down",
  19803. PRESENCE_STATUS: "xmpp.presence_status",
  19804. RESERVATION_ERROR: "xmpp.room_reservation_error",
  19805. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  19806. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  19807. // TODO: only used in a hack, should probably be removed.
  19808. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  19809. // TODO: only used in a hack, should probably be removed.
  19810. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  19811. // TODO: only used in a hack, should probably be removed.
  19812. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  19813. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  19814. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  19815. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  19816. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  19817. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  19818. // xmpp is connected and obtained user media
  19819. READY_TO_JOIN: 'xmpp.ready_to_join',
  19820. FOCUS_LEFT: "xmpp.focus_left",
  19821. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  19822. };
  19823. module.exports = XMPPEvents;
  19824. },{}]},{},[7])(7)
  19825. });