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

lib-jitsi-meet.js 783KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. /**
  18. * Creates a JitsiConference object with the given name and properties.
  19. * Note: this constructor is not a part of the public API (objects should be
  20. * created using JitsiConnection.createConference).
  21. * @param options.config properties / settings related to the conference that will be created.
  22. * @param options.name the name of the conference
  23. * @param options.connection the JitsiConnection object for this JitsiConference.
  24. * @constructor
  25. */
  26. function JitsiConference(options) {
  27. if(!options.name || options.name.toLowerCase() !== options.name) {
  28. logger.error("Invalid conference name (no conference name passed or it"
  29. + "contains invalid characters like capital letters)!");
  30. return;
  31. }
  32. this.options = options;
  33. this.connection = this.options.connection;
  34. this.xmpp = this.connection.xmpp;
  35. this.eventEmitter = new EventEmitter();
  36. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  37. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  38. this.rtc = new RTC(this.room, options);
  39. if(!RTC.options.disableAudioLevels)
  40. this.statistics = new Statistics();
  41. setupListeners(this);
  42. this.participants = {};
  43. this.lastDominantSpeaker = null;
  44. this.dtmfManager = null;
  45. this.somebodySupportsDTMF = false;
  46. this.authEnabled = false;
  47. this.authIdentity;
  48. this.startAudioMuted = false;
  49. this.startVideoMuted = false;
  50. this.tracks = [];
  51. }
  52. /**
  53. * Joins the conference.
  54. * @param password {string} the password
  55. */
  56. JitsiConference.prototype.join = function (password) {
  57. if(this.room)
  58. this.room.join(password);
  59. };
  60. /**
  61. * Check if joined to the conference.
  62. */
  63. JitsiConference.prototype.isJoined = function () {
  64. return this.room && this.room.joined;
  65. };
  66. /**
  67. * Leaves the conference.
  68. */
  69. JitsiConference.prototype.leave = function () {
  70. if(this.xmpp && this.room)
  71. this.xmpp.leaveRoom(this.room.roomjid);
  72. this.room = null;
  73. };
  74. /**
  75. * Returns name of this conference.
  76. */
  77. JitsiConference.prototype.getName = function () {
  78. return this.options.name;
  79. };
  80. /**
  81. * Check if authentication is enabled for this conference.
  82. */
  83. JitsiConference.prototype.isAuthEnabled = function () {
  84. return this.authEnabled;
  85. };
  86. /**
  87. * Check if user is logged in.
  88. */
  89. JitsiConference.prototype.isLoggedIn = function () {
  90. return !!this.authIdentity;
  91. };
  92. /**
  93. * Get authorized login.
  94. */
  95. JitsiConference.prototype.getAuthLogin = function () {
  96. return this.authIdentity;
  97. };
  98. /**
  99. * Check if external authentication is enabled for this conference.
  100. */
  101. JitsiConference.prototype.isExternalAuthEnabled = function () {
  102. return this.room && this.room.moderator.isExternalAuthEnabled();
  103. };
  104. /**
  105. * Get url for external authentication.
  106. * @param {boolean} [urlForPopup] if true then return url for login popup,
  107. * else url of login page.
  108. * @returns {Promise}
  109. */
  110. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  111. return new Promise(function (resolve, reject) {
  112. if (!this.isExternalAuthEnabled()) {
  113. reject();
  114. return;
  115. }
  116. if (urlForPopup) {
  117. this.room.moderator.getPopupLoginUrl(resolve, reject);
  118. } else {
  119. this.room.moderator.getLoginUrl(resolve, reject);
  120. }
  121. }.bind(this));
  122. };
  123. /**
  124. * Returns the local tracks.
  125. */
  126. JitsiConference.prototype.getLocalTracks = function () {
  127. if (this.rtc) {
  128. return this.rtc.localStreams;
  129. } else {
  130. return [];
  131. }
  132. };
  133. /**
  134. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  135. * in JitsiConferenceEvents.
  136. * @param eventId the event ID.
  137. * @param handler handler for the event.
  138. *
  139. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  140. */
  141. JitsiConference.prototype.on = function (eventId, handler) {
  142. if(this.eventEmitter)
  143. this.eventEmitter.on(eventId, handler);
  144. };
  145. /**
  146. * Removes event listener
  147. * @param eventId the event ID.
  148. * @param [handler] optional, the specific handler to unbind
  149. *
  150. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  151. */
  152. JitsiConference.prototype.off = function (eventId, handler) {
  153. if(this.eventEmitter)
  154. this.eventEmitter.removeListener(eventId, handler);
  155. };
  156. // Common aliases for event emitter
  157. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  158. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  159. /**
  160. * Receives notifications from another participants for commands / custom events
  161. * (send by sendPresenceCommand method).
  162. * @param command {String} the name of the command
  163. * @param handler {Function} handler for the command
  164. */
  165. JitsiConference.prototype.addCommandListener = function (command, handler) {
  166. if(this.room)
  167. this.room.addPresenceListener(command, handler);
  168. };
  169. /**
  170. * Removes command listener
  171. * @param command {String} the name of the command
  172. */
  173. JitsiConference.prototype.removeCommandListener = function (command) {
  174. if(this.room)
  175. this.room.removePresenceListener(command);
  176. };
  177. /**
  178. * Sends text message to the other participants in the conference
  179. * @param message the text message.
  180. */
  181. JitsiConference.prototype.sendTextMessage = function (message) {
  182. if(this.room)
  183. this.room.sendMessage(message);
  184. };
  185. /**
  186. * Send presence command.
  187. * @param name the name of the command.
  188. * @param values Object with keys and values that will be send.
  189. **/
  190. JitsiConference.prototype.sendCommand = function (name, values) {
  191. if(this.room) {
  192. this.room.addToPresence(name, values);
  193. this.room.sendPresence();
  194. }
  195. };
  196. /**
  197. * Send presence command one time.
  198. * @param name the name of the command.
  199. * @param values Object with keys and values that will be send.
  200. **/
  201. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  202. this.sendCommand(name, values);
  203. this.removeCommand(name);
  204. };
  205. /**
  206. * Send presence command.
  207. * @param name the name of the command.
  208. * @param values Object with keys and values that will be send.
  209. * @param persistent if false the command will be sent only one time
  210. **/
  211. JitsiConference.prototype.removeCommand = function (name) {
  212. if(this.room)
  213. this.room.removeFromPresence(name);
  214. };
  215. /**
  216. * Sets the display name for this conference.
  217. * @param name the display name to set
  218. */
  219. JitsiConference.prototype.setDisplayName = function(name) {
  220. if(this.room){
  221. // remove previously set nickname
  222. this.room.removeFromPresence("nick");
  223. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  224. this.room.sendPresence();
  225. }
  226. };
  227. /**
  228. * Adds JitsiLocalTrack object to the conference.
  229. * @param track the JitsiLocalTrack object.
  230. */
  231. JitsiConference.prototype.addTrack = function (track) {
  232. this.room.addStream(track.getOriginalStream(), function () {
  233. this.rtc.addLocalStream(track);
  234. if (this.startAudioMuted && track.isAudioTrack()) {
  235. track.mute();
  236. }
  237. if (this.startVideoMuted && track.isVideoTrack()) {
  238. track.mute();
  239. }
  240. if (track.startMuted) {
  241. track.mute();
  242. }
  243. this.tracks.push(track);
  244. var muteHandler = this._fireMuteChangeEvent.bind(this, track);
  245. var stopHandler = this.removeTrack.bind(this, track);
  246. var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  247. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  248. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  249. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  250. this.addEventListener(JitsiConferenceEvents.TRACK_REMOVED, function (someTrack) {
  251. if (someTrack !== track) {
  252. return;
  253. }
  254. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  255. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  256. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  257. });
  258. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  259. }.bind(this));
  260. };
  261. /**
  262. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  263. * @param audioLevel the audio level
  264. */
  265. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  266. this.eventEmitter.emit(
  267. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  268. this.myUserId(), audioLevel);
  269. };
  270. /**
  271. * Fires TRACK_MUTE_CHANGED change conference event.
  272. * @param track the JitsiTrack object related to the event.
  273. */
  274. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  275. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  276. };
  277. /**
  278. * Removes JitsiLocalTrack object to the conference.
  279. * @param track the JitsiLocalTrack object.
  280. */
  281. JitsiConference.prototype.removeTrack = function (track) {
  282. var pos = this.tracks.indexOf(track);
  283. if (pos > -1) {
  284. this.tracks.splice(pos, 1);
  285. }
  286. if(!this.room){
  287. if(this.rtc)
  288. this.rtc.removeLocalStream(track);
  289. return;
  290. }
  291. this.room.removeStream(track.getOriginalStream(), function(){
  292. this.rtc.removeLocalStream(track);
  293. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  294. }.bind(this));
  295. };
  296. /**
  297. * Get role of the local user.
  298. * @returns {string} user role: 'moderator' or 'none'
  299. */
  300. JitsiConference.prototype.getRole = function () {
  301. return this.room.role;
  302. };
  303. /**
  304. * Check if local user is moderator.
  305. * @returns {boolean} true if local user is moderator, false otherwise.
  306. */
  307. JitsiConference.prototype.isModerator = function () {
  308. return this.room.isModerator();
  309. };
  310. /**
  311. * Set password for the room.
  312. * @param {string} password new password for the room.
  313. * @returns {Promise}
  314. */
  315. JitsiConference.prototype.lock = function (password) {
  316. if (!this.isModerator()) {
  317. return Promise.reject();
  318. }
  319. var conference = this;
  320. return new Promise(function (resolve, reject) {
  321. conference.room.lockRoom(password || "", function () {
  322. resolve();
  323. }, function (err) {
  324. reject(err);
  325. }, function () {
  326. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  327. });
  328. });
  329. };
  330. /**
  331. * Remove password from the room.
  332. * @returns {Promise}
  333. */
  334. JitsiConference.prototype.unlock = function () {
  335. return this.lock();
  336. };
  337. /**
  338. * Elects the participant with the given id to be the selected participant or the speaker.
  339. * @param id the identifier of the participant
  340. */
  341. JitsiConference.prototype.selectParticipant = function(participantId) {
  342. if (this.rtc) {
  343. this.rtc.selectedEndpoint(participantId);
  344. }
  345. };
  346. /**
  347. *
  348. * @param id the identifier of the participant
  349. */
  350. JitsiConference.prototype.pinParticipant = function(participantId) {
  351. if (this.rtc) {
  352. this.rtc.pinEndpoint(participantId);
  353. }
  354. };
  355. /**
  356. * Returns the list of participants for this conference.
  357. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  358. */
  359. JitsiConference.prototype.getParticipants = function() {
  360. return Object.keys(this.participants).map(function (key) {
  361. return this.participants[key];
  362. }, this);
  363. };
  364. /**
  365. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  366. * undefined if there isn't one).
  367. * @param id the id of the participant.
  368. */
  369. JitsiConference.prototype.getParticipantById = function(id) {
  370. return this.participants[id];
  371. };
  372. /**
  373. * Kick participant from this conference.
  374. * @param {string} id id of the participant to kick
  375. */
  376. JitsiConference.prototype.kickParticipant = function (id) {
  377. var participant = this.getParticipantById(id);
  378. if (!participant) {
  379. return;
  380. }
  381. this.room.kick(participant.getJid());
  382. };
  383. /**
  384. * Kick participant from this conference.
  385. * @param {string} id id of the participant to kick
  386. */
  387. JitsiConference.prototype.muteParticipant = function (id) {
  388. var participant = this.getParticipantById(id);
  389. if (!participant) {
  390. return;
  391. }
  392. this.room.muteParticipant(participant.getJid(), true);
  393. };
  394. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  395. var id = Strophe.getResourceFromJid(jid);
  396. if (id === 'focus' || this.myUserId() === id) {
  397. return;
  398. }
  399. var participant = new JitsiParticipant(jid, this, nick);
  400. participant._role = role;
  401. this.participants[id] = participant;
  402. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  403. this.xmpp.connection.disco.info(
  404. jid, "node", function(iq) {
  405. participant._supportsDTMF = $(iq).find(
  406. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  407. this.updateDTMFSupport();
  408. }.bind(this)
  409. );
  410. };
  411. JitsiConference.prototype.onMemberLeft = function (jid) {
  412. var id = Strophe.getResourceFromJid(jid);
  413. if (id === 'focus' || this.myUserId() === id) {
  414. return;
  415. }
  416. var participant = this.participants[id];
  417. delete this.participants[id];
  418. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  419. };
  420. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  421. var id = Strophe.getResourceFromJid(jid);
  422. var participant = this.getParticipantById(id);
  423. if (!participant) {
  424. return;
  425. }
  426. participant._role = role;
  427. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  428. };
  429. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  430. var id = Strophe.getResourceFromJid(jid);
  431. var participant = this.getParticipantById(id);
  432. if (!participant) {
  433. return;
  434. }
  435. participant._displayName = displayName;
  436. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  437. };
  438. JitsiConference.prototype.onTrackAdded = function (track) {
  439. var id = track.getParticipantId();
  440. var participant = this.getParticipantById(id);
  441. if (!participant) {
  442. return;
  443. }
  444. // add track to JitsiParticipant
  445. participant._tracks.push(track);
  446. var emitter = this.eventEmitter;
  447. track.addEventListener(
  448. JitsiTrackEvents.TRACK_STOPPED,
  449. function () {
  450. // remove track from JitsiParticipant
  451. var pos = participant._tracks.indexOf(track);
  452. if (pos > -1) {
  453. participant._tracks.splice(pos, 1);
  454. }
  455. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  456. }
  457. );
  458. track.addEventListener(
  459. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  460. function () {
  461. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  462. }
  463. );
  464. track.addEventListener(
  465. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  466. function (audioLevel) {
  467. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  468. }
  469. );
  470. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  471. };
  472. JitsiConference.prototype.updateDTMFSupport = function () {
  473. var somebodySupportsDTMF = false;
  474. var participants = this.getParticipants();
  475. // check if at least 1 participant supports DTMF
  476. for (var i = 0; i < participants.length; i += 1) {
  477. if (participants[i].supportsDTMF()) {
  478. somebodySupportsDTMF = true;
  479. break;
  480. }
  481. }
  482. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  483. this.somebodySupportsDTMF = somebodySupportsDTMF;
  484. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  485. }
  486. };
  487. /**
  488. * Allows to check if there is at least one user in the conference
  489. * that supports DTMF.
  490. * @returns {boolean} true if somebody supports DTMF, false otherwise
  491. */
  492. JitsiConference.prototype.isDTMFSupported = function () {
  493. return this.somebodySupportsDTMF;
  494. };
  495. /**
  496. * Returns the local user's ID
  497. * @return {string} local user's ID
  498. */
  499. JitsiConference.prototype.myUserId = function () {
  500. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  501. };
  502. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  503. if (!this.dtmfManager) {
  504. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  505. if (!connection) {
  506. logger.warn("cannot sendTones: no conneciton");
  507. return;
  508. }
  509. var tracks = this.getLocalTracks().filter(function (track) {
  510. return track.isAudioTrack();
  511. });
  512. if (!tracks.length) {
  513. logger.warn("cannot sendTones: no local audio stream");
  514. return;
  515. }
  516. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  517. }
  518. this.dtmfManager.sendTones(tones, duration, pause);
  519. };
  520. /**
  521. * Returns true if the recording is supproted and false if not.
  522. */
  523. JitsiConference.prototype.isRecordingSupported = function () {
  524. if(this.room)
  525. return this.room.isRecordingSupported();
  526. return false;
  527. };
  528. /**
  529. * Returns null if the recording is not supported, "on" if the recording started
  530. * and "off" if the recording is not started.
  531. */
  532. JitsiConference.prototype.getRecordingState = function () {
  533. if(this.room)
  534. return this.room.getRecordingState();
  535. return "off";
  536. }
  537. /**
  538. * Returns the url of the recorded video.
  539. */
  540. JitsiConference.prototype.getRecordingURL = function () {
  541. if(this.room)
  542. return this.room.getRecordingURL();
  543. return null;
  544. }
  545. /**
  546. * Starts/stops the recording
  547. */
  548. JitsiConference.prototype.toggleRecording = function (options) {
  549. if(this.room)
  550. return this.room.toggleRecording(options, function (status, error) {
  551. this.eventEmitter.emit(
  552. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  553. }.bind(this));
  554. this.eventEmitter.emit(
  555. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  556. new Error("The conference is not created yet!"));
  557. }
  558. /**
  559. * Returns true if the SIP calls are supported and false otherwise
  560. */
  561. JitsiConference.prototype.isSIPCallingSupported = function () {
  562. if(this.room)
  563. return this.room.isSIPCallingSupported();
  564. return false;
  565. }
  566. /**
  567. * Dials a number.
  568. * @param number the number
  569. */
  570. JitsiConference.prototype.dial = function (number) {
  571. if(this.room)
  572. return this.room.dial(number);
  573. return new Promise(function(resolve, reject){
  574. reject(new Error("The conference is not created yet!"))});
  575. }
  576. /**
  577. * Hangup an existing call
  578. */
  579. JitsiConference.prototype.hangup = function () {
  580. if(this.room)
  581. return this.room.hangup();
  582. return new Promise(function(resolve, reject){
  583. reject(new Error("The conference is not created yet!"))});
  584. }
  585. /**
  586. * Returns the phone number for joining the conference.
  587. */
  588. JitsiConference.prototype.getPhoneNumber = function () {
  589. if(this.room)
  590. return this.room.getPhoneNumber();
  591. return null;
  592. }
  593. /**
  594. * Returns the pin for joining the conference with phone.
  595. */
  596. JitsiConference.prototype.getPhonePin = function () {
  597. if(this.room)
  598. return this.room.getPhonePin();
  599. return null;
  600. }
  601. /**
  602. * Returns the connection state for the current room. Its ice connection state
  603. * for its session.
  604. */
  605. JitsiConference.prototype.getConnectionState = function () {
  606. if(this.room)
  607. return this.room.getConnectionState();
  608. return null;
  609. }
  610. /**
  611. * Make all new participants mute their audio/video on join.
  612. * @param {boolean} audioMuted if audio should be muted.
  613. * @param {boolean} videoMuted if video should be muted.
  614. */
  615. JitsiConference.prototype.setStartMuted = function (audioMuted, videoMuted) {
  616. if (!this.isModerator()) {
  617. return;
  618. }
  619. this.room.removeFromPresence("startmuted");
  620. this.room.addToPresence("startmuted", {
  621. attributes: {
  622. audio: audioMuted,
  623. video: videoMuted,
  624. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  625. }
  626. });
  627. this.room.sendPresence();
  628. };
  629. /**
  630. * Check if audio is muted on join.
  631. */
  632. JitsiConference.prototype.isStartAudioMuted = function () {
  633. return this.startAudioMuted;
  634. };
  635. /**
  636. * Check if video is muted on join.
  637. */
  638. JitsiConference.prototype.isStartVideoMuted = function () {
  639. return this.startVideoMuted;
  640. };
  641. /**
  642. * Setups the listeners needed for the conference.
  643. * @param conference the conference
  644. */
  645. function setupListeners(conference) {
  646. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  647. conference.rtc.onIncommingCall(event);
  648. if(conference.statistics)
  649. conference.statistics.startRemoteStats(event.peerconnection);
  650. });
  651. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  652. function (data, sid, thessrc) {
  653. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  654. if (track) {
  655. conference.onTrackAdded(track);
  656. }
  657. }
  658. );
  659. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  660. function (value) {
  661. conference.rtc.setAudioMute(value);
  662. }
  663. );
  664. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  665. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  666. });
  667. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  668. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  669. });
  670. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  671. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  672. });
  673. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  674. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  675. });
  676. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  677. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  678. });
  679. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  680. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  681. });
  682. // FIXME
  683. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  684. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  685. // });
  686. conference.room.addListener(XMPPEvents.KICKED, function () {
  687. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  688. });
  689. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  690. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  691. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  692. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  693. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  694. });
  695. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  696. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  697. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  698. });
  699. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  700. function () {
  701. conference.eventEmitter.emit(
  702. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  703. });
  704. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  705. conference.eventEmitter.emit(
  706. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  707. });
  708. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  709. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  710. });
  711. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  712. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  713. });
  714. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  715. conference.authEnabled = authEnabled;
  716. conference.authIdentity = authIdentity;
  717. });
  718. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  719. var id = Strophe.getResourceFromJid(jid);
  720. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  721. });
  722. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  723. if(conference.lastDominantSpeaker !== id && conference.room) {
  724. conference.lastDominantSpeaker = id;
  725. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  726. }
  727. });
  728. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  729. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  730. });
  731. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  732. function (lastNEndpoints, endpointsEnteringLastN) {
  733. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  734. lastNEndpoints, endpointsEnteringLastN);
  735. });
  736. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  737. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  738. });
  739. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audioMuted, videoMuted) {
  740. conference.startAudioMuted = audioMuted;
  741. conference.startVideoMuted = videoMuted;
  742. // mute existing local tracks because this is initial mute from Jicofo
  743. conference.tracks.forEach(function (track) {
  744. if (conference.startAudioMuted && track.isAudioTrack()) {
  745. track.mute();
  746. }
  747. if (conference.startVideoMuted && track.isVideoTrack()) {
  748. track.mute();
  749. }
  750. });
  751. var initiallyMuted = audioMuted || videoMuted;
  752. conference.eventEmitter.emit(
  753. JitsiConferenceEvents.START_MUTED,
  754. conference.startAudioMuted,
  755. conference.startVideoMuted,
  756. initiallyMuted
  757. );
  758. });
  759. conference.room.addPresenceListener("startmuted", function (data, from) {
  760. var isModerator = false;
  761. if (conference.myUserId() === from && conference.isModerator()) {
  762. isModerator = true;
  763. } else {
  764. var participant = conference.getParticipantById(from);
  765. if (participant && participant.isModerator()) {
  766. isModerator = true;
  767. }
  768. }
  769. if (!isModerator) {
  770. return;
  771. }
  772. var startAudioMuted = data.attributes.audio === 'true';
  773. var startVideoMuted = data.attributes.video === 'true';
  774. var updated = false;
  775. if (startAudioMuted !== conference.startAudioMuted) {
  776. conference.startAudioMuted = startAudioMuted;
  777. updated = true;
  778. }
  779. if (startVideoMuted !== conference.startVideoMuted) {
  780. conference.startVideoMuted = startVideoMuted;
  781. updated = true;
  782. }
  783. if (updated) {
  784. conference.eventEmitter.emit(
  785. JitsiConferenceEvents.START_MUTED,
  786. conference.startAudioMuted,
  787. conference.startVideoMuted,
  788. false
  789. );
  790. }
  791. });
  792. if(conference.statistics) {
  793. //FIXME: Maybe remove event should not be associated with the conference.
  794. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  795. var userId = null;
  796. var jid = conference.room.getJidBySSRC(ssrc);
  797. if (!jid)
  798. return;
  799. conference.rtc.setAudioLevel(jid, level);
  800. });
  801. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  802. function () {
  803. conference.statistics.dispose();
  804. });
  805. // FIXME: Maybe we should move this.
  806. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  807. // conference.room.updateDeviceAvailability(devices);
  808. // });
  809. }
  810. }
  811. module.exports = JitsiConference;
  812. }).call(this,"/JitsiConference.js")
  813. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":80,"./service/authentication/AuthenticationEvents":83,"./service/xmpp/XMPPEvents":87,"events":44,"jitsi-meet-logger":48}],2:[function(require,module,exports){
  814. /**
  815. * Enumeration with the errors for the conference.
  816. * @type {{string: string}}
  817. */
  818. var JitsiConferenceErrors = {
  819. /**
  820. * Indicates that a password is required in order to join the conference.
  821. */
  822. PASSWORD_REQUIRED: "conference.passwordRequired",
  823. /**
  824. * Indicates that client must be authenticated to create the conference.
  825. */
  826. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  827. /**
  828. * Indicates that password cannot be set for this conference.
  829. */
  830. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  831. /**
  832. * Indicates that a connection error occurred when trying to join a
  833. * conference.
  834. */
  835. CONNECTION_ERROR: "conference.connectionError",
  836. /**
  837. * Indicates that the conference setup failed.
  838. */
  839. SETUP_FAILED: "conference.setup_failed",
  840. /**
  841. * Indicates that there is no available videobridge.
  842. */
  843. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  844. /**
  845. * Many more errors TBD here.
  846. */
  847. };
  848. module.exports = JitsiConferenceErrors;
  849. },{}],3:[function(require,module,exports){
  850. /**
  851. * Enumeration with the events for the conference.
  852. * @type {{string: string}}
  853. */
  854. var JitsiConferenceEvents = {
  855. /**
  856. * A new media track was added to the conference.
  857. */
  858. TRACK_ADDED: "conference.trackAdded",
  859. /**
  860. * The media track was removed from the conference.
  861. */
  862. TRACK_REMOVED: "conference.trackRemoved",
  863. /**
  864. * The dominant speaker was changed.
  865. */
  866. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  867. /**
  868. * A new user joinned the conference.
  869. */
  870. USER_JOINED: "conference.userJoined",
  871. /**
  872. * A user has left the conference.
  873. */
  874. USER_LEFT: "conference.userLeft",
  875. /**
  876. * User role changed.
  877. */
  878. USER_ROLE_CHANGED: "conference.roleChanged",
  879. /**
  880. * New text message was received.
  881. */
  882. MESSAGE_RECEIVED: "conference.messageReceived",
  883. /**
  884. * A user has changed it display name
  885. */
  886. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  887. /**
  888. * A participant avatar has changed.
  889. */
  890. AVATAR_CHANGED: "conference.avatarChanged",
  891. /**
  892. * New connection statistics are received.
  893. */
  894. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  895. /**
  896. * The Last N set is changed.
  897. */
  898. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  899. /**
  900. * You are included / excluded in somebody's last N set
  901. */
  902. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  903. /**
  904. * A media track ( attached to the conference) mute status was changed.
  905. */
  906. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  907. /**
  908. * Audio levels of a media track ( attached to the conference) was changed.
  909. */
  910. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  911. /**
  912. * Indicates that the connection to the conference has been interrupted
  913. * for some reason.
  914. */
  915. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  916. /**
  917. * Indicates that the connection to the conference has been restored.
  918. */
  919. CONNECTION_RESTORED: "conference.connectionRestored",
  920. /**
  921. * Indicates that conference failed.
  922. */
  923. CONFERENCE_FAILED: "conference.failed",
  924. /**
  925. * Indicates that conference has been joined.
  926. */
  927. CONFERENCE_JOINED: "conference.joined",
  928. /**
  929. * Indicates that conference has been left.
  930. */
  931. CONFERENCE_LEFT: "conference.left",
  932. /**
  933. * You are kicked from the conference.
  934. */
  935. KICKED: "conferenece.kicked",
  936. /**
  937. * Indicates that start muted settings changed.
  938. */
  939. START_MUTED: "conference.start_muted",
  940. /**
  941. * Indicates that DTMF support changed.
  942. */
  943. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  944. /**
  945. * Indicates that recording state changed.
  946. */
  947. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  948. /**
  949. * Indicates that phone number changed.
  950. */
  951. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  952. };
  953. module.exports = JitsiConferenceEvents;
  954. },{}],4:[function(require,module,exports){
  955. var JitsiConference = require("./JitsiConference");
  956. var XMPP = require("./modules/xmpp/xmpp");
  957. /**
  958. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  959. * JitsiConference interface.
  960. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  961. * @param token the JWT token used to authenticate with the server(optional)
  962. * @param options Object with properties / settings related to connection with the server.
  963. * @constructor
  964. */
  965. function JitsiConnection(appID, token, options) {
  966. this.appID = appID;
  967. this.token = token;
  968. this.options = options;
  969. this.xmpp = new XMPP(options);
  970. this.conferences = {};
  971. }
  972. /**
  973. * Connect the client with the server.
  974. * @param options {object} connecting options (for example authentications parameters).
  975. */
  976. JitsiConnection.prototype.connect = function (options) {
  977. if(!options)
  978. options = {};
  979. this.xmpp.connect(options.id, options.password);
  980. }
  981. /**
  982. * Disconnect the client from the server.
  983. */
  984. JitsiConnection.prototype.disconnect = function () {
  985. this.xmpp.disconnect();
  986. }
  987. /**
  988. * This method allows renewal of the tokens if they are expiring.
  989. * @param token the new token.
  990. */
  991. JitsiConnection.prototype.setToken = function (token) {
  992. this.token = token;
  993. }
  994. /**
  995. * Creates and joins new conference.
  996. * @param name the name of the conference; if null - a generated name will be
  997. * provided from the api
  998. * @param options Object with properties / settings related to the conference
  999. * that will be created.
  1000. * @returns {JitsiConference} returns the new conference object.
  1001. */
  1002. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1003. this.conferences[name] = new JitsiConference({name: name, config: options,
  1004. connection: this});
  1005. return this.conferences[name];
  1006. }
  1007. /**
  1008. * Subscribes the passed listener to the event.
  1009. * @param event {JitsiConnectionEvents} the connection event.
  1010. * @param listener {Function} the function that will receive the event
  1011. */
  1012. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1013. this.xmpp.addListener(event, listener);
  1014. }
  1015. /**
  1016. * Unsubscribes the passed handler.
  1017. * @param event {JitsiConnectionEvents} the connection event.
  1018. * @param listener {Function} the function that will receive the event
  1019. */
  1020. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1021. this.xmpp.removeListener(event, listener);
  1022. }
  1023. module.exports = JitsiConnection;
  1024. },{"./JitsiConference":1,"./modules/xmpp/xmpp":42}],5:[function(require,module,exports){
  1025. /**
  1026. * Enumeration with the errors for the connection.
  1027. * @type {{string: string}}
  1028. */
  1029. var JitsiConnectionErrors = {
  1030. /**
  1031. * Indicates that a password is required in order to join the conference.
  1032. */
  1033. PASSWORD_REQUIRED: "connection.passwordRequired",
  1034. /**
  1035. * Indicates that a connection error occurred when trying to join a
  1036. * conference.
  1037. */
  1038. CONNECTION_ERROR: "connection.connectionError",
  1039. /**
  1040. * Not specified errors.
  1041. */
  1042. OTHER_ERROR: "connection.otherError"
  1043. };
  1044. module.exports = JitsiConnectionErrors;
  1045. },{}],6:[function(require,module,exports){
  1046. /**
  1047. * Enumeration with the events for the connection.
  1048. * @type {{string: string}}
  1049. */
  1050. var JitsiConnnectionEvents = {
  1051. /**
  1052. * Indicates that the connection has been failed for some reason.
  1053. */
  1054. CONNECTION_FAILED: "connection.connectionFailed",
  1055. /**
  1056. * Indicates that the connection has been established.
  1057. */
  1058. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1059. /**
  1060. * Indicates that the connection has been disconnected.
  1061. */
  1062. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1063. /**
  1064. * Indicates that the perfomed action cannot be executed because the
  1065. * connection is not in the correct state(connected, disconnected, etc.)
  1066. */
  1067. WRONG_STATE: "connection.wrongState"
  1068. };
  1069. module.exports = JitsiConnnectionEvents;
  1070. },{}],7:[function(require,module,exports){
  1071. var JitsiConnection = require("./JitsiConnection");
  1072. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1073. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1074. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1075. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1076. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1077. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1078. var Logger = require("jitsi-meet-logger");
  1079. var RTC = require("./modules/RTC/RTC");
  1080. var Statistics = require("./modules/statistics/statistics");
  1081. var Resolutions = require("./service/RTC/Resolutions");
  1082. function getLowerResolution(resolution) {
  1083. if(!Resolutions[resolution])
  1084. return null;
  1085. var order = Resolutions[resolution].order;
  1086. var res = null;
  1087. var resName = null;
  1088. for(var i in Resolutions) {
  1089. var tmp = Resolutions[i];
  1090. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1091. resName = i;
  1092. res = tmp;
  1093. }
  1094. }
  1095. return resName;
  1096. }
  1097. /**
  1098. * Namespace for the interface of Jitsi Meet Library.
  1099. */
  1100. var LibJitsiMeet = {
  1101. JitsiConnection: JitsiConnection,
  1102. events: {
  1103. conference: JitsiConferenceEvents,
  1104. connection: JitsiConnectionEvents,
  1105. track: JitsiTrackEvents
  1106. },
  1107. errors: {
  1108. conference: JitsiConferenceErrors,
  1109. connection: JitsiConnectionErrors,
  1110. track: JitsiTrackErrors
  1111. },
  1112. logLevels: Logger.levels,
  1113. init: function (options) {
  1114. return RTC.init(options || {});
  1115. },
  1116. /**
  1117. * Returns whether the desktop sharing is enabled or not.
  1118. * @returns {boolean}
  1119. */
  1120. isDesktopSharingEnabled: function () {
  1121. return RTC.isDesktopSharingEnabled();
  1122. },
  1123. setLogLevel: function (level) {
  1124. Logger.setLogLevel(level);
  1125. },
  1126. /**
  1127. * Creates the media tracks and returns them trough the callback.
  1128. * @param options Object with properties / settings specifying the tracks which should be created.
  1129. * should be created or some additional configurations about resolution for example.
  1130. * @param {Array} options.devices the devices that will be requested
  1131. * @param {string} options.resolution resolution constraints
  1132. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1133. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1134. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1135. * @param {string} options.cameraDeviceId
  1136. * @param {string} options.micDeviceId
  1137. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1138. * A promise that returns an array of created JitsiTracks if resolved,
  1139. * or a JitsiConferenceError if rejected.
  1140. */
  1141. createLocalTracks: function (options) {
  1142. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1143. function(tracks) {
  1144. if(!RTC.options.disableAudioLevels)
  1145. for(var i = 0; i < tracks.length; i++) {
  1146. var track = tracks[i];
  1147. var mStream = track.getOriginalStream();
  1148. if(track.getType() === "audio"){
  1149. Statistics.startLocalStats(mStream,
  1150. track.setAudioLevel.bind(track));
  1151. track.addEventListener(
  1152. JitsiTrackEvents.TRACK_STOPPED,
  1153. function(){
  1154. Statistics.stopLocalStats(mStream);
  1155. });
  1156. }
  1157. }
  1158. return tracks;
  1159. }).catch(function (error) {
  1160. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1161. var oldResolution = options.resolution || '360';
  1162. var newResolution = getLowerResolution(oldResolution);
  1163. if(newResolution === null)
  1164. return Promise.reject(error);
  1165. options.resolution = newResolution;
  1166. return LibJitsiMeet.createLocalTracks(options);
  1167. }
  1168. return Promise.reject(error);
  1169. });
  1170. },
  1171. /**
  1172. * Checks if its possible to enumerate available cameras/micropones.
  1173. * @returns {boolean} true if available, false otherwise.
  1174. */
  1175. isDeviceListAvailable: function () {
  1176. return RTC.isDeviceListAvailable();
  1177. },
  1178. /**
  1179. * Returns true if changing the camera / microphone device is supported and
  1180. * false if not.
  1181. * @returns {boolean} true if available, false otherwise.
  1182. */
  1183. isDeviceChangeAvailable: function () {
  1184. return RTC.isDeviceChangeAvailable();
  1185. },
  1186. enumerateDevices: function (callback) {
  1187. RTC.enumerateDevices(callback);
  1188. }
  1189. };
  1190. require("es6-promise").polyfill()
  1191. //Setups the promise object.
  1192. window.Promise = window.Promise || require("es6-promise").Promise;
  1193. module.exports = LibJitsiMeet;
  1194. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/Resolutions":81,"es6-promise":46,"jitsi-meet-logger":48}],8:[function(require,module,exports){
  1195. /* global Strophe */
  1196. /**
  1197. * Represents a participant in (a member of) a conference.
  1198. */
  1199. function JitsiParticipant(jid, conference, displayName){
  1200. this._jid = jid;
  1201. this._id = Strophe.getResourceFromJid(jid);
  1202. this._conference = conference;
  1203. this._displayName = displayName;
  1204. this._supportsDTMF = false;
  1205. this._tracks = [];
  1206. this._role = 'none';
  1207. }
  1208. /**
  1209. * @returns {JitsiConference} The conference that this participant belongs to.
  1210. */
  1211. JitsiParticipant.prototype.getConference = function() {
  1212. return this._conference;
  1213. };
  1214. /**
  1215. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1216. */
  1217. JitsiParticipant.prototype.getTracks = function() {
  1218. return this._tracks;
  1219. };
  1220. /**
  1221. * @returns {String} The ID of this participant.
  1222. */
  1223. JitsiParticipant.prototype.getId = function() {
  1224. return this._id;
  1225. };
  1226. /**
  1227. * @returns {String} The JID of this participant.
  1228. */
  1229. JitsiParticipant.prototype.getJid = function() {
  1230. return this._jid;
  1231. };
  1232. /**
  1233. * @returns {String} The human-readable display name of this participant.
  1234. */
  1235. JitsiParticipant.prototype.getDisplayName = function() {
  1236. return this._displayName;
  1237. };
  1238. /**
  1239. * @returns {Boolean} Whether this participant is a moderator or not.
  1240. */
  1241. JitsiParticipant.prototype.isModerator = function() {
  1242. return this._role === 'moderator';
  1243. };
  1244. // Gets a link to an etherpad instance advertised by the participant?
  1245. //JitsiParticipant.prototype.getEtherpad = function() {
  1246. //
  1247. //}
  1248. /*
  1249. * @returns {Boolean} Whether this participant has muted their audio.
  1250. */
  1251. JitsiParticipant.prototype.isAudioMuted = function() {
  1252. return this.getTracks().reduce(function (track, isAudioMuted) {
  1253. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1254. }, true);
  1255. };
  1256. /*
  1257. * @returns {Boolean} Whether this participant has muted their video.
  1258. */
  1259. JitsiParticipant.prototype.isVideoMuted = function() {
  1260. return this.getTracks().reduce(function (track, isVideoMuted) {
  1261. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1262. }, true);
  1263. };
  1264. /*
  1265. * @returns {???} The latest statistics reported by this participant
  1266. * (i.e. info used to populate the GSM bars)
  1267. * TODO: do we expose this or handle it internally?
  1268. */
  1269. JitsiParticipant.prototype.getLatestStats = function() {
  1270. };
  1271. /**
  1272. * @returns {String} The role of this participant.
  1273. */
  1274. JitsiParticipant.prototype.getRole = function() {
  1275. return this._role;
  1276. };
  1277. /*
  1278. * @returns {Boolean} Whether this participant is
  1279. * the conference focus (i.e. jicofo).
  1280. */
  1281. JitsiParticipant.prototype.isFocus = function() {
  1282. };
  1283. /*
  1284. * @returns {Boolean} Whether this participant is
  1285. * a conference recorder (i.e. jirecon).
  1286. */
  1287. JitsiParticipant.prototype.isRecorder = function() {
  1288. };
  1289. /*
  1290. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1291. */
  1292. JitsiParticipant.prototype.isSipGateway = function() {
  1293. };
  1294. /**
  1295. * @returns {Boolean} Whether this participant
  1296. * is currently sharing their screen.
  1297. */
  1298. JitsiParticipant.prototype.isScreenSharing = function() {
  1299. };
  1300. /**
  1301. * @returns {String} The user agent of this participant
  1302. * (i.e. browser userAgent string).
  1303. */
  1304. JitsiParticipant.prototype.getUserAgent = function() {
  1305. };
  1306. /**
  1307. * Kicks the participant from the conference (requires certain privileges).
  1308. */
  1309. JitsiParticipant.prototype.kick = function() {
  1310. };
  1311. /**
  1312. * Asks this participant to mute themselves.
  1313. */
  1314. JitsiParticipant.prototype.askToMute = function() {
  1315. };
  1316. JitsiParticipant.prototype.supportsDTMF = function () {
  1317. return this._supportsDTMF;
  1318. };
  1319. module.exports = JitsiParticipant;
  1320. },{}],9:[function(require,module,exports){
  1321. module.exports = {
  1322. /**
  1323. * Returns JitsiTrackErrors based on the error object passed by GUM
  1324. * @param error the error
  1325. * @param {Array} devices Array with the requested devices
  1326. */
  1327. parseError: function (error, devices) {
  1328. devices = devices || [];
  1329. if (typeof error == "object" && error.constraintName && error.name
  1330. && (error.name == "ConstraintNotSatisfiedError" ||
  1331. error.name == "OverconstrainedError") &&
  1332. (error.constraintName == "minWidth" ||
  1333. error.constraintName == "maxWidth" ||
  1334. error.constraintName == "minHeight" ||
  1335. error.constraintName == "maxHeight") &&
  1336. devices.indexOf("video") !== -1) {
  1337. return this.UNSUPPORTED_RESOLUTION;
  1338. } else {
  1339. return this.GENERAL;
  1340. }
  1341. },
  1342. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1343. GENERAL: "gum.general"
  1344. };
  1345. },{}],10:[function(require,module,exports){
  1346. var JitsiTrackEvents = {
  1347. /**
  1348. * A media track mute status was changed.
  1349. */
  1350. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1351. /**
  1352. * Audio levels of a this track was changed.
  1353. */
  1354. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1355. /**
  1356. * The media track was removed to the conference.
  1357. */
  1358. TRACK_STOPPED: "track.stopped"
  1359. };
  1360. module.exports = JitsiTrackEvents;
  1361. },{}],11:[function(require,module,exports){
  1362. (function (__filename){
  1363. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1364. function JitsiDTMFManager (localAudio, peerConnection) {
  1365. var tracks = localAudio._getTracks();
  1366. if (!tracks.length) {
  1367. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1368. }
  1369. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1370. logger.debug("Initialized DTMFSender");
  1371. }
  1372. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1373. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1374. };
  1375. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1376. },{"jitsi-meet-logger":48}],12:[function(require,module,exports){
  1377. (function (__filename){
  1378. /* global config, APP, Strophe */
  1379. // cache datachannels to avoid garbage collection
  1380. // https://code.google.com/p/chromium/issues/detail?id=405545
  1381. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1382. var RTCEvents = require("../../service/RTC/RTCEvents");
  1383. /**
  1384. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1385. * @param peerConnection WebRTC peer connection instance.
  1386. */
  1387. function DataChannels(peerConnection, emitter) {
  1388. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1389. this.eventEmitter = emitter;
  1390. this._dataChannels = [];
  1391. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1392. // Although it's not a requirement to open separate channels from both bridge
  1393. // and peer as single channel can be used for sending and receiving data.
  1394. // So either channel opened by the bridge or the one opened here is enough
  1395. // for communication with the bridge.
  1396. /*var dataChannelOptions =
  1397. {
  1398. reliable: true
  1399. };
  1400. var dataChannel
  1401. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1402. // Can be used only when is in open state
  1403. dataChannel.onopen = function ()
  1404. {
  1405. dataChannel.send("My channel !!!");
  1406. };
  1407. dataChannel.onmessage = function (event)
  1408. {
  1409. var msgData = event.data;
  1410. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1411. };*/
  1412. };
  1413. /**
  1414. * Callback triggered by PeerConnection when new data channel is opened
  1415. * on the bridge.
  1416. * @param event the event info object.
  1417. */
  1418. DataChannels.prototype.onDataChannel = function (event) {
  1419. var dataChannel = event.channel;
  1420. var self = this;
  1421. dataChannel.onopen = function () {
  1422. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1423. // Code sample for sending string and/or binary data
  1424. // Sends String message to the bridge
  1425. //dataChannel.send("Hello bridge!");
  1426. // Sends 12 bytes binary message to the bridge
  1427. //dataChannel.send(new ArrayBuffer(12));
  1428. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1429. };
  1430. dataChannel.onerror = function (error) {
  1431. logger.error("Data Channel Error:", error, dataChannel);
  1432. };
  1433. dataChannel.onmessage = function (event) {
  1434. var data = event.data;
  1435. // JSON
  1436. var obj;
  1437. try {
  1438. obj = JSON.parse(data);
  1439. }
  1440. catch (e) {
  1441. logger.error(
  1442. "Failed to parse data channel message as JSON: ",
  1443. data,
  1444. dataChannel);
  1445. }
  1446. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1447. var colibriClass = obj.colibriClass;
  1448. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1449. // Endpoint ID from the Videobridge.
  1450. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1451. logger.info(
  1452. "Data channel new dominant speaker event: ",
  1453. dominantSpeakerEndpoint);
  1454. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1455. }
  1456. else if ("InLastNChangeEvent" === colibriClass) {
  1457. var oldValue = obj.oldValue;
  1458. var newValue = obj.newValue;
  1459. // Make sure that oldValue and newValue are of type boolean.
  1460. var type;
  1461. if ((type = typeof oldValue) !== 'boolean') {
  1462. if (type === 'string') {
  1463. oldValue = (oldValue == "true");
  1464. } else {
  1465. oldValue = new Boolean(oldValue).valueOf();
  1466. }
  1467. }
  1468. if ((type = typeof newValue) !== 'boolean') {
  1469. if (type === 'string') {
  1470. newValue = (newValue == "true");
  1471. } else {
  1472. newValue = new Boolean(newValue).valueOf();
  1473. }
  1474. }
  1475. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1476. }
  1477. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1478. // The new/latest list of last-n endpoint IDs.
  1479. var lastNEndpoints = obj.lastNEndpoints;
  1480. // The list of endpoint IDs which are entering the list of
  1481. // last-n at this time i.e. were not in the old list of last-n
  1482. // endpoint IDs.
  1483. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1484. logger.info(
  1485. "Data channel new last-n event: ",
  1486. lastNEndpoints, endpointsEnteringLastN, obj);
  1487. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1488. lastNEndpoints, endpointsEnteringLastN, obj);
  1489. }
  1490. else {
  1491. logger.debug("Data channel JSON-formatted message: ", obj);
  1492. // The received message appears to be appropriately formatted
  1493. // (i.e. is a JSON object which assigns a value to the mandatory
  1494. // property colibriClass) so don't just swallow it, expose it to
  1495. // public consumption.
  1496. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1497. }
  1498. }
  1499. };
  1500. dataChannel.onclose = function () {
  1501. logger.info("The Data Channel closed", dataChannel);
  1502. var idx = self._dataChannels.indexOf(dataChannel);
  1503. if (idx > -1)
  1504. self._dataChannels = self._dataChannels.splice(idx, 1);
  1505. };
  1506. this._dataChannels.push(dataChannel);
  1507. };
  1508. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1509. this._onXXXEndpointChanged("selected", userResource);
  1510. }
  1511. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1512. this._onXXXEndpointChanged("pinnned", userResource);
  1513. }
  1514. /**
  1515. * Notifies Videobridge about a change in the value of a specific
  1516. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1517. *
  1518. * @param xxx the name of the endpoint-related property whose value changed
  1519. * @param userResource the new value of the endpoint-related property after the
  1520. * change
  1521. */
  1522. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1523. // Derive the correct words from xxx such as selected and Selected, pinned
  1524. // and Pinned.
  1525. var head = xxx.charAt(0);
  1526. var tail = xxx.substring(1);
  1527. var lower = head.toLowerCase() + tail;
  1528. var upper = head.toUpperCase() + tail;
  1529. // Notify Videobridge about the specified endpoint change.
  1530. console.log(lower + ' endpoint changed: ', userResource);
  1531. this._some(function (dataChannel) {
  1532. if (dataChannel.readyState == 'open') {
  1533. console.log(
  1534. 'sending ' + lower
  1535. + ' endpoint changed notification to the bridge: ',
  1536. userResource);
  1537. var jsonObject = {};
  1538. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1539. jsonObject[lower + "Endpoint"]
  1540. = (userResource ? userResource : null);
  1541. dataChannel.send(JSON.stringify(jsonObject));
  1542. return true;
  1543. }
  1544. });
  1545. }
  1546. DataChannels.prototype._some = function (callback, thisArg) {
  1547. var dataChannels = this._dataChannels;
  1548. if (dataChannels && dataChannels.length !== 0) {
  1549. if (thisArg)
  1550. return dataChannels.some(callback, thisArg);
  1551. else
  1552. return dataChannels.some(callback);
  1553. } else {
  1554. return false;
  1555. }
  1556. }
  1557. module.exports = DataChannels;
  1558. }).call(this,"/modules/RTC/DataChannels.js")
  1559. },{"../../service/RTC/RTCEvents":80,"jitsi-meet-logger":48}],13:[function(require,module,exports){
  1560. var JitsiTrack = require("./JitsiTrack");
  1561. var RTCBrowserType = require("./RTCBrowserType");
  1562. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1563. var RTCUtils = require("./RTCUtils");
  1564. /**
  1565. * Represents a single media track (either audio or video).
  1566. * @constructor
  1567. */
  1568. function JitsiLocalTrack(stream, videoType,
  1569. resolution)
  1570. {
  1571. this.videoType = videoType;
  1572. this.dontFireRemoveEvent = false;
  1573. this.resolution = resolution;
  1574. this.startMuted = false;
  1575. var self = this;
  1576. JitsiTrack.call(this, null, stream,
  1577. function () {
  1578. if(!this.dontFireRemoveEvent)
  1579. this.eventEmitter.emit(
  1580. JitsiTrackEvents.TRACK_STOPPED);
  1581. this.dontFireRemoveEvent = false;
  1582. }.bind(this));
  1583. }
  1584. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1585. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1586. /**
  1587. * Mutes / unmutes the track.
  1588. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1589. */
  1590. JitsiLocalTrack.prototype._setMute = function (mute) {
  1591. if (this.isMuted() === mute) {
  1592. return;
  1593. }
  1594. if(!this.rtc) {
  1595. this.startMuted = mute;
  1596. return;
  1597. }
  1598. var isAudio = this.type === JitsiTrack.AUDIO;
  1599. this.dontFireRemoveEvent = false;
  1600. if ((window.location.protocol != "https:") ||
  1601. (isAudio) || this.videoType === "desktop" ||
  1602. // FIXME FF does not support 'removeStream' method used to mute
  1603. RTCBrowserType.isFirefox()) {
  1604. var tracks = this._getTracks();
  1605. for (var idx = 0; idx < tracks.length; idx++) {
  1606. tracks[idx].enabled = !mute;
  1607. }
  1608. if(isAudio)
  1609. this.rtc.room.setAudioMute(mute);
  1610. else
  1611. this.rtc.room.setVideoMute(mute);
  1612. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1613. } else {
  1614. if (mute) {
  1615. this.dontFireRemoveEvent = true;
  1616. this.rtc.room.removeStream(this.stream, function () {});
  1617. RTCUtils.stopMediaStream(this.stream);
  1618. if(isAudio)
  1619. this.rtc.room.setAudioMute(mute);
  1620. else
  1621. this.rtc.room.setVideoMute(mute);
  1622. this.stream = null;
  1623. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1624. //FIXME: Maybe here we should set the SRC for the containers to something
  1625. } else {
  1626. var self = this;
  1627. RTCUtils.obtainAudioAndVideoPermissions({
  1628. devices: (isAudio ? ["audio"] : ["video"]),
  1629. resolution: self.resolution})
  1630. .then(function (streams) {
  1631. var stream = null;
  1632. for(var i = 0; i < streams.length; i++) {
  1633. stream = streams[i];
  1634. if(stream.type === self.type) {
  1635. self.stream = stream.stream;
  1636. self.videoType = stream.videoType;
  1637. break;
  1638. }
  1639. }
  1640. if(!stream)
  1641. return;
  1642. for(var i = 0; i < self.containers.length; i++)
  1643. {
  1644. RTCUtils.attachMediaStream(
  1645. self.containers[i], self.stream);
  1646. }
  1647. self.rtc.room.addStream(stream.stream,
  1648. function () {
  1649. if(isAudio)
  1650. self.rtc.room.setAudioMute(mute);
  1651. else
  1652. self.rtc.room.setVideoMute(mute);
  1653. self.eventEmitter.emit(
  1654. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1655. });
  1656. });
  1657. }
  1658. }
  1659. }
  1660. /**
  1661. * Stops sending the media track. And removes it from the HTML.
  1662. * NOTE: Works for local tracks only.
  1663. */
  1664. JitsiLocalTrack.prototype.stop = function () {
  1665. if(!this.stream)
  1666. return;
  1667. if(this.rtc)
  1668. this.rtc.room.removeStream(this.stream, function () {});
  1669. RTCUtils.stopMediaStream(this.stream);
  1670. this.detach();
  1671. }
  1672. /**
  1673. * Returns <tt>true</tt> - if the stream is muted
  1674. * and <tt>false</tt> otherwise.
  1675. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1676. * and <tt>false</tt> otherwise.
  1677. */
  1678. JitsiLocalTrack.prototype.isMuted = function () {
  1679. if (!this.stream)
  1680. return true;
  1681. var tracks = [];
  1682. var isAudio = this.type === JitsiTrack.AUDIO;
  1683. if (isAudio) {
  1684. tracks = this.stream.getAudioTracks();
  1685. } else {
  1686. if (!this.isActive())
  1687. return true;
  1688. tracks = this.stream.getVideoTracks();
  1689. }
  1690. for (var idx = 0; idx < tracks.length; idx++) {
  1691. if(tracks[idx].enabled)
  1692. return false;
  1693. }
  1694. return true;
  1695. };
  1696. /**
  1697. * Private method. Updates rtc property of the track.
  1698. * @param rtc the rtc instance.
  1699. */
  1700. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1701. this.rtc = rtc;
  1702. };
  1703. /**
  1704. * Return true;
  1705. */
  1706. JitsiLocalTrack.prototype.isLocal = function () {
  1707. return true;
  1708. }
  1709. module.exports = JitsiLocalTrack;
  1710. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1711. var JitsiTrack = require("./JitsiTrack");
  1712. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1713. /**
  1714. * Represents a single media track (either audio or video).
  1715. * @param RTC the rtc instance.
  1716. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1717. * @param sid sid for the Media Stream
  1718. * @param ssrc ssrc for the Media Stream
  1719. * @param eventEmitter the event emitter
  1720. * @constructor
  1721. */
  1722. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1723. JitsiTrack.call(this, RTC, data.stream,
  1724. function () {
  1725. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1726. }.bind(this));
  1727. this.rtc = RTC;
  1728. this.sid = sid;
  1729. this.stream = data.stream;
  1730. this.peerjid = data.peerjid;
  1731. this.videoType = data.videoType;
  1732. this.ssrc = ssrc;
  1733. this.muted = false;
  1734. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1735. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1736. this.muted = true;
  1737. }
  1738. }
  1739. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1740. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1741. /**
  1742. * Sets current muted status and fires an events for the change.
  1743. * @param value the muted status.
  1744. */
  1745. JitsiRemoteTrack.prototype.setMute = function (value) {
  1746. this.stream.muted = value;
  1747. this.muted = value;
  1748. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1749. };
  1750. /**
  1751. * Returns the current muted status of the track.
  1752. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1753. */
  1754. JitsiRemoteTrack.prototype.isMuted = function () {
  1755. return this.muted;
  1756. };
  1757. /**
  1758. * Returns the participant id which owns the track.
  1759. * @returns {string} the id of the participants.
  1760. */
  1761. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1762. return Strophe.getResourceFromJid(this.peerjid);
  1763. };
  1764. /**
  1765. * Return false;
  1766. */
  1767. JitsiRemoteTrack.prototype.isLocal = function () {
  1768. return false;
  1769. };
  1770. delete JitsiRemoteTrack.prototype.stop;
  1771. delete JitsiRemoteTrack.prototype.start;
  1772. module.exports = JitsiRemoteTrack;
  1773. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1774. var RTCBrowserType = require("./RTCBrowserType");
  1775. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1776. var EventEmitter = require("events");
  1777. var RTC = require("./RTCUtils");
  1778. /**
  1779. * This implements 'onended' callback normally fired by WebRTC after the stream
  1780. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1781. * @param jitsiTrack our track object holding the original WebRTC stream object
  1782. * to which 'onended' handling will be added.
  1783. */
  1784. function implementOnEndedHandling(jitsiTrack) {
  1785. var stream = jitsiTrack.getOriginalStream();
  1786. var originalStop = stream.stop;
  1787. stream.stop = function () {
  1788. originalStop.apply(stream);
  1789. if (jitsiTrack.isActive()) {
  1790. stream.onended();
  1791. }
  1792. };
  1793. }
  1794. /**
  1795. * Adds onended/oninactive handler to a MediaStream.
  1796. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1797. * @param handler the handler
  1798. */
  1799. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1800. if(RTCBrowserType.isTemasysPluginUsed()) {
  1801. // themasys
  1802. //FIXME: Seems that not working properly.
  1803. if(mediaStream.onended) {
  1804. mediaStream.onended = handler;
  1805. } else if(mediaStream.addEventListener) {
  1806. mediaStream.addEventListener('ended', function () {
  1807. handler(mediaStream);
  1808. });
  1809. } else if(mediaStream.attachEvent) {
  1810. mediaStream.attachEvent('ended', function () {
  1811. handler(mediaStream);
  1812. });
  1813. }
  1814. }
  1815. else {
  1816. if(typeof mediaStream.active !== "undefined")
  1817. mediaStream.oninactive = handler;
  1818. else
  1819. mediaStream.onended = handler;
  1820. }
  1821. }
  1822. /**
  1823. * Represents a single media track (either audio or video).
  1824. * @constructor
  1825. * @param rtc the rtc instance
  1826. * @param stream the stream
  1827. * @param streamInactiveHandler the function that will handle
  1828. * onended/oninactive events of the stream.
  1829. */
  1830. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1831. {
  1832. /**
  1833. * Array with the HTML elements that are displaying the streams.
  1834. * @type {Array}
  1835. */
  1836. this.containers = [];
  1837. this.rtc = rtc;
  1838. this.stream = stream;
  1839. this.eventEmitter = new EventEmitter();
  1840. this.audioLevel = -1;
  1841. this.type = (this.stream.getVideoTracks().length > 0)?
  1842. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1843. if(this.type == "audio") {
  1844. this._getTracks = function () {
  1845. return this.stream.getAudioTracks();
  1846. }.bind(this);
  1847. } else {
  1848. this._getTracks = function () {
  1849. return this.stream.getVideoTracks();
  1850. }.bind(this);
  1851. }
  1852. if (RTCBrowserType.isFirefox() && this.stream) {
  1853. implementOnEndedHandling(this);
  1854. }
  1855. if(stream)
  1856. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1857. }
  1858. /**
  1859. * JitsiTrack video type.
  1860. * @type {string}
  1861. */
  1862. JitsiTrack.VIDEO = "video";
  1863. /**
  1864. * JitsiTrack audio type.
  1865. * @type {string}
  1866. */
  1867. JitsiTrack.AUDIO = "audio";
  1868. /**
  1869. * Returns the type (audio or video) of this track.
  1870. */
  1871. JitsiTrack.prototype.getType = function() {
  1872. return this.type;
  1873. };
  1874. /**
  1875. * Check if this is audiotrack.
  1876. */
  1877. JitsiTrack.prototype.isAudioTrack = function () {
  1878. return this.getType() === JitsiTrack.AUDIO;
  1879. };
  1880. /**
  1881. * Check if this is videotrack.
  1882. */
  1883. JitsiTrack.prototype.isVideoTrack = function () {
  1884. return this.getType() === JitsiTrack.VIDEO;
  1885. };
  1886. /**
  1887. * Returns the RTCMediaStream from the browser (?).
  1888. */
  1889. JitsiTrack.prototype.getOriginalStream = function() {
  1890. return this.stream;
  1891. }
  1892. /**
  1893. * Mutes the track.
  1894. */
  1895. JitsiTrack.prototype.mute = function () {
  1896. this._setMute(true);
  1897. }
  1898. /**
  1899. * Unmutes the stream.
  1900. */
  1901. JitsiTrack.prototype.unmute = function () {
  1902. this._setMute(false);
  1903. }
  1904. /**
  1905. * Attaches the MediaStream of this track to an HTML container (?).
  1906. * Adds the container to the list of containers that are displaying the track.
  1907. * @param container the HTML container
  1908. */
  1909. JitsiTrack.prototype.attach = function (container) {
  1910. if(this.stream)
  1911. require("./RTCUtils").attachMediaStream(container, this.stream);
  1912. this.containers.push(container);
  1913. }
  1914. /**
  1915. * Removes the track from the passed HTML container.
  1916. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1917. */
  1918. JitsiTrack.prototype.detach = function (container) {
  1919. for(var i = 0; i < this.containers.length; i++)
  1920. {
  1921. if(this.containers[i].is(container))
  1922. {
  1923. this.containers.splice(i,1);
  1924. }
  1925. if(!container)
  1926. {
  1927. this.containers[i].find(">video").remove();
  1928. }
  1929. }
  1930. if(container)
  1931. $(container).find(">video").remove();
  1932. }
  1933. /**
  1934. * Stops sending the media track. And removes it from the HTML.
  1935. * NOTE: Works for local tracks only.
  1936. */
  1937. JitsiTrack.prototype.stop = function () {
  1938. }
  1939. /**
  1940. * Returns true if this is a video track and the source of the video is a
  1941. * screen capture as opposed to a camera.
  1942. */
  1943. JitsiTrack.prototype.isScreenSharing = function(){
  1944. }
  1945. /**
  1946. * Returns id of the track.
  1947. * @returns {string} id of the track or null if this is fake track.
  1948. */
  1949. JitsiTrack.prototype._getId = function () {
  1950. var tracks = this.stream.getTracks();
  1951. if(!tracks || tracks.length === 0)
  1952. return null;
  1953. return tracks[0].id;
  1954. };
  1955. /**
  1956. * Returns id of the track.
  1957. * @returns {string} id of the track or null if this is fake track.
  1958. */
  1959. JitsiTrack.prototype.getId = function () {
  1960. return RTC.getStreamID(this.stream);
  1961. };
  1962. /**
  1963. * Checks whether the MediaStream is avtive/not ended.
  1964. * When there is no check for active we don't have information and so
  1965. * will return that stream is active (in case of FF).
  1966. * @returns {boolean} whether MediaStream is active.
  1967. */
  1968. JitsiTrack.prototype.isActive = function () {
  1969. if((typeof this.stream.active !== "undefined"))
  1970. return this.stream.active;
  1971. else
  1972. return true;
  1973. };
  1974. /**
  1975. * Attaches a handler for events(For example - "audio level changed".).
  1976. * All possible event are defined in JitsiTrackEvents.
  1977. * @param eventId the event ID.
  1978. * @param handler handler for the event.
  1979. */
  1980. JitsiTrack.prototype.on = function (eventId, handler) {
  1981. if(this.eventEmitter)
  1982. this.eventEmitter.on(eventId, handler);
  1983. }
  1984. /**
  1985. * Removes event listener
  1986. * @param eventId the event ID.
  1987. * @param [handler] optional, the specific handler to unbind
  1988. */
  1989. JitsiTrack.prototype.off = function (eventId, handler) {
  1990. if(this.eventEmitter)
  1991. this.eventEmitter.removeListener(eventId, handler);
  1992. }
  1993. // Common aliases for event emitter
  1994. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1995. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1996. /**
  1997. * Sets the audio level for the stream
  1998. * @param audioLevel the new audio level
  1999. */
  2000. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2001. if(this.audioLevel !== audioLevel) {
  2002. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2003. audioLevel);
  2004. this.audioLevel = audioLevel;
  2005. }
  2006. }
  2007. module.exports = JitsiTrack;
  2008. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":44}],16:[function(require,module,exports){
  2009. /* global APP */
  2010. var EventEmitter = require("events");
  2011. var RTCBrowserType = require("./RTCBrowserType");
  2012. var RTCUtils = require("./RTCUtils.js");
  2013. var JitsiTrack = require("./JitsiTrack");
  2014. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2015. var DataChannels = require("./DataChannels");
  2016. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2017. var DesktopSharingEventTypes
  2018. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2019. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2020. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2021. function createLocalTracks(streams) {
  2022. var newStreams = []
  2023. for (var i = 0; i < streams.length; i++) {
  2024. var localStream = new JitsiLocalTrack(streams[i].stream,
  2025. streams[i].videoType, streams[i].resolution);
  2026. newStreams.push(localStream);
  2027. if (streams[i].isMuted === true)
  2028. localStream.setMute(true);
  2029. }
  2030. return newStreams;
  2031. }
  2032. function RTC(room, options) {
  2033. this.room = room;
  2034. this.localStreams = [];
  2035. //FIXME: we should start removing those streams.
  2036. //FIXME: We should support multiple streams per jid.
  2037. this.remoteStreams = {};
  2038. this.localAudio = null;
  2039. this.localVideo = null;
  2040. this.eventEmitter = new EventEmitter();
  2041. var self = this;
  2042. this.options = options || {};
  2043. room.addPresenceListener("videomuted", function (values, from) {
  2044. if(self.remoteStreams[from]) {
  2045. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  2046. }
  2047. });
  2048. room.addPresenceListener("audiomuted", function (values, from) {
  2049. if(self.remoteStreams[from]) {
  2050. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  2051. }
  2052. });
  2053. }
  2054. /**
  2055. * Creates the local MediaStreams.
  2056. * @param {Object} [options] optional parameters
  2057. * @param {Array} options.devices the devices that will be requested
  2058. * @param {string} options.resolution resolution constraints
  2059. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2060. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2061. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2062. * @param {string} options.cameraDeviceId
  2063. * @param {string} options.micDeviceId
  2064. * @returns {*} Promise object that will receive the new JitsiTracks
  2065. */
  2066. RTC.obtainAudioAndVideoPermissions = function (options) {
  2067. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  2068. }
  2069. RTC.prototype.onIncommingCall = function(event) {
  2070. if(this.options.config.openSctp)
  2071. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2072. for(var i = 0; i < this.localStreams.length; i++)
  2073. if(this.localStreams[i])
  2074. {
  2075. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2076. }
  2077. }
  2078. RTC.prototype.selectedEndpoint = function (id) {
  2079. if(this.dataChannels)
  2080. this.dataChannels.handleSelectedEndpointEvent(id);
  2081. }
  2082. RTC.prototype.pinEndpoint = function (id) {
  2083. if(this.dataChannels)
  2084. this.dataChannels.handlePinnedEndpointEvent(id);
  2085. }
  2086. RTC.prototype.addListener = function (type, listener) {
  2087. this.eventEmitter.on(type, listener);
  2088. };
  2089. RTC.prototype.removeListener = function (eventType, listener) {
  2090. this.eventEmitter.removeListener(eventType, listener);
  2091. };
  2092. RTC.addListener = function (eventType, listener) {
  2093. RTCUtils.addListener(eventType, listener);
  2094. }
  2095. RTC.removeListener = function (eventType, listener) {
  2096. RTCUtils.removeListener(eventType, listener)
  2097. }
  2098. RTC.isRTCReady = function () {
  2099. return RTCUtils.isRTCReady();
  2100. }
  2101. RTC.init = function (options) {
  2102. this.options = options || {};
  2103. return RTCUtils.init(this.options);
  2104. }
  2105. RTC.getDeviceAvailability = function () {
  2106. return RTCUtils.getDeviceAvailability();
  2107. }
  2108. RTC.prototype.addLocalStream = function (stream) {
  2109. this.localStreams.push(stream);
  2110. stream._setRTC(this);
  2111. if (stream.type == "audio") {
  2112. this.localAudio = stream;
  2113. } else {
  2114. this.localVideo = stream;
  2115. }
  2116. };
  2117. /**
  2118. * Set mute for all local audio streams attached to the conference.
  2119. * @param value the mute value
  2120. */
  2121. RTC.prototype.setAudioMute = function (value) {
  2122. for(var i = 0; i < this.localStreams.length; i++) {
  2123. var stream = this.localStreams[i];
  2124. if(stream.getType() !== "audio") {
  2125. continue;
  2126. }
  2127. stream._setMute(value);
  2128. }
  2129. }
  2130. RTC.prototype.removeLocalStream = function (stream) {
  2131. for(var i = 0; i < this.localStreams.length; i++) {
  2132. if(this.localStreams[i].getOriginalStream() === stream) {
  2133. delete this.localStreams[i];
  2134. return;
  2135. }
  2136. }
  2137. };
  2138. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2139. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2140. if(!data.peerjid)
  2141. return;
  2142. var jid = Strophe.getResourceFromJid(data.peerjid);
  2143. if(!this.remoteStreams[jid]) {
  2144. this.remoteStreams[jid] = {};
  2145. }
  2146. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2147. return remoteStream;
  2148. };
  2149. RTC.getPCConstraints = function () {
  2150. return RTCUtils.pc_constraints;
  2151. };
  2152. RTC.attachMediaStream = function (elSelector, stream) {
  2153. RTCUtils.attachMediaStream(elSelector, stream);
  2154. };
  2155. RTC.getStreamID = function (stream) {
  2156. return RTCUtils.getStreamID(stream);
  2157. };
  2158. RTC.getVideoSrc = function (element) {
  2159. return RTCUtils.getVideoSrc(element);
  2160. };
  2161. /**
  2162. * Returns true if retrieving the the list of input devices is supported and
  2163. * false if not.
  2164. */
  2165. RTC.isDeviceListAvailable = function () {
  2166. return RTCUtils.isDeviceListAvailable();
  2167. };
  2168. /**
  2169. * Returns true if changing the camera / microphone device is supported and
  2170. * false if not.
  2171. */
  2172. RTC.isDeviceChangeAvailable = function () {
  2173. return RTCUtils.isDeviceChangeAvailable();
  2174. }
  2175. /**
  2176. * Allows to receive list of available cameras/microphones.
  2177. * @param {function} callback would receive array of devices as an argument
  2178. */
  2179. RTC.enumerateDevices = function (callback) {
  2180. RTCUtils.enumerateDevices(callback);
  2181. };
  2182. RTC.setVideoSrc = function (element, src) {
  2183. RTCUtils.setVideoSrc(element, src);
  2184. };
  2185. /**
  2186. * A method to handle stopping of the stream.
  2187. * One point to handle the differences in various implementations.
  2188. * @param mediaStream MediaStream object to stop.
  2189. */
  2190. RTC.stopMediaStream = function (mediaStream) {
  2191. RTCUtils.stopMediaStream(mediaStream);
  2192. };
  2193. /**
  2194. * Returns whether the desktop sharing is enabled or not.
  2195. * @returns {boolean}
  2196. */
  2197. RTC.isDesktopSharingEnabled = function () {
  2198. return RTCUtils.isDesktopSharingEnabled();
  2199. }
  2200. RTC.prototype.getVideoElementName = function () {
  2201. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2202. };
  2203. RTC.prototype.dispose = function() {
  2204. };
  2205. RTC.prototype.switchVideoStreams = function (newStream) {
  2206. this.localVideo.stream = newStream;
  2207. this.localStreams = [];
  2208. //in firefox we have only one stream object
  2209. if (this.localAudio.getOriginalStream() != newStream)
  2210. this.localStreams.push(this.localAudio);
  2211. this.localStreams.push(this.localVideo);
  2212. };
  2213. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2214. if(!jid)
  2215. return;
  2216. var resource = Strophe.getResourceFromJid(jid);
  2217. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2218. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2219. }
  2220. module.exports = RTC;
  2221. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/RTCEvents.js":80,"../../service/desktopsharing/DesktopSharingEventTypes":84,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":44}],17:[function(require,module,exports){
  2222. var currentBrowser;
  2223. var browserVersion;
  2224. var isAndroid;
  2225. var RTCBrowserType = {
  2226. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2227. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2228. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2229. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2230. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2231. getBrowserType: function () {
  2232. return currentBrowser;
  2233. },
  2234. isChrome: function () {
  2235. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2236. },
  2237. isOpera: function () {
  2238. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2239. },
  2240. isFirefox: function () {
  2241. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2242. },
  2243. isIExplorer: function () {
  2244. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2245. },
  2246. isSafari: function () {
  2247. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2248. },
  2249. isTemasysPluginUsed: function () {
  2250. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2251. },
  2252. getFirefoxVersion: function () {
  2253. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2254. },
  2255. getChromeVersion: function () {
  2256. return RTCBrowserType.isChrome() ? browserVersion : null;
  2257. },
  2258. usesPlanB: function() {
  2259. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2260. RTCBrowserType.isTemasysPluginUsed();
  2261. },
  2262. usesUnifiedPlan: function() {
  2263. return RTCBrowserType.isFirefox();
  2264. },
  2265. /**
  2266. * Whether the browser is running on an android device.
  2267. */
  2268. isAndroid: function() {
  2269. return isAndroid;
  2270. }
  2271. // Add version getters for other browsers when needed
  2272. };
  2273. // detectOpera() must be called before detectChrome() !!!
  2274. // otherwise Opera wil be detected as Chrome
  2275. function detectChrome() {
  2276. if (navigator.webkitGetUserMedia) {
  2277. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2278. var userAgent = navigator.userAgent.toLowerCase();
  2279. // We can assume that user agent is chrome, because it's
  2280. // enforced when 'ext' streaming method is set
  2281. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2282. console.log("This appears to be Chrome, ver: " + ver);
  2283. return ver;
  2284. }
  2285. return null;
  2286. }
  2287. function detectOpera() {
  2288. var userAgent = navigator.userAgent;
  2289. if (userAgent.match(/Opera|OPR/)) {
  2290. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2291. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2292. console.info("This appears to be Opera, ver: " + version);
  2293. return version;
  2294. }
  2295. return null;
  2296. }
  2297. function detectFirefox() {
  2298. if (navigator.mozGetUserMedia) {
  2299. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2300. var version = parseInt(
  2301. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2302. console.log('This appears to be Firefox, ver: ' + version);
  2303. return version;
  2304. }
  2305. return null;
  2306. }
  2307. function detectSafari() {
  2308. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2309. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2310. console.info("This appears to be Safari");
  2311. // FIXME detect Safari version when needed
  2312. return 1;
  2313. }
  2314. return null;
  2315. }
  2316. function detectIE() {
  2317. var version;
  2318. var ua = window.navigator.userAgent;
  2319. var msie = ua.indexOf('MSIE ');
  2320. if (msie > 0) {
  2321. // IE 10 or older => return version number
  2322. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2323. }
  2324. var trident = ua.indexOf('Trident/');
  2325. if (!version && trident > 0) {
  2326. // IE 11 => return version number
  2327. var rv = ua.indexOf('rv:');
  2328. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2329. }
  2330. var edge = ua.indexOf('Edge/');
  2331. if (!version && edge > 0) {
  2332. // IE 12 => return version number
  2333. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2334. }
  2335. if (version) {
  2336. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2337. console.info("This appears to be IExplorer, ver: " + version);
  2338. }
  2339. return version;
  2340. }
  2341. function detectBrowser() {
  2342. var version;
  2343. var detectors = [
  2344. detectOpera,
  2345. detectChrome,
  2346. detectFirefox,
  2347. detectIE,
  2348. detectSafari
  2349. ];
  2350. // Try all browser detectors
  2351. for (var i = 0; i < detectors.length; i++) {
  2352. version = detectors[i]();
  2353. if (version)
  2354. return version;
  2355. }
  2356. console.warn("Browser type defaults to Safari ver 1");
  2357. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2358. return 1;
  2359. }
  2360. browserVersion = detectBrowser();
  2361. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2362. module.exports = RTCBrowserType;
  2363. },{}],18:[function(require,module,exports){
  2364. (function (__filename){
  2365. /* global config, require, attachMediaStream, getUserMedia,
  2366. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2367. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2368. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2369. */
  2370. /* jshint -W101 */
  2371. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2372. var RTCBrowserType = require("./RTCBrowserType");
  2373. var Resolutions = require("../../service/RTC/Resolutions");
  2374. var RTCEvents = require("../../service/RTC/RTCEvents");
  2375. var AdapterJS = require("./adapter.screenshare");
  2376. var SDPUtil = require("../xmpp/SDPUtil");
  2377. var EventEmitter = require("events");
  2378. var screenObtainer = require("./ScreenObtainer");
  2379. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2380. var eventEmitter = new EventEmitter();
  2381. var devices = {
  2382. audio: true,
  2383. video: true
  2384. };
  2385. var rtcReady = false;
  2386. function setResolutionConstraints(constraints, resolution) {
  2387. var isAndroid = RTCBrowserType.isAndroid();
  2388. if (Resolutions[resolution]) {
  2389. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2390. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2391. }
  2392. else if (isAndroid) {
  2393. // FIXME can't remember if the purpose of this was to always request
  2394. // low resolution on Android ? if yes it should be moved up front
  2395. constraints.video.mandatory.minWidth = 320;
  2396. constraints.video.mandatory.minHeight = 240;
  2397. constraints.video.mandatory.maxFrameRate = 15;
  2398. }
  2399. if (constraints.video.mandatory.minWidth)
  2400. constraints.video.mandatory.maxWidth =
  2401. constraints.video.mandatory.minWidth;
  2402. if (constraints.video.mandatory.minHeight)
  2403. constraints.video.mandatory.maxHeight =
  2404. constraints.video.mandatory.minHeight;
  2405. }
  2406. /**
  2407. * @param {string[]} um required user media types
  2408. *
  2409. * @param {Object} [options={}] optional parameters
  2410. * @param {string} options.resolution
  2411. * @param {number} options.bandwidth
  2412. * @param {number} options.fps
  2413. * @param {string} options.desktopStream
  2414. * @param {string} options.cameraDeviceId
  2415. * @param {string} options.micDeviceId
  2416. * @param {bool} firefox_fake_device
  2417. */
  2418. function getConstraints(um, options) {
  2419. var constraints = {audio: false, video: false};
  2420. if (um.indexOf('video') >= 0) {
  2421. // same behaviour as true
  2422. constraints.video = { mandatory: {}, optional: [] };
  2423. if (options.cameraDeviceId) {
  2424. constraints.video.optional.push({
  2425. sourceId: options.cameraDeviceId
  2426. });
  2427. }
  2428. constraints.video.optional.push({ googLeakyBucket: true });
  2429. setResolutionConstraints(constraints, options.resolution);
  2430. }
  2431. if (um.indexOf('audio') >= 0) {
  2432. if (!RTCBrowserType.isFirefox()) {
  2433. // same behaviour as true
  2434. constraints.audio = { mandatory: {}, optional: []};
  2435. if (options.micDeviceId) {
  2436. constraints.audio.optional.push({
  2437. sourceId: options.micDeviceId
  2438. });
  2439. }
  2440. // if it is good enough for hangouts...
  2441. constraints.audio.optional.push(
  2442. {googEchoCancellation: true},
  2443. {googAutoGainControl: true},
  2444. {googNoiseSupression: true},
  2445. {googHighpassFilter: true},
  2446. {googNoisesuppression2: true},
  2447. {googEchoCancellation2: true},
  2448. {googAutoGainControl2: true}
  2449. );
  2450. } else {
  2451. if (options.micDeviceId) {
  2452. constraints.audio = {
  2453. mandatory: {},
  2454. optional: [{
  2455. sourceId: options.micDeviceId
  2456. }]};
  2457. } else {
  2458. constraints.audio = true;
  2459. }
  2460. }
  2461. }
  2462. if (um.indexOf('screen') >= 0) {
  2463. if (RTCBrowserType.isChrome()) {
  2464. constraints.video = {
  2465. mandatory: {
  2466. chromeMediaSource: "screen",
  2467. googLeakyBucket: true,
  2468. maxWidth: window.screen.width,
  2469. maxHeight: window.screen.height,
  2470. maxFrameRate: 3
  2471. },
  2472. optional: []
  2473. };
  2474. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2475. constraints.video = {
  2476. optional: [
  2477. {
  2478. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2479. }
  2480. ]
  2481. };
  2482. } else if (RTCBrowserType.isFirefox()) {
  2483. constraints.video = {
  2484. mozMediaSource: "window",
  2485. mediaSource: "window"
  2486. };
  2487. } else {
  2488. logger.error(
  2489. "'screen' WebRTC media source is supported only in Chrome" +
  2490. " and with Temasys plugin");
  2491. }
  2492. }
  2493. if (um.indexOf('desktop') >= 0) {
  2494. constraints.video = {
  2495. mandatory: {
  2496. chromeMediaSource: "desktop",
  2497. chromeMediaSourceId: options.desktopStream,
  2498. googLeakyBucket: true,
  2499. maxWidth: window.screen.width,
  2500. maxHeight: window.screen.height,
  2501. maxFrameRate: 3
  2502. },
  2503. optional: []
  2504. };
  2505. }
  2506. if (options.bandwidth) {
  2507. if (!constraints.video) {
  2508. //same behaviour as true
  2509. constraints.video = {mandatory: {}, optional: []};
  2510. }
  2511. constraints.video.optional.push({bandwidth: options.bandwidth});
  2512. }
  2513. if (options.fps) {
  2514. // for some cameras it might be necessary to request 30fps
  2515. // so they choose 30fps mjpg over 10fps yuy2
  2516. if (!constraints.video) {
  2517. // same behaviour as true;
  2518. constraints.video = {mandatory: {}, optional: []};
  2519. }
  2520. constraints.video.mandatory.minFrameRate = options.fps;
  2521. }
  2522. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2523. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2524. // this later can be a problem with some of the tests
  2525. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2526. {
  2527. // seems to be fixed now, removing this experimental fix, as having
  2528. // multiple audio tracks brake the tests
  2529. //constraints.audio = true;
  2530. constraints.fake = true;
  2531. }
  2532. return constraints;
  2533. }
  2534. function setAvailableDevices(um, available) {
  2535. if (um.indexOf("video") != -1) {
  2536. devices.video = available;
  2537. }
  2538. if (um.indexOf("audio") != -1) {
  2539. devices.audio = available;
  2540. }
  2541. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2542. }
  2543. // In case of IE we continue from 'onReady' callback
  2544. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2545. // once it is initialized.
  2546. function onReady (options, GUM) {
  2547. rtcReady = true;
  2548. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2549. screenObtainer.init(eventEmitter, options, GUM);
  2550. }
  2551. /**
  2552. * Apply function with arguments if function exists.
  2553. * Do nothing if function not provided.
  2554. * @param {function} [fn] function to apply
  2555. * @param {Array} [args=[]] arguments for function
  2556. */
  2557. function maybeApply(fn, args) {
  2558. if (fn) {
  2559. fn.apply(null, args || []);
  2560. }
  2561. }
  2562. var getUserMediaStatus = {
  2563. initialized: false,
  2564. callbacks: []
  2565. };
  2566. /**
  2567. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2568. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2569. * @param {Function} getUserMedia native function
  2570. * @returns {Function} wrapped function
  2571. */
  2572. function wrapGetUserMedia(getUserMedia) {
  2573. return function (constraints, successCallback, errorCallback) {
  2574. getUserMedia(constraints, function (stream) {
  2575. maybeApply(successCallback, [stream]);
  2576. if (!getUserMediaStatus.initialized) {
  2577. getUserMediaStatus.initialized = true;
  2578. getUserMediaStatus.callbacks.forEach(function (callback) {
  2579. callback();
  2580. });
  2581. getUserMediaStatus.callbacks.length = 0;
  2582. }
  2583. }, function (error) {
  2584. maybeApply(errorCallback, [error]);
  2585. });
  2586. };
  2587. }
  2588. /**
  2589. * Create stub device which equals to auto selected device.
  2590. * @param {string} kind if that should be `audio` or `video` device
  2591. * @returns {Object} stub device description in `enumerateDevices` format
  2592. */
  2593. function createAutoDeviceInfo(kind) {
  2594. return {
  2595. facing: null,
  2596. label: 'Auto',
  2597. kind: kind,
  2598. deviceId: '',
  2599. groupId: null
  2600. };
  2601. }
  2602. /**
  2603. * Execute function after getUserMedia was executed at least once.
  2604. * @param {Function} callback function to execute after getUserMedia
  2605. */
  2606. function afterUserMediaInitialized(callback) {
  2607. if (getUserMediaStatus.initialized) {
  2608. callback();
  2609. } else {
  2610. getUserMediaStatus.callbacks.push(callback);
  2611. }
  2612. }
  2613. /**
  2614. * Wrapper function which makes enumerateDevices to wait
  2615. * until someone executes getUserMedia first time.
  2616. * @param {Function} enumerateDevices native function
  2617. * @returns {Funtion} wrapped function
  2618. */
  2619. function wrapEnumerateDevices(enumerateDevices) {
  2620. return function (callback) {
  2621. // enumerate devices only after initial getUserMedia
  2622. afterUserMediaInitialized(function () {
  2623. enumerateDevices().then(function (devices) {
  2624. //add auto devices
  2625. devices.unshift(
  2626. createAutoDeviceInfo('audioinput'),
  2627. createAutoDeviceInfo('videoinput')
  2628. );
  2629. callback(devices);
  2630. }, function (err) {
  2631. console.error('cannot enumerate devices: ', err);
  2632. // return only auto devices
  2633. callback([createAutoDeviceInfo('audioInput'),
  2634. createAutoDeviceInfo('videoinput')]);
  2635. });
  2636. });
  2637. };
  2638. }
  2639. /**
  2640. * Use old MediaStreamTrack to get devices list and
  2641. * convert it to enumerateDevices format.
  2642. * @param {Function} callback function to call when received devices list.
  2643. */
  2644. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2645. MediaStreamTrack.getSources(function (sources) {
  2646. var devices = sources.map(function (source) {
  2647. var kind = (source.kind || '').toLowerCase();
  2648. return {
  2649. facing: source.facing || null,
  2650. label: source.label,
  2651. kind: kind ? kind + 'input': null,
  2652. deviceId: source.id,
  2653. groupId: source.groupId || null
  2654. };
  2655. });
  2656. //add auto devices
  2657. devices.unshift(
  2658. createAutoDeviceInfo('audioinput'),
  2659. createAutoDeviceInfo('videoinput')
  2660. );
  2661. callback(devices);
  2662. });
  2663. }
  2664. function obtainDevices(options) {
  2665. if(!options.devices || options.devices.length === 0) {
  2666. return options.successCallback(options.streams || {});
  2667. }
  2668. var device = options.devices.splice(0, 1);
  2669. var devices = [];
  2670. devices.push(device);
  2671. options.deviceGUM[device](function (stream) {
  2672. options.streams = options.streams || {};
  2673. options.streams[device] = stream;
  2674. obtainDevices(options);
  2675. },
  2676. function (error) {
  2677. Object.keys(options.streams).forEach(function(device) {
  2678. RTCUtils.stopMediaStream(options.streams[device]);
  2679. });
  2680. logger.error(
  2681. "failed to obtain " + device + " stream - stop", error);
  2682. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2683. });
  2684. }
  2685. /**
  2686. * Handles the newly created Media Streams.
  2687. * @param streams the new Media Streams
  2688. * @param resolution the resolution of the video streams
  2689. * @returns {*[]} object that describes the new streams
  2690. */
  2691. function handleLocalStream(streams, resolution) {
  2692. var audioStream, videoStream, desktopStream, res = [];
  2693. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2694. // an object with two properties: audioStream, videoStream.
  2695. if (window.webkitMediaStream) {
  2696. var audioVideo = streams.audioVideo;
  2697. if (audioVideo) {
  2698. var audioTracks = audioVideo.getAudioTracks();
  2699. if(audioTracks.length) {
  2700. audioStream = new webkitMediaStream();
  2701. for (var i = 0; i < audioTracks.length; i++) {
  2702. audioStream.addTrack(audioTracks[i]);
  2703. }
  2704. }
  2705. var videoTracks = audioVideo.getVideoTracks();
  2706. if(videoTracks.length) {
  2707. videoStream = new webkitMediaStream();
  2708. for (var j = 0; j < videoTracks.length; j++) {
  2709. videoStream.addTrack(videoTracks[j]);
  2710. }
  2711. }
  2712. }
  2713. if (streams && streams.desktopStream)
  2714. desktopStream = streams.desktopStream;
  2715. }
  2716. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2717. if (streams && streams.audio)
  2718. audioStream = streams.audio;
  2719. if (streams && streams.video)
  2720. videoStream = streams.video;
  2721. if(streams && streams.desktop)
  2722. desktopStream = streams.desktop;
  2723. }
  2724. if (desktopStream)
  2725. res.push({stream: desktopStream,
  2726. type: "video", videoType: "desktop"});
  2727. if(audioStream)
  2728. res.push({stream: audioStream, type: "audio", videoType: null});
  2729. if(videoStream)
  2730. res.push({stream: videoStream, type: "video", videoType: "camera",
  2731. resolution: resolution});
  2732. return res;
  2733. }
  2734. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2735. var RTCUtils = {
  2736. init: function (options) {
  2737. return new Promise(function(resolve, reject) {
  2738. if (RTCBrowserType.isFirefox()) {
  2739. var FFversion = RTCBrowserType.getFirefoxVersion();
  2740. if (FFversion < 40) {
  2741. logger.error(
  2742. "Firefox version too old: " + FFversion +
  2743. ". Required >= 40.");
  2744. reject(new Error("Firefox version too old: " + FFversion +
  2745. ". Required >= 40."));
  2746. return;
  2747. }
  2748. this.peerconnection = mozRTCPeerConnection;
  2749. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2750. this.enumerateDevices = wrapEnumerateDevices(
  2751. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2752. );
  2753. this.pc_constraints = {};
  2754. this.attachMediaStream = function (element, stream) {
  2755. // srcObject is being standardized and FF will eventually
  2756. // support that unprefixed. FF also supports the
  2757. // "element.src = URL.createObjectURL(...)" combo, but that
  2758. // will be deprecated in favour of srcObject.
  2759. //
  2760. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2761. // https://github.com/webrtc/samples/issues/302
  2762. if (!element[0])
  2763. return;
  2764. element[0].mozSrcObject = stream;
  2765. element[0].play();
  2766. };
  2767. this.getStreamID = function (stream) {
  2768. var id = stream.id;
  2769. if (!id) {
  2770. var tracks = stream.getVideoTracks();
  2771. if (!tracks || tracks.length === 0) {
  2772. tracks = stream.getAudioTracks();
  2773. }
  2774. id = tracks[0].id;
  2775. }
  2776. return SDPUtil.filter_special_chars(id);
  2777. };
  2778. this.getVideoSrc = function (element) {
  2779. if (!element)
  2780. return null;
  2781. return element.mozSrcObject;
  2782. };
  2783. this.setVideoSrc = function (element, src) {
  2784. if (element)
  2785. element.mozSrcObject = src;
  2786. };
  2787. RTCSessionDescription = mozRTCSessionDescription;
  2788. RTCIceCandidate = mozRTCIceCandidate;
  2789. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2790. this.peerconnection = webkitRTCPeerConnection;
  2791. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2792. if (navigator.mediaDevices) {
  2793. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2794. this.enumerateDevices = wrapEnumerateDevices(
  2795. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2796. );
  2797. } else {
  2798. this.getUserMedia = getUserMedia;
  2799. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2800. }
  2801. this.attachMediaStream = function (element, stream) {
  2802. // saves the created url for the stream, so we can reuse it
  2803. // and not keep creating urls
  2804. if (!stream.jitsiObjectURL) {
  2805. stream.jitsiObjectURL
  2806. = webkitURL.createObjectURL(stream);
  2807. }
  2808. element.attr('src', stream.jitsiObjectURL);
  2809. };
  2810. this.getStreamID = function (stream) {
  2811. // streams from FF endpoints have the characters '{' and '}'
  2812. // that make jQuery choke.
  2813. return SDPUtil.filter_special_chars(stream.id);
  2814. };
  2815. this.getVideoSrc = function (element) {
  2816. if (!element)
  2817. return null;
  2818. return element.getAttribute("src");
  2819. };
  2820. this.setVideoSrc = function (element, src) {
  2821. if (element)
  2822. element.setAttribute("src", src);
  2823. };
  2824. // DTLS should now be enabled by default but..
  2825. this.pc_constraints = {'optional': [
  2826. {'DtlsSrtpKeyAgreement': 'true'}
  2827. ]};
  2828. if (options.useIPv6) {
  2829. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2830. this.pc_constraints.optional.push({googIPv6: true});
  2831. }
  2832. if (RTCBrowserType.isAndroid()) {
  2833. this.pc_constraints = {}; // disable DTLS on Android
  2834. }
  2835. if (!webkitMediaStream.prototype.getVideoTracks) {
  2836. webkitMediaStream.prototype.getVideoTracks = function () {
  2837. return this.videoTracks;
  2838. };
  2839. }
  2840. if (!webkitMediaStream.prototype.getAudioTracks) {
  2841. webkitMediaStream.prototype.getAudioTracks = function () {
  2842. return this.audioTracks;
  2843. };
  2844. }
  2845. }
  2846. // Detect IE/Safari
  2847. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2848. //AdapterJS.WebRTCPlugin.setLogLevel(
  2849. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2850. var self = this;
  2851. AdapterJS.webRTCReady(function (isPlugin) {
  2852. self.peerconnection = RTCPeerConnection;
  2853. self.getUserMedia = window.getUserMedia;
  2854. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2855. self.attachMediaStream = function (elSel, stream) {
  2856. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2857. return;
  2858. }
  2859. attachMediaStream(elSel[0], stream);
  2860. };
  2861. self.getStreamID = function (stream) {
  2862. var id = SDPUtil.filter_special_chars(stream.label);
  2863. return id;
  2864. };
  2865. self.getVideoSrc = function (element) {
  2866. if (!element) {
  2867. logger.warn("Attempt to get video SRC of null element");
  2868. return null;
  2869. }
  2870. var children = element.children;
  2871. for (var i = 0; i !== children.length; ++i) {
  2872. if (children[i].name === 'streamId') {
  2873. return children[i].value;
  2874. }
  2875. }
  2876. //logger.info(element.id + " SRC: " + src);
  2877. return null;
  2878. };
  2879. self.setVideoSrc = function (element, src) {
  2880. //logger.info("Set video src: ", element, src);
  2881. if (!src) {
  2882. logger.warn("Not attaching video stream, 'src' is null");
  2883. return;
  2884. }
  2885. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2886. var stream = AdapterJS.WebRTCPlugin.plugin
  2887. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2888. attachMediaStream(element, stream);
  2889. };
  2890. onReady(options, self.getUserMediaWithConstraints);
  2891. resolve();
  2892. });
  2893. } else {
  2894. try {
  2895. logger.error('Browser does not appear to be WebRTC-capable');
  2896. } catch (e) {
  2897. }
  2898. reject('Browser does not appear to be WebRTC-capable');
  2899. return;
  2900. }
  2901. // Call onReady() if Temasys plugin is not used
  2902. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2903. onReady(options, this.getUserMediaWithConstraints);
  2904. resolve();
  2905. }
  2906. }.bind(this));
  2907. },
  2908. /**
  2909. * @param {string[]} um required user media types
  2910. * @param {function} success_callback
  2911. * @param {Function} failure_callback
  2912. * @param {Object} [options] optional parameters
  2913. * @param {string} options.resolution
  2914. * @param {number} options.bandwidth
  2915. * @param {number} options.fps
  2916. * @param {string} options.desktopStream
  2917. * @param {string} options.cameraDeviceId
  2918. * @param {string} options.micDeviceId
  2919. **/
  2920. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2921. options = options || {};
  2922. var resolution = options.resolution;
  2923. var constraints = getConstraints(um, options);
  2924. logger.info("Get media constraints", constraints);
  2925. try {
  2926. this.getUserMedia(constraints,
  2927. function (stream) {
  2928. logger.log('onUserMediaSuccess');
  2929. setAvailableDevices(um, true);
  2930. success_callback(stream);
  2931. },
  2932. function (error) {
  2933. setAvailableDevices(um, false);
  2934. logger.warn('Failed to get access to local media. Error ',
  2935. error, constraints);
  2936. if (failure_callback) {
  2937. failure_callback(error, resolution);
  2938. }
  2939. });
  2940. } catch (e) {
  2941. logger.error('GUM failed: ', e);
  2942. if (failure_callback) {
  2943. failure_callback(e);
  2944. }
  2945. }
  2946. },
  2947. /**
  2948. * Creates the local MediaStreams.
  2949. * @param {Object} [options] optional parameters
  2950. * @param {Array} options.devices the devices that will be requested
  2951. * @param {string} options.resolution resolution constraints
  2952. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2953. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2954. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2955. * @param {string} options.cameraDeviceId
  2956. * @param {string} options.micDeviceId
  2957. * @returns {*} Promise object that will receive the new JitsiTracks
  2958. */
  2959. obtainAudioAndVideoPermissions: function (options) {
  2960. var self = this;
  2961. options = options || {};
  2962. return new Promise(function (resolve, reject) {
  2963. var successCallback = function (stream) {
  2964. resolve(handleLocalStream(stream, options.resolution));
  2965. };
  2966. options.devices = options.devices || ['audio', 'video'];
  2967. if(!screenObtainer.isSupported()
  2968. && options.devices.indexOf("desktop") !== -1){
  2969. reject(new Error("Desktop sharing is not supported!"));
  2970. }
  2971. if (RTCBrowserType.isFirefox() ||
  2972. RTCBrowserType.isTemasysPluginUsed()) {
  2973. var GUM = function (device, s, e) {
  2974. this.getUserMediaWithConstraints(device, s, e, options);
  2975. };
  2976. var deviceGUM = {
  2977. "audio": GUM.bind(self, ["audio"]),
  2978. "video": GUM.bind(self, ["video"])
  2979. };
  2980. if(screenObtainer.isSupported()){
  2981. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  2982. screenObtainer);
  2983. }
  2984. // With FF/IE we can't split the stream into audio and video because FF
  2985. // doesn't support media stream constructors. So, we need to get the
  2986. // audio stream separately from the video stream using two distinct GUM
  2987. // calls. Not very user friendly :-( but we don't have many other
  2988. // options neither.
  2989. //
  2990. // Note that we pack those 2 streams in a single object and pass it to
  2991. // the successCallback method.
  2992. obtainDevices({
  2993. devices: options.devices,
  2994. streams: [],
  2995. successCallback: successCallback,
  2996. errorCallback: reject,
  2997. deviceGUM: deviceGUM
  2998. });
  2999. } else {
  3000. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3001. if (hasDesktop) {
  3002. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3003. }
  3004. options.resolution = options.resolution || '360';
  3005. if(options.devices.length) {
  3006. this.getUserMediaWithConstraints(
  3007. options.devices,
  3008. function (stream) {
  3009. if((options.devices.indexOf("audio") !== -1 &&
  3010. !stream.getAudioTracks().length) ||
  3011. (options.devices.indexOf("video") !== -1 &&
  3012. !stream.getVideoTracks().length))
  3013. {
  3014. self.stopMediaStream(stream);
  3015. reject(JitsiTrackErrors.parseError(
  3016. new Error("Unable to get the audio and " +
  3017. "video tracks."),
  3018. options.devices));
  3019. return;
  3020. }
  3021. if(hasDesktop) {
  3022. screenObtainer.obtainStream(
  3023. function (desktopStream) {
  3024. successCallback({audioVideo: stream,
  3025. desktopStream: desktopStream});
  3026. }, function (error) {
  3027. self.stopMediaStream(stream);
  3028. reject(
  3029. JitsiTrackErrors.parseError(error,
  3030. options.devices));
  3031. });
  3032. } else {
  3033. successCallback({audioVideo: stream});
  3034. }
  3035. },
  3036. function (error) {
  3037. reject(JitsiTrackErrors.parseError(error,
  3038. options.devices));
  3039. },
  3040. options);
  3041. } else if (hasDesktop) {
  3042. screenObtainer.obtainStream(
  3043. function (stream) {
  3044. successCallback({desktopStream: stream});
  3045. }, function (error) {
  3046. reject(
  3047. JitsiTrackErrors.parseError(error,
  3048. ["desktop"]));
  3049. });
  3050. }
  3051. }
  3052. }.bind(this));
  3053. },
  3054. addListener: function (eventType, listener) {
  3055. eventEmitter.on(eventType, listener);
  3056. },
  3057. removeListener: function (eventType, listener) {
  3058. eventEmitter.removeListener(eventType, listener);
  3059. },
  3060. getDeviceAvailability: function () {
  3061. return devices;
  3062. },
  3063. isRTCReady: function () {
  3064. return rtcReady;
  3065. },
  3066. /**
  3067. * Checks if its possible to enumerate available cameras/micropones.
  3068. * @returns {boolean} true if available, false otherwise.
  3069. */
  3070. isDeviceListAvailable: function () {
  3071. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3072. if (isEnumerateDevicesAvailable) {
  3073. return true;
  3074. }
  3075. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3076. },
  3077. /**
  3078. * Returns true if changing the camera / microphone device is supported and
  3079. * false if not.
  3080. */
  3081. isDeviceChangeAvailable: function () {
  3082. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3083. RTCBrowserType.isTemasysPluginUsed())
  3084. return true;
  3085. return false;
  3086. },
  3087. /**
  3088. * A method to handle stopping of the stream.
  3089. * One point to handle the differences in various implementations.
  3090. * @param mediaStream MediaStream object to stop.
  3091. */
  3092. stopMediaStream: function (mediaStream) {
  3093. mediaStream.getTracks().forEach(function (track) {
  3094. // stop() not supported with IE
  3095. if (track.stop) {
  3096. track.stop();
  3097. }
  3098. });
  3099. // leave stop for implementation still using it
  3100. if (mediaStream.stop) {
  3101. mediaStream.stop();
  3102. }
  3103. // if we have done createObjectURL, lets clean it
  3104. if (mediaStream.jitsiObjectURL) {
  3105. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3106. }
  3107. },
  3108. /**
  3109. * Returns whether the desktop sharing is enabled or not.
  3110. * @returns {boolean}
  3111. */
  3112. isDesktopSharingEnabled: function () {
  3113. return screenObtainer.isSupported();
  3114. }
  3115. };
  3116. module.exports = RTCUtils;
  3117. }).call(this,"/modules/RTC/RTCUtils.js")
  3118. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":80,"../../service/RTC/Resolutions":81,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":44,"jitsi-meet-logger":48}],19:[function(require,module,exports){
  3119. (function (__filename){
  3120. /* global chrome, $, alert */
  3121. /* jshint -W003 */
  3122. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3123. var RTCBrowserType = require("./RTCBrowserType");
  3124. var AdapterJS = require("./adapter.screenshare");
  3125. var DesktopSharingEventTypes
  3126. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3127. /**
  3128. * Indicates whether the Chrome desktop sharing extension is installed.
  3129. * @type {boolean}
  3130. */
  3131. var chromeExtInstalled = false;
  3132. /**
  3133. * Indicates whether an update of the Chrome desktop sharing extension is
  3134. * required.
  3135. * @type {boolean}
  3136. */
  3137. var chromeExtUpdateRequired = false;
  3138. /**
  3139. * Whether the jidesha extension for firefox is installed for the domain on
  3140. * which we are running. Null designates an unknown value.
  3141. * @type {null}
  3142. */
  3143. var firefoxExtInstalled = null;
  3144. /**
  3145. * If set to true, detection of an installed firefox extension will be started
  3146. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3147. * user tries to enable screen sharing).
  3148. */
  3149. var reDetectFirefoxExtension = false;
  3150. var GUM = null;
  3151. /**
  3152. * Handles obtaining a stream from a screen capture on different browsers.
  3153. */
  3154. var ScreenObtainer = {
  3155. /**
  3156. * The EventEmitter to use to emit events.
  3157. * @type {null}
  3158. */
  3159. eventEmitter: null,
  3160. obtainStream: null,
  3161. /**
  3162. * Initializes the function used to obtain a screen capture
  3163. * (this.obtainStream).
  3164. *
  3165. * If the browser is Chrome, it uses the value of
  3166. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3167. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3168. * use the "screen" media source (if the value is 'webrtc'),
  3169. * or disable screen capture (if the value is other).
  3170. * Note that for the "screen" media source to work the
  3171. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3172. */
  3173. init: function(eventEmitter, options, gum) {
  3174. this.eventEmitter = eventEmitter;
  3175. var obtainDesktopStream = null;
  3176. this.options = options = options || {};
  3177. GUM = gum;
  3178. if (RTCBrowserType.isFirefox())
  3179. initFirefoxExtensionDetection(options);
  3180. // TODO remove this, options.desktopSharing is deprecated.
  3181. var chromeMethod =
  3182. (options.desktopSharingChromeMethod || options.desktopSharing);
  3183. if (RTCBrowserType.isTemasysPluginUsed()) {
  3184. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3185. logger.info("Screensharing not supported by this plugin " +
  3186. "version");
  3187. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3188. logger.info(
  3189. "Screensharing not available with Temasys plugin on" +
  3190. " this site");
  3191. } else {
  3192. obtainDesktopStream = obtainWebRTCScreen;
  3193. logger.info("Using Temasys plugin for desktop sharing");
  3194. }
  3195. } else if (RTCBrowserType.isChrome()) {
  3196. if (chromeMethod == "ext") {
  3197. if (RTCBrowserType.getChromeVersion() >= 34) {
  3198. obtainDesktopStream =
  3199. this.obtainScreenFromExtension;
  3200. logger.info("Using Chrome extension for desktop sharing");
  3201. initChromeExtension(options);
  3202. } else {
  3203. logger.info("Chrome extension not supported until ver 34");
  3204. }
  3205. } else if (chromeMethod == "webrtc") {
  3206. obtainDesktopStream = obtainWebRTCScreen;
  3207. logger.info("Using Chrome WebRTC for desktop sharing");
  3208. }
  3209. } else if (RTCBrowserType.isFirefox()) {
  3210. if (options.desktopSharingFirefoxDisabled) {
  3211. obtainDesktopStream = null;
  3212. } else if (window.location.protocol === "http:"){
  3213. logger.log("Screen sharing is not supported over HTTP. " +
  3214. "Use of HTTPS is required.");
  3215. obtainDesktopStream = null;
  3216. } else {
  3217. obtainDesktopStream = this.obtainScreenOnFirefox;
  3218. }
  3219. }
  3220. if (!obtainDesktopStream) {
  3221. logger.info("Desktop sharing disabled");
  3222. }
  3223. this.obtainStream = obtainDesktopStream;
  3224. },
  3225. /**
  3226. * Checks whether obtaining a screen capture is supported in the current
  3227. * environment.
  3228. * @returns {boolean}
  3229. */
  3230. isSupported: function() {
  3231. return !!this.obtainStream;
  3232. },
  3233. /**
  3234. * Obtains a screen capture stream on Firefox.
  3235. * @param callback
  3236. * @param errorCallback
  3237. */
  3238. obtainScreenOnFirefox:
  3239. function (callback, errorCallback) {
  3240. var self = this;
  3241. var extensionRequired = false;
  3242. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3243. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3244. RTCBrowserType.getFirefoxVersion() <=
  3245. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3246. extensionRequired = true;
  3247. logger.log("Jidesha extension required on firefox version " +
  3248. RTCBrowserType.getFirefoxVersion());
  3249. }
  3250. if (!extensionRequired || firefoxExtInstalled === true) {
  3251. obtainWebRTCScreen(callback, errorCallback);
  3252. return;
  3253. }
  3254. if (reDetectFirefoxExtension) {
  3255. reDetectFirefoxExtension = false;
  3256. initFirefoxExtensionDetection(this.options);
  3257. }
  3258. // Give it some (more) time to initialize, and assume lack of
  3259. // extension if it hasn't.
  3260. if (firefoxExtInstalled === null) {
  3261. window.setTimeout(
  3262. function() {
  3263. if (firefoxExtInstalled === null)
  3264. firefoxExtInstalled = false;
  3265. self.obtainScreenOnFirefox(callback, errorCallback);
  3266. },
  3267. 300
  3268. );
  3269. logger.log("Waiting for detection of jidesha on firefox to " +
  3270. "finish.");
  3271. return;
  3272. }
  3273. // We need an extension and it isn't installed.
  3274. // Make sure we check for the extension when the user clicks again.
  3275. firefoxExtInstalled = null;
  3276. reDetectFirefoxExtension = true;
  3277. // Prompt the user to install the extension
  3278. this.eventEmitter.emit(
  3279. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  3280. this.options.desktopSharingFirefoxExtensionURL);
  3281. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3282. // stuck in 'switching' mode.
  3283. errorCallback('Firefox extension required.');
  3284. },
  3285. /**
  3286. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3287. * 'desktop' stream for returned stream token.
  3288. */
  3289. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3290. if (chromeExtInstalled) {
  3291. doGetStreamFromExtension(this.options, streamCallback,
  3292. failCallback);
  3293. } else {
  3294. if (chromeExtUpdateRequired) {
  3295. alert(
  3296. 'Jitsi Desktop Streamer requires update. ' +
  3297. 'Changes will take effect after next Chrome restart.');
  3298. }
  3299. chrome.webstore.install(
  3300. getWebStoreInstallUrl(this.options),
  3301. function (arg) {
  3302. logger.log("Extension installed successfully", arg);
  3303. chromeExtInstalled = true;
  3304. // We need to give a moment for the endpoint to become
  3305. // available
  3306. window.setTimeout(function () {
  3307. doGetStreamFromExtension(this.options, streamCallback,
  3308. failCallback);
  3309. }, 500);
  3310. },
  3311. function (arg) {
  3312. logger.log("Failed to install the extension", arg);
  3313. failCallback(arg);
  3314. }
  3315. );
  3316. }
  3317. }
  3318. };
  3319. /**
  3320. * Obtains a desktop stream using getUserMedia.
  3321. * For this to work on Chrome, the
  3322. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3323. *
  3324. * On firefox, the document's domain must be white-listed in the
  3325. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3326. * 'about:config'.
  3327. */
  3328. function obtainWebRTCScreen(streamCallback, failCallback) {
  3329. GUM(
  3330. ['screen'],
  3331. streamCallback,
  3332. failCallback
  3333. );
  3334. }
  3335. /**
  3336. * Constructs inline install URL for Chrome desktop streaming extension.
  3337. * The 'chromeExtensionId' must be defined in options parameter.
  3338. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3339. * @returns {string}
  3340. */
  3341. function getWebStoreInstallUrl(options)
  3342. {
  3343. //TODO remove chromeExtensionId (deprecated)
  3344. return "https://chrome.google.com/webstore/detail/" +
  3345. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3346. }
  3347. /**
  3348. * Checks whether an update of the Chrome extension is required.
  3349. * @param minVersion minimal required version
  3350. * @param extVersion current extension version
  3351. * @returns {boolean}
  3352. */
  3353. function isUpdateRequired(minVersion, extVersion) {
  3354. try {
  3355. var s1 = minVersion.split('.');
  3356. var s2 = extVersion.split('.');
  3357. var len = Math.max(s1.length, s2.length);
  3358. for (var i = 0; i < len; i++) {
  3359. var n1 = 0,
  3360. n2 = 0;
  3361. if (i < s1.length)
  3362. n1 = parseInt(s1[i]);
  3363. if (i < s2.length)
  3364. n2 = parseInt(s2[i]);
  3365. if (isNaN(n1) || isNaN(n2)) {
  3366. return true;
  3367. } else if (n1 !== n2) {
  3368. return n1 > n2;
  3369. }
  3370. }
  3371. // will happen if both versions have identical numbers in
  3372. // their components (even if one of them is longer, has more components)
  3373. return false;
  3374. }
  3375. catch (e) {
  3376. logger.error("Failed to parse extension version", e);
  3377. return true;
  3378. }
  3379. }
  3380. function checkChromeExtInstalled(callback, options) {
  3381. if (!chrome || !chrome.runtime) {
  3382. // No API, so no extension for sure
  3383. callback(false, false);
  3384. return;
  3385. }
  3386. chrome.runtime.sendMessage(
  3387. //TODO: remove chromeExtensionId (deprecated)
  3388. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3389. { getVersion: true },
  3390. function (response) {
  3391. if (!response || !response.version) {
  3392. // Communication failure - assume that no endpoint exists
  3393. logger.warn(
  3394. "Extension not installed?: ", chrome.runtime.lastError);
  3395. callback(false, false);
  3396. return;
  3397. }
  3398. // Check installed extension version
  3399. var extVersion = response.version;
  3400. logger.log('Extension version is: ' + extVersion);
  3401. //TODO: remove minChromeExtVersion (deprecated)
  3402. var updateRequired
  3403. = isUpdateRequired(
  3404. (options.desktopSharingChromeMinExtVersion ||
  3405. options.minChromeExtVersion),
  3406. extVersion);
  3407. callback(!updateRequired, updateRequired);
  3408. }
  3409. );
  3410. }
  3411. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3412. // Sends 'getStream' msg to the extension.
  3413. // Extension id must be defined in the config.
  3414. chrome.runtime.sendMessage(
  3415. //TODO: remove chromeExtensionId (deprecated)
  3416. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3417. {
  3418. getStream: true,
  3419. //TODO: remove desktopSharingSources (deprecated).
  3420. sources: (options.desktopSharingChromeSources ||
  3421. options.desktopSharingSources)
  3422. },
  3423. function (response) {
  3424. if (!response) {
  3425. failCallback(chrome.runtime.lastError);
  3426. return;
  3427. }
  3428. logger.log("Response from extension: " + response);
  3429. if (response.streamId) {
  3430. GUM(
  3431. ['desktop'],
  3432. function (stream) {
  3433. streamCallback(stream);
  3434. },
  3435. failCallback,
  3436. {desktopStream: response.streamId});
  3437. } else {
  3438. failCallback("Extension failed to get the stream");
  3439. }
  3440. }
  3441. );
  3442. }
  3443. /**
  3444. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3445. * config.js to support inline installs. Host site must be selected as main
  3446. * website of published extension.
  3447. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3448. */
  3449. function initInlineInstalls(options)
  3450. {
  3451. $("link[rel=chrome-webstore-item]").attr("href",
  3452. getWebStoreInstallUrl(options));
  3453. }
  3454. function initChromeExtension(options) {
  3455. // Initialize Chrome extension inline installs
  3456. initInlineInstalls(options);
  3457. // Check if extension is installed
  3458. checkChromeExtInstalled(function (installed, updateRequired) {
  3459. chromeExtInstalled = installed;
  3460. chromeExtUpdateRequired = updateRequired;
  3461. logger.info(
  3462. "Chrome extension installed: " + chromeExtInstalled +
  3463. " updateRequired: " + chromeExtUpdateRequired);
  3464. }, options);
  3465. }
  3466. /**
  3467. * Starts the detection of an installed jidesha extension for firefox.
  3468. * @param options supports "desktopSharingFirefoxDisabled",
  3469. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3470. */
  3471. function initFirefoxExtensionDetection(options) {
  3472. if (options.desktopSharingFirefoxDisabled) {
  3473. return;
  3474. }
  3475. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3476. return;
  3477. if (!options.desktopSharingFirefoxExtId) {
  3478. firefoxExtInstalled = false;
  3479. return;
  3480. }
  3481. var img = document.createElement('img');
  3482. img.onload = function(){
  3483. logger.log("Detected firefox screen sharing extension.");
  3484. firefoxExtInstalled = true;
  3485. };
  3486. img.onerror = function(){
  3487. logger.log("Detected lack of firefox screen sharing extension.");
  3488. firefoxExtInstalled = false;
  3489. };
  3490. // The jidesha extension exposes an empty image file under the url:
  3491. // "chrome://EXT_ID/content/DOMAIN.png"
  3492. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3493. // DOMAIN is a domain whitelisted by the extension.
  3494. var src = "chrome://" +
  3495. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3496. "/content/" + document.location.hostname + ".png";
  3497. img.setAttribute('src', src);
  3498. }
  3499. module.exports = ScreenObtainer;
  3500. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3501. },{"../../service/desktopsharing/DesktopSharingEventTypes":84,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":48}],20:[function(require,module,exports){
  3502. (function (__filename){
  3503. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3504. var console = require("jitsi-meet-logger").getLogger(__filename);
  3505. // Adapter's interface.
  3506. var AdapterJS = AdapterJS || {};
  3507. // Browserify compatibility
  3508. if(typeof exports !== 'undefined') {
  3509. module.exports = AdapterJS;
  3510. }
  3511. AdapterJS.options = AdapterJS.options || {};
  3512. // uncomment to get virtual webcams
  3513. // AdapterJS.options.getAllCams = true;
  3514. // uncomment to prevent the install prompt when the plugin in not yet installed
  3515. // AdapterJS.options.hidePluginInstallPrompt = true;
  3516. // AdapterJS version
  3517. AdapterJS.VERSION = '0.12.3';
  3518. // This function will be called when the WebRTC API is ready to be used
  3519. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3520. // the plugin
  3521. // You may Override this function to synchronise the start of your application
  3522. // with the WebRTC API being ready.
  3523. // If you decide not to override use this synchronisation, it may result in
  3524. // an extensive CPU usage on the plugin start (once per tab loaded)
  3525. // Params:
  3526. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3527. //
  3528. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3529. // The WebRTC API is ready.
  3530. // Override me and do whatever you want here
  3531. };
  3532. // Sets a callback function to be called when the WebRTC interface is ready.
  3533. // The first argument is the function to callback.\
  3534. // Throws an error if the first argument is not a function
  3535. AdapterJS.webRTCReady = function (callback) {
  3536. if (typeof callback !== 'function') {
  3537. throw new Error('Callback provided is not a function');
  3538. }
  3539. if (true === AdapterJS.onwebrtcreadyDone) {
  3540. // All WebRTC interfaces are ready, just call the callback
  3541. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3542. } else {
  3543. // will be triggered automatically when your browser/plugin is ready.
  3544. AdapterJS.onwebrtcready = callback;
  3545. }
  3546. };
  3547. // Plugin namespace
  3548. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3549. // The object to store plugin information
  3550. AdapterJS.WebRTCPlugin.pluginInfo = {
  3551. prefix : 'Tem',
  3552. plugName : 'TemWebRTCPlugin',
  3553. pluginId : 'plugin0',
  3554. type : 'application/x-temwebrtcplugin',
  3555. onload : '__TemWebRTCReady0',
  3556. portalLink : 'http://skylink.io/plugin/',
  3557. downloadLink : null, //set below
  3558. companyName: 'Temasys'
  3559. };
  3560. if(!!navigator.platform.match(/^Mac/i)) {
  3561. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3562. }
  3563. else if(!!navigator.platform.match(/^Win/i)) {
  3564. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3565. }
  3566. AdapterJS.WebRTCPlugin.TAGS = {
  3567. NONE : 'none',
  3568. AUDIO : 'audio',
  3569. VIDEO : 'video'
  3570. };
  3571. // Unique identifier of each opened page
  3572. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3573. // Use this whenever you want to call the plugin.
  3574. AdapterJS.WebRTCPlugin.plugin = null;
  3575. // Set log level for the plugin once it is ready.
  3576. // The different values are
  3577. // This is an asynchronous function that will run when the plugin is ready
  3578. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3579. // Defines webrtc's JS interface according to the plugin's implementation.
  3580. // Define plugin Browsers as WebRTC Interface.
  3581. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3582. // This function detects whether or not a plugin is installed.
  3583. // Checks if Not IE (firefox, for example), else if it's IE,
  3584. // we're running IE and do something. If not it is not supported.
  3585. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3586. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3587. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3588. // Inject the HTML DOM object element into the page.
  3589. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3590. // States of readiness that the plugin goes through when
  3591. // being injected and stated
  3592. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3593. NONE : 0, // no plugin use
  3594. INITIALIZING : 1, // Detected need for plugin
  3595. INJECTING : 2, // Injecting plugin
  3596. INJECTED: 3, // Plugin element injected but not usable yet
  3597. READY: 4 // Plugin ready to be used
  3598. };
  3599. // Current state of the plugin. You cannot use the plugin before this is
  3600. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3601. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3602. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3603. // Used to make sure AdapterJS.onwebrtcready is only called once
  3604. AdapterJS.onwebrtcreadyDone = false;
  3605. // Log levels for the plugin.
  3606. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3607. /*
  3608. Log outputs are prefixed in some cases.
  3609. INFO: Information reported by the plugin.
  3610. ERROR: Errors originating from within the plugin.
  3611. WEBRTC: Error originating from within the libWebRTC library
  3612. */
  3613. // From the least verbose to the most verbose
  3614. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3615. NONE : 'NONE',
  3616. ERROR : 'ERROR',
  3617. WARNING : 'WARNING',
  3618. INFO: 'INFO',
  3619. VERBOSE: 'VERBOSE',
  3620. SENSITIVE: 'SENSITIVE'
  3621. };
  3622. // Does a waiting check before proceeding to load the plugin.
  3623. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3624. // This methid will use an interval to wait for the plugin to be ready.
  3625. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3626. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3627. // This function will be called when plugin is ready. It sends necessary
  3628. // details to the plugin.
  3629. // The function will wait for the document to be ready and the set the
  3630. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3631. // indicating that it can start being requested.
  3632. // This function is not in the IE/Safari condition brackets so that
  3633. // TemPluginLoaded function might be called on Chrome/Firefox.
  3634. // This function is the only private function that is not encapsulated to
  3635. // allow the plugin method to be called.
  3636. __TemWebRTCReady0 = function () {
  3637. if (document.readyState === 'complete') {
  3638. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3639. AdapterJS.maybeThroughWebRTCReady();
  3640. } else {
  3641. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3642. if (document.readyState === 'complete') {
  3643. // TODO: update comments, we wait for the document to be ready
  3644. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3645. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3646. AdapterJS.maybeThroughWebRTCReady();
  3647. }
  3648. }, 100);
  3649. }
  3650. };
  3651. AdapterJS.maybeThroughWebRTCReady = function() {
  3652. if (!AdapterJS.onwebrtcreadyDone) {
  3653. AdapterJS.onwebrtcreadyDone = true;
  3654. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3655. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3656. }
  3657. }
  3658. };
  3659. // Text namespace
  3660. AdapterJS.TEXT = {
  3661. PLUGIN: {
  3662. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3663. 'to work on this browser.',
  3664. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3665. BUTTON: 'Install Now'
  3666. },
  3667. REFRESH: {
  3668. REQUIRE_REFRESH: 'Please refresh page',
  3669. BUTTON: 'Refresh Page'
  3670. }
  3671. };
  3672. // The result of ice connection states.
  3673. // - starting: Ice connection is starting.
  3674. // - checking: Ice connection is checking.
  3675. // - connected Ice connection is connected.
  3676. // - completed Ice connection is connected.
  3677. // - done Ice connection has been completed.
  3678. // - disconnected Ice connection has been disconnected.
  3679. // - failed Ice connection has failed.
  3680. // - closed Ice connection is closed.
  3681. AdapterJS._iceConnectionStates = {
  3682. starting : 'starting',
  3683. checking : 'checking',
  3684. connected : 'connected',
  3685. completed : 'connected',
  3686. done : 'completed',
  3687. disconnected : 'disconnected',
  3688. failed : 'failed',
  3689. closed : 'closed'
  3690. };
  3691. //The IceConnection states that has been fired for each peer.
  3692. AdapterJS._iceConnectionFiredStates = [];
  3693. // Check if WebRTC Interface is defined.
  3694. AdapterJS.isDefined = null;
  3695. // This function helps to retrieve the webrtc detected browser information.
  3696. // This sets:
  3697. // - webrtcDetectedBrowser: The browser agent name.
  3698. // - webrtcDetectedVersion: The browser version.
  3699. // - webrtcDetectedType: The types of webRTC support.
  3700. // - 'moz': Mozilla implementation of webRTC.
  3701. // - 'webkit': WebKit implementation of webRTC.
  3702. // - 'plugin': Using the plugin implementation.
  3703. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3704. var hasMatch, checkMatch = navigator.userAgent.match(
  3705. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3706. if (/trident/i.test(checkMatch[1])) {
  3707. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3708. webrtcDetectedBrowser = 'IE';
  3709. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3710. } else if (checkMatch[1] === 'Chrome') {
  3711. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3712. if (hasMatch !== null) {
  3713. webrtcDetectedBrowser = 'opera';
  3714. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3715. }
  3716. }
  3717. if (navigator.userAgent.indexOf('Safari')) {
  3718. if (typeof InstallTrigger !== 'undefined') {
  3719. webrtcDetectedBrowser = 'firefox';
  3720. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3721. webrtcDetectedBrowser = 'IE';
  3722. } else if (
  3723. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3724. webrtcDetectedBrowser = 'safari';
  3725. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3726. webrtcDetectedBrowser = 'opera';
  3727. } else if (!!window.chrome) {
  3728. webrtcDetectedBrowser = 'chrome';
  3729. }
  3730. }
  3731. if (!webrtcDetectedBrowser) {
  3732. webrtcDetectedVersion = checkMatch[1];
  3733. }
  3734. if (!webrtcDetectedVersion) {
  3735. try {
  3736. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3737. [navigator.appName, navigator.appVersion, '-?'];
  3738. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3739. checkMatch.splice(1, 1, hasMatch[1]);
  3740. }
  3741. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3742. } catch (error) { }
  3743. }
  3744. };
  3745. // To fix configuration as some browsers does not support
  3746. // the 'urls' attribute.
  3747. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3748. if (pcConfig === null) {
  3749. return;
  3750. }
  3751. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3752. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3753. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3754. delete pcConfig.iceServers[i].urls;
  3755. }
  3756. }
  3757. };
  3758. AdapterJS.addEvent = function(elem, evnt, func) {
  3759. if (elem.addEventListener) { // W3C DOM
  3760. elem.addEventListener(evnt, func, false);
  3761. } else if (elem.attachEvent) {// OLD IE DOM
  3762. elem.attachEvent('on'+evnt, func);
  3763. } else { // No much to do
  3764. elem[evnt] = func;
  3765. }
  3766. };
  3767. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3768. // only inject once the page is ready
  3769. if (document.readyState !== 'complete') {
  3770. return;
  3771. }
  3772. var w = window;
  3773. var i = document.createElement('iframe');
  3774. i.style.position = 'fixed';
  3775. i.style.top = '-41px';
  3776. i.style.left = 0;
  3777. i.style.right = 0;
  3778. i.style.width = '100%';
  3779. i.style.height = '40px';
  3780. i.style.backgroundColor = '#ffffe1';
  3781. i.style.border = 'none';
  3782. i.style.borderBottom = '1px solid #888888';
  3783. i.style.zIndex = '9999999';
  3784. if(typeof i.style.webkitTransition === 'string') {
  3785. i.style.webkitTransition = 'all .5s ease-out';
  3786. } else if(typeof i.style.transition === 'string') {
  3787. i.style.transition = 'all .5s ease-out';
  3788. }
  3789. document.body.appendChild(i);
  3790. c = (i.contentWindow) ? i.contentWindow :
  3791. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3792. c.document.open();
  3793. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3794. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3795. 'middle; cursor: default;">' + text + '</span>');
  3796. if(buttonText && buttonLink) {
  3797. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3798. c.document.close();
  3799. // On click on okay
  3800. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3801. if (!!displayRefreshBar) {
  3802. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3803. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3804. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3805. }
  3806. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3807. e.preventDefault();
  3808. try {
  3809. event.cancelBubble = true;
  3810. } catch(error) { }
  3811. var pluginInstallInterval = setInterval(function(){
  3812. if(! isIE) {
  3813. navigator.plugins.refresh(false);
  3814. }
  3815. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3816. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3817. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3818. function() { // plugin now installed
  3819. clearInterval(pluginInstallInterval);
  3820. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3821. },
  3822. function() {
  3823. // still no plugin detected, nothing to do
  3824. });
  3825. } , 500);
  3826. });
  3827. // On click on Cancel
  3828. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3829. w.document.body.removeChild(i);
  3830. });
  3831. } else {
  3832. c.document.close();
  3833. }
  3834. setTimeout(function() {
  3835. if(typeof i.style.webkitTransform === 'string') {
  3836. i.style.webkitTransform = 'translateY(40px)';
  3837. } else if(typeof i.style.transform === 'string') {
  3838. i.style.transform = 'translateY(40px)';
  3839. } else {
  3840. i.style.top = '0px';
  3841. }
  3842. }, 300);
  3843. };
  3844. // -----------------------------------------------------------
  3845. // Detected webrtc implementation. Types are:
  3846. // - 'moz': Mozilla implementation of webRTC.
  3847. // - 'webkit': WebKit implementation of webRTC.
  3848. // - 'plugin': Using the plugin implementation.
  3849. webrtcDetectedType = null;
  3850. // Detected webrtc datachannel support. Types are:
  3851. // - 'SCTP': SCTP datachannel support.
  3852. // - 'RTP': RTP datachannel support.
  3853. webrtcDetectedDCSupport = null;
  3854. // Set the settings for creating DataChannels, MediaStream for
  3855. // Cross-browser compability.
  3856. // - This is only for SCTP based support browsers.
  3857. // the 'urls' attribute.
  3858. checkMediaDataChannelSettings =
  3859. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3860. if (typeof callback !== 'function') {
  3861. return;
  3862. }
  3863. var beOfferer = true;
  3864. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3865. // Nightly version does not require MozDontOfferDataChannel for interop
  3866. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3867. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3868. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3869. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3870. // Resends an updated version of constraints for MozDataChannel to work
  3871. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3872. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3873. try {
  3874. delete constraints.mandatory.MozDontOfferDataChannel;
  3875. } catch (error) {
  3876. console.error('Failed deleting MozDontOfferDataChannel');
  3877. console.error(error);
  3878. }
  3879. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3880. constraints.mandatory.MozDontOfferDataChannel = true;
  3881. }
  3882. if (!isLocalFirefox) {
  3883. // temporary measure to remove Moz* constraints in non Firefox browsers
  3884. for (var prop in constraints.mandatory) {
  3885. if (constraints.mandatory.hasOwnProperty(prop)) {
  3886. if (prop.indexOf('Moz') !== -1) {
  3887. delete constraints.mandatory[prop];
  3888. }
  3889. }
  3890. }
  3891. }
  3892. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3893. // interopability of the media stream
  3894. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3895. beOfferer = false;
  3896. }
  3897. callback(beOfferer, constraints);
  3898. };
  3899. // Handles the differences for all browsers ice connection state output.
  3900. // - Tested outcomes are:
  3901. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3902. // - Chrome (answerer) : 'checking' > 'connected'
  3903. // - Firefox (offerer) : 'checking' > 'connected'
  3904. // - Firefox (answerer): 'checking' > 'connected'
  3905. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3906. if (typeof callback !== 'function') {
  3907. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3908. return;
  3909. }
  3910. peerId = (peerId) ? peerId : 'peer';
  3911. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3912. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3913. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3914. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3915. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3916. }
  3917. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3918. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3919. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3920. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3921. setTimeout(function () {
  3922. AdapterJS._iceConnectionFiredStates[peerId]
  3923. .push(AdapterJS._iceConnectionStates.done);
  3924. callback(AdapterJS._iceConnectionStates.done);
  3925. }, 1000);
  3926. }
  3927. callback(iceConnectionState);
  3928. }
  3929. return;
  3930. };
  3931. // Firefox:
  3932. // - Creates iceServer from the url for Firefox.
  3933. // - Create iceServer with stun url.
  3934. // - Create iceServer with turn url.
  3935. // - Ignore the transport parameter from TURN url for FF version <=27.
  3936. // - Return null for createIceServer if transport=tcp.
  3937. // - FF 27 and above supports transport parameters in TURN url,
  3938. // - So passing in the full url to create iceServer.
  3939. // Chrome:
  3940. // - Creates iceServer from the url for Chrome M33 and earlier.
  3941. // - Create iceServer with stun url.
  3942. // - Chrome M28 & above uses below TURN format.
  3943. // Plugin:
  3944. // - Creates Ice Server for Plugin Browsers
  3945. // - If Stun - Create iceServer with stun url.
  3946. // - Else - Create iceServer with turn url
  3947. // - This is a WebRTC Function
  3948. createIceServer = null;
  3949. // Firefox:
  3950. // - Creates IceServers for Firefox
  3951. // - Use .url for FireFox.
  3952. // - Multiple Urls support
  3953. // Chrome:
  3954. // - Creates iceServers from the urls for Chrome M34 and above.
  3955. // - .urls is supported since Chrome M34.
  3956. // - Multiple Urls support
  3957. // Plugin:
  3958. // - Creates Ice Servers for Plugin Browsers
  3959. // - Multiple Urls support
  3960. // - This is a WebRTC Function
  3961. createIceServers = null;
  3962. //------------------------------------------------------------
  3963. //The RTCPeerConnection object.
  3964. RTCPeerConnection = null;
  3965. // Creates RTCSessionDescription object for Plugin Browsers
  3966. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3967. RTCSessionDescription : null;
  3968. // Creates RTCIceCandidate object for Plugin Browsers
  3969. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3970. RTCIceCandidate : null;
  3971. // Get UserMedia (only difference is the prefix).
  3972. // Code from Adam Barth.
  3973. getUserMedia = null;
  3974. // Attach a media stream to an element.
  3975. attachMediaStream = null;
  3976. // Re-attach a media stream to an element.
  3977. reattachMediaStream = null;
  3978. // Detected browser agent name. Types are:
  3979. // - 'firefox': Firefox browser.
  3980. // - 'chrome': Chrome browser.
  3981. // - 'opera': Opera browser.
  3982. // - 'safari': Safari browser.
  3983. // - 'IE' - Internet Explorer browser.
  3984. webrtcDetectedBrowser = null;
  3985. // Detected browser version.
  3986. webrtcDetectedVersion = null;
  3987. // Check for browser types and react accordingly
  3988. if (navigator.mozGetUserMedia) {
  3989. webrtcDetectedBrowser = 'firefox';
  3990. webrtcDetectedVersion = parseInt(navigator
  3991. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3992. webrtcDetectedType = 'moz';
  3993. webrtcDetectedDCSupport = 'SCTP';
  3994. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3995. AdapterJS.maybeFixConfiguration(pcConfig);
  3996. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3997. };
  3998. // The RTCSessionDescription object.
  3999. RTCSessionDescription = mozRTCSessionDescription;
  4000. window.RTCSessionDescription = RTCSessionDescription;
  4001. // The RTCIceCandidate object.
  4002. RTCIceCandidate = mozRTCIceCandidate;
  4003. window.RTCIceCandidate = RTCIceCandidate;
  4004. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4005. navigator.getUserMedia = window.getUserMedia;
  4006. // Shim for MediaStreamTrack.getSources.
  4007. MediaStreamTrack.getSources = function(successCb) {
  4008. setTimeout(function() {
  4009. var infos = [
  4010. { kind: 'audio', id: 'default', label:'', facing:'' },
  4011. { kind: 'video', id: 'default', label:'', facing:'' }
  4012. ];
  4013. successCb(infos);
  4014. }, 0);
  4015. };
  4016. createIceServer = function (url, username, password) {
  4017. var iceServer = null;
  4018. var url_parts = url.split(':');
  4019. if (url_parts[0].indexOf('stun') === 0) {
  4020. iceServer = { url : url };
  4021. } else if (url_parts[0].indexOf('turn') === 0) {
  4022. if (webrtcDetectedVersion < 27) {
  4023. var turn_url_parts = url.split('?');
  4024. if (turn_url_parts.length === 1 ||
  4025. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4026. iceServer = {
  4027. url : turn_url_parts[0],
  4028. credential : password,
  4029. username : username
  4030. };
  4031. }
  4032. } else {
  4033. iceServer = {
  4034. url : url,
  4035. credential : password,
  4036. username : username
  4037. };
  4038. }
  4039. }
  4040. return iceServer;
  4041. };
  4042. createIceServers = function (urls, username, password) {
  4043. var iceServers = [];
  4044. for (var i = 0; i < urls.length; i++) {
  4045. var iceServer = createIceServer(urls[i], username, password);
  4046. if (iceServer !== null) {
  4047. iceServers.push(iceServer);
  4048. }
  4049. }
  4050. return iceServers;
  4051. };
  4052. attachMediaStream = function (element, stream) {
  4053. element.mozSrcObject = stream;
  4054. if (stream !== null)
  4055. element.play();
  4056. return element;
  4057. };
  4058. reattachMediaStream = function (to, from) {
  4059. to.mozSrcObject = from.mozSrcObject;
  4060. to.play();
  4061. return to;
  4062. };
  4063. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4064. if (!callback) {
  4065. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4066. ': 1 argument required, but only 0 present.');
  4067. }
  4068. return callback([]);
  4069. };
  4070. // Fake get{Video,Audio}Tracks
  4071. if (!MediaStream.prototype.getVideoTracks) {
  4072. MediaStream.prototype.getVideoTracks = function () {
  4073. return [];
  4074. };
  4075. }
  4076. if (!MediaStream.prototype.getAudioTracks) {
  4077. MediaStream.prototype.getAudioTracks = function () {
  4078. return [];
  4079. };
  4080. }
  4081. AdapterJS.maybeThroughWebRTCReady();
  4082. } else if (navigator.webkitGetUserMedia) {
  4083. webrtcDetectedBrowser = 'chrome';
  4084. webrtcDetectedType = 'webkit';
  4085. webrtcDetectedVersion = parseInt(navigator
  4086. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4087. // check if browser is opera 20+
  4088. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4089. if (checkIfOpera !== null) {
  4090. webrtcDetectedBrowser = 'opera';
  4091. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4092. }
  4093. // check browser datachannel support
  4094. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4095. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4096. webrtcDetectedDCSupport = 'SCTP';
  4097. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4098. webrtcDetectedVersion > 24) {
  4099. webrtcDetectedDCSupport = 'RTP';
  4100. } else {
  4101. webrtcDetectedDCSupport = '';
  4102. }
  4103. createIceServer = function (url, username, password) {
  4104. var iceServer = null;
  4105. var url_parts = url.split(':');
  4106. if (url_parts[0].indexOf('stun') === 0) {
  4107. iceServer = { 'url' : url };
  4108. } else if (url_parts[0].indexOf('turn') === 0) {
  4109. iceServer = {
  4110. 'url' : url,
  4111. 'credential' : password,
  4112. 'username' : username
  4113. };
  4114. }
  4115. return iceServer;
  4116. };
  4117. createIceServers = function (urls, username, password) {
  4118. var iceServers = [];
  4119. if (webrtcDetectedVersion >= 34) {
  4120. iceServers = {
  4121. 'urls' : urls,
  4122. 'credential' : password,
  4123. 'username' : username
  4124. };
  4125. } else {
  4126. for (var i = 0; i < urls.length; i++) {
  4127. var iceServer = createIceServer(urls[i], username, password);
  4128. if (iceServer !== null) {
  4129. iceServers.push(iceServer);
  4130. }
  4131. }
  4132. }
  4133. return iceServers;
  4134. };
  4135. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4136. if (webrtcDetectedVersion < 34) {
  4137. AdapterJS.maybeFixConfiguration(pcConfig);
  4138. }
  4139. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4140. };
  4141. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4142. navigator.getUserMedia = window.getUserMedia;
  4143. attachMediaStream = function (element, stream) {
  4144. if (typeof element.srcObject !== 'undefined') {
  4145. element.srcObject = stream;
  4146. } else if (typeof element.mozSrcObject !== 'undefined') {
  4147. element.mozSrcObject = stream;
  4148. } else if (typeof element.src !== 'undefined') {
  4149. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4150. } else {
  4151. console.log('Error attaching stream to element.');
  4152. }
  4153. return element;
  4154. };
  4155. reattachMediaStream = function (to, from) {
  4156. to.src = from.src;
  4157. return to;
  4158. };
  4159. AdapterJS.maybeThroughWebRTCReady();
  4160. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4161. /Edge\/(\d+).(\d+)$/)) {
  4162. webrtcDetectedBrowser = 'edge';
  4163. webrtcDetectedVersion =
  4164. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4165. // the minimum version still supported by adapter.
  4166. webrtcMinimumVersion = 12;
  4167. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4168. attachMediaStream = function(element, stream) {
  4169. element.srcObject = stream;
  4170. return element;
  4171. };
  4172. reattachMediaStream = function(to, from) {
  4173. to.srcObject = from.srcObject;
  4174. return to;
  4175. };
  4176. AdapterJS.maybeThroughWebRTCReady();
  4177. } else { // TRY TO USE PLUGIN
  4178. // IE 9 is not offering an implementation of console.log until you open a console
  4179. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4180. /* jshint -W020 */
  4181. console = {} || console;
  4182. // Implemented based on console specs from MDN
  4183. // You may override these functions
  4184. console.log = function (arg) {};
  4185. console.info = function (arg) {};
  4186. console.error = function (arg) {};
  4187. console.dir = function (arg) {};
  4188. console.exception = function (arg) {};
  4189. console.trace = function (arg) {};
  4190. console.warn = function (arg) {};
  4191. console.count = function (arg) {};
  4192. console.debug = function (arg) {};
  4193. console.count = function (arg) {};
  4194. console.time = function (arg) {};
  4195. console.timeEnd = function (arg) {};
  4196. console.group = function (arg) {};
  4197. console.groupCollapsed = function (arg) {};
  4198. console.groupEnd = function (arg) {};
  4199. /* jshint +W020 */
  4200. }
  4201. webrtcDetectedType = 'plugin';
  4202. webrtcDetectedDCSupport = 'plugin';
  4203. AdapterJS.parseWebrtcDetectedBrowser();
  4204. isIE = webrtcDetectedBrowser === 'IE';
  4205. /* jshint -W035 */
  4206. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4207. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4208. /* empty because it needs to prevent the function from running. */
  4209. }
  4210. };
  4211. /* jshint +W035 */
  4212. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4213. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4214. // Call immediately if possible
  4215. // Once the plugin is set, the code will always take this path
  4216. callback();
  4217. } else {
  4218. // otherwise start a 100ms interval
  4219. var checkPluginReadyState = setInterval(function () {
  4220. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4221. clearInterval(checkPluginReadyState);
  4222. callback();
  4223. }
  4224. }, 100);
  4225. }
  4226. };
  4227. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4228. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4229. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4230. });
  4231. };
  4232. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4233. // only inject once the page is ready
  4234. if (document.readyState !== 'complete') {
  4235. return;
  4236. }
  4237. // Prevent multiple injections
  4238. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4239. return;
  4240. }
  4241. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4242. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4243. var frag = document.createDocumentFragment();
  4244. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4245. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4246. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4247. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4248. '<param name="pluginId" value="' +
  4249. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4250. '<param name="windowless" value="false" /> ' +
  4251. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4252. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4253. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4254. // uncomment to be able to use virtual cams
  4255. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4256. '</object>';
  4257. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4258. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4259. }
  4260. document.body.appendChild(frag);
  4261. // Need to re-fetch the plugin
  4262. AdapterJS.WebRTCPlugin.plugin =
  4263. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4264. } else {
  4265. // Load Plugin
  4266. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4267. AdapterJS.WebRTCPlugin.plugin.id =
  4268. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4269. // IE will only start the plugin if it's ACTUALLY visible
  4270. if (isIE) {
  4271. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4272. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4273. } else { // The size of the plugin on Safari should be 0x0px
  4274. // so that the autorisation prompt is at the top
  4275. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4276. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4277. }
  4278. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4279. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4280. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4281. '<param name="pluginId" value="' +
  4282. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4283. '<param name="windowless" value="false" /> ' +
  4284. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4285. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4286. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4287. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4288. }
  4289. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4290. };
  4291. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4292. function (comName, plugName, installedCb, notInstalledCb) {
  4293. if (!isIE) {
  4294. var pluginArray = navigator.plugins;
  4295. for (var i = 0; i < pluginArray.length; i++) {
  4296. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4297. installedCb();
  4298. return;
  4299. }
  4300. }
  4301. notInstalledCb();
  4302. } else {
  4303. try {
  4304. var axo = new ActiveXObject(comName + '.' + plugName);
  4305. } catch (e) {
  4306. notInstalledCb();
  4307. return;
  4308. }
  4309. installedCb();
  4310. }
  4311. };
  4312. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4313. if (AdapterJS.WebRTCPlugin.pluginState ===
  4314. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4315. console.error("AdapterJS - WebRTC interface has already been defined");
  4316. return;
  4317. }
  4318. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4319. AdapterJS.isDefined = function (variable) {
  4320. return variable !== null && variable !== undefined;
  4321. };
  4322. createIceServer = function (url, username, password) {
  4323. var iceServer = null;
  4324. var url_parts = url.split(':');
  4325. if (url_parts[0].indexOf('stun') === 0) {
  4326. iceServer = {
  4327. 'url' : url,
  4328. 'hasCredentials' : false
  4329. };
  4330. } else if (url_parts[0].indexOf('turn') === 0) {
  4331. iceServer = {
  4332. 'url' : url,
  4333. 'hasCredentials' : true,
  4334. 'credential' : password,
  4335. 'username' : username
  4336. };
  4337. }
  4338. return iceServer;
  4339. };
  4340. createIceServers = function (urls, username, password) {
  4341. var iceServers = [];
  4342. for (var i = 0; i < urls.length; ++i) {
  4343. iceServers.push(createIceServer(urls[i], username, password));
  4344. }
  4345. return iceServers;
  4346. };
  4347. RTCSessionDescription = function (info) {
  4348. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4349. return AdapterJS.WebRTCPlugin.plugin.
  4350. ConstructSessionDescription(info.type, info.sdp);
  4351. };
  4352. RTCPeerConnection = function (servers, constraints) {
  4353. var iceServers = null;
  4354. if (servers) {
  4355. iceServers = servers.iceServers;
  4356. for (var i = 0; i < iceServers.length; i++) {
  4357. if (iceServers[i].urls && !iceServers[i].url) {
  4358. iceServers[i].url = iceServers[i].urls;
  4359. }
  4360. iceServers[i].hasCredentials = AdapterJS.
  4361. isDefined(iceServers[i].username) &&
  4362. AdapterJS.isDefined(iceServers[i].credential);
  4363. }
  4364. }
  4365. var mandatory = (constraints && constraints.mandatory) ?
  4366. constraints.mandatory : null;
  4367. var optional = (constraints && constraints.optional) ?
  4368. constraints.optional : null;
  4369. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4370. return AdapterJS.WebRTCPlugin.plugin.
  4371. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4372. iceServers, mandatory, optional);
  4373. };
  4374. MediaStreamTrack = {};
  4375. MediaStreamTrack.getSources = function (callback) {
  4376. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4377. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4378. });
  4379. };
  4380. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4381. constraints.audio = constraints.audio || false;
  4382. constraints.video = constraints.video || false;
  4383. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4384. AdapterJS.WebRTCPlugin.plugin.
  4385. getUserMedia(constraints, successCallback, failureCallback);
  4386. });
  4387. };
  4388. window.navigator.getUserMedia = window.getUserMedia;
  4389. attachMediaStream = function (element, stream) {
  4390. if (!element || !element.parentNode) {
  4391. return;
  4392. }
  4393. var streamId;
  4394. if (stream === null) {
  4395. streamId = '';
  4396. } else {
  4397. if (typeof stream.enableSoundTracks !== 'undefined') {
  4398. stream.enableSoundTracks(true);
  4399. }
  4400. streamId = stream.id;
  4401. }
  4402. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4403. var nodeName = element.nodeName.toLowerCase();
  4404. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4405. var tag;
  4406. switch(nodeName) {
  4407. case 'audio':
  4408. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4409. break;
  4410. case 'video':
  4411. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4412. break;
  4413. default:
  4414. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4415. }
  4416. var frag = document.createDocumentFragment();
  4417. var temp = document.createElement('div');
  4418. var classHTML = '';
  4419. if (element.className) {
  4420. classHTML = 'class="' + element.className + '" ';
  4421. } else if (element.attributes && element.attributes['class']) {
  4422. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4423. }
  4424. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4425. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4426. '<param name="pluginId" value="' + elementId + '" /> ' +
  4427. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4428. '<param name="windowless" value="true" /> ' +
  4429. '<param name="streamId" value="' + streamId + '" /> ' +
  4430. '<param name="tag" value="' + tag + '" /> ' +
  4431. '</object>';
  4432. while (temp.firstChild) {
  4433. frag.appendChild(temp.firstChild);
  4434. }
  4435. var height = '';
  4436. var width = '';
  4437. if (element.clientWidth || element.clientHeight) {
  4438. width = element.clientWidth;
  4439. height = element.clientHeight;
  4440. }
  4441. else if (element.width || element.height) {
  4442. width = element.width;
  4443. height = element.height;
  4444. }
  4445. element.parentNode.insertBefore(frag, element);
  4446. frag = document.getElementById(elementId);
  4447. frag.width = width;
  4448. frag.height = height;
  4449. element.parentNode.removeChild(element);
  4450. } else { // already an <object> tag, just change the stream id
  4451. var children = element.children;
  4452. for (var i = 0; i !== children.length; ++i) {
  4453. if (children[i].name === 'streamId') {
  4454. children[i].value = streamId;
  4455. break;
  4456. }
  4457. }
  4458. element.setStreamId(streamId);
  4459. }
  4460. var newElement = document.getElementById(elementId);
  4461. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4462. return newElement;
  4463. };
  4464. reattachMediaStream = function (to, from) {
  4465. var stream = null;
  4466. var children = from.children;
  4467. for (var i = 0; i !== children.length; ++i) {
  4468. if (children[i].name === 'streamId') {
  4469. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4470. stream = AdapterJS.WebRTCPlugin.plugin
  4471. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4472. break;
  4473. }
  4474. }
  4475. if (stream !== null) {
  4476. return attachMediaStream(to, stream);
  4477. } else {
  4478. console.log('Could not find the stream associated with this element');
  4479. }
  4480. };
  4481. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4482. properties = Object.getOwnPropertyNames( prototype );
  4483. for(prop in properties) {
  4484. propName = properties[prop];
  4485. if (typeof(propName.slice) === 'function') {
  4486. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4487. if (isIE) {
  4488. destElem.attachEvent(propName,srcElem[propName]);
  4489. } else {
  4490. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4491. }
  4492. } else {
  4493. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4494. }
  4495. }
  4496. }
  4497. var subPrototype = Object.getPrototypeOf(prototype)
  4498. if(subPrototype != null) {
  4499. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4500. }
  4501. }
  4502. RTCIceCandidate = function (candidate) {
  4503. if (!candidate.sdpMid) {
  4504. candidate.sdpMid = '';
  4505. }
  4506. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4507. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4508. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4509. );
  4510. };
  4511. // inject plugin
  4512. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4513. AdapterJS.WebRTCPlugin.injectPlugin();
  4514. };
  4515. // This function will be called if the plugin is needed (browser different
  4516. // from Chrome or Firefox), but the plugin is not installed.
  4517. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4518. function() {
  4519. AdapterJS.addEvent(document,
  4520. 'readystatechange',
  4521. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4522. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4523. };
  4524. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4525. if (AdapterJS.options.hidePluginInstallPrompt) {
  4526. return;
  4527. }
  4528. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4529. if(downloadLink) { // if download link
  4530. var popupString;
  4531. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4532. popupString = 'This website requires you to install the ' +
  4533. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4534. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4535. ' WebRTC Plugin</a>' +
  4536. ' to work on this browser.';
  4537. } else { // no portal link, just print a generic explanation
  4538. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4539. }
  4540. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4541. } else { // no download link, just print a generic explanation
  4542. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4543. }
  4544. };
  4545. // Try to detect the plugin and act accordingly
  4546. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4547. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4548. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4549. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4550. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4551. }
  4552. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4553. },{"jitsi-meet-logger":48}],21:[function(require,module,exports){
  4554. (function (__filename){
  4555. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4556. function supportsLocalStorage() {
  4557. try {
  4558. return 'localStorage' in window && window.localStorage !== null;
  4559. } catch (e) {
  4560. logger.log("localstorage is not supported");
  4561. return false;
  4562. }
  4563. }
  4564. function generateUniqueId() {
  4565. function _p8() {
  4566. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4567. }
  4568. return _p8() + _p8() + _p8() + _p8();
  4569. }
  4570. function Settings(conferenceID) {
  4571. this.displayName = '';
  4572. this.userId;
  4573. this.confSettings = null;
  4574. this.conferenceID = conferenceID;
  4575. if (supportsLocalStorage()) {
  4576. if(!window.localStorage.getItem(conferenceID))
  4577. this.confSettings = {};
  4578. else
  4579. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4580. if(!this.confSettings.jitsiMeetId) {
  4581. this.confSettings.jitsiMeetId = generateUniqueId();
  4582. logger.log("generated id",
  4583. this.confSettings.jitsiMeetId);
  4584. this.save();
  4585. }
  4586. this.userId = this.confSettings.jitsiMeetId || '';
  4587. this.displayName = this.confSettings.displayname || '';
  4588. } else {
  4589. logger.log("local storage is not supported");
  4590. this.userId = generateUniqueId();
  4591. }
  4592. }
  4593. Settings.prototype.save = function () {
  4594. if(!supportsLocalStorage())
  4595. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4596. }
  4597. Settings.prototype.setDisplayName = function (newDisplayName) {
  4598. this.displayName = newDisplayName;
  4599. if(this.confSettings != null)
  4600. this.confSettings.displayname = displayName;
  4601. this.save();
  4602. return this.displayName;
  4603. },
  4604. Settings.prototype.getSettings = function () {
  4605. return {
  4606. displayName: this.displayName,
  4607. uid: this.userId
  4608. };
  4609. },
  4610. module.exports = Settings;
  4611. }).call(this,"/modules/settings/Settings.js")
  4612. },{"jitsi-meet-logger":48}],22:[function(require,module,exports){
  4613. /* global config */
  4614. /**
  4615. * Provides statistics for the local stream.
  4616. */
  4617. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4618. /**
  4619. * Size of the webaudio analyzer buffer.
  4620. * @type {number}
  4621. */
  4622. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4623. /**
  4624. * Value of the webaudio analyzer smoothing time parameter.
  4625. * @type {number}
  4626. */
  4627. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4628. /**
  4629. * Converts time domain data array to audio level.
  4630. * @param samples the time domain data array.
  4631. * @returns {number} the audio level
  4632. */
  4633. function timeDomainDataToAudioLevel(samples) {
  4634. var maxVolume = 0;
  4635. var length = samples.length;
  4636. for (var i = 0; i < length; i++) {
  4637. if (maxVolume < samples[i])
  4638. maxVolume = samples[i];
  4639. }
  4640. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4641. }
  4642. /**
  4643. * Animates audio level change
  4644. * @param newLevel the new audio level
  4645. * @param lastLevel the last audio level
  4646. * @returns {Number} the audio level to be set
  4647. */
  4648. function animateLevel(newLevel, lastLevel) {
  4649. var value = 0;
  4650. var diff = lastLevel - newLevel;
  4651. if(diff > 0.2) {
  4652. value = lastLevel - 0.2;
  4653. }
  4654. else if(diff < -0.4) {
  4655. value = lastLevel + 0.4;
  4656. }
  4657. else {
  4658. value = newLevel;
  4659. }
  4660. return parseFloat(value.toFixed(3));
  4661. }
  4662. /**
  4663. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4664. *
  4665. * @param stream the local stream
  4666. * @param interval stats refresh interval given in ms.
  4667. * @param callback function that receives the audio levels.
  4668. * @constructor
  4669. */
  4670. function LocalStatsCollector(stream, interval, callback) {
  4671. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4672. this.stream = stream;
  4673. this.intervalId = null;
  4674. this.intervalMilis = interval;
  4675. this.audioLevel = 0;
  4676. this.callback = callback;
  4677. }
  4678. /**
  4679. * Starts the collecting the statistics.
  4680. */
  4681. LocalStatsCollector.prototype.start = function () {
  4682. if (!window.AudioContext ||
  4683. RTCBrowserType.isTemasysPluginUsed())
  4684. return;
  4685. var context = new AudioContext();
  4686. var analyser = context.createAnalyser();
  4687. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4688. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4689. var source = context.createMediaStreamSource(this.stream);
  4690. source.connect(analyser);
  4691. var self = this;
  4692. this.intervalId = setInterval(
  4693. function () {
  4694. var array = new Uint8Array(analyser.frequencyBinCount);
  4695. analyser.getByteTimeDomainData(array);
  4696. var audioLevel = timeDomainDataToAudioLevel(array);
  4697. if (audioLevel != self.audioLevel) {
  4698. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4699. self.callback(self.audioLevel);
  4700. }
  4701. },
  4702. this.intervalMilis
  4703. );
  4704. };
  4705. /**
  4706. * Stops collecting the statistics.
  4707. */
  4708. LocalStatsCollector.prototype.stop = function () {
  4709. if (this.intervalId) {
  4710. clearInterval(this.intervalId);
  4711. this.intervalId = null;
  4712. }
  4713. };
  4714. module.exports = LocalStatsCollector;
  4715. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4716. (function (__filename){
  4717. /* global require, ssrc2jid */
  4718. /* jshint -W117 */
  4719. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4720. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4721. var StatisticsEvents = require("../../service/statistics/Events");
  4722. /* Whether we support the browser we are running into for logging statistics */
  4723. var browserSupported = RTCBrowserType.isChrome() ||
  4724. RTCBrowserType.isOpera();
  4725. var keyMap = {};
  4726. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4727. "ssrc": "ssrc",
  4728. "packetsReceived": "packetsReceived",
  4729. "packetsLost": "packetsLost",
  4730. "packetsSent": "packetsSent",
  4731. "bytesReceived": "bytesReceived",
  4732. "bytesSent": "bytesSent"
  4733. };
  4734. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4735. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4736. "sendBandwidth": "googAvailableSendBandwidth",
  4737. "remoteAddress": "googRemoteAddress",
  4738. "transportType": "googTransportType",
  4739. "localAddress": "googLocalAddress",
  4740. "activeConnection": "googActiveConnection",
  4741. "ssrc": "ssrc",
  4742. "packetsReceived": "packetsReceived",
  4743. "packetsSent": "packetsSent",
  4744. "packetsLost": "packetsLost",
  4745. "bytesReceived": "bytesReceived",
  4746. "bytesSent": "bytesSent",
  4747. "googFrameHeightReceived": "googFrameHeightReceived",
  4748. "googFrameWidthReceived": "googFrameWidthReceived",
  4749. "googFrameHeightSent": "googFrameHeightSent",
  4750. "googFrameWidthSent": "googFrameWidthSent",
  4751. "audioInputLevel": "audioInputLevel",
  4752. "audioOutputLevel": "audioOutputLevel"
  4753. };
  4754. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4755. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4756. /**
  4757. * Calculates packet lost percent using the number of lost packets and the
  4758. * number of all packet.
  4759. * @param lostPackets the number of lost packets
  4760. * @param totalPackets the number of all packets.
  4761. * @returns {number} packet loss percent
  4762. */
  4763. function calculatePacketLoss(lostPackets, totalPackets) {
  4764. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4765. return 0;
  4766. return Math.round((lostPackets/totalPackets)*100);
  4767. }
  4768. function getStatValue(item, name) {
  4769. var browserType = RTCBrowserType.getBrowserType();
  4770. if (!keyMap[browserType][name])
  4771. throw "The property isn't supported!";
  4772. var key = keyMap[browserType][name];
  4773. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4774. item.stat(key) : item[key];
  4775. }
  4776. function formatAudioLevel(audioLevel) {
  4777. return Math.min(Math.max(audioLevel, 0), 1);
  4778. }
  4779. /**
  4780. * Checks whether a certain record should be included in the logged statistics.
  4781. */
  4782. function acceptStat(reportId, reportType, statName) {
  4783. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4784. return false;
  4785. if (reportType == "ssrc") {
  4786. if (statName == "googTrackId" ||
  4787. statName == "transportId" ||
  4788. statName == "ssrc")
  4789. return false;
  4790. }
  4791. return true;
  4792. }
  4793. /**
  4794. * Checks whether a certain record should be included in the logged statistics.
  4795. */
  4796. function acceptReport(id, type) {
  4797. if (id.substring(0, 15) == "googCertificate" ||
  4798. id.substring(0, 9) == "googTrack" ||
  4799. id.substring(0, 20) == "googLibjingleSession")
  4800. return false;
  4801. if (type == "googComponent")
  4802. return false;
  4803. return true;
  4804. }
  4805. /**
  4806. * Peer statistics data holder.
  4807. * @constructor
  4808. */
  4809. function PeerStats()
  4810. {
  4811. this.ssrc2Loss = {};
  4812. this.ssrc2AudioLevel = {};
  4813. this.ssrc2bitrate = {};
  4814. this.ssrc2resolution = {};
  4815. }
  4816. /**
  4817. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4818. * represented by this instance.
  4819. * @param lossRate new packet loss rate value to be set.
  4820. */
  4821. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4822. {
  4823. this.ssrc2Loss = lossRate;
  4824. };
  4825. /**
  4826. * Sets resolution that belong to the ssrc
  4827. * represented by this instance.
  4828. * @param resolution new resolution value to be set.
  4829. */
  4830. PeerStats.prototype.setSsrcResolution = function (resolution)
  4831. {
  4832. if(resolution === null && this.ssrc2resolution[ssrc])
  4833. {
  4834. delete this.ssrc2resolution[ssrc];
  4835. }
  4836. else if(resolution !== null)
  4837. this.ssrc2resolution[ssrc] = resolution;
  4838. };
  4839. /**
  4840. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4841. * represented by this instance.
  4842. * @param ssrc audio or video RTP stream SSRC.
  4843. * @param bitrate new bitrate value to be set.
  4844. */
  4845. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4846. {
  4847. if(this.ssrc2bitrate[ssrc])
  4848. {
  4849. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4850. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4851. }
  4852. else {
  4853. this.ssrc2bitrate[ssrc] = bitrate;
  4854. }
  4855. };
  4856. /**
  4857. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4858. * the stream which belongs to the peer represented by this instance.
  4859. * @param ssrc RTP stream SSRC for which current audio level value will be
  4860. * updated.
  4861. * @param audioLevel the new audio level value to be set. Value is truncated to
  4862. * fit the range from 0 to 1.
  4863. */
  4864. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4865. {
  4866. // Range limit 0 - 1
  4867. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4868. };
  4869. function ConferenceStats() {
  4870. /**
  4871. * The bandwidth
  4872. * @type {{}}
  4873. */
  4874. this.bandwidth = {};
  4875. /**
  4876. * The bit rate
  4877. * @type {{}}
  4878. */
  4879. this.bitrate = {};
  4880. /**
  4881. * The packet loss rate
  4882. * @type {{}}
  4883. */
  4884. this.packetLoss = null;
  4885. /**
  4886. * Array with the transport information.
  4887. * @type {Array}
  4888. */
  4889. this.transport = [];
  4890. }
  4891. /**
  4892. * <tt>StatsCollector</tt> registers for stats updates of given
  4893. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4894. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4895. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4896. * instance as an event source.
  4897. *
  4898. * @param peerconnection webRTC peer connection object.
  4899. * @param interval stats refresh interval given in ms.
  4900. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4901. * called on stats update.
  4902. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4903. * @constructor
  4904. */
  4905. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4906. {
  4907. this.peerconnection = peerconnection;
  4908. this.baselineAudioLevelsReport = null;
  4909. this.currentAudioLevelsReport = null;
  4910. this.currentStatsReport = null;
  4911. this.baselineStatsReport = null;
  4912. this.audioLevelsIntervalId = null;
  4913. this.eventEmitter = eventEmitter;
  4914. this.config = config || {};
  4915. this.conferenceStats = new ConferenceStats();
  4916. /**
  4917. * Gather PeerConnection stats once every this many milliseconds.
  4918. */
  4919. this.GATHER_INTERVAL = 15000;
  4920. /**
  4921. * Log stats via the focus once every this many milliseconds.
  4922. */
  4923. this.LOG_INTERVAL = 60000;
  4924. /**
  4925. * Gather stats and store them in this.statsToBeLogged.
  4926. */
  4927. this.gatherStatsIntervalId = null;
  4928. /**
  4929. * Send the stats already saved in this.statsToBeLogged to be logged via
  4930. * the focus.
  4931. */
  4932. this.logStatsIntervalId = null;
  4933. /**
  4934. * Stores the statistics which will be send to the focus to be logged.
  4935. */
  4936. this.statsToBeLogged =
  4937. {
  4938. timestamps: [],
  4939. stats: {}
  4940. };
  4941. // Updates stats interval
  4942. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4943. this.statsIntervalId = null;
  4944. this.statsIntervalMilis = statsInterval;
  4945. // Map of ssrcs to PeerStats
  4946. this.ssrc2stats = {};
  4947. }
  4948. module.exports = StatsCollector;
  4949. /**
  4950. * Stops stats updates.
  4951. */
  4952. StatsCollector.prototype.stop = function () {
  4953. if (this.audioLevelsIntervalId) {
  4954. clearInterval(this.audioLevelsIntervalId);
  4955. this.audioLevelsIntervalId = null;
  4956. }
  4957. if (this.statsIntervalId)
  4958. {
  4959. clearInterval(this.statsIntervalId);
  4960. this.statsIntervalId = null;
  4961. }
  4962. if(this.logStatsIntervalId)
  4963. {
  4964. clearInterval(this.logStatsIntervalId);
  4965. this.logStatsIntervalId = null;
  4966. }
  4967. if(this.gatherStatsIntervalId)
  4968. {
  4969. clearInterval(this.gatherStatsIntervalId);
  4970. this.gatherStatsIntervalId = null;
  4971. }
  4972. };
  4973. /**
  4974. * Callback passed to <tt>getStats</tt> method.
  4975. * @param error an error that occurred on <tt>getStats</tt> call.
  4976. */
  4977. StatsCollector.prototype.errorCallback = function (error)
  4978. {
  4979. logger.error("Get stats error", error);
  4980. this.stop();
  4981. };
  4982. /**
  4983. * Starts stats updates.
  4984. */
  4985. StatsCollector.prototype.start = function ()
  4986. {
  4987. var self = this;
  4988. this.audioLevelsIntervalId = setInterval(
  4989. function () {
  4990. // Interval updates
  4991. self.peerconnection.getStats(
  4992. function (report) {
  4993. var results = null;
  4994. if (!report || !report.result ||
  4995. typeof report.result != 'function') {
  4996. results = report;
  4997. }
  4998. else {
  4999. results = report.result();
  5000. }
  5001. //logger.error("Got interval report", results);
  5002. self.currentAudioLevelsReport = results;
  5003. self.processAudioLevelReport();
  5004. self.baselineAudioLevelsReport =
  5005. self.currentAudioLevelsReport;
  5006. },
  5007. self.errorCallback
  5008. );
  5009. },
  5010. self.audioLevelsIntervalMilis
  5011. );
  5012. // if (!this.config.disableStats && browserSupported) {
  5013. // this.statsIntervalId = setInterval(
  5014. // function () {
  5015. // // Interval updates
  5016. // self.peerconnection.getStats(
  5017. // function (report) {
  5018. // var results = null;
  5019. // if (!report || !report.result ||
  5020. // typeof report.result != 'function') {
  5021. // //firefox
  5022. // results = report;
  5023. // }
  5024. // else {
  5025. // //chrome
  5026. // results = report.result();
  5027. // }
  5028. // //logger.error("Got interval report", results);
  5029. // self.currentStatsReport = results;
  5030. // try {
  5031. // self.processStatsReport();
  5032. // }
  5033. // catch (e) {
  5034. // logger.error("Unsupported key:" + e, e);
  5035. // }
  5036. //
  5037. // self.baselineStatsReport = self.currentStatsReport;
  5038. // },
  5039. // self.errorCallback
  5040. // );
  5041. // },
  5042. // self.statsIntervalMilis
  5043. // );
  5044. // }
  5045. //
  5046. // if (this.config.logStats && browserSupported) {
  5047. // this.gatherStatsIntervalId = setInterval(
  5048. // function () {
  5049. // self.peerconnection.getStats(
  5050. // function (report) {
  5051. // self.addStatsToBeLogged(report.result());
  5052. // },
  5053. // function () {
  5054. // }
  5055. // );
  5056. // },
  5057. // this.GATHER_INTERVAL
  5058. // );
  5059. //
  5060. // this.logStatsIntervalId = setInterval(
  5061. // function() { self.logStats(); },
  5062. // this.LOG_INTERVAL);
  5063. // }
  5064. };
  5065. /**
  5066. * Converts the stats to the format used for logging, and saves the data in
  5067. * this.statsToBeLogged.
  5068. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5069. */
  5070. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5071. var self = this;
  5072. var num_records = this.statsToBeLogged.timestamps.length;
  5073. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5074. reports.map(function (report) {
  5075. if (!acceptReport(report.id, report.type))
  5076. return;
  5077. var stat = self.statsToBeLogged.stats[report.id];
  5078. if (!stat) {
  5079. stat = self.statsToBeLogged.stats[report.id] = {};
  5080. }
  5081. stat.type = report.type;
  5082. report.names().map(function (name) {
  5083. if (!acceptStat(report.id, report.type, name))
  5084. return;
  5085. var values = stat[name];
  5086. if (!values) {
  5087. values = stat[name] = [];
  5088. }
  5089. while (values.length < num_records) {
  5090. values.push(null);
  5091. }
  5092. values.push(report.stat(name));
  5093. });
  5094. });
  5095. };
  5096. //FIXME:
  5097. //StatsCollector.prototype.logStats = function () {
  5098. //
  5099. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5100. // return;
  5101. // // Reset the stats
  5102. // this.statsToBeLogged.stats = {};
  5103. // this.statsToBeLogged.timestamps = [];
  5104. //};
  5105. /**
  5106. * Stats processing logic.
  5107. */
  5108. StatsCollector.prototype.processStatsReport = function () {
  5109. if (!this.baselineStatsReport) {
  5110. return;
  5111. }
  5112. for (var idx in this.currentStatsReport) {
  5113. var now = this.currentStatsReport[idx];
  5114. try {
  5115. if (getStatValue(now, 'receiveBandwidth') ||
  5116. getStatValue(now, 'sendBandwidth')) {
  5117. this.conferenceStats.bandwidth = {
  5118. "download": Math.round(
  5119. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5120. "upload": Math.round(
  5121. (getStatValue(now, 'sendBandwidth')) / 1000)
  5122. };
  5123. }
  5124. }
  5125. catch(e){/*not supported*/}
  5126. if(now.type == 'googCandidatePair')
  5127. {
  5128. var ip, type, localIP, active;
  5129. try {
  5130. ip = getStatValue(now, 'remoteAddress');
  5131. type = getStatValue(now, "transportType");
  5132. localIP = getStatValue(now, "localAddress");
  5133. active = getStatValue(now, "activeConnection");
  5134. }
  5135. catch(e){/*not supported*/}
  5136. if(!ip || !type || !localIP || active != "true")
  5137. continue;
  5138. var addressSaved = false;
  5139. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5140. {
  5141. if(this.conferenceStats.transport[i].ip == ip &&
  5142. this.conferenceStats.transport[i].type == type &&
  5143. this.conferenceStats.transport[i].localip == localIP)
  5144. {
  5145. addressSaved = true;
  5146. }
  5147. }
  5148. if(addressSaved)
  5149. continue;
  5150. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5151. continue;
  5152. }
  5153. if(now.type == "candidatepair")
  5154. {
  5155. if(now.state == "succeeded")
  5156. continue;
  5157. var local = this.currentStatsReport[now.localCandidateId];
  5158. var remote = this.currentStatsReport[now.remoteCandidateId];
  5159. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5160. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5161. }
  5162. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5163. now.type != "inboundrtp") {
  5164. continue;
  5165. }
  5166. var before = this.baselineStatsReport[idx];
  5167. if (!before) {
  5168. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5169. continue;
  5170. }
  5171. var ssrc = getStatValue(now, 'ssrc');
  5172. if(!ssrc)
  5173. continue;
  5174. var ssrcStats = this.ssrc2stats[ssrc];
  5175. if (!ssrcStats) {
  5176. ssrcStats = new PeerStats();
  5177. this.ssrc2stats[ssrc] = ssrcStats;
  5178. }
  5179. var isDownloadStream = true;
  5180. var key = 'packetsReceived';
  5181. var packetsNow = getStatValue(now, key);
  5182. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5183. isDownloadStream = false;
  5184. key = 'packetsSent';
  5185. packetsNow = getStatValue(now, key);
  5186. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5187. console.warn("No packetsReceived nor packetsSent stat found");
  5188. continue;
  5189. }
  5190. }
  5191. if (!packetsNow || packetsNow < 0)
  5192. packetsNow = 0;
  5193. var packetsBefore = getStatValue(before, key);
  5194. if (!packetsBefore || packetsBefore < 0)
  5195. packetsBefore = 0;
  5196. var packetRate = packetsNow - packetsBefore;
  5197. if (!packetRate || packetRate < 0)
  5198. packetRate = 0;
  5199. var currentLoss = getStatValue(now, 'packetsLost');
  5200. if (!currentLoss || currentLoss < 0)
  5201. currentLoss = 0;
  5202. var previousLoss = getStatValue(before, 'packetsLost');
  5203. if (!previousLoss || previousLoss < 0)
  5204. previousLoss = 0;
  5205. var lossRate = currentLoss - previousLoss;
  5206. if (!lossRate || lossRate < 0)
  5207. lossRate = 0;
  5208. var packetsTotal = (packetRate + lossRate);
  5209. ssrcStats.setSsrcLoss(ssrc,
  5210. {"packetsTotal": packetsTotal,
  5211. "packetsLost": lossRate,
  5212. "isDownloadStream": isDownloadStream});
  5213. var bytesReceived = 0, bytesSent = 0;
  5214. if(getStatValue(now, "bytesReceived")) {
  5215. bytesReceived = getStatValue(now, "bytesReceived") -
  5216. getStatValue(before, "bytesReceived");
  5217. }
  5218. if (getStatValue(now, "bytesSent")) {
  5219. bytesSent = getStatValue(now, "bytesSent") -
  5220. getStatValue(before, "bytesSent");
  5221. }
  5222. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5223. if (bytesReceived <= 0 || time <= 0) {
  5224. bytesReceived = 0;
  5225. } else {
  5226. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5227. }
  5228. if (bytesSent <= 0 || time <= 0) {
  5229. bytesSent = 0;
  5230. } else {
  5231. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5232. }
  5233. ssrcStats.setSsrcBitrate(ssrc, {
  5234. "download": bytesReceived,
  5235. "upload": bytesSent});
  5236. var resolution = {height: null, width: null};
  5237. try {
  5238. if (getStatValue(now, "googFrameHeightReceived") &&
  5239. getStatValue(now, "googFrameWidthReceived")) {
  5240. resolution.height =
  5241. getStatValue(now, "googFrameHeightReceived");
  5242. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5243. }
  5244. else if (getStatValue(now, "googFrameHeightSent") &&
  5245. getStatValue(now, "googFrameWidthSent")) {
  5246. resolution.height = getStatValue(now, "googFrameHeightSent");
  5247. resolution.width = getStatValue(now, "googFrameWidthSent");
  5248. }
  5249. }
  5250. catch(e){/*not supported*/}
  5251. if (resolution.height && resolution.width) {
  5252. ssrcStats.setSsrcResolution(ssrc, resolution);
  5253. } else {
  5254. ssrcStats.setSsrcResolution(ssrc, null);
  5255. }
  5256. }
  5257. var self = this;
  5258. // Jid stats
  5259. var totalPackets = {download: 0, upload: 0};
  5260. var lostPackets = {download: 0, upload: 0};
  5261. var bitrateDownload = 0;
  5262. var bitrateUpload = 0;
  5263. var resolutions = {};
  5264. Object.keys(this.ssrc2stats).forEach(
  5265. function (jid) {
  5266. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5267. function (ssrc) {
  5268. var type = "upload";
  5269. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5270. type = "download";
  5271. totalPackets[type] +=
  5272. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5273. lostPackets[type] +=
  5274. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5275. }
  5276. );
  5277. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5278. function (ssrc) {
  5279. bitrateDownload +=
  5280. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5281. bitrateUpload +=
  5282. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5283. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5284. }
  5285. );
  5286. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5287. }
  5288. );
  5289. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5290. this.conferenceStats.packetLoss = {
  5291. total:
  5292. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5293. totalPackets.download + totalPackets.upload),
  5294. download:
  5295. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5296. upload:
  5297. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5298. };
  5299. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5300. {
  5301. "bitrate": this.conferenceStats.bitrate,
  5302. "packetLoss": this.conferenceStats.packetLoss,
  5303. "bandwidth": this.conferenceStats.bandwidth,
  5304. "resolution": resolutions,
  5305. "transport": this.conferenceStats.transport
  5306. });
  5307. this.conferenceStats.transport = [];
  5308. };
  5309. /**
  5310. * Stats processing logic.
  5311. */
  5312. StatsCollector.prototype.processAudioLevelReport = function () {
  5313. if (!this.baselineAudioLevelsReport) {
  5314. return;
  5315. }
  5316. for (var idx in this.currentAudioLevelsReport) {
  5317. var now = this.currentAudioLevelsReport[idx];
  5318. //if we don't have "packetsReceived" this is local stream
  5319. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5320. continue;
  5321. }
  5322. var before = this.baselineAudioLevelsReport[idx];
  5323. if (!before) {
  5324. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5325. continue;
  5326. }
  5327. var ssrc = getStatValue(now, 'ssrc');
  5328. if (!ssrc) {
  5329. if((Date.now() - now.timestamp) < 3000)
  5330. logger.warn("No ssrc: ");
  5331. continue;
  5332. }
  5333. var ssrcStats = this.ssrc2stats[ssrc];
  5334. if (!ssrcStats) {
  5335. ssrcStats = new PeerStats();
  5336. this.ssrc2stats[ssrc] = ssrcStats;
  5337. }
  5338. // Audio level
  5339. var audioLevel = null;
  5340. try {
  5341. audioLevel = getStatValue(now, 'audioInputLevel');
  5342. if (!audioLevel)
  5343. audioLevel = getStatValue(now, 'audioOutputLevel');
  5344. }
  5345. catch(e) {/*not supported*/
  5346. logger.warn("Audio Levels are not available in the statistics.");
  5347. clearInterval(this.audioLevelsIntervalId);
  5348. return;
  5349. }
  5350. if (audioLevel) {
  5351. // TODO: can't find specs about what this value really is,
  5352. // but it seems to vary between 0 and around 32k.
  5353. audioLevel = audioLevel / 32767;
  5354. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5355. this.eventEmitter.emit(
  5356. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5357. }
  5358. }
  5359. };
  5360. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5361. },{"../../service/statistics/Events":85,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],24:[function(require,module,exports){
  5362. /* global require, APP */
  5363. var LocalStats = require("./LocalStatsCollector.js");
  5364. var RTPStats = require("./RTPStatsCollector.js");
  5365. var EventEmitter = require("events");
  5366. var StatisticsEvents = require("../../service/statistics/Events");
  5367. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  5368. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5369. //var CallStats = require("./CallStats");
  5370. //var RTCEvents = require("../../service/RTC/RTCEvents");
  5371. //
  5372. //function onDisposeConference(onUnload) {
  5373. // CallStats.sendTerminateEvent();
  5374. // stopRemote();
  5375. // if(onUnload) {
  5376. // stopLocal();
  5377. // eventEmitter.removeAllListeners();
  5378. // }
  5379. //}
  5380. var eventEmitter = new EventEmitter();
  5381. function Statistics() {
  5382. this.rtpStats = null;
  5383. this.eventEmitter = new EventEmitter();
  5384. }
  5385. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5386. if (this.rtpStats) {
  5387. this.rtpStats.stop();
  5388. }
  5389. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5390. this.rtpStats.start();
  5391. }
  5392. Statistics.localStats = [];
  5393. Statistics.startLocalStats = function (stream, callback) {
  5394. var localStats = new LocalStats(stream, 200, callback);
  5395. this.localStats.push(localStats);
  5396. localStats.start();
  5397. }
  5398. Statistics.prototype.addAudioLevelListener = function(listener)
  5399. {
  5400. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5401. }
  5402. Statistics.prototype.removeAudioLevelListener = function(listener)
  5403. {
  5404. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5405. }
  5406. Statistics.prototype.dispose = function () {
  5407. Statistics.stopAllLocalStats();
  5408. this.stopRemote();
  5409. if(this.eventEmitter)
  5410. this.eventEmitter.removeAllListeners();
  5411. if(eventEmitter)
  5412. eventEmitter.removeAllListeners();
  5413. }
  5414. Statistics.stopAllLocalStats = function () {
  5415. for(var i = 0; i < this.localStats.length; i++)
  5416. this.localStats[i].stop();
  5417. this.localStats = [];
  5418. }
  5419. Statistics.stopLocalStats = function (stream) {
  5420. for(var i = 0; i < Statistics.localStats.length; i++)
  5421. if(Statistics.localStats[i].stream === stream){
  5422. var localStats = Statistics.localStats.splice(i, 1);
  5423. localStats.stop();
  5424. break;
  5425. }
  5426. }
  5427. Statistics.prototype.stopRemote = function () {
  5428. if (this.rtpStats) {
  5429. this.rtpStats.stop();
  5430. this.eventEmitter.emit(StatisticsEvents.STOP);
  5431. this.rtpStats = null;
  5432. }
  5433. };
  5434. /**
  5435. * Obtains audio level reported in the stats for specified peer.
  5436. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5437. * audio level.
  5438. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5439. * level.
  5440. * @returns {*} a float form 0 to 1 that represents current audio level or
  5441. * <tt>null</tt> if for any reason the value is not available
  5442. * at this time.
  5443. */
  5444. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5445. var peerStats = this.rtpStats.jid2stats[peerJid];
  5446. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5447. };
  5448. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5449. //
  5450. //var statistics = {
  5451. // /**
  5452. // * Indicates that this audio level is for local jid.
  5453. // * @type {string}
  5454. // */
  5455. // LOCAL_JID: 'local',
  5456. //
  5457. // addConnectionStatsListener: function(listener)
  5458. // {
  5459. // eventEmitter.on("statistics.connectionstats", listener);
  5460. // },
  5461. //
  5462. // removeConnectionStatsListener: function(listener)
  5463. // {
  5464. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5465. // },
  5466. //
  5467. //
  5468. // addRemoteStatsStopListener: function(listener)
  5469. // {
  5470. // eventEmitter.on("statistics.stop", listener);
  5471. // },
  5472. //
  5473. // removeRemoteStatsStopListener: function(listener)
  5474. // {
  5475. // eventEmitter.removeListener("statistics.stop", listener);
  5476. // },
  5477. //
  5478. //
  5479. // stopRemoteStatistics: function()
  5480. // {
  5481. // stopRemote();
  5482. // },
  5483. //
  5484. //// Already implemented with the constructor
  5485. // start: function () {
  5486. // APP.RTC.addStreamListener(onStreamCreated,
  5487. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5488. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5489. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5490. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5491. // startRemoteStats(event.peerconnection);
  5492. //// CallStats.init(event);
  5493. // });
  5494. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5495. //// CallStats.init(session);
  5496. //// });
  5497. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5498. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5499. //// CallStats.sendMuteEvent(mute, "audio");
  5500. //// });
  5501. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5502. //// CallStats.sendSetupFailedEvent();
  5503. //// });
  5504. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5505. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5506. //// CallStats.sendMuteEvent(mute, "video");
  5507. //// });
  5508. // }
  5509. //};
  5510. module.exports = Statistics;
  5511. },{"../../service/statistics/Events":85,"../../service/statistics/constants":86,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":44}],25:[function(require,module,exports){
  5512. /**
  5513. /**
  5514. * @const
  5515. */
  5516. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5517. /**
  5518. * Hexadecimal digits.
  5519. * @const
  5520. */
  5521. var HEX_DIGITS = '0123456789abcdef';
  5522. /**
  5523. * Generates random int within the range [min, max]
  5524. * @param min the minimum value for the generated number
  5525. * @param max the maximum value for the generated number
  5526. * @returns random int number
  5527. */
  5528. function randomInt(min, max) {
  5529. return Math.floor(Math.random() * (max - min + 1)) + min;
  5530. }
  5531. /**
  5532. * Get random element from array or string.
  5533. * @param {Array|string} arr source
  5534. * @returns array element or string character
  5535. */
  5536. function randomElement(arr) {
  5537. return arr[randomInt(0, arr.length - 1)];
  5538. }
  5539. /**
  5540. * Generate random alphanumeric string.
  5541. * @param {number} length expected string length
  5542. * @returns {string} random string of specified length
  5543. */
  5544. function randomAlphanumStr(length) {
  5545. var result = '';
  5546. for (var i = 0; i < length; i += 1) {
  5547. result += randomElement(ALPHANUM);
  5548. }
  5549. return result;
  5550. }
  5551. /**
  5552. * Exported interface.
  5553. */
  5554. var RandomUtil = {
  5555. /**
  5556. * Returns a random hex digit.
  5557. * @returns {*}
  5558. */
  5559. randomHexDigit: function() {
  5560. return randomElement(HEX_DIGITS);
  5561. },
  5562. /**
  5563. * Returns a random string of hex digits with length 'len'.
  5564. * @param len the length.
  5565. */
  5566. randomHexString: function (len) {
  5567. var ret = '';
  5568. while (len--) {
  5569. ret += this.randomHexDigit();
  5570. }
  5571. return ret;
  5572. },
  5573. randomElement: randomElement,
  5574. randomAlphanumStr: randomAlphanumStr
  5575. };
  5576. module.exports = RandomUtil;
  5577. },{}],26:[function(require,module,exports){
  5578. (function (__filename){
  5579. /* global Strophe, $, $pres, $iq, $msg */
  5580. /* jshint -W101,-W069 */
  5581. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5582. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5583. var Moderator = require("./moderator");
  5584. var EventEmitter = require("events");
  5585. var Recorder = require("./recording");
  5586. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  5587. var parser = {
  5588. packet2JSON: function (packet, nodes) {
  5589. var self = this;
  5590. $(packet).children().each(function (index) {
  5591. var tagName = $(this).prop("tagName");
  5592. var node = {
  5593. tagName: tagName
  5594. };
  5595. node.attributes = {};
  5596. $($(this)[0].attributes).each(function( index, attr ) {
  5597. node.attributes[ attr.name ] = attr.value;
  5598. });
  5599. var text = Strophe.getText($(this)[0]);
  5600. if (text) {
  5601. node.value = text;
  5602. }
  5603. node.children = [];
  5604. nodes.push(node);
  5605. self.packet2JSON($(this), node.children);
  5606. });
  5607. },
  5608. JSON2packet: function (nodes, packet) {
  5609. for(var i = 0; i < nodes.length; i++) {
  5610. var node = nodes[i];
  5611. if(!node || node === null){
  5612. continue;
  5613. }
  5614. packet.c(node.tagName, node.attributes);
  5615. if(node.value)
  5616. packet.t(node.value);
  5617. if(node.children)
  5618. this.JSON2packet(node.children, packet);
  5619. packet.up();
  5620. }
  5621. // packet.up();
  5622. }
  5623. };
  5624. /**
  5625. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5626. * @param pres the presence JSON
  5627. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5628. */
  5629. function filterNodeFromPresenceJSON(pres, nodeName){
  5630. var res = [];
  5631. for(var i = 0; i < pres.length; i++)
  5632. if(pres[i].tagName === nodeName)
  5633. res.push(pres[i]);
  5634. return res;
  5635. }
  5636. function ChatRoom(connection, jid, password, XMPP, options) {
  5637. this.eventEmitter = new EventEmitter();
  5638. this.xmpp = XMPP;
  5639. this.connection = connection;
  5640. this.roomjid = Strophe.getBareJidFromJid(jid);
  5641. this.myroomjid = jid;
  5642. this.password = password;
  5643. logger.info("Joined MUC as " + this.myroomjid);
  5644. this.members = {};
  5645. this.presMap = {};
  5646. this.presHandlers = {};
  5647. this.joined = false;
  5648. this.role = 'none';
  5649. this.focusMucJid = null;
  5650. this.bridgeIsDown = false;
  5651. this.options = options || {};
  5652. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5653. this.initPresenceMap();
  5654. this.session = null;
  5655. var self = this;
  5656. this.lastPresences = {};
  5657. this.phoneNumber = null;
  5658. this.phonePin = null;
  5659. }
  5660. ChatRoom.prototype.initPresenceMap = function () {
  5661. this.presMap['to'] = this.myroomjid;
  5662. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5663. this.presMap["nodes"] = [];
  5664. this.presMap["nodes"].push( {
  5665. "tagName": "user-agent",
  5666. "value": navigator.userAgent,
  5667. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5668. });
  5669. };
  5670. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5671. this.presMap["nodes"].push( {
  5672. "tagName": "devices",
  5673. "children": [
  5674. {
  5675. "tagName": "audio",
  5676. "value": devices.audio,
  5677. },
  5678. {
  5679. "tagName": "video",
  5680. "value": devices.video,
  5681. }
  5682. ]
  5683. });
  5684. };
  5685. ChatRoom.prototype.join = function (password) {
  5686. if(password)
  5687. this.password = password;
  5688. var self = this;
  5689. this.moderator.allocateConferenceFocus(function()
  5690. {
  5691. self.sendPresence(true);
  5692. }.bind(this));
  5693. };
  5694. ChatRoom.prototype.sendPresence = function (fromJoin) {
  5695. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  5696. // Too early to send presence - not initialized
  5697. return;
  5698. }
  5699. var pres = $pres({to: this.presMap['to'] });
  5700. pres.c('x', {xmlns: this.presMap['xns']});
  5701. if (this.password) {
  5702. pres.c('password').t(this.password).up();
  5703. }
  5704. pres.up();
  5705. // Send XEP-0115 'c' stanza that contains our capabilities info
  5706. if (this.connection.caps) {
  5707. this.connection.caps.node = this.xmpp.options.clientNode;
  5708. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5709. }
  5710. parser.JSON2packet(this.presMap.nodes, pres);
  5711. this.connection.send(pres);
  5712. };
  5713. ChatRoom.prototype.doLeave = function () {
  5714. logger.log("do leave", this.myroomjid);
  5715. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5716. this.presMap.length = 0;
  5717. this.connection.send(pres);
  5718. };
  5719. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5720. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5721. var getForm = $iq({type: 'get', to: this.roomjid})
  5722. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5723. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5724. var self = this;
  5725. this.connection.sendIQ(getForm, function (form) {
  5726. if (!$(form).find(
  5727. '>query>x[xmlns="jabber:x:data"]' +
  5728. '>field[var="muc#roomconfig_whois"]').length) {
  5729. logger.error('non-anonymous rooms not supported');
  5730. return;
  5731. }
  5732. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5733. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5734. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5735. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5736. .c('value')
  5737. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5738. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5739. .c('value').t('anyone').up().up();
  5740. self.connection.sendIQ(formSubmit);
  5741. }, function (error) {
  5742. logger.error("Error getting room configuration form");
  5743. });
  5744. };
  5745. ChatRoom.prototype.onPresence = function (pres) {
  5746. var from = pres.getAttribute('from');
  5747. // Parse roles.
  5748. var member = {};
  5749. member.show = $(pres).find('>show').text();
  5750. member.status = $(pres).find('>status').text();
  5751. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5752. member.affiliation = tmp.attr('affiliation');
  5753. member.role = tmp.attr('role');
  5754. // Focus recognition
  5755. member.jid = tmp.attr('jid');
  5756. member.isFocus = false;
  5757. if (member.jid
  5758. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5759. member.isFocus = true;
  5760. }
  5761. $(pres).find(">x").remove();
  5762. var nodes = [];
  5763. parser.packet2JSON(pres, nodes);
  5764. this.lastPresences[from] = nodes;
  5765. var jibri = null;
  5766. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  5767. // events
  5768. for(var i = 0; i < nodes.length; i++)
  5769. {
  5770. var node = nodes[i];
  5771. switch(node.tagName)
  5772. {
  5773. case "nick":
  5774. member.nick = node.value;
  5775. break;
  5776. case "userId":
  5777. member.id = node.value;
  5778. break;
  5779. }
  5780. }
  5781. if (from == this.myroomjid) {
  5782. if (member.affiliation == 'owner'
  5783. && this.role !== member.role) {
  5784. this.role = member.role;
  5785. this.eventEmitter.emit(
  5786. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5787. }
  5788. if (!this.joined) {
  5789. this.joined = true;
  5790. console.log("(TIME) MUC joined:\t", window.performance.now());
  5791. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  5792. }
  5793. } else if (this.members[from] === undefined) {
  5794. // new participant
  5795. this.members[from] = member;
  5796. logger.log('entered', from, member);
  5797. if (member.isFocus) {
  5798. this.focusMucJid = from;
  5799. if(!this.recording) {
  5800. this.recording = new Recorder(this.options.recordingType,
  5801. this.eventEmitter, this.connection, this.focusMucJid,
  5802. this.options.jirecon, this.roomjid);
  5803. if(this.lastJibri)
  5804. this.recording.handleJibriPresence(this.lastJibri);
  5805. }
  5806. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5807. }
  5808. else {
  5809. this.eventEmitter.emit(
  5810. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  5811. }
  5812. } else {
  5813. // Presence update for existing participant
  5814. // Watch role change:
  5815. if (this.members[from].role != member.role) {
  5816. this.members[from].role = member.role;
  5817. this.eventEmitter.emit(
  5818. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5819. }
  5820. // store the new display name
  5821. if(member.displayName)
  5822. this.members[from].displayName = member.displayName;
  5823. }
  5824. // after we had fired member or room joined events, lets fire events
  5825. // for the rest info we got in presence
  5826. for(var i = 0; i < nodes.length; i++)
  5827. {
  5828. var node = nodes[i];
  5829. switch(node.tagName)
  5830. {
  5831. case "nick":
  5832. if(!member.isFocus) {
  5833. var displayName = !this.xmpp.options.displayJids
  5834. ? member.nick : Strophe.getResourceFromJid(from);
  5835. if (displayName && displayName.length > 0) {
  5836. this.eventEmitter.emit(
  5837. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5838. }
  5839. }
  5840. break;
  5841. case "bridgeIsDown":
  5842. if(!this.bridgeIsDown) {
  5843. this.bridgeIsDown = true;
  5844. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5845. }
  5846. break;
  5847. case "jibri-recording-status":
  5848. var jibri = node;
  5849. break;
  5850. case "call-control":
  5851. var att = node.attributes;
  5852. if(!att)
  5853. break;
  5854. this.phoneNumber = att.phone || null;
  5855. this.phonePin = att.pin || null;
  5856. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  5857. break;
  5858. default :
  5859. this.processNode(node, from);
  5860. }
  5861. }
  5862. if(!member.isFocus)
  5863. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id);
  5864. // Trigger status message update
  5865. if (member.status) {
  5866. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5867. }
  5868. if(jibri)
  5869. {
  5870. this.lastJibri = jibri;
  5871. if(this.recording)
  5872. this.recording.handleJibriPresence(jibri);
  5873. }
  5874. };
  5875. ChatRoom.prototype.processNode = function (node, from) {
  5876. if(this.presHandlers[node.tagName])
  5877. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  5878. };
  5879. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5880. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5881. msg.c('body', body).up();
  5882. if (nickname) {
  5883. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5884. }
  5885. this.connection.send(msg);
  5886. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5887. };
  5888. ChatRoom.prototype.setSubject = function (subject) {
  5889. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5890. msg.c('subject', subject);
  5891. this.connection.send(msg);
  5892. logger.log("topic changed to " + subject);
  5893. };
  5894. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5895. delete this.lastPresences[jid];
  5896. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5897. this.moderator.onMucMemberLeft(jid);
  5898. };
  5899. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5900. // room destroyed ?
  5901. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5902. '>destroy').length) {
  5903. var reason;
  5904. var reasonSelect = $(pres).find(
  5905. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5906. '>destroy>reason');
  5907. if (reasonSelect.length) {
  5908. reason = reasonSelect.text();
  5909. }
  5910. this.xmpp.leaveRoom(this.roomjid);
  5911. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5912. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5913. return true;
  5914. }
  5915. // Status code 110 indicates that this notification is "self-presence".
  5916. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5917. delete this.members[from];
  5918. this.onParticipantLeft(from);
  5919. }
  5920. // If the status code is 110 this means we're leaving and we would like
  5921. // to remove everyone else from our view, so we trigger the event.
  5922. else if (Object.keys(this.members).length > 1) {
  5923. for (var i in this.members) {
  5924. var member = this.members[i];
  5925. delete this.members[i];
  5926. this.onParticipantLeft(member);
  5927. }
  5928. }
  5929. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5930. if (this.myroomjid === from) {
  5931. this.xmpp.leaveRoom(this.roomjid);
  5932. this.eventEmitter.emit(XMPPEvents.KICKED);
  5933. }
  5934. }
  5935. };
  5936. ChatRoom.prototype.onMessage = function (msg, from) {
  5937. var nick =
  5938. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5939. .text() ||
  5940. Strophe.getResourceFromJid(from);
  5941. var txt = $(msg).find('>body').text();
  5942. var type = msg.getAttribute("type");
  5943. if (type == "error") {
  5944. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5945. $(msg).find('>text').text(), txt);
  5946. return true;
  5947. }
  5948. var subject = $(msg).find('>subject');
  5949. if (subject.length) {
  5950. var subjectText = subject.text();
  5951. if (subjectText || subjectText === "") {
  5952. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5953. logger.log("Subject is changed to " + subjectText);
  5954. }
  5955. }
  5956. // xep-0203 delay
  5957. var stamp = $(msg).find('>delay').attr('stamp');
  5958. if (!stamp) {
  5959. // or xep-0091 delay, UTC timestamp
  5960. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5961. if (stamp) {
  5962. // the format is CCYYMMDDThh:mm:ss
  5963. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5964. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5965. }
  5966. }
  5967. if (txt) {
  5968. logger.log('chat', nick, txt);
  5969. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5970. from, nick, txt, this.myroomjid, stamp);
  5971. }
  5972. };
  5973. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5974. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5975. logger.log('on password required', from);
  5976. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5977. } else if ($(pres).find(
  5978. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5979. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5980. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5981. // enter the room by replying with 'not-authorized'. This would
  5982. // result in reconnection from authorized domain.
  5983. // We're either missing Jicofo/Prosody config for anonymous
  5984. // domains or something is wrong.
  5985. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5986. } else {
  5987. logger.warn('onPresError ', pres);
  5988. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5989. }
  5990. } else {
  5991. logger.warn('onPresError ', pres);
  5992. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5993. }
  5994. };
  5995. ChatRoom.prototype.kick = function (jid) {
  5996. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5997. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5998. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5999. .c('reason').t('You have been kicked.').up().up().up();
  6000. this.connection.sendIQ(
  6001. kickIQ,
  6002. function (result) {
  6003. logger.log('Kick participant with jid: ', jid, result);
  6004. },
  6005. function (error) {
  6006. logger.log('Kick participant error: ', error);
  6007. });
  6008. };
  6009. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  6010. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  6011. var ob = this;
  6012. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  6013. function (res) {
  6014. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  6015. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6016. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6017. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6018. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  6019. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  6020. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  6021. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  6022. ob.connection.sendIQ(formsubmit,
  6023. onSuccess,
  6024. onError);
  6025. } else {
  6026. onNotSupported();
  6027. }
  6028. }, onError);
  6029. };
  6030. ChatRoom.prototype.addToPresence = function (key, values) {
  6031. values.tagName = key;
  6032. this.presMap["nodes"].push(values);
  6033. };
  6034. ChatRoom.prototype.removeFromPresence = function (key) {
  6035. for(var i = 0; i < this.presMap.nodes.length; i++)
  6036. {
  6037. if(key === this.presMap.nodes[i].tagName)
  6038. this.presMap.nodes.splice(i, 1);
  6039. }
  6040. };
  6041. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  6042. this.presHandlers[name] = handler;
  6043. };
  6044. ChatRoom.prototype.removePresenceListener = function (name) {
  6045. delete this.presHandlers[name];
  6046. };
  6047. ChatRoom.prototype.isModerator = function () {
  6048. return this.role === 'moderator';
  6049. };
  6050. ChatRoom.prototype.getMemberRole = function (peerJid) {
  6051. if (this.members[peerJid]) {
  6052. return this.members[peerJid].role;
  6053. }
  6054. return null;
  6055. };
  6056. ChatRoom.prototype.setJingleSession = function(session){
  6057. this.session = session;
  6058. this.session.room = this;
  6059. };
  6060. ChatRoom.prototype.removeStream = function (stream, callback) {
  6061. if(!this.session)
  6062. return;
  6063. this.session.removeStream(stream, callback);
  6064. };
  6065. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  6066. if(this.session) {
  6067. // FIXME: will block switchInProgress on true value in case of exception
  6068. this.session.switchStreams(stream, oldStream, callback, isAudio);
  6069. } else {
  6070. // We are done immediately
  6071. logger.warn("No conference handler or conference not started yet");
  6072. callback();
  6073. }
  6074. };
  6075. ChatRoom.prototype.addStream = function (stream, callback) {
  6076. if(this.session) {
  6077. // FIXME: will block switchInProgress on true value in case of exception
  6078. this.session.addStream(stream, callback);
  6079. } else {
  6080. // We are done immediately
  6081. logger.warn("No conference handler or conference not started yet");
  6082. callback();
  6083. }
  6084. };
  6085. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  6086. var self = this;
  6087. var localCallback = function (mute) {
  6088. self.sendVideoInfoPresence(mute);
  6089. if(callback)
  6090. callback(mute);
  6091. };
  6092. if(this.session)
  6093. {
  6094. this.session.setVideoMute(
  6095. mute, localCallback, options);
  6096. }
  6097. else {
  6098. localCallback(mute);
  6099. }
  6100. };
  6101. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  6102. //This will be for remote streams only
  6103. // if (this.forceMuted && !mute) {
  6104. // logger.info("Asking focus for unmute");
  6105. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  6106. // // FIXME: wait for result before resetting muted status
  6107. // this.forceMuted = false;
  6108. // }
  6109. return this.sendAudioInfoPresence(mute, callback);
  6110. };
  6111. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  6112. this.removeFromPresence("audiomuted");
  6113. this.addToPresence("audiomuted",
  6114. {attributes:
  6115. {"audions": "http://jitsi.org/jitmeet/audio"},
  6116. value: mute.toString()});
  6117. };
  6118. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  6119. this.addAudioInfoToPresence(mute);
  6120. if(this.connection) {
  6121. this.sendPresence();
  6122. }
  6123. if(callback)
  6124. callback();
  6125. };
  6126. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  6127. this.removeFromPresence("videomuted");
  6128. this.addToPresence("videomuted",
  6129. {attributes:
  6130. {"videons": "http://jitsi.org/jitmeet/video"},
  6131. value: mute.toString()});
  6132. };
  6133. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  6134. this.addVideoInfoToPresence(mute);
  6135. if(!this.connection)
  6136. return;
  6137. this.sendPresence();
  6138. };
  6139. ChatRoom.prototype.addListener = function(type, listener) {
  6140. this.eventEmitter.on(type, listener);
  6141. };
  6142. ChatRoom.prototype.removeListener = function (type, listener) {
  6143. this.eventEmitter.removeListener(type, listener);
  6144. };
  6145. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  6146. if(this.lastPresences[data.peerjid])
  6147. {
  6148. var pres = this.lastPresences[data.peerjid];
  6149. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  6150. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  6151. data.videomuted = ((videomuted.length > 0
  6152. && videomuted[0]
  6153. && videomuted[0]["value"] === "true")? true : false);
  6154. data.audiomuted = ((audiomuted.length > 0
  6155. && audiomuted[0]
  6156. && audiomuted[0]["value"] === "true")? true : false);
  6157. }
  6158. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  6159. };
  6160. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  6161. if (!this.session)
  6162. return null;
  6163. return this.session.getSsrcOwner(ssrc);
  6164. };
  6165. /**
  6166. * Returns true if the recording is supproted and false if not.
  6167. */
  6168. ChatRoom.prototype.isRecordingSupported = function () {
  6169. if(this.recording)
  6170. return this.recording.isSupported();
  6171. return false;
  6172. };
  6173. /**
  6174. * Returns null if the recording is not supported, "on" if the recording started
  6175. * and "off" if the recording is not started.
  6176. */
  6177. ChatRoom.prototype.getRecordingState = function () {
  6178. if(this.recording)
  6179. return this.recording.getState();
  6180. return "off";
  6181. }
  6182. /**
  6183. * Returns the url of the recorded video.
  6184. */
  6185. ChatRoom.prototype.getRecordingURL = function () {
  6186. if(this.recording)
  6187. return this.recording.getURL();
  6188. return null;
  6189. }
  6190. /**
  6191. * Starts/stops the recording
  6192. * @param token token for authentication
  6193. * @param statusChangeHandler {function} receives the new status as argument.
  6194. */
  6195. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  6196. if(this.recording)
  6197. return this.recording.toggleRecording(options, statusChangeHandler);
  6198. return statusChangeHandler("error",
  6199. new Error("The conference is not created yet!"));
  6200. }
  6201. /**
  6202. * Returns true if the SIP calls are supported and false otherwise
  6203. */
  6204. ChatRoom.prototype.isSIPCallingSupported = function () {
  6205. if(this.moderator)
  6206. return this.moderator.isSipGatewayEnabled();
  6207. return false;
  6208. }
  6209. /**
  6210. * Dials a number.
  6211. * @param number the number
  6212. */
  6213. ChatRoom.prototype.dial = function (number) {
  6214. return this.connection.rayo.dial(number, "fromnumber",
  6215. Strophe.getNodeFromJid(this.myroomjid), this.password,
  6216. this.focusMucJid);
  6217. }
  6218. /**
  6219. * Hangup an existing call
  6220. */
  6221. ChatRoom.prototype.hangup = function () {
  6222. return this.connection.rayo.hangup();
  6223. }
  6224. /**
  6225. * Returns the phone number for joining the conference.
  6226. */
  6227. ChatRoom.prototype.getPhoneNumber = function () {
  6228. return this.phoneNumber;
  6229. }
  6230. /**
  6231. * Returns the pin for joining the conference with phone.
  6232. */
  6233. ChatRoom.prototype.getPhonePin = function () {
  6234. return this.phonePin;
  6235. }
  6236. /**
  6237. * Returns the connection state for the current session.
  6238. */
  6239. ChatRoom.prototype.getConnectionState = function () {
  6240. if(!this.session)
  6241. return null;
  6242. return this.session.getIceConnectionState();
  6243. }
  6244. /**
  6245. * Mutes remote participant.
  6246. * @param jid of the participant
  6247. * @param mute
  6248. */
  6249. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  6250. logger.info("set mute", mute);
  6251. var iqToFocus = $iq(
  6252. {to: this.focusMucJid, type: 'set'})
  6253. .c('mute', {
  6254. xmlns: 'http://jitsi.org/jitmeet/audio',
  6255. jid: jid
  6256. })
  6257. .t(mute.toString())
  6258. .up();
  6259. this.connection.sendIQ(
  6260. iqToFocus,
  6261. function (result) {
  6262. logger.log('set mute', result);
  6263. },
  6264. function (error) {
  6265. logger.log('set mute error', error);
  6266. });
  6267. }
  6268. ChatRoom.prototype.onMute = function (iq) {
  6269. var from = iq.getAttribute('from');
  6270. if (from !== this.focusMucJid) {
  6271. logger.warn("Ignored mute from non focus peer");
  6272. return false;
  6273. }
  6274. var mute = $(iq).find('mute');
  6275. if (mute.length) {
  6276. var doMuteAudio = mute.text() === "true";
  6277. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  6278. }
  6279. return true;
  6280. }
  6281. module.exports = ChatRoom;
  6282. }).call(this,"/modules/xmpp/ChatRoom.js")
  6283. },{"../../service/xmpp/XMPPEvents":87,"./moderator":34,"./recording":35,"events":44,"jitsi-meet-logger":48}],27:[function(require,module,exports){
  6284. (function (__filename){
  6285. /*
  6286. * JingleSession provides an API to manage a single Jingle session. We will
  6287. * have different implementations depending on the underlying interface used
  6288. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  6289. */
  6290. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6291. function JingleSession(me, sid, connection, service, eventEmitter) {
  6292. /**
  6293. * Our JID.
  6294. */
  6295. this.me = me;
  6296. /**
  6297. * The Jingle session identifier.
  6298. */
  6299. this.sid = sid;
  6300. /**
  6301. * The XMPP connection.
  6302. */
  6303. this.connection = connection;
  6304. /**
  6305. * The XMPP service.
  6306. */
  6307. this.service = service;
  6308. /**
  6309. * The event emitter.
  6310. */
  6311. this.eventEmitter = eventEmitter;
  6312. /**
  6313. * Whether to use dripping or not. Dripping is sending trickle candidates
  6314. * not one-by-one.
  6315. * Note: currently we do not support 'false'.
  6316. */
  6317. this.usedrip = true;
  6318. /**
  6319. * When dripping is used, stores ICE candidates which are to be sent.
  6320. */
  6321. this.drip_container = [];
  6322. // Media constraints. Is this WebRTC only?
  6323. this.media_constraints = null;
  6324. // ICE servers config (RTCConfiguration?).
  6325. this.ice_config = {};
  6326. // The chat room instance associated with the session.
  6327. this.room = null;
  6328. }
  6329. /**
  6330. * Prepares this object to initiate a session.
  6331. * @param peerjid the JID of the remote peer.
  6332. * @param isInitiator whether we will be the Jingle initiator.
  6333. * @param media_constraints
  6334. * @param ice_config
  6335. */
  6336. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  6337. media_constraints, ice_config) {
  6338. this.media_constraints = media_constraints;
  6339. this.ice_config = ice_config;
  6340. if (this.state !== null) {
  6341. logger.error('attempt to initiate on session ' + this.sid +
  6342. 'in state ' + this.state);
  6343. return;
  6344. }
  6345. this.state = 'pending';
  6346. this.initiator = isInitiator ? this.me : peerjid;
  6347. this.responder = !isInitiator ? this.me : peerjid;
  6348. this.peerjid = peerjid;
  6349. this.doInitialize();
  6350. };
  6351. /**
  6352. * Finishes initialization.
  6353. */
  6354. JingleSession.prototype.doInitialize = function() {};
  6355. /**
  6356. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  6357. * Note: currently only used on transport-info
  6358. */
  6359. JingleSession.prototype.addIceCandidates = function(contents) {};
  6360. /**
  6361. * Handles an 'add-source' event.
  6362. *
  6363. * @param contents an array of Jingle 'content' elements.
  6364. */
  6365. JingleSession.prototype.addSources = function(contents) {};
  6366. /**
  6367. * Handles a 'remove-source' event.
  6368. *
  6369. * @param contents an array of Jingle 'content' elements.
  6370. */
  6371. JingleSession.prototype.removeSources = function(contents) {};
  6372. /**
  6373. * Terminates this Jingle session (stops sending media and closes the streams?)
  6374. */
  6375. JingleSession.prototype.terminate = function() {};
  6376. /**
  6377. * Sends a Jingle session-terminate message to the peer and terminates the
  6378. * session.
  6379. * @param reason
  6380. * @param text
  6381. */
  6382. JingleSession.prototype.sendTerminate = function(reason, text) {};
  6383. /**
  6384. * Handles an offer from the remote peer (prepares to accept a session).
  6385. * @param jingle the 'jingle' XML element.
  6386. */
  6387. JingleSession.prototype.setOffer = function(jingle) {};
  6388. /**
  6389. * Handles an answer from the remote peer (prepares to accept a session).
  6390. * @param jingle the 'jingle' XML element.
  6391. */
  6392. JingleSession.prototype.setAnswer = function(jingle) {};
  6393. module.exports = JingleSession;
  6394. }).call(this,"/modules/xmpp/JingleSession.js")
  6395. },{"jitsi-meet-logger":48}],28:[function(require,module,exports){
  6396. (function (__filename){
  6397. /* jshint -W117 */
  6398. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6399. var JingleSession = require("./JingleSession");
  6400. var TraceablePeerConnection = require("./TraceablePeerConnection");
  6401. var SDPDiffer = require("./SDPDiffer");
  6402. var SDPUtil = require("./SDPUtil");
  6403. var SDP = require("./SDP");
  6404. var async = require("async");
  6405. var transform = require("sdp-transform");
  6406. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6407. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6408. var SSRCReplacement = require("./LocalSSRCReplacement");
  6409. var RTC = require("../RTC/RTC");
  6410. // Jingle stuff
  6411. function JingleSessionPC(me, sid, connection, service) {
  6412. JingleSession.call(this, me, sid, connection, service);
  6413. this.initiator = null;
  6414. this.responder = null;
  6415. this.peerjid = null;
  6416. this.state = null;
  6417. this.localSDP = null;
  6418. this.remoteSDP = null;
  6419. this.relayedStreams = [];
  6420. this.usetrickle = true;
  6421. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  6422. this.hadstuncandidate = false;
  6423. this.hadturncandidate = false;
  6424. this.lasticecandidate = false;
  6425. this.statsinterval = null;
  6426. this.reason = null;
  6427. this.addssrc = [];
  6428. this.removessrc = [];
  6429. this.pendingop = null;
  6430. this.switchstreams = false;
  6431. this.addingStreams = false;
  6432. this.wait = true;
  6433. /**
  6434. * A map that stores SSRCs of local streams
  6435. * @type {{}} maps media type('audio' or 'video') to SSRC number
  6436. */
  6437. this.localStreamsSSRC = {};
  6438. this.ssrcOwners = {};
  6439. this.ssrcVideoTypes = {};
  6440. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  6441. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  6442. /**
  6443. * The indicator which determines whether the (local) video has been muted
  6444. * in response to a user command in contrast to an automatic decision made
  6445. * by the application logic.
  6446. */
  6447. this.videoMuteByUser = false;
  6448. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  6449. // We start with the queue paused. We resume it when the signaling state is
  6450. // stable and the ice connection state is connected.
  6451. this.modifySourcesQueue.pause();
  6452. }
  6453. //XXX this is badly broken...
  6454. JingleSessionPC.prototype = JingleSession.prototype;
  6455. JingleSessionPC.prototype.constructor = JingleSessionPC;
  6456. JingleSessionPC.prototype.setOffer = function(offer) {
  6457. this.setRemoteDescription(offer, 'offer');
  6458. };
  6459. JingleSessionPC.prototype.setAnswer = function(answer) {
  6460. this.setRemoteDescription(answer, 'answer');
  6461. };
  6462. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  6463. var signalingState = this.peerconnection.signalingState;
  6464. var iceConnectionState = this.peerconnection.iceConnectionState;
  6465. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  6466. this.modifySourcesQueue.resume();
  6467. } else {
  6468. this.modifySourcesQueue.pause();
  6469. }
  6470. };
  6471. JingleSessionPC.prototype.doInitialize = function () {
  6472. var self = this;
  6473. this.hadstuncandidate = false;
  6474. this.hadturncandidate = false;
  6475. this.lasticecandidate = false;
  6476. // True if reconnect is in progress
  6477. this.isreconnect = false;
  6478. // Set to true if the connection was ever stable
  6479. this.wasstable = false;
  6480. this.peerconnection = new TraceablePeerConnection(
  6481. this.connection.jingle.ice_config,
  6482. RTC.getPCConstraints(),
  6483. this);
  6484. this.peerconnection.onicecandidate = function (event) {
  6485. var protocol;
  6486. if (event && event.candidate) {
  6487. protocol = (typeof event.candidate.protocol === 'string')
  6488. ? event.candidate.protocol.toLowerCase() : '';
  6489. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6490. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6491. return;
  6492. }
  6493. }
  6494. self.sendIceCandidate(event.candidate);
  6495. };
  6496. this.peerconnection.onaddstream = function (event) {
  6497. if (event.stream.id !== 'default') {
  6498. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  6499. self.remoteStreamAdded(event);
  6500. } else {
  6501. // This is a recvonly stream. Clients that implement Unified Plan,
  6502. // such as Firefox use recvonly "streams/channels/tracks" for
  6503. // receiving remote stream/tracks, as opposed to Plan B where there
  6504. // are only 3 channels: audio, video and data.
  6505. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  6506. }
  6507. };
  6508. this.peerconnection.onremovestream = function (event) {
  6509. // Remove the stream from remoteStreams
  6510. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  6511. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  6512. };
  6513. this.peerconnection.onsignalingstatechange = function (event) {
  6514. if (!(self && self.peerconnection)) return;
  6515. if (self.peerconnection.signalingState === 'stable') {
  6516. self.wasstable = true;
  6517. }
  6518. self.updateModifySourcesQueue();
  6519. };
  6520. /**
  6521. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6522. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6523. * RTCPeerConnection.iceConnectionState changes.
  6524. *
  6525. * @param event the event containing information about the change
  6526. */
  6527. this.peerconnection.oniceconnectionstatechange = function (event) {
  6528. if (!(self && self.peerconnection)) return;
  6529. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6530. ":\t", window.performance.now());
  6531. self.updateModifySourcesQueue();
  6532. switch (self.peerconnection.iceConnectionState) {
  6533. case 'connected':
  6534. // Informs interested parties that the connection has been restored.
  6535. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6536. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6537. self.isreconnect = false;
  6538. break;
  6539. case 'disconnected':
  6540. self.isreconnect = true;
  6541. // Informs interested parties that the connection has been interrupted.
  6542. if (self.wasstable)
  6543. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6544. break;
  6545. case 'failed':
  6546. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6547. break;
  6548. }
  6549. onIceConnectionStateChange(self.sid, self);
  6550. };
  6551. this.peerconnection.onnegotiationneeded = function (event) {
  6552. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6553. };
  6554. this.relayedStreams.forEach(function(stream) {
  6555. self.peerconnection.addStream(stream);
  6556. });
  6557. };
  6558. function onIceConnectionStateChange(sid, session) {
  6559. switch (session.peerconnection.iceConnectionState) {
  6560. case 'checking':
  6561. session.timeChecking = (new Date()).getTime();
  6562. session.firstconnect = true;
  6563. break;
  6564. case 'completed': // on caller side
  6565. case 'connected':
  6566. if (session.firstconnect) {
  6567. session.firstconnect = false;
  6568. var metadata = {};
  6569. metadata.setupTime
  6570. = (new Date()).getTime() - session.timeChecking;
  6571. session.peerconnection.getStats(function (res) {
  6572. if(res && res.result) {
  6573. res.result().forEach(function (report) {
  6574. if (report.type == 'googCandidatePair' &&
  6575. report.stat('googActiveConnection') == 'true') {
  6576. metadata.localCandidateType
  6577. = report.stat('googLocalCandidateType');
  6578. metadata.remoteCandidateType
  6579. = report.stat('googRemoteCandidateType');
  6580. // log pair as well so we can get nice pie
  6581. // charts
  6582. metadata.candidatePair
  6583. = report.stat('googLocalCandidateType') +
  6584. ';' +
  6585. report.stat('googRemoteCandidateType');
  6586. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6587. {
  6588. metadata.ipv6 = true;
  6589. }
  6590. }
  6591. });
  6592. }
  6593. });
  6594. }
  6595. break;
  6596. }
  6597. }
  6598. JingleSessionPC.prototype.accept = function () {
  6599. this.state = 'active';
  6600. var pranswer = this.peerconnection.localDescription;
  6601. if (!pranswer || pranswer.type != 'pranswer') {
  6602. return;
  6603. }
  6604. logger.log('going from pranswer to answer');
  6605. if (this.usetrickle) {
  6606. // remove candidates already sent from session-accept
  6607. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6608. for (var i = 0; i < lines.length; i++) {
  6609. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6610. }
  6611. }
  6612. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6613. // FIXME: change any inactive to sendrecv or whatever they were originally
  6614. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6615. }
  6616. var prsdp = new SDP(pranswer.sdp);
  6617. if (self.webrtcIceTcpDisable) {
  6618. prsdp.removeTcpCandidates = true;
  6619. }
  6620. if (self.webrtcIceUdpDisable) {
  6621. prsdp.removeUdpCandidates = true;
  6622. }
  6623. var accept = $iq({to: this.peerjid,
  6624. type: 'set'})
  6625. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6626. action: 'session-accept',
  6627. initiator: this.initiator,
  6628. responder: this.responder,
  6629. sid: this.sid });
  6630. // FIXME why do we generate session-accept in 3 different places ?
  6631. prsdp.toJingle(
  6632. accept,
  6633. this.initiator == this.me ? 'initiator' : 'responder');
  6634. var sdp = this.peerconnection.localDescription.sdp;
  6635. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6636. // FIXME: change any inactive to sendrecv or whatever they were originally
  6637. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6638. }
  6639. var self = this;
  6640. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6641. function () {
  6642. //logger.log('setLocalDescription success');
  6643. self.setLocalDescription();
  6644. SSRCReplacement.processSessionInit(accept);
  6645. self.connection.sendIQ(accept,
  6646. function () {
  6647. var ack = {};
  6648. ack.source = 'answer';
  6649. $(document).trigger('ack.jingle', [self.sid, ack]);
  6650. },
  6651. function (stanza) {
  6652. var error = ($(stanza).find('error').length) ? {
  6653. code: $(stanza).find('error').attr('code'),
  6654. reason: $(stanza).find('error :first')[0].tagName
  6655. }:{};
  6656. error.source = 'answer';
  6657. JingleSessionPC.onJingleError(self.sid, error);
  6658. },
  6659. 10000);
  6660. },
  6661. function (e) {
  6662. logger.error('setLocalDescription failed', e);
  6663. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6664. }
  6665. );
  6666. };
  6667. JingleSessionPC.prototype.terminate = function (reason) {
  6668. this.state = 'ended';
  6669. this.reason = reason;
  6670. this.peerconnection.close();
  6671. if (this.statsinterval !== null) {
  6672. window.clearInterval(this.statsinterval);
  6673. this.statsinterval = null;
  6674. }
  6675. };
  6676. JingleSessionPC.prototype.active = function () {
  6677. return this.state == 'active';
  6678. };
  6679. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6680. var self = this;
  6681. if (candidate && !this.lasticecandidate) {
  6682. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6683. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6684. if (!(ice && jcand)) {
  6685. logger.error('failed to get ice && jcand');
  6686. return;
  6687. }
  6688. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6689. if (jcand.type === 'srflx') {
  6690. this.hadstuncandidate = true;
  6691. } else if (jcand.type === 'relay') {
  6692. this.hadturncandidate = true;
  6693. }
  6694. if (this.usetrickle) {
  6695. if (this.usedrip) {
  6696. if (this.drip_container.length === 0) {
  6697. // start 20ms callout
  6698. window.setTimeout(function () {
  6699. if (self.drip_container.length === 0) return;
  6700. self.sendIceCandidates(self.drip_container);
  6701. self.drip_container = [];
  6702. }, 20);
  6703. }
  6704. this.drip_container.push(candidate);
  6705. return;
  6706. } else {
  6707. self.sendIceCandidate([candidate]);
  6708. }
  6709. }
  6710. } else {
  6711. //logger.log('sendIceCandidate: last candidate.');
  6712. if (!this.usetrickle) {
  6713. //logger.log('should send full offer now...');
  6714. //FIXME why do we generate session-accept in 3 different places ?
  6715. var init = $iq({to: this.peerjid,
  6716. type: 'set'})
  6717. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6718. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6719. initiator: this.initiator,
  6720. sid: this.sid});
  6721. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6722. if (self.webrtcIceTcpDisable) {
  6723. this.localSDP.removeTcpCandidates = true;
  6724. }
  6725. if (self.webrtcIceUdpDisable) {
  6726. this.localSDP.removeUdpCandidates = true;
  6727. }
  6728. var sendJingle = function (ssrc) {
  6729. if(!ssrc)
  6730. ssrc = {};
  6731. self.localSDP.toJingle(
  6732. init,
  6733. self.initiator == self.me ? 'initiator' : 'responder',
  6734. ssrc);
  6735. SSRCReplacement.processSessionInit(init);
  6736. self.connection.sendIQ(init,
  6737. function () {
  6738. //logger.log('session initiate ack');
  6739. var ack = {};
  6740. ack.source = 'offer';
  6741. $(document).trigger('ack.jingle', [self.sid, ack]);
  6742. },
  6743. function (stanza) {
  6744. self.state = 'error';
  6745. self.peerconnection.close();
  6746. var error = ($(stanza).find('error').length) ? {
  6747. code: $(stanza).find('error').attr('code'),
  6748. reason: $(stanza).find('error :first')[0].tagName,
  6749. }:{};
  6750. error.source = 'offer';
  6751. JingleSessionPC.onJingleError(self.sid, error);
  6752. },
  6753. 10000);
  6754. };
  6755. sendJingle();
  6756. }
  6757. this.lasticecandidate = true;
  6758. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6759. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6760. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6761. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6762. }
  6763. }
  6764. };
  6765. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6766. logger.log('sendIceCandidates', candidates);
  6767. var cand = $iq({to: this.peerjid, type: 'set'})
  6768. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6769. action: 'transport-info',
  6770. initiator: this.initiator,
  6771. sid: this.sid});
  6772. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6773. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6774. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6775. if (cands.length > 0) {
  6776. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6777. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6778. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6779. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6780. }).c('transport', ice);
  6781. for (var i = 0; i < cands.length; i++) {
  6782. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6783. }
  6784. // add fingerprint
  6785. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6786. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6787. tmp.required = true;
  6788. cand.c(
  6789. 'fingerprint',
  6790. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6791. .t(tmp.fingerprint);
  6792. delete tmp.fingerprint;
  6793. cand.attrs(tmp);
  6794. cand.up();
  6795. }
  6796. cand.up(); // transport
  6797. cand.up(); // content
  6798. }
  6799. }
  6800. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6801. //logger.log('was this the last candidate', this.lasticecandidate);
  6802. this.connection.sendIQ(cand,
  6803. function () {
  6804. var ack = {};
  6805. ack.source = 'transportinfo';
  6806. $(document).trigger('ack.jingle', [this.sid, ack]);
  6807. },
  6808. function (stanza) {
  6809. var error = ($(stanza).find('error').length) ? {
  6810. code: $(stanza).find('error').attr('code'),
  6811. reason: $(stanza).find('error :first')[0].tagName,
  6812. }:{};
  6813. error.source = 'transportinfo';
  6814. JingleSessionPC.onJingleError(this.sid, error);
  6815. },
  6816. 10000);
  6817. };
  6818. JingleSessionPC.prototype.sendOffer = function () {
  6819. //logger.log('sendOffer...');
  6820. var self = this;
  6821. this.peerconnection.createOffer(function (sdp) {
  6822. self.createdOffer(sdp);
  6823. },
  6824. function (e) {
  6825. logger.error('createOffer failed', e);
  6826. },
  6827. this.media_constraints
  6828. );
  6829. };
  6830. // FIXME createdOffer is never used in jitsi-meet
  6831. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6832. //logger.log('createdOffer', sdp);
  6833. var self = this;
  6834. this.localSDP = new SDP(sdp.sdp);
  6835. //this.localSDP.mangle();
  6836. var sendJingle = function () {
  6837. var init = $iq({to: this.peerjid,
  6838. type: 'set'})
  6839. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6840. action: 'session-initiate',
  6841. initiator: this.initiator,
  6842. sid: this.sid});
  6843. self.localSDP.toJingle(
  6844. init,
  6845. this.initiator == this.me ? 'initiator' : 'responder');
  6846. SSRCReplacement.processSessionInit(init);
  6847. self.connection.sendIQ(init,
  6848. function () {
  6849. var ack = {};
  6850. ack.source = 'offer';
  6851. $(document).trigger('ack.jingle', [self.sid, ack]);
  6852. },
  6853. function (stanza) {
  6854. self.state = 'error';
  6855. self.peerconnection.close();
  6856. var error = ($(stanza).find('error').length) ? {
  6857. code: $(stanza).find('error').attr('code'),
  6858. reason: $(stanza).find('error :first')[0].tagName,
  6859. }:{};
  6860. error.source = 'offer';
  6861. JingleSessionPC.onJingleError(self.sid, error);
  6862. },
  6863. 10000);
  6864. }
  6865. sdp.sdp = this.localSDP.raw;
  6866. this.peerconnection.setLocalDescription(sdp,
  6867. function () {
  6868. if(self.usetrickle)
  6869. {
  6870. sendJingle();
  6871. }
  6872. self.setLocalDescription();
  6873. //logger.log('setLocalDescription success');
  6874. },
  6875. function (e) {
  6876. logger.error('setLocalDescription failed', e);
  6877. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6878. }
  6879. );
  6880. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6881. for (var i = 0; i < cands.length; i++) {
  6882. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6883. if (cand.type == 'srflx') {
  6884. this.hadstuncandidate = true;
  6885. } else if (cand.type == 'relay') {
  6886. this.hadturncandidate = true;
  6887. }
  6888. }
  6889. };
  6890. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6891. var self = this;
  6892. $(contents).each(function (idx, content) {
  6893. var name = $(content).attr('name');
  6894. var mediaType = this.getAttribute('name');
  6895. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6896. ssrcs.each(function () {
  6897. var ssrc = this.getAttribute('ssrc');
  6898. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6899. function () {
  6900. var owner = this.getAttribute('owner');
  6901. self.ssrcOwners[ssrc] = owner;
  6902. }
  6903. );
  6904. });
  6905. });
  6906. };
  6907. /**
  6908. * Returns the SSRC of local audio stream.
  6909. * @param mediaType 'audio' or 'video' media type
  6910. * @returns {*} the SSRC number of local audio or video stream.
  6911. */
  6912. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6913. return this.localStreamsSSRC[mediaType];
  6914. };
  6915. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6916. return this.ssrcOwners[ssrc];
  6917. };
  6918. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6919. //logger.log('setting remote description... ', desctype);
  6920. this.remoteSDP = new SDP('');
  6921. if (self.webrtcIceTcpDisable) {
  6922. this.remoteSDP.removeTcpCandidates = true;
  6923. }
  6924. if (self.webrtcIceUdpDisable) {
  6925. this.remoteSDP.removeUdpCandidates = true;
  6926. }
  6927. this.remoteSDP.fromJingle(elem);
  6928. this.readSsrcInfo($(elem).find(">content"));
  6929. if (this.peerconnection.remoteDescription) {
  6930. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6931. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6932. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6933. for (var i = 0; i < pranswer.media.length; i++) {
  6934. // make sure we have ice ufrag and pwd
  6935. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6936. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6937. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6938. } else {
  6939. logger.warn('no ice ufrag?');
  6940. }
  6941. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6942. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6943. } else {
  6944. logger.warn('no ice pwd?');
  6945. }
  6946. }
  6947. // copy over candidates
  6948. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6949. for (var j = 0; j < lines.length; j++) {
  6950. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6951. }
  6952. }
  6953. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6954. }
  6955. }
  6956. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6957. this.peerconnection.setRemoteDescription(remotedesc,
  6958. function () {
  6959. //logger.log('setRemoteDescription success');
  6960. },
  6961. function (e) {
  6962. logger.error('setRemoteDescription error', e);
  6963. JingleSessionPC.onJingleFatalError(self, e);
  6964. }
  6965. );
  6966. };
  6967. /**
  6968. * Adds remote ICE candidates to this Jingle session.
  6969. * @param elem An array of Jingle "content" elements?
  6970. */
  6971. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6972. var self = this;
  6973. if (this.peerconnection.signalingState == 'closed') {
  6974. return;
  6975. }
  6976. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6977. logger.log('trickle ice candidate arriving before session accept...');
  6978. // create a PRANSWER for setRemoteDescription
  6979. if (!this.remoteSDP) {
  6980. var cobbled = 'v=0\r\n' +
  6981. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6982. 's=-\r\n' +
  6983. 't=0 0\r\n';
  6984. // first, take some things from the local description
  6985. for (var i = 0; i < this.localSDP.media.length; i++) {
  6986. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6987. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6988. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6989. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6990. }
  6991. cobbled += 'a=inactive\r\n';
  6992. }
  6993. this.remoteSDP = new SDP(cobbled);
  6994. }
  6995. // then add things like ice and dtls from remote candidate
  6996. elem.each(function () {
  6997. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6998. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6999. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7000. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  7001. var tmp = $(this).find('transport');
  7002. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  7003. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  7004. tmp = $(this).find('transport>fingerprint');
  7005. if (tmp.length) {
  7006. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  7007. } else {
  7008. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  7009. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  7010. }
  7011. break;
  7012. }
  7013. }
  7014. }
  7015. });
  7016. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7017. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  7018. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  7019. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  7020. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  7021. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  7022. }).length == this.remoteSDP.media.length;
  7023. if (iscomplete) {
  7024. logger.log('setting pranswer');
  7025. try {
  7026. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  7027. function() {
  7028. },
  7029. function(e) {
  7030. logger.log('setRemoteDescription pranswer failed', e.toString());
  7031. });
  7032. } catch (e) {
  7033. logger.error('setting pranswer failed', e);
  7034. }
  7035. } else {
  7036. //logger.log('not yet setting pranswer');
  7037. }
  7038. }
  7039. // operate on each content element
  7040. elem.each(function () {
  7041. // would love to deactivate this, but firefox still requires it
  7042. var idx = -1;
  7043. var i;
  7044. for (i = 0; i < self.remoteSDP.media.length; i++) {
  7045. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7046. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7047. idx = i;
  7048. break;
  7049. }
  7050. }
  7051. if (idx == -1) { // fall back to localdescription
  7052. for (i = 0; i < self.localSDP.media.length; i++) {
  7053. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7054. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7055. idx = i;
  7056. break;
  7057. }
  7058. }
  7059. }
  7060. var name = $(this).attr('name');
  7061. // TODO: check ice-pwd and ice-ufrag?
  7062. $(this).find('transport>candidate').each(function () {
  7063. var line, candidate;
  7064. var protocol = this.getAttribute('protocol');
  7065. protocol =
  7066. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  7067. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7068. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7069. return;
  7070. }
  7071. line = SDPUtil.candidateFromJingle(this);
  7072. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  7073. sdpMid: name,
  7074. candidate: line});
  7075. try {
  7076. self.peerconnection.addIceCandidate(candidate);
  7077. } catch (e) {
  7078. logger.error('addIceCandidate failed', e.toString(), line);
  7079. }
  7080. });
  7081. });
  7082. };
  7083. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  7084. //logger.log('createAnswer', provisional);
  7085. var self = this;
  7086. this.peerconnection.createAnswer(
  7087. function (sdp) {
  7088. self.createdAnswer(sdp, provisional);
  7089. },
  7090. function (e) {
  7091. logger.error('createAnswer failed', e);
  7092. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7093. },
  7094. this.media_constraints
  7095. );
  7096. };
  7097. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  7098. //logger.log('createAnswer callback');
  7099. var self = this;
  7100. this.localSDP = new SDP(sdp.sdp);
  7101. //this.localSDP.mangle();
  7102. this.usepranswer = provisional === true;
  7103. if (this.usetrickle) {
  7104. if (this.usepranswer) {
  7105. sdp.type = 'pranswer';
  7106. for (var i = 0; i < this.localSDP.media.length; i++) {
  7107. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  7108. }
  7109. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  7110. }
  7111. }
  7112. var self = this;
  7113. var sendJingle = function (ssrcs) {
  7114. // FIXME why do we generate session-accept in 3 different places ?
  7115. var accept = $iq({to: self.peerjid,
  7116. type: 'set'})
  7117. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7118. action: 'session-accept',
  7119. initiator: self.initiator,
  7120. responder: self.responder,
  7121. sid: self.sid });
  7122. if (self.webrtcIceTcpDisable) {
  7123. self.localSDP.removeTcpCandidates = true;
  7124. }
  7125. if (self.webrtcIceUdpDisable) {
  7126. self.localSDP.removeUdpCandidates = true;
  7127. }
  7128. self.localSDP.toJingle(
  7129. accept,
  7130. self.initiator == self.me ? 'initiator' : 'responder',
  7131. ssrcs);
  7132. SSRCReplacement.processSessionInit(accept);
  7133. self.connection.sendIQ(accept,
  7134. function () {
  7135. var ack = {};
  7136. ack.source = 'answer';
  7137. $(document).trigger('ack.jingle', [self.sid, ack]);
  7138. },
  7139. function (stanza) {
  7140. var error = ($(stanza).find('error').length) ? {
  7141. code: $(stanza).find('error').attr('code'),
  7142. reason: $(stanza).find('error :first')[0].tagName,
  7143. }:{};
  7144. error.source = 'answer';
  7145. JingleSessionPC.onJingleError(self.sid, error);
  7146. },
  7147. 10000);
  7148. }
  7149. sdp.sdp = this.localSDP.raw;
  7150. this.peerconnection.setLocalDescription(sdp,
  7151. function () {
  7152. //logger.log('setLocalDescription success');
  7153. if (self.usetrickle && !self.usepranswer) {
  7154. sendJingle();
  7155. }
  7156. self.setLocalDescription();
  7157. },
  7158. function (e) {
  7159. logger.error('setLocalDescription failed', e);
  7160. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7161. }
  7162. );
  7163. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7164. for (var j = 0; j < cands.length; j++) {
  7165. var cand = SDPUtil.parse_icecandidate(cands[j]);
  7166. if (cand.type == 'srflx') {
  7167. this.hadstuncandidate = true;
  7168. } else if (cand.type == 'relay') {
  7169. this.hadturncandidate = true;
  7170. }
  7171. }
  7172. };
  7173. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  7174. var self = this,
  7175. term = $iq({to: this.peerjid,
  7176. type: 'set'})
  7177. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7178. action: 'session-terminate',
  7179. initiator: this.initiator,
  7180. sid: this.sid})
  7181. .c('reason')
  7182. .c(reason || 'success');
  7183. if (text) {
  7184. term.up().c('text').t(text);
  7185. }
  7186. this.connection.sendIQ(term,
  7187. function () {
  7188. self.peerconnection.close();
  7189. self.peerconnection = null;
  7190. self.terminate();
  7191. var ack = {};
  7192. ack.source = 'terminate';
  7193. $(document).trigger('ack.jingle', [self.sid, ack]);
  7194. },
  7195. function (stanza) {
  7196. var error = ($(stanza).find('error').length) ? {
  7197. code: $(stanza).find('error').attr('code'),
  7198. reason: $(stanza).find('error :first')[0].tagName,
  7199. }:{};
  7200. $(document).trigger('ack.jingle', [self.sid, error]);
  7201. },
  7202. 10000);
  7203. if (this.statsinterval !== null) {
  7204. window.clearInterval(this.statsinterval);
  7205. this.statsinterval = null;
  7206. }
  7207. };
  7208. /**
  7209. * Handles a Jingle source-add message for this Jingle session.
  7210. * @param elem An array of Jingle "content" elements.
  7211. */
  7212. JingleSessionPC.prototype.addSource = function (elem) {
  7213. var self = this;
  7214. // FIXME: dirty waiting
  7215. if (!this.peerconnection.localDescription)
  7216. {
  7217. logger.warn("addSource - localDescription not ready yet")
  7218. setTimeout(function()
  7219. {
  7220. self.addSource(elem);
  7221. },
  7222. 200
  7223. );
  7224. return;
  7225. }
  7226. logger.log('addssrc', new Date().getTime());
  7227. logger.log('ice', this.peerconnection.iceConnectionState);
  7228. this.readSsrcInfo(elem);
  7229. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7230. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7231. $(elem).each(function (idx, content) {
  7232. var name = $(content).attr('name');
  7233. var lines = '';
  7234. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7235. var semantics = this.getAttribute('semantics');
  7236. var ssrcs = $(this).find('>source').map(function () {
  7237. return this.getAttribute('ssrc');
  7238. }).get();
  7239. if (ssrcs.length) {
  7240. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7241. }
  7242. });
  7243. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7244. tmp.each(function () {
  7245. var ssrc = $(this).attr('ssrc');
  7246. if(mySdp.containsSSRC(ssrc)){
  7247. /**
  7248. * This happens when multiple participants change their streams at the same time and
  7249. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  7250. * addssrc are scheduled for update IQ. See
  7251. */
  7252. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  7253. return;
  7254. }
  7255. if (sdp.containsSSRC(ssrc)) {
  7256. logger.warn("Source-add request for existing SSRC: " + ssrc);
  7257. return;
  7258. }
  7259. $(this).find('>parameter').each(function () {
  7260. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7261. if ($(this).attr('value') && $(this).attr('value').length)
  7262. lines += ':' + $(this).attr('value');
  7263. lines += '\r\n';
  7264. });
  7265. });
  7266. sdp.media.forEach(function(media, idx) {
  7267. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7268. return;
  7269. sdp.media[idx] += lines;
  7270. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  7271. self.addssrc[idx] += lines;
  7272. });
  7273. sdp.raw = sdp.session + sdp.media.join('');
  7274. });
  7275. this.modifySourcesQueue.push(function() {
  7276. // When a source is added and if this is FF, a new channel is allocated
  7277. // for receiving the added source. We need to diffuse the SSRC of this
  7278. // new recvonly channel to the rest of the peers.
  7279. logger.log('modify sources done');
  7280. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7281. logger.log("SDPs", mySdp, newSdp);
  7282. self.notifyMySSRCUpdate(mySdp, newSdp);
  7283. });
  7284. };
  7285. /**
  7286. * Handles a Jingle source-remove message for this Jingle session.
  7287. * @param elem An array of Jingle "content" elements.
  7288. */
  7289. JingleSessionPC.prototype.removeSource = function (elem) {
  7290. var self = this;
  7291. // FIXME: dirty waiting
  7292. if (!this.peerconnection.localDescription) {
  7293. logger.warn("removeSource - localDescription not ready yet");
  7294. setTimeout(function() {
  7295. self.removeSource(elem);
  7296. },
  7297. 200
  7298. );
  7299. return;
  7300. }
  7301. logger.log('removessrc', new Date().getTime());
  7302. logger.log('ice', this.peerconnection.iceConnectionState);
  7303. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7304. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7305. $(elem).each(function (idx, content) {
  7306. var name = $(content).attr('name');
  7307. var lines = '';
  7308. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7309. var semantics = this.getAttribute('semantics');
  7310. var ssrcs = $(this).find('>source').map(function () {
  7311. return this.getAttribute('ssrc');
  7312. }).get();
  7313. if (ssrcs.length) {
  7314. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7315. }
  7316. });
  7317. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7318. tmp.each(function () {
  7319. var ssrc = $(this).attr('ssrc');
  7320. // This should never happen, but can be useful for bug detection
  7321. if(mySdp.containsSSRC(ssrc)){
  7322. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  7323. return;
  7324. }
  7325. $(this).find('>parameter').each(function () {
  7326. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7327. if ($(this).attr('value') && $(this).attr('value').length)
  7328. lines += ':' + $(this).attr('value');
  7329. lines += '\r\n';
  7330. });
  7331. });
  7332. sdp.media.forEach(function(media, idx) {
  7333. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7334. return;
  7335. sdp.media[idx] += lines;
  7336. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  7337. self.removessrc[idx] += lines;
  7338. });
  7339. sdp.raw = sdp.session + sdp.media.join('');
  7340. });
  7341. this.modifySourcesQueue.push(function() {
  7342. // When a source is removed and if this is FF, the recvonly channel that
  7343. // receives the remote stream is deactivated . We need to diffuse the
  7344. // recvonly SSRC removal to the rest of the peers.
  7345. logger.log('modify sources done');
  7346. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7347. logger.log("SDPs", mySdp, newSdp);
  7348. self.notifyMySSRCUpdate(mySdp, newSdp);
  7349. });
  7350. };
  7351. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  7352. var self = this;
  7353. if (this.peerconnection.signalingState == 'closed') return;
  7354. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  7355. || this.switchstreams || this.addingStreams)){
  7356. // There is nothing to do since scheduled job might have been executed by another succeeding call
  7357. this.setLocalDescription();
  7358. if(successCallback){
  7359. successCallback();
  7360. }
  7361. queueCallback();
  7362. return;
  7363. }
  7364. // Reset switch streams flags
  7365. this.switchstreams = false;
  7366. this.addingStreams = false;
  7367. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7368. // add sources
  7369. this.addssrc.forEach(function(lines, idx) {
  7370. sdp.media[idx] += lines;
  7371. });
  7372. this.addssrc = [];
  7373. // remove sources
  7374. this.removessrc.forEach(function(lines, idx) {
  7375. lines = lines.split('\r\n');
  7376. lines.pop(); // remove empty last element;
  7377. lines.forEach(function(line) {
  7378. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  7379. });
  7380. });
  7381. this.removessrc = [];
  7382. sdp.raw = sdp.session + sdp.media.join('');
  7383. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  7384. function() {
  7385. if(self.signalingState == 'closed') {
  7386. logger.error("createAnswer attempt on closed state");
  7387. queueCallback("createAnswer attempt on closed state");
  7388. return;
  7389. }
  7390. self.peerconnection.createAnswer(
  7391. function(modifiedAnswer) {
  7392. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  7393. if (self.pendingop !== null) {
  7394. var sdp = new SDP(modifiedAnswer.sdp);
  7395. if (sdp.media.length > 1) {
  7396. switch(self.pendingop) {
  7397. case 'mute':
  7398. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  7399. break;
  7400. case 'unmute':
  7401. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  7402. break;
  7403. }
  7404. sdp.raw = sdp.session + sdp.media.join('');
  7405. modifiedAnswer.sdp = sdp.raw;
  7406. }
  7407. self.pendingop = null;
  7408. }
  7409. // FIXME: pushing down an answer while ice connection state
  7410. // is still checking is bad...
  7411. //logger.log(self.peerconnection.iceConnectionState);
  7412. // trying to work around another chrome bug
  7413. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  7414. self.peerconnection.setLocalDescription(modifiedAnswer,
  7415. function() {
  7416. //logger.log('modified setLocalDescription ok');
  7417. self.setLocalDescription();
  7418. if(successCallback){
  7419. successCallback();
  7420. }
  7421. queueCallback();
  7422. },
  7423. function(error) {
  7424. logger.error('modified setLocalDescription failed', error);
  7425. queueCallback(error);
  7426. }
  7427. );
  7428. },
  7429. function(error) {
  7430. logger.error('modified answer failed', error);
  7431. queueCallback(error);
  7432. }
  7433. );
  7434. },
  7435. function(error) {
  7436. logger.error('modify failed', error);
  7437. queueCallback(error);
  7438. }
  7439. );
  7440. };
  7441. /**
  7442. * Switches video streams.
  7443. * @param newStream new stream that will be used as video of this session.
  7444. * @param oldStream old video stream of this session.
  7445. * @param successCallback callback executed after successful stream switch.
  7446. * @param isAudio whether the streams are audio (if true) or video (if false).
  7447. */
  7448. JingleSessionPC.prototype.switchStreams =
  7449. function (newStream, oldStream, successCallback, isAudio) {
  7450. var self = this;
  7451. var sender, newTrack;
  7452. var senderKind = isAudio ? 'audio' : 'video';
  7453. // Remember SDP to figure out added/removed SSRCs
  7454. var oldSdp = null;
  7455. if (self.peerconnection) {
  7456. if (self.peerconnection.localDescription) {
  7457. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7458. }
  7459. if (RTCBrowserType.getBrowserType() ===
  7460. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  7461. // On Firefox we don't replace MediaStreams as this messes up the
  7462. // m-lines (which can't be removed in Plan Unified) and brings a lot
  7463. // of complications. Instead, we use the RTPSender and replace just
  7464. // the track.
  7465. // Find the right sender (for audio or video)
  7466. self.peerconnection.peerconnection.getSenders().some(function (s) {
  7467. if (s.track && s.track.kind === senderKind) {
  7468. sender = s;
  7469. return true;
  7470. }
  7471. });
  7472. if (sender) {
  7473. // We assume that our streams have a single track, either audio
  7474. // or video.
  7475. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  7476. newStream.getVideoTracks()[0];
  7477. sender.replaceTrack(newTrack)
  7478. .then(function() {
  7479. console.log("Replaced a track, isAudio=" + isAudio);
  7480. })
  7481. .catch(function(err) {
  7482. console.log("Failed to replace a track: " + err);
  7483. });
  7484. } else {
  7485. console.log("Cannot switch tracks: no RTPSender.");
  7486. }
  7487. } else {
  7488. self.peerconnection.removeStream(oldStream, true);
  7489. if (newStream) {
  7490. self.peerconnection.addStream(newStream);
  7491. }
  7492. }
  7493. }
  7494. // Conference is not active
  7495. if (!oldSdp) {
  7496. successCallback();
  7497. return;
  7498. }
  7499. self.switchstreams = true;
  7500. self.modifySourcesQueue.push(function() {
  7501. logger.log('modify sources done');
  7502. successCallback();
  7503. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7504. logger.log("SDPs", oldSdp, newSdp);
  7505. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7506. });
  7507. };
  7508. /**
  7509. * Adds streams.
  7510. * @param stream new stream that will be added.
  7511. * @param success_callback callback executed after successful stream addition.
  7512. */
  7513. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7514. var self = this;
  7515. // Remember SDP to figure out added/removed SSRCs
  7516. var oldSdp = null;
  7517. if(this.peerconnection) {
  7518. if(this.peerconnection.localDescription) {
  7519. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7520. }
  7521. if(stream)
  7522. this.peerconnection.addStream(stream);
  7523. }
  7524. // Conference is not active
  7525. if(!oldSdp || !this.peerconnection) {
  7526. callback();
  7527. return;
  7528. }
  7529. this.addingStreams = true;
  7530. this.modifySourcesQueue.push(function() {
  7531. logger.log('modify sources done');
  7532. callback();
  7533. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7534. logger.log("SDPs", oldSdp, newSdp);
  7535. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7536. });
  7537. }
  7538. /**
  7539. * Remove streams.
  7540. * @param stream stream that will be removed.
  7541. * @param success_callback callback executed after successful stream addition.
  7542. */
  7543. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7544. var self = this;
  7545. // Remember SDP to figure out added/removed SSRCs
  7546. var oldSdp = null;
  7547. if(this.peerconnection) {
  7548. if(this.peerconnection.localDescription) {
  7549. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7550. }
  7551. if(stream)
  7552. this.peerconnection.removeStream(stream);
  7553. }
  7554. // Conference is not active
  7555. if(!oldSdp || !this.peerconnection) {
  7556. callback();
  7557. return;
  7558. }
  7559. this.addingStreams = true;
  7560. this.modifySourcesQueue.push(function() {
  7561. logger.log('modify sources done');
  7562. callback();
  7563. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7564. logger.log("SDPs", oldSdp, newSdp);
  7565. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7566. });
  7567. }
  7568. /**
  7569. * Figures out added/removed ssrcs and send update IQs.
  7570. * @param old_sdp SDP object for old description.
  7571. * @param new_sdp SDP object for new description.
  7572. */
  7573. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7574. if (!(this.peerconnection.signalingState == 'stable' &&
  7575. this.peerconnection.iceConnectionState == 'connected')){
  7576. logger.log("Too early to send updates");
  7577. return;
  7578. }
  7579. // send source-remove IQ.
  7580. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7581. var remove = $iq({to: this.peerjid, type: 'set'})
  7582. .c('jingle', {
  7583. xmlns: 'urn:xmpp:jingle:1',
  7584. action: 'source-remove',
  7585. initiator: this.initiator,
  7586. sid: this.sid
  7587. }
  7588. );
  7589. var removed = sdpDiffer.toJingle(remove);
  7590. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7591. // it in the current form
  7592. if (removed)
  7593. remove = SSRCReplacement.processSourceRemove(remove);
  7594. if (removed && remove) {
  7595. logger.info("Sending source-remove", remove);
  7596. this.connection.sendIQ(remove,
  7597. function (res) {
  7598. logger.info('got remove result', res);
  7599. },
  7600. function (err) {
  7601. logger.error('got remove error', err);
  7602. }
  7603. );
  7604. } else {
  7605. logger.log('removal not necessary');
  7606. }
  7607. // send source-add IQ.
  7608. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7609. var add = $iq({to: this.peerjid, type: 'set'})
  7610. .c('jingle', {
  7611. xmlns: 'urn:xmpp:jingle:1',
  7612. action: 'source-add',
  7613. initiator: this.initiator,
  7614. sid: this.sid
  7615. }
  7616. );
  7617. var added = sdpDiffer.toJingle(add);
  7618. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7619. // it in the current form
  7620. if (added)
  7621. add = SSRCReplacement.processSourceAdd(add);
  7622. if (added && add) {
  7623. logger.info("Sending source-add", add);
  7624. this.connection.sendIQ(add,
  7625. function (res) {
  7626. logger.info('got add result', res);
  7627. },
  7628. function (err) {
  7629. logger.error('got add error', err);
  7630. }
  7631. );
  7632. } else {
  7633. logger.log('addition not necessary');
  7634. }
  7635. };
  7636. /**
  7637. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7638. *
  7639. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7640. * tracks; otherwise, <tt>false</tt>
  7641. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7642. * tracks have been enabled/disabled. The function may, optionally, return
  7643. * another function which is to be invoked after the whole mute/unmute operation
  7644. * has completed successfully.
  7645. * @param options an object which specifies optional arguments such as the
  7646. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7647. * specifies whether the method was initiated in response to a user command (in
  7648. * contrast to an automatic decision made by the application logic)
  7649. */
  7650. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7651. var byUser;
  7652. if (options) {
  7653. byUser = options.byUser;
  7654. if (typeof byUser === 'undefined') {
  7655. byUser = true;
  7656. }
  7657. } else {
  7658. byUser = true;
  7659. }
  7660. // The user's command to mute the (local) video takes precedence over any
  7661. // automatic decision made by the application logic.
  7662. if (byUser) {
  7663. this.videoMuteByUser = mute;
  7664. } else if (this.videoMuteByUser) {
  7665. return;
  7666. }
  7667. this.hardMuteVideo(mute);
  7668. var self = this;
  7669. var oldSdp = null;
  7670. if(self.peerconnection) {
  7671. if(self.peerconnection.localDescription) {
  7672. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7673. }
  7674. }
  7675. this.modifySourcesQueue.push(function() {
  7676. logger.log('modify sources done');
  7677. callback(mute);
  7678. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7679. logger.log("SDPs", oldSdp, newSdp);
  7680. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7681. });
  7682. };
  7683. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7684. this.pendingop = muted ? 'mute' : 'unmute';
  7685. };
  7686. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7687. var info = $iq({to: this.peerjid,
  7688. type: 'set'})
  7689. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7690. action: 'session-info',
  7691. initiator: this.initiator,
  7692. sid: this.sid });
  7693. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7694. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7695. if (content) {
  7696. info.attrs({'name': content});
  7697. }
  7698. this.connection.send(info);
  7699. };
  7700. JingleSessionPC.prototype.sendRinging = function () {
  7701. var info = $iq({to: this.peerjid,
  7702. type: 'set'})
  7703. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7704. action: 'session-info',
  7705. initiator: this.initiator,
  7706. sid: this.sid });
  7707. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7708. this.connection.send(info);
  7709. };
  7710. JingleSessionPC.prototype.getStats = function (interval) {
  7711. var self = this;
  7712. var recv = {audio: 0, video: 0};
  7713. var lost = {audio: 0, video: 0};
  7714. var lastrecv = {audio: 0, video: 0};
  7715. var lastlost = {audio: 0, video: 0};
  7716. var loss = {audio: 0, video: 0};
  7717. var delta = {audio: 0, video: 0};
  7718. this.statsinterval = window.setInterval(function () {
  7719. if (self && self.peerconnection && self.peerconnection.getStats) {
  7720. self.peerconnection.getStats(function (stats) {
  7721. var results = stats.result();
  7722. // TODO: there are so much statistics you can get from this..
  7723. for (var i = 0; i < results.length; ++i) {
  7724. if (results[i].type == 'ssrc') {
  7725. var packetsrecv = results[i].stat('packetsReceived');
  7726. var packetslost = results[i].stat('packetsLost');
  7727. if (packetsrecv && packetslost) {
  7728. packetsrecv = parseInt(packetsrecv, 10);
  7729. packetslost = parseInt(packetslost, 10);
  7730. if (results[i].stat('googFrameRateReceived')) {
  7731. lastlost.video = lost.video;
  7732. lastrecv.video = recv.video;
  7733. recv.video = packetsrecv;
  7734. lost.video = packetslost;
  7735. } else {
  7736. lastlost.audio = lost.audio;
  7737. lastrecv.audio = recv.audio;
  7738. recv.audio = packetsrecv;
  7739. lost.audio = packetslost;
  7740. }
  7741. }
  7742. }
  7743. }
  7744. delta.audio = recv.audio - lastrecv.audio;
  7745. delta.video = recv.video - lastrecv.video;
  7746. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7747. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7748. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7749. });
  7750. }
  7751. }, interval || 3000);
  7752. return this.statsinterval;
  7753. };
  7754. JingleSessionPC.onJingleError = function (session, error)
  7755. {
  7756. logger.error("Jingle error", error);
  7757. }
  7758. JingleSessionPC.onJingleFatalError = function (session, error)
  7759. {
  7760. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7761. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7762. }
  7763. JingleSessionPC.prototype.setLocalDescription = function () {
  7764. var self = this;
  7765. var newssrcs = [];
  7766. if(!this.peerconnection.localDescription)
  7767. return;
  7768. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7769. var i;
  7770. session.media.forEach(function (media) {
  7771. if (media.ssrcs && media.ssrcs.length > 0) {
  7772. // TODO(gp) maybe exclude FID streams?
  7773. media.ssrcs.forEach(function (ssrc) {
  7774. if (ssrc.attribute !== 'cname') {
  7775. return;
  7776. }
  7777. newssrcs.push({
  7778. 'ssrc': ssrc.id,
  7779. 'type': media.type
  7780. });
  7781. // FIXME allows for only one SSRC per media type
  7782. self.localStreamsSSRC[media.type] = ssrc.id;
  7783. });
  7784. }
  7785. });
  7786. logger.log('new ssrcs', newssrcs);
  7787. // Bind us as local SSRCs owner
  7788. if (newssrcs.length > 0) {
  7789. for (i = 0; i < newssrcs.length; i++) {
  7790. var ssrc = newssrcs[i].ssrc;
  7791. var myJid = self.me;
  7792. self.ssrcOwners[ssrc] = myJid;
  7793. }
  7794. }
  7795. }
  7796. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7797. JingleSessionPC.prototype.sendKeyframe = function () {
  7798. var pc = this.peerconnection;
  7799. logger.log('sendkeyframe', pc.iceConnectionState);
  7800. if (pc.iceConnectionState !== 'connected') return; // safe...
  7801. var self = this;
  7802. pc.setRemoteDescription(
  7803. pc.remoteDescription,
  7804. function () {
  7805. pc.createAnswer(
  7806. function (modifiedAnswer) {
  7807. pc.setLocalDescription(
  7808. modifiedAnswer,
  7809. function () {
  7810. // noop
  7811. },
  7812. function (error) {
  7813. logger.log('triggerKeyframe setLocalDescription failed', error);
  7814. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7815. }
  7816. );
  7817. },
  7818. function (error) {
  7819. logger.log('triggerKeyframe createAnswer failed', error);
  7820. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7821. }
  7822. );
  7823. },
  7824. function (error) {
  7825. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7826. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7827. }
  7828. );
  7829. }
  7830. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7831. var self = this;
  7832. var thessrc;
  7833. var streamId = RTC.getStreamID(data.stream);
  7834. // look up an associated JID for a stream id
  7835. if (!streamId) {
  7836. logger.error("No stream ID for", data.stream);
  7837. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7838. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7839. var ssrclines = this.peerconnection.remoteDescription?
  7840. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7841. ssrclines = ssrclines.filter(function (line) {
  7842. // NOTE(gp) previously we filtered on the mslabel, but that property
  7843. // is not always present.
  7844. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7845. if (RTCBrowserType.isTemasysPluginUsed()) {
  7846. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7847. } else {
  7848. return ((line.indexOf('msid:' + streamId) !== -1));
  7849. }
  7850. });
  7851. if (ssrclines.length) {
  7852. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7853. if (!self.ssrcOwners[thessrc]) {
  7854. logger.error("No SSRC owner known for: " + thessrc);
  7855. return;
  7856. }
  7857. data.peerjid = self.ssrcOwners[thessrc];
  7858. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7859. } else {
  7860. logger.error("No SSRC lines for ", streamId);
  7861. }
  7862. }
  7863. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7864. var isVideo = data.stream.getVideoTracks().length > 0;
  7865. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7866. if (isVideo &&
  7867. data.peerjid && this.peerjid === data.peerjid &&
  7868. data.stream.getVideoTracks().length === 0 &&
  7869. RTC.localVideo.getTracks().length > 0) {
  7870. window.setTimeout(function () {
  7871. self.sendKeyframe();
  7872. }, 3000);
  7873. }
  7874. }
  7875. /**
  7876. * Returns the ice connection state for the peer connection.
  7877. * @returns the ice connection state for the peer connection.
  7878. */
  7879. JingleSessionPC.prototype.getIceConnectionState = function () {
  7880. return this.peerconnection.iceConnectionState;
  7881. }
  7882. module.exports = JingleSessionPC;
  7883. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7884. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":43,"jitsi-meet-logger":48,"sdp-transform":76}],29:[function(require,module,exports){
  7885. (function (__filename){
  7886. /* global $ */
  7887. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7888. /*
  7889. Here we do modifications of local video SSRCs. There are 2 situations we have
  7890. to handle:
  7891. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7892. have no local camera and it is not generated automatically, but SSRC=1 is
  7893. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7894. and we won't be able to request video key frames correctly.
  7895. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7896. in future. It turned out that Chrome may keep on using the SSRC of removed
  7897. video stream in RTCP even though a new one has been created. So we just
  7898. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7899. notifications are blocked once first video SSRC is advertised to the focus.
  7900. What this hack does:
  7901. 1. Stores the SSRC of the first video stream created by
  7902. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7903. b) watching for 'source-add' for new video stream if it has not been
  7904. created in step a)
  7905. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7906. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7907. returned to the other parts of the application.
  7908. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7909. blocks those notifications. This makes Jicofo and all participants think
  7910. that it exists all the time even if the video stream has been removed or
  7911. replaced locally. Thanks to that there is no additional signaling activity
  7912. on video mute or when switching to the desktop stream.
  7913. */
  7914. var SDP = require('./SDP');
  7915. var RandomUtil = require('../util/RandomUtil');
  7916. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7917. /**
  7918. * The hack is enabled on all browsers except FF by default
  7919. * FIXME finish the hack once removeStream method is implemented in FF
  7920. * @type {boolean}
  7921. */
  7922. var isEnabled = !RTCBrowserType.isFirefox();
  7923. /**
  7924. * Stored SSRC of local video stream.
  7925. */
  7926. var localVideoSSRC;
  7927. /**
  7928. * SSRC used for recvonly video stream when we have no local camera.
  7929. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7930. * instead of 1.
  7931. */
  7932. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7933. /**
  7934. * cname for <tt>localRecvOnlySSRC</tt>
  7935. */
  7936. var localRecvOnlyCName;
  7937. /**
  7938. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7939. * from given Jingle IQ.
  7940. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7941. * @param actionName display name of the action which will be printed in log
  7942. * messages.
  7943. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7944. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7945. * other SSRCs left to be signaled after removing it.
  7946. */
  7947. var filterOutSource = function (modifyIq, actionName) {
  7948. var modifyIqTree = $(modifyIq.tree());
  7949. if (!localVideoSSRC)
  7950. return modifyIqTree[0];
  7951. var videoSSRC = modifyIqTree.find(
  7952. '>jingle>content[name="video"]' +
  7953. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7954. if (!videoSSRC.length) {
  7955. return modifyIqTree[0];
  7956. }
  7957. logger.info(
  7958. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7959. videoSSRC.remove();
  7960. // Check if any sources still left to be added/removed
  7961. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7962. return modifyIqTree[0];
  7963. } else {
  7964. return null;
  7965. }
  7966. };
  7967. /**
  7968. * Scans given Jingle IQ for video SSRC and stores it.
  7969. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7970. */
  7971. var storeLocalVideoSSRC = function (jingleIq) {
  7972. var videoSSRCs =
  7973. $(jingleIq.tree())
  7974. .find('>jingle>content[name="video"]>description>source');
  7975. videoSSRCs.each(function (idx, ssrcElem) {
  7976. if (localVideoSSRC)
  7977. return;
  7978. // We consider SSRC real only if it has msid attribute
  7979. // recvonly streams in FF do not have it as well as local SSRCs
  7980. // we generate for recvonly streams in Chrome
  7981. var ssrSel = $(ssrcElem);
  7982. var msid = ssrSel.find('>parameter[name="msid"]');
  7983. if (msid.length) {
  7984. var ssrcVal = ssrSel.attr('ssrc');
  7985. if (ssrcVal) {
  7986. localVideoSSRC = ssrcVal;
  7987. logger.info('Stored local video SSRC' +
  7988. ' for future re-use: ' + localVideoSSRC);
  7989. }
  7990. }
  7991. });
  7992. };
  7993. /**
  7994. * Generates new label/mslabel attribute
  7995. * @returns {string} label/mslabel attribute
  7996. */
  7997. function generateLabel() {
  7998. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7999. "-" + RandomUtil.randomHexString(4) + "-" +
  8000. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  8001. }
  8002. /**
  8003. * Generates new SSRC for local video recvonly stream.
  8004. * FIXME what about eventual SSRC collision ?
  8005. */
  8006. function generateRecvonlySSRC() {
  8007. localVideoSSRC = localRecvOnlySSRC =
  8008. localVideoSSRC ?
  8009. localVideoSSRC : Math.random().toString(10).substring(2, 11);
  8010. localRecvOnlyCName =
  8011. Math.random().toString(36).substring(2);
  8012. localRecvOnlyMSLabel = generateLabel();
  8013. localRecvOnlyLabel = generateLabel();
  8014. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  8015. logger.info(
  8016. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  8017. ", cname: " + localRecvOnlyCName);
  8018. }
  8019. var LocalSSRCReplacement = {
  8020. /**
  8021. * Method must be called before 'session-initiate' or 'session-invite' is
  8022. * sent. Scans the IQ for local video SSRC and stores it if detected.
  8023. *
  8024. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  8025. * which will be scanned for local video SSRC.
  8026. */
  8027. processSessionInit: function (sessionInit) {
  8028. if (!isEnabled)
  8029. return;
  8030. if (localVideoSSRC) {
  8031. logger.error("Local SSRC stored already: " + localVideoSSRC);
  8032. return;
  8033. }
  8034. storeLocalVideoSSRC(sessionInit);
  8035. },
  8036. /**
  8037. * If we have local video SSRC stored searched given
  8038. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  8039. * with the stored one.
  8040. * @param localDescription local description object that will have local
  8041. * video SSRC replaced with the stored one
  8042. * @returns modified <tt>localDescription</tt> object.
  8043. */
  8044. mungeLocalVideoSSRC: function (localDescription) {
  8045. if (!isEnabled)
  8046. return localDescription;
  8047. if (!localDescription) {
  8048. logger.warn("localDescription is null or undefined");
  8049. return localDescription;
  8050. }
  8051. // IF we have local video SSRC stored make sure it is replaced
  8052. // with old SSRC
  8053. var sdp = new SDP(localDescription.sdp);
  8054. if (sdp.media.length < 2)
  8055. return;
  8056. if (localVideoSSRC && sdp.media[1].indexOf("a=ssrc:") !== -1 &&
  8057. !sdp.containsSSRC(localVideoSSRC)) {
  8058. // Get new video SSRC
  8059. var map = sdp.getMediaSsrcMap();
  8060. var videoPart = map[1];
  8061. var videoSSRCs = videoPart.ssrcs;
  8062. var newSSRC = Object.keys(videoSSRCs)[0];
  8063. logger.info(
  8064. "Replacing new video SSRC: " + newSSRC +
  8065. " with " + localVideoSSRC);
  8066. localDescription.sdp =
  8067. sdp.raw.replace(
  8068. new RegExp('a=ssrc:' + newSSRC, 'g'),
  8069. 'a=ssrc:' + localVideoSSRC);
  8070. }
  8071. else if (sdp.media[1].indexOf('a=ssrc:') === -1 &&
  8072. sdp.media[1].indexOf('a=recvonly') !== -1) {
  8073. // Make sure we have any SSRC for recvonly video stream
  8074. if (!localRecvOnlySSRC) {
  8075. generateRecvonlySSRC();
  8076. }
  8077. logger.info('No SSRC in video recvonly stream' +
  8078. ' - adding SSRC: ' + localRecvOnlySSRC);
  8079. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  8080. ' cname:' + localRecvOnlyCName + '\r\n' +
  8081. 'a=ssrc:' + localRecvOnlySSRC +
  8082. ' msid:' + localRecvOnlyMSID + '\r\n' +
  8083. 'a=ssrc:' + localRecvOnlySSRC +
  8084. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  8085. 'a=ssrc:' + localRecvOnlySSRC +
  8086. ' label:' + localRecvOnlyLabel + '\r\n';
  8087. localDescription.sdp = sdp.session + sdp.media.join('');
  8088. }
  8089. return localDescription;
  8090. },
  8091. /**
  8092. * Method must be called before 'source-add' notification is sent. In case
  8093. * we have local video SSRC advertised already it will be removed from the
  8094. * notification. If no other SSRCs are described by given IQ null will be
  8095. * returned which means that there is no point in sending the notification.
  8096. * @param sourceAdd 'source-add' Jingle IQ to be processed
  8097. * @returns modified 'source-add' IQ which can be sent to the focus or
  8098. * <tt>null</tt> if no notification shall be sent. It is no longer
  8099. * a Strophe IQ Builder instance, but DOM element tree.
  8100. */
  8101. processSourceAdd: function (sourceAdd) {
  8102. if (!isEnabled)
  8103. return sourceAdd;
  8104. if (!localVideoSSRC) {
  8105. // Store local SSRC if available
  8106. storeLocalVideoSSRC(sourceAdd);
  8107. return sourceAdd;
  8108. } else {
  8109. return filterOutSource(sourceAdd, 'source-add');
  8110. }
  8111. },
  8112. /**
  8113. * Method must be called before 'source-remove' notification is sent.
  8114. * Removes local video SSRC from the notification. If there are no other
  8115. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  8116. * means that there is no point in sending the notification.
  8117. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  8118. * @returns modified 'source-remove' IQ which can be sent to the focus or
  8119. * <tt>null</tt> if no notification shall be sent. It is no longer
  8120. * a Strophe IQ Builder instance, but DOM element tree.
  8121. */
  8122. processSourceRemove: function (sourceRemove) {
  8123. if (!isEnabled)
  8124. return sourceRemove;
  8125. return filterOutSource(sourceRemove, 'source-remove');
  8126. },
  8127. /**
  8128. * Turns the hack on or off
  8129. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  8130. * to disable it
  8131. */
  8132. setEnabled: function (enabled) {
  8133. isEnabled = enabled;
  8134. }
  8135. };
  8136. module.exports = LocalSSRCReplacement;
  8137. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  8138. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":48}],30:[function(require,module,exports){
  8139. (function (__filename){
  8140. /* jshint -W117 */
  8141. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8142. var SDPUtil = require("./SDPUtil");
  8143. // SDP STUFF
  8144. function SDP(sdp) {
  8145. /**
  8146. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  8147. * @type {boolean}
  8148. */
  8149. this.removeTcpCandidates = false;
  8150. /**
  8151. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  8152. * @type {boolean}
  8153. */
  8154. this.removeUdpCandidates = false;
  8155. this.media = sdp.split('\r\nm=');
  8156. for (var i = 1; i < this.media.length; i++) {
  8157. this.media[i] = 'm=' + this.media[i];
  8158. if (i != this.media.length - 1) {
  8159. this.media[i] += '\r\n';
  8160. }
  8161. }
  8162. this.session = this.media.shift() + '\r\n';
  8163. this.raw = this.session + this.media.join('');
  8164. }
  8165. /**
  8166. * Returns map of MediaChannel mapped per channel idx.
  8167. */
  8168. SDP.prototype.getMediaSsrcMap = function() {
  8169. var self = this;
  8170. var media_ssrcs = {};
  8171. var tmp;
  8172. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  8173. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  8174. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  8175. var media = {
  8176. mediaindex: mediaindex,
  8177. mid: mid,
  8178. ssrcs: {},
  8179. ssrcGroups: []
  8180. };
  8181. media_ssrcs[mediaindex] = media;
  8182. tmp.forEach(function (line) {
  8183. var linessrc = line.substring(7).split(' ')[0];
  8184. // allocate new ChannelSsrc
  8185. if(!media.ssrcs[linessrc]) {
  8186. media.ssrcs[linessrc] = {
  8187. ssrc: linessrc,
  8188. lines: []
  8189. };
  8190. }
  8191. media.ssrcs[linessrc].lines.push(line);
  8192. });
  8193. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  8194. tmp.forEach(function(line){
  8195. var idx = line.indexOf(' ');
  8196. var semantics = line.substr(0, idx).substr(13);
  8197. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8198. if (ssrcs.length) {
  8199. media.ssrcGroups.push({
  8200. semantics: semantics,
  8201. ssrcs: ssrcs
  8202. });
  8203. }
  8204. });
  8205. }
  8206. return media_ssrcs;
  8207. };
  8208. /**
  8209. * Returns <tt>true</tt> if this SDP contains given SSRC.
  8210. * @param ssrc the ssrc to check.
  8211. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  8212. */
  8213. SDP.prototype.containsSSRC = function (ssrc) {
  8214. // FIXME this code is really strange - improve it if you can
  8215. var medias = this.getMediaSsrcMap();
  8216. var result = false;
  8217. Object.keys(medias).forEach(function (mediaindex) {
  8218. if (result)
  8219. return;
  8220. if (medias[mediaindex].ssrcs[ssrc]) {
  8221. result = true;
  8222. }
  8223. });
  8224. return result;
  8225. };
  8226. // remove iSAC and CN from SDP
  8227. SDP.prototype.mangle = function () {
  8228. var i, j, mline, lines, rtpmap, newdesc;
  8229. for (i = 0; i < this.media.length; i++) {
  8230. lines = this.media[i].split('\r\n');
  8231. lines.pop(); // remove empty last element
  8232. mline = SDPUtil.parse_mline(lines.shift());
  8233. if (mline.media != 'audio')
  8234. continue;
  8235. newdesc = '';
  8236. mline.fmt.length = 0;
  8237. for (j = 0; j < lines.length; j++) {
  8238. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  8239. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  8240. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  8241. continue;
  8242. mline.fmt.push(rtpmap.id);
  8243. newdesc += lines[j] + '\r\n';
  8244. } else {
  8245. newdesc += lines[j] + '\r\n';
  8246. }
  8247. }
  8248. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  8249. this.media[i] += newdesc;
  8250. }
  8251. this.raw = this.session + this.media.join('');
  8252. };
  8253. // remove lines matching prefix from session section
  8254. SDP.prototype.removeSessionLines = function(prefix) {
  8255. var self = this;
  8256. var lines = SDPUtil.find_lines(this.session, prefix);
  8257. lines.forEach(function(line) {
  8258. self.session = self.session.replace(line + '\r\n', '');
  8259. });
  8260. this.raw = this.session + this.media.join('');
  8261. return lines;
  8262. }
  8263. // remove lines matching prefix from a media section specified by mediaindex
  8264. // TODO: non-numeric mediaindex could match mid
  8265. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  8266. var self = this;
  8267. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  8268. lines.forEach(function(line) {
  8269. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  8270. });
  8271. this.raw = this.session + this.media.join('');
  8272. return lines;
  8273. }
  8274. // add content's to a jingle element
  8275. SDP.prototype.toJingle = function (elem, thecreator) {
  8276. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  8277. var self = this;
  8278. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  8279. // new bundle plan
  8280. if (SDPUtil.find_line(this.session, 'a=group:')) {
  8281. lines = SDPUtil.find_lines(this.session, 'a=group:');
  8282. for (i = 0; i < lines.length; i++) {
  8283. tmp = lines[i].split(' ');
  8284. var semantics = tmp.shift().substr(8);
  8285. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  8286. for (j = 0; j < tmp.length; j++) {
  8287. elem.c('content', {name: tmp[j]}).up();
  8288. }
  8289. elem.up();
  8290. }
  8291. }
  8292. for (i = 0; i < this.media.length; i++) {
  8293. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  8294. if (!(mline.media === 'audio' ||
  8295. mline.media === 'video' ||
  8296. mline.media === 'application'))
  8297. {
  8298. continue;
  8299. }
  8300. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  8301. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  8302. } else {
  8303. ssrc = false;
  8304. }
  8305. elem.c('content', {creator: thecreator, name: mline.media});
  8306. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  8307. // prefer identifier from a=mid if present
  8308. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  8309. elem.attrs({ name: mid });
  8310. }
  8311. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  8312. elem.c('description',
  8313. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  8314. media: mline.media });
  8315. if (ssrc) {
  8316. elem.attrs({ssrc: ssrc});
  8317. }
  8318. for (j = 0; j < mline.fmt.length; j++) {
  8319. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  8320. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  8321. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  8322. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  8323. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  8324. for (k = 0; k < tmp.length; k++) {
  8325. elem.c('parameter', tmp[k]).up();
  8326. }
  8327. }
  8328. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  8329. elem.up();
  8330. }
  8331. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  8332. elem.c('encryption', {required: 1});
  8333. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  8334. crypto.forEach(function(line) {
  8335. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  8336. });
  8337. elem.up(); // end of encryption
  8338. }
  8339. if (ssrc) {
  8340. // new style mapping
  8341. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8342. // FIXME: group by ssrc and support multiple different ssrcs
  8343. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  8344. if(ssrclines.length > 0) {
  8345. ssrclines.forEach(function (line) {
  8346. var idx = line.indexOf(' ');
  8347. var linessrc = line.substr(0, idx).substr(7);
  8348. if (linessrc != ssrc) {
  8349. elem.up();
  8350. ssrc = linessrc;
  8351. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8352. }
  8353. var kv = line.substr(idx + 1);
  8354. elem.c('parameter');
  8355. if (kv.indexOf(':') == -1) {
  8356. elem.attrs({ name: kv });
  8357. } else {
  8358. var k = kv.split(':', 2)[0];
  8359. elem.attrs({ name: k });
  8360. var v = kv.split(':', 2)[1];
  8361. v = SDPUtil.filter_special_chars(v);
  8362. elem.attrs({ value: v });
  8363. }
  8364. elem.up();
  8365. });
  8366. } else {
  8367. elem.up();
  8368. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8369. elem.c('parameter');
  8370. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  8371. elem.up();
  8372. var msid = null;
  8373. if(mline.media == "audio")
  8374. {
  8375. msid = APP.RTC.localAudio._getId();
  8376. }
  8377. else
  8378. {
  8379. msid = APP.RTC.localVideo._getId();
  8380. }
  8381. if(msid != null)
  8382. {
  8383. msid = SDPUtil.filter_special_chars(msid);
  8384. elem.c('parameter');
  8385. elem.attrs({name: "msid", value:msid});
  8386. elem.up();
  8387. elem.c('parameter');
  8388. elem.attrs({name: "mslabel", value:msid});
  8389. elem.up();
  8390. elem.c('parameter');
  8391. elem.attrs({name: "label", value:msid});
  8392. elem.up();
  8393. }
  8394. }
  8395. elem.up();
  8396. // XEP-0339 handle ssrc-group attributes
  8397. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  8398. ssrc_group_lines.forEach(function(line) {
  8399. var idx = line.indexOf(' ');
  8400. var semantics = line.substr(0, idx).substr(13);
  8401. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8402. if (ssrcs.length) {
  8403. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8404. ssrcs.forEach(function(ssrc) {
  8405. elem.c('source', { ssrc: ssrc })
  8406. .up();
  8407. });
  8408. elem.up();
  8409. }
  8410. });
  8411. }
  8412. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  8413. elem.c('rtcp-mux').up();
  8414. }
  8415. // XEP-0293 -- map a=rtcp-fb:*
  8416. this.rtcpFbToJingle(i, elem, '*');
  8417. // XEP-0294
  8418. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  8419. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  8420. for (j = 0; j < lines.length; j++) {
  8421. tmp = SDPUtil.parse_extmap(lines[j]);
  8422. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  8423. uri: tmp.uri,
  8424. id: tmp.value });
  8425. if (tmp.hasOwnProperty('direction')) {
  8426. switch (tmp.direction) {
  8427. case 'sendonly':
  8428. elem.attrs({senders: 'responder'});
  8429. break;
  8430. case 'recvonly':
  8431. elem.attrs({senders: 'initiator'});
  8432. break;
  8433. case 'sendrecv':
  8434. elem.attrs({senders: 'both'});
  8435. break;
  8436. case 'inactive':
  8437. elem.attrs({senders: 'none'});
  8438. break;
  8439. }
  8440. }
  8441. // TODO: handle params
  8442. elem.up();
  8443. }
  8444. }
  8445. elem.up(); // end of description
  8446. }
  8447. // map ice-ufrag/pwd, dtls fingerprint, candidates
  8448. this.transportToJingle(i, elem);
  8449. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  8450. elem.attrs({senders: 'both'});
  8451. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  8452. elem.attrs({senders: 'initiator'});
  8453. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  8454. elem.attrs({senders: 'responder'});
  8455. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  8456. elem.attrs({senders: 'none'});
  8457. }
  8458. if (mline.port == '0') {
  8459. // estos hack to reject an m-line
  8460. elem.attrs({senders: 'rejected'});
  8461. }
  8462. elem.up(); // end of content
  8463. }
  8464. elem.up();
  8465. return elem;
  8466. };
  8467. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  8468. var tmp, sctpmap, sctpAttrs, fingerprints;
  8469. var self = this;
  8470. elem.c('transport');
  8471. // XEP-0343 DTLS/SCTP
  8472. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  8473. {
  8474. sctpmap = SDPUtil.find_line(
  8475. this.media[mediaindex], 'a=sctpmap:', self.session);
  8476. if (sctpmap)
  8477. {
  8478. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  8479. elem.c('sctpmap',
  8480. {
  8481. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  8482. number: sctpAttrs[0], /* SCTP port */
  8483. protocol: sctpAttrs[1] /* protocol */
  8484. });
  8485. // Optional stream count attribute
  8486. if (sctpAttrs.length > 2)
  8487. elem.attrs({ streams: sctpAttrs[2]});
  8488. elem.up();
  8489. }
  8490. }
  8491. // XEP-0320
  8492. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  8493. fingerprints.forEach(function(line) {
  8494. tmp = SDPUtil.parse_fingerprint(line);
  8495. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  8496. elem.c('fingerprint').t(tmp.fingerprint);
  8497. delete tmp.fingerprint;
  8498. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  8499. if (line) {
  8500. tmp.setup = line.substr(8);
  8501. }
  8502. elem.attrs(tmp);
  8503. elem.up(); // end of fingerprint
  8504. });
  8505. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  8506. if (tmp) {
  8507. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  8508. elem.attrs(tmp);
  8509. // XEP-0176
  8510. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  8511. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  8512. lines.forEach(function (line) {
  8513. var candidate = SDPUtil.candidateToJingle(line);
  8514. var protocol = (candidate &&
  8515. typeof candidate.protocol === 'string')
  8516. ? candidate.protocol.toLowerCase() : '';
  8517. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8518. (self.removeUdpCandidates && protocol === 'udp')) {
  8519. return;
  8520. }
  8521. elem.c('candidate', candidate).up();
  8522. });
  8523. }
  8524. }
  8525. elem.up(); // end of transport
  8526. }
  8527. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  8528. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  8529. lines.forEach(function (line) {
  8530. var tmp = SDPUtil.parse_rtcpfb(line);
  8531. if (tmp.type == 'trr-int') {
  8532. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  8533. elem.up();
  8534. } else {
  8535. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  8536. if (tmp.params.length > 0) {
  8537. elem.attrs({'subtype': tmp.params[0]});
  8538. }
  8539. elem.up();
  8540. }
  8541. });
  8542. };
  8543. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8544. var media = '';
  8545. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8546. if (tmp.length) {
  8547. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8548. if (tmp.attr('value')) {
  8549. media += tmp.attr('value');
  8550. } else {
  8551. media += '0';
  8552. }
  8553. media += '\r\n';
  8554. }
  8555. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8556. tmp.each(function () {
  8557. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8558. if ($(this).attr('subtype')) {
  8559. media += ' ' + $(this).attr('subtype');
  8560. }
  8561. media += '\r\n';
  8562. });
  8563. return media;
  8564. };
  8565. // construct an SDP from a jingle stanza
  8566. SDP.prototype.fromJingle = function (jingle) {
  8567. var self = this;
  8568. this.raw = 'v=0\r\n' +
  8569. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8570. 's=-\r\n' +
  8571. 't=0 0\r\n';
  8572. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8573. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8574. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8575. var contents = $(group).find('>content').map(function (idx, content) {
  8576. return content.getAttribute('name');
  8577. }).get();
  8578. if (contents.length > 0) {
  8579. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8580. }
  8581. });
  8582. }
  8583. this.session = this.raw;
  8584. jingle.find('>content').each(function () {
  8585. var m = self.jingle2media($(this));
  8586. self.media.push(m);
  8587. });
  8588. // reconstruct msid-semantic -- apparently not necessary
  8589. /*
  8590. var msid = SDPUtil.parse_ssrc(this.raw);
  8591. if (msid.hasOwnProperty('mslabel')) {
  8592. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8593. }
  8594. */
  8595. this.raw = this.session + this.media.join('');
  8596. };
  8597. // translate a jingle content element into an an SDP media part
  8598. SDP.prototype.jingle2media = function (content) {
  8599. var media = '',
  8600. desc = content.find('description'),
  8601. ssrc = desc.attr('ssrc'),
  8602. self = this,
  8603. tmp;
  8604. var sctp = content.find(
  8605. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8606. tmp = { media: desc.attr('media') };
  8607. tmp.port = '1';
  8608. if (content.attr('senders') == 'rejected') {
  8609. // estos hack to reject an m-line.
  8610. tmp.port = '0';
  8611. }
  8612. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8613. if (sctp.length)
  8614. tmp.proto = 'DTLS/SCTP';
  8615. else
  8616. tmp.proto = 'RTP/SAVPF';
  8617. } else {
  8618. tmp.proto = 'RTP/AVPF';
  8619. }
  8620. if (!sctp.length) {
  8621. tmp.fmt = desc.find('payload-type').map(
  8622. function () { return this.getAttribute('id'); }).get();
  8623. media += SDPUtil.build_mline(tmp) + '\r\n';
  8624. } else {
  8625. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8626. media += 'a=sctpmap:' + sctp.attr('number') +
  8627. ' ' + sctp.attr('protocol');
  8628. var streamCount = sctp.attr('streams');
  8629. if (streamCount)
  8630. media += ' ' + streamCount + '\r\n';
  8631. else
  8632. media += '\r\n';
  8633. }
  8634. media += 'c=IN IP4 0.0.0.0\r\n';
  8635. if (!sctp.length)
  8636. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8637. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8638. if (tmp.length) {
  8639. if (tmp.attr('ufrag')) {
  8640. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8641. }
  8642. if (tmp.attr('pwd')) {
  8643. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8644. }
  8645. tmp.find('>fingerprint').each(function () {
  8646. // FIXME: check namespace at some point
  8647. media += 'a=fingerprint:' + this.getAttribute('hash');
  8648. media += ' ' + $(this).text();
  8649. media += '\r\n';
  8650. if (this.getAttribute('setup')) {
  8651. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8652. }
  8653. });
  8654. }
  8655. switch (content.attr('senders')) {
  8656. case 'initiator':
  8657. media += 'a=sendonly\r\n';
  8658. break;
  8659. case 'responder':
  8660. media += 'a=recvonly\r\n';
  8661. break;
  8662. case 'none':
  8663. media += 'a=inactive\r\n';
  8664. break;
  8665. case 'both':
  8666. media += 'a=sendrecv\r\n';
  8667. break;
  8668. }
  8669. media += 'a=mid:' + content.attr('name') + '\r\n';
  8670. // <description><rtcp-mux/></description>
  8671. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8672. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8673. if (desc.find('rtcp-mux').length) {
  8674. media += 'a=rtcp-mux\r\n';
  8675. }
  8676. if (desc.find('encryption').length) {
  8677. desc.find('encryption>crypto').each(function () {
  8678. media += 'a=crypto:' + this.getAttribute('tag');
  8679. media += ' ' + this.getAttribute('crypto-suite');
  8680. media += ' ' + this.getAttribute('key-params');
  8681. if (this.getAttribute('session-params')) {
  8682. media += ' ' + this.getAttribute('session-params');
  8683. }
  8684. media += '\r\n';
  8685. });
  8686. }
  8687. desc.find('payload-type').each(function () {
  8688. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8689. if ($(this).find('>parameter').length) {
  8690. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8691. media += $(this).find('parameter').map(function () {
  8692. return (this.getAttribute('name')
  8693. ? (this.getAttribute('name') + '=') : '') +
  8694. this.getAttribute('value');
  8695. }).get().join('; ');
  8696. media += '\r\n';
  8697. }
  8698. // xep-0293
  8699. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8700. });
  8701. // xep-0293
  8702. media += self.rtcpFbFromJingle(desc, '*');
  8703. // xep-0294
  8704. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8705. tmp.each(function () {
  8706. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8707. });
  8708. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8709. var protocol = this.getAttribute('protocol');
  8710. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8711. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8712. (self.removeUdpCandidates && protocol === 'udp')) {
  8713. return;
  8714. }
  8715. media += SDPUtil.candidateFromJingle(this);
  8716. });
  8717. // XEP-0339 handle ssrc-group attributes
  8718. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8719. var semantics = this.getAttribute('semantics');
  8720. var ssrcs = $(this).find('>source').map(function() {
  8721. return this.getAttribute('ssrc');
  8722. }).get();
  8723. if (ssrcs.length) {
  8724. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8725. }
  8726. });
  8727. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8728. tmp.each(function () {
  8729. var ssrc = this.getAttribute('ssrc');
  8730. $(this).find('>parameter').each(function () {
  8731. var name = this.getAttribute('name');
  8732. var value = this.getAttribute('value');
  8733. value = SDPUtil.filter_special_chars(value);
  8734. media += 'a=ssrc:' + ssrc + ' ' + name;
  8735. if (value && value.length)
  8736. media += ':' + value;
  8737. media += '\r\n';
  8738. });
  8739. });
  8740. return media;
  8741. };
  8742. module.exports = SDP;
  8743. }).call(this,"/modules/xmpp/SDP.js")
  8744. },{"./SDPUtil":32,"jitsi-meet-logger":48}],31:[function(require,module,exports){
  8745. var SDPUtil = require("./SDPUtil");
  8746. function SDPDiffer(mySDP, otherSDP)
  8747. {
  8748. this.mySDP = mySDP;
  8749. this.otherSDP = otherSDP;
  8750. }
  8751. /**
  8752. * Returns map of MediaChannel that contains media contained in
  8753. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8754. */
  8755. SDPDiffer.prototype.getNewMedia = function() {
  8756. // this could be useful in Array.prototype.
  8757. function arrayEquals(array) {
  8758. // if the other array is a falsy value, return
  8759. if (!array)
  8760. return false;
  8761. // compare lengths - can save a lot of time
  8762. if (this.length != array.length)
  8763. return false;
  8764. for (var i = 0, l=this.length; i < l; i++) {
  8765. // Check if we have nested arrays
  8766. if (this[i] instanceof Array && array[i] instanceof Array) {
  8767. // recurse into the nested arrays
  8768. if (!this[i].equals(array[i]))
  8769. return false;
  8770. }
  8771. else if (this[i] != array[i]) {
  8772. // Warning - two different object instances will never be
  8773. // equal: {x:20} != {x:20}
  8774. return false;
  8775. }
  8776. }
  8777. return true;
  8778. }
  8779. var myMedias = this.mySDP.getMediaSsrcMap();
  8780. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8781. var newMedia = {};
  8782. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8783. var myMedia = myMedias[othersMediaIdx];
  8784. var othersMedia = othersMedias[othersMediaIdx];
  8785. if(!myMedia && othersMedia) {
  8786. // Add whole channel
  8787. newMedia[othersMediaIdx] = othersMedia;
  8788. return;
  8789. }
  8790. // Look for new ssrcs across the channel
  8791. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8792. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8793. // Allocate channel if we've found ssrc that doesn't exist in
  8794. // our channel
  8795. if(!newMedia[othersMediaIdx]){
  8796. newMedia[othersMediaIdx] = {
  8797. mediaindex: othersMedia.mediaindex,
  8798. mid: othersMedia.mid,
  8799. ssrcs: {},
  8800. ssrcGroups: []
  8801. };
  8802. }
  8803. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8804. }
  8805. });
  8806. // Look for new ssrc groups across the channels
  8807. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8808. // try to match the other ssrc-group with an ssrc-group of ours
  8809. var matched = false;
  8810. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8811. var mySsrcGroup = myMedia.ssrcGroups[i];
  8812. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8813. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8814. [mySsrcGroup.ssrcs])) {
  8815. matched = true;
  8816. break;
  8817. }
  8818. }
  8819. if (!matched) {
  8820. // Allocate channel if we've found an ssrc-group that doesn't
  8821. // exist in our channel
  8822. if(!newMedia[othersMediaIdx]){
  8823. newMedia[othersMediaIdx] = {
  8824. mediaindex: othersMedia.mediaindex,
  8825. mid: othersMedia.mid,
  8826. ssrcs: {},
  8827. ssrcGroups: []
  8828. };
  8829. }
  8830. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8831. }
  8832. });
  8833. });
  8834. return newMedia;
  8835. };
  8836. /**
  8837. * TODO: document!
  8838. */
  8839. SDPDiffer.prototype.toJingle = function(modify) {
  8840. var sdpMediaSsrcs = this.getNewMedia();
  8841. var modified = false;
  8842. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8843. modified = true;
  8844. var media = sdpMediaSsrcs[mediaindex];
  8845. modify.c('content', {name: media.mid});
  8846. modify.c('description',
  8847. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8848. // FIXME: not completely sure this operates on blocks and / or handles
  8849. // different ssrcs correctly
  8850. // generate sources from lines
  8851. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8852. var mediaSsrc = media.ssrcs[ssrcNum];
  8853. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8854. modify.attrs({ssrc: mediaSsrc.ssrc});
  8855. // iterate over ssrc lines
  8856. mediaSsrc.lines.forEach(function (line) {
  8857. var idx = line.indexOf(' ');
  8858. var kv = line.substr(idx + 1);
  8859. modify.c('parameter');
  8860. if (kv.indexOf(':') == -1) {
  8861. modify.attrs({ name: kv });
  8862. } else {
  8863. var nv = kv.split(':', 2);
  8864. var name = nv[0];
  8865. var value = SDPUtil.filter_special_chars(nv[1]);
  8866. modify.attrs({ name: name });
  8867. modify.attrs({ value: value });
  8868. }
  8869. modify.up(); // end of parameter
  8870. });
  8871. modify.up(); // end of source
  8872. });
  8873. // generate source groups from lines
  8874. media.ssrcGroups.forEach(function(ssrcGroup) {
  8875. if (ssrcGroup.ssrcs.length) {
  8876. modify.c('ssrc-group', {
  8877. semantics: ssrcGroup.semantics,
  8878. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8879. });
  8880. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8881. modify.c('source', { ssrc: ssrc })
  8882. .up(); // end of source
  8883. });
  8884. modify.up(); // end of ssrc-group
  8885. }
  8886. });
  8887. modify.up(); // end of description
  8888. modify.up(); // end of content
  8889. });
  8890. return modified;
  8891. };
  8892. module.exports = SDPDiffer;
  8893. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8894. (function (__filename){
  8895. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8896. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8897. SDPUtil = {
  8898. filter_special_chars: function (text) {
  8899. return text.replace(/[\\\/\{,\}\+]/g, "");
  8900. },
  8901. iceparams: function (mediadesc, sessiondesc) {
  8902. var data = null;
  8903. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8904. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8905. data = {
  8906. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8907. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8908. };
  8909. }
  8910. return data;
  8911. },
  8912. parse_iceufrag: function (line) {
  8913. return line.substring(12);
  8914. },
  8915. build_iceufrag: function (frag) {
  8916. return 'a=ice-ufrag:' + frag;
  8917. },
  8918. parse_icepwd: function (line) {
  8919. return line.substring(10);
  8920. },
  8921. build_icepwd: function (pwd) {
  8922. return 'a=ice-pwd:' + pwd;
  8923. },
  8924. parse_mid: function (line) {
  8925. return line.substring(6);
  8926. },
  8927. parse_mline: function (line) {
  8928. var parts = line.substring(2).split(' '),
  8929. data = {};
  8930. data.media = parts.shift();
  8931. data.port = parts.shift();
  8932. data.proto = parts.shift();
  8933. if (parts[parts.length - 1] === '') { // trailing whitespace
  8934. parts.pop();
  8935. }
  8936. data.fmt = parts;
  8937. return data;
  8938. },
  8939. build_mline: function (mline) {
  8940. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8941. },
  8942. parse_rtpmap: function (line) {
  8943. var parts = line.substring(9).split(' '),
  8944. data = {};
  8945. data.id = parts.shift();
  8946. parts = parts[0].split('/');
  8947. data.name = parts.shift();
  8948. data.clockrate = parts.shift();
  8949. data.channels = parts.length ? parts.shift() : '1';
  8950. return data;
  8951. },
  8952. /**
  8953. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8954. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8955. * @returns [SCTP port number, protocol, streams]
  8956. */
  8957. parse_sctpmap: function (line)
  8958. {
  8959. var parts = line.substring(10).split(' ');
  8960. var sctpPort = parts[0];
  8961. var protocol = parts[1];
  8962. // Stream count is optional
  8963. var streamCount = parts.length > 2 ? parts[2] : null;
  8964. return [sctpPort, protocol, streamCount];// SCTP port
  8965. },
  8966. build_rtpmap: function (el) {
  8967. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8968. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8969. line += '/' + el.getAttribute('channels');
  8970. }
  8971. return line;
  8972. },
  8973. parse_crypto: function (line) {
  8974. var parts = line.substring(9).split(' '),
  8975. data = {};
  8976. data.tag = parts.shift();
  8977. data['crypto-suite'] = parts.shift();
  8978. data['key-params'] = parts.shift();
  8979. if (parts.length) {
  8980. data['session-params'] = parts.join(' ');
  8981. }
  8982. return data;
  8983. },
  8984. parse_fingerprint: function (line) { // RFC 4572
  8985. var parts = line.substring(14).split(' '),
  8986. data = {};
  8987. data.hash = parts.shift();
  8988. data.fingerprint = parts.shift();
  8989. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8990. return data;
  8991. },
  8992. parse_fmtp: function (line) {
  8993. var parts = line.split(' '),
  8994. i, key, value,
  8995. data = [];
  8996. parts.shift();
  8997. parts = parts.join(' ').split(';');
  8998. for (i = 0; i < parts.length; i++) {
  8999. key = parts[i].split('=')[0];
  9000. while (key.length && key[0] == ' ') {
  9001. key = key.substring(1);
  9002. }
  9003. value = parts[i].split('=')[1];
  9004. if (key && value) {
  9005. data.push({name: key, value: value});
  9006. } else if (key) {
  9007. // rfc 4733 (DTMF) style stuff
  9008. data.push({name: '', value: key});
  9009. }
  9010. }
  9011. return data;
  9012. },
  9013. parse_icecandidate: function (line) {
  9014. var candidate = {},
  9015. elems = line.split(' ');
  9016. candidate.foundation = elems[0].substring(12);
  9017. candidate.component = elems[1];
  9018. candidate.protocol = elems[2].toLowerCase();
  9019. candidate.priority = elems[3];
  9020. candidate.ip = elems[4];
  9021. candidate.port = elems[5];
  9022. // elems[6] => "typ"
  9023. candidate.type = elems[7];
  9024. candidate.generation = 0; // default value, may be overwritten below
  9025. for (var i = 8; i < elems.length; i += 2) {
  9026. switch (elems[i]) {
  9027. case 'raddr':
  9028. candidate['rel-addr'] = elems[i + 1];
  9029. break;
  9030. case 'rport':
  9031. candidate['rel-port'] = elems[i + 1];
  9032. break;
  9033. case 'generation':
  9034. candidate.generation = elems[i + 1];
  9035. break;
  9036. case 'tcptype':
  9037. candidate.tcptype = elems[i + 1];
  9038. break;
  9039. default: // TODO
  9040. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9041. }
  9042. }
  9043. candidate.network = '1';
  9044. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9045. return candidate;
  9046. },
  9047. build_icecandidate: function (cand) {
  9048. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9049. line += ' ';
  9050. switch (cand.type) {
  9051. case 'srflx':
  9052. case 'prflx':
  9053. case 'relay':
  9054. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9055. line += 'raddr';
  9056. line += ' ';
  9057. line += cand['rel-addr'];
  9058. line += ' ';
  9059. line += 'rport';
  9060. line += ' ';
  9061. line += cand['rel-port'];
  9062. line += ' ';
  9063. }
  9064. break;
  9065. }
  9066. if (cand.hasOwnAttribute('tcptype')) {
  9067. line += 'tcptype';
  9068. line += ' ';
  9069. line += cand.tcptype;
  9070. line += ' ';
  9071. }
  9072. line += 'generation';
  9073. line += ' ';
  9074. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9075. return line;
  9076. },
  9077. parse_ssrc: function (desc) {
  9078. // proprietary mapping of a=ssrc lines
  9079. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9080. // and parse according to that
  9081. var lines = desc.split('\r\n'),
  9082. data = {};
  9083. for (var i = 0; i < lines.length; i++) {
  9084. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9085. var idx = lines[i].indexOf(' ');
  9086. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9087. }
  9088. }
  9089. return data;
  9090. },
  9091. parse_rtcpfb: function (line) {
  9092. var parts = line.substr(10).split(' ');
  9093. var data = {};
  9094. data.pt = parts.shift();
  9095. data.type = parts.shift();
  9096. data.params = parts;
  9097. return data;
  9098. },
  9099. parse_extmap: function (line) {
  9100. var parts = line.substr(9).split(' ');
  9101. var data = {};
  9102. data.value = parts.shift();
  9103. if (data.value.indexOf('/') != -1) {
  9104. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9105. data.value = data.value.substr(0, data.value.indexOf('/'));
  9106. } else {
  9107. data.direction = 'both';
  9108. }
  9109. data.uri = parts.shift();
  9110. data.params = parts;
  9111. return data;
  9112. },
  9113. find_line: function (haystack, needle, sessionpart) {
  9114. var lines = haystack.split('\r\n');
  9115. for (var i = 0; i < lines.length; i++) {
  9116. if (lines[i].substring(0, needle.length) == needle) {
  9117. return lines[i];
  9118. }
  9119. }
  9120. if (!sessionpart) {
  9121. return false;
  9122. }
  9123. // search session part
  9124. lines = sessionpart.split('\r\n');
  9125. for (var j = 0; j < lines.length; j++) {
  9126. if (lines[j].substring(0, needle.length) == needle) {
  9127. return lines[j];
  9128. }
  9129. }
  9130. return false;
  9131. },
  9132. find_lines: function (haystack, needle, sessionpart) {
  9133. var lines = haystack.split('\r\n'),
  9134. needles = [];
  9135. for (var i = 0; i < lines.length; i++) {
  9136. if (lines[i].substring(0, needle.length) == needle)
  9137. needles.push(lines[i]);
  9138. }
  9139. if (needles.length || !sessionpart) {
  9140. return needles;
  9141. }
  9142. // search session part
  9143. lines = sessionpart.split('\r\n');
  9144. for (var j = 0; j < lines.length; j++) {
  9145. if (lines[j].substring(0, needle.length) == needle) {
  9146. needles.push(lines[j]);
  9147. }
  9148. }
  9149. return needles;
  9150. },
  9151. candidateToJingle: function (line) {
  9152. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  9153. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  9154. if (line.indexOf('candidate:') === 0) {
  9155. line = 'a=' + line;
  9156. } else if (line.substring(0, 12) != 'a=candidate:') {
  9157. logger.log('parseCandidate called with a line that is not a candidate line');
  9158. logger.log(line);
  9159. return null;
  9160. }
  9161. if (line.substring(line.length - 2) == '\r\n') // chomp it
  9162. line = line.substring(0, line.length - 2);
  9163. var candidate = {},
  9164. elems = line.split(' '),
  9165. i;
  9166. if (elems[6] != 'typ') {
  9167. logger.log('did not find typ in the right place');
  9168. logger.log(line);
  9169. return null;
  9170. }
  9171. candidate.foundation = elems[0].substring(12);
  9172. candidate.component = elems[1];
  9173. candidate.protocol = elems[2].toLowerCase();
  9174. candidate.priority = elems[3];
  9175. candidate.ip = elems[4];
  9176. candidate.port = elems[5];
  9177. // elems[6] => "typ"
  9178. candidate.type = elems[7];
  9179. candidate.generation = '0'; // default, may be overwritten below
  9180. for (i = 8; i < elems.length; i += 2) {
  9181. switch (elems[i]) {
  9182. case 'raddr':
  9183. candidate['rel-addr'] = elems[i + 1];
  9184. break;
  9185. case 'rport':
  9186. candidate['rel-port'] = elems[i + 1];
  9187. break;
  9188. case 'generation':
  9189. candidate.generation = elems[i + 1];
  9190. break;
  9191. case 'tcptype':
  9192. candidate.tcptype = elems[i + 1];
  9193. break;
  9194. default: // TODO
  9195. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9196. }
  9197. }
  9198. candidate.network = '1';
  9199. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9200. return candidate;
  9201. },
  9202. candidateFromJingle: function (cand) {
  9203. var line = 'a=candidate:';
  9204. line += cand.getAttribute('foundation');
  9205. line += ' ';
  9206. line += cand.getAttribute('component');
  9207. line += ' ';
  9208. var protocol = cand.getAttribute('protocol');
  9209. // use tcp candidates for FF
  9210. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  9211. protocol = 'tcp';
  9212. }
  9213. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  9214. line += ' ';
  9215. line += cand.getAttribute('priority');
  9216. line += ' ';
  9217. line += cand.getAttribute('ip');
  9218. line += ' ';
  9219. line += cand.getAttribute('port');
  9220. line += ' ';
  9221. line += 'typ';
  9222. line += ' ' + cand.getAttribute('type');
  9223. line += ' ';
  9224. switch (cand.getAttribute('type')) {
  9225. case 'srflx':
  9226. case 'prflx':
  9227. case 'relay':
  9228. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  9229. line += 'raddr';
  9230. line += ' ';
  9231. line += cand.getAttribute('rel-addr');
  9232. line += ' ';
  9233. line += 'rport';
  9234. line += ' ';
  9235. line += cand.getAttribute('rel-port');
  9236. line += ' ';
  9237. }
  9238. break;
  9239. }
  9240. if (protocol.toLowerCase() == 'tcp') {
  9241. line += 'tcptype';
  9242. line += ' ';
  9243. line += cand.getAttribute('tcptype');
  9244. line += ' ';
  9245. }
  9246. line += 'generation';
  9247. line += ' ';
  9248. line += cand.getAttribute('generation') || '0';
  9249. return line + '\r\n';
  9250. }
  9251. };
  9252. module.exports = SDPUtil;
  9253. }).call(this,"/modules/xmpp/SDPUtil.js")
  9254. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],33:[function(require,module,exports){
  9255. (function (__filename){
  9256. /* global $ */
  9257. var RTC = require('../RTC/RTC');
  9258. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9259. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  9260. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9261. var SSRCReplacement = require("./LocalSSRCReplacement");
  9262. function TraceablePeerConnection(ice_config, constraints, session) {
  9263. var self = this;
  9264. this.session = session;
  9265. var RTCPeerConnectionType = null;
  9266. if (RTCBrowserType.isFirefox()) {
  9267. RTCPeerConnectionType = mozRTCPeerConnection;
  9268. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  9269. RTCPeerConnectionType = RTCPeerConnection;
  9270. } else {
  9271. RTCPeerConnectionType = webkitRTCPeerConnection;
  9272. }
  9273. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  9274. this.updateLog = [];
  9275. this.stats = {};
  9276. this.statsinterval = null;
  9277. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9278. var Interop = require('sdp-interop').Interop;
  9279. this.interop = new Interop();
  9280. var Simulcast = require('sdp-simulcast');
  9281. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  9282. // override as desired
  9283. this.trace = function (what, info) {
  9284. /*logger.warn('WTRACE', what, info);
  9285. if (info && RTCBrowserType.isIExplorer()) {
  9286. if (info.length > 1024) {
  9287. logger.warn('WTRACE', what, info.substr(1024));
  9288. }
  9289. if (info.length > 2048) {
  9290. logger.warn('WTRACE', what, info.substr(2048));
  9291. }
  9292. }*/
  9293. self.updateLog.push({
  9294. time: new Date(),
  9295. type: what,
  9296. value: info || ""
  9297. });
  9298. };
  9299. this.onicecandidate = null;
  9300. this.peerconnection.onicecandidate = function (event) {
  9301. // FIXME: this causes stack overflow with Temasys Plugin
  9302. if (!RTCBrowserType.isTemasysPluginUsed())
  9303. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  9304. if (self.onicecandidate !== null) {
  9305. self.onicecandidate(event);
  9306. }
  9307. };
  9308. this.onaddstream = null;
  9309. this.peerconnection.onaddstream = function (event) {
  9310. self.trace('onaddstream', event.stream.id);
  9311. if (self.onaddstream !== null) {
  9312. self.onaddstream(event);
  9313. }
  9314. };
  9315. this.onremovestream = null;
  9316. this.peerconnection.onremovestream = function (event) {
  9317. self.trace('onremovestream', event.stream.id);
  9318. if (self.onremovestream !== null) {
  9319. self.onremovestream(event);
  9320. }
  9321. };
  9322. this.onsignalingstatechange = null;
  9323. this.peerconnection.onsignalingstatechange = function (event) {
  9324. self.trace('onsignalingstatechange', self.signalingState);
  9325. if (self.onsignalingstatechange !== null) {
  9326. self.onsignalingstatechange(event);
  9327. }
  9328. };
  9329. this.oniceconnectionstatechange = null;
  9330. this.peerconnection.oniceconnectionstatechange = function (event) {
  9331. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  9332. if (self.oniceconnectionstatechange !== null) {
  9333. self.oniceconnectionstatechange(event);
  9334. }
  9335. };
  9336. this.onnegotiationneeded = null;
  9337. this.peerconnection.onnegotiationneeded = function (event) {
  9338. self.trace('onnegotiationneeded');
  9339. if (self.onnegotiationneeded !== null) {
  9340. self.onnegotiationneeded(event);
  9341. }
  9342. };
  9343. self.ondatachannel = null;
  9344. this.peerconnection.ondatachannel = function (event) {
  9345. self.trace('ondatachannel', event);
  9346. if (self.ondatachannel !== null) {
  9347. self.ondatachannel(event);
  9348. }
  9349. };
  9350. // XXX: do all non-firefox browsers which we support also support this?
  9351. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  9352. this.statsinterval = window.setInterval(function() {
  9353. self.peerconnection.getStats(function(stats) {
  9354. var results = stats.result();
  9355. var now = new Date();
  9356. for (var i = 0; i < results.length; ++i) {
  9357. results[i].names().forEach(function (name) {
  9358. var id = results[i].id + '-' + name;
  9359. if (!self.stats[id]) {
  9360. self.stats[id] = {
  9361. startTime: now,
  9362. endTime: now,
  9363. values: [],
  9364. times: []
  9365. };
  9366. }
  9367. self.stats[id].values.push(results[i].stat(name));
  9368. self.stats[id].times.push(now.getTime());
  9369. if (self.stats[id].values.length > self.maxstats) {
  9370. self.stats[id].values.shift();
  9371. self.stats[id].times.shift();
  9372. }
  9373. self.stats[id].endTime = now;
  9374. });
  9375. }
  9376. });
  9377. }, 1000);
  9378. }
  9379. }
  9380. /**
  9381. * Returns a string representation of a SessionDescription object.
  9382. */
  9383. var dumpSDP = function(description) {
  9384. if (typeof description === 'undefined' || description == null) {
  9385. return '';
  9386. }
  9387. return 'type: ' + description.type + '\r\n' + description.sdp;
  9388. };
  9389. /**
  9390. * Takes a SessionDescription object and returns a "normalized" version.
  9391. * Currently it only takes care of ordering the a=ssrc lines.
  9392. */
  9393. var normalizePlanB = function(desc) {
  9394. if (typeof desc !== 'object' || desc === null ||
  9395. typeof desc.sdp !== 'string') {
  9396. logger.warn('An empty description was passed as an argument.');
  9397. return desc;
  9398. }
  9399. var transform = require('sdp-transform');
  9400. var session = transform.parse(desc.sdp);
  9401. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  9402. Array.isArray(session.media)) {
  9403. session.media.forEach(function (mLine) {
  9404. // Chrome appears to be picky about the order in which a=ssrc lines
  9405. // are listed in an m-line when rtx is enabled (and thus there are
  9406. // a=ssrc-group lines with FID semantics). Specifically if we have
  9407. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  9408. // the "a=ssrc:S1" lines, SRD fails.
  9409. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  9410. // first.
  9411. var firstSsrcs = [];
  9412. var newSsrcLines = [];
  9413. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  9414. mLine.ssrcGroups.forEach(function (group) {
  9415. if (typeof group.semantics !== 'undefined' &&
  9416. group.semantics === 'FID') {
  9417. if (typeof group.ssrcs !== 'undefined') {
  9418. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  9419. }
  9420. }
  9421. });
  9422. }
  9423. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  9424. var i;
  9425. for (i = 0; i<mLine.ssrcs.length; i++){
  9426. if (typeof mLine.ssrcs[i] === 'object'
  9427. && typeof mLine.ssrcs[i].id !== 'undefined'
  9428. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  9429. newSsrcLines.push(mLine.ssrcs[i]);
  9430. delete mLine.ssrcs[i];
  9431. }
  9432. }
  9433. for (i = 0; i<mLine.ssrcs.length; i++){
  9434. if (typeof mLine.ssrcs[i] !== 'undefined') {
  9435. newSsrcLines.push(mLine.ssrcs[i]);
  9436. }
  9437. }
  9438. mLine.ssrcs = newSsrcLines;
  9439. }
  9440. });
  9441. }
  9442. var resStr = transform.write(session);
  9443. return new RTCSessionDescription({
  9444. type: desc.type,
  9445. sdp: resStr
  9446. });
  9447. };
  9448. var getters = {
  9449. signalingState: function () {
  9450. return this.peerconnection.signalingState;
  9451. },
  9452. iceConnectionState: function () {
  9453. return this.peerconnection.iceConnectionState;
  9454. },
  9455. localDescription: function() {
  9456. var desc = this.peerconnection.localDescription;
  9457. // FIXME this should probably be after the Unified Plan -> Plan B
  9458. // transformation.
  9459. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  9460. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  9461. // if we're running on FF, transform to Plan B first.
  9462. if (RTCBrowserType.usesUnifiedPlan()) {
  9463. desc = this.interop.toPlanB(desc);
  9464. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  9465. }
  9466. return desc;
  9467. },
  9468. remoteDescription: function() {
  9469. var desc = this.peerconnection.remoteDescription;
  9470. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  9471. // if we're running on FF, transform to Plan B first.
  9472. if (RTCBrowserType.usesUnifiedPlan()) {
  9473. desc = this.interop.toPlanB(desc);
  9474. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  9475. }
  9476. return desc;
  9477. }
  9478. };
  9479. Object.keys(getters).forEach(function (prop) {
  9480. Object.defineProperty(
  9481. TraceablePeerConnection.prototype,
  9482. prop, {
  9483. get: getters[prop]
  9484. }
  9485. );
  9486. });
  9487. TraceablePeerConnection.prototype.addStream = function (stream) {
  9488. this.trace('addStream', stream.id);
  9489. try
  9490. {
  9491. this.peerconnection.addStream(stream);
  9492. }
  9493. catch (e)
  9494. {
  9495. logger.error(e);
  9496. }
  9497. };
  9498. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  9499. this.trace('removeStream', stream.id);
  9500. if(stopStreams) {
  9501. RTC.stopMediaStream(stream);
  9502. }
  9503. try {
  9504. // FF doesn't support this yet.
  9505. if (this.peerconnection.removeStream)
  9506. this.peerconnection.removeStream(stream);
  9507. } catch (e) {
  9508. logger.error(e);
  9509. }
  9510. };
  9511. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  9512. this.trace('createDataChannel', label, opts);
  9513. return this.peerconnection.createDataChannel(label, opts);
  9514. };
  9515. TraceablePeerConnection.prototype.setLocalDescription
  9516. = function (description, successCallback, failureCallback) {
  9517. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  9518. // if we're running on FF, transform to Plan A first.
  9519. if (RTCBrowserType.usesUnifiedPlan()) {
  9520. description = this.interop.toUnifiedPlan(description);
  9521. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  9522. }
  9523. var self = this;
  9524. this.peerconnection.setLocalDescription(description,
  9525. function () {
  9526. self.trace('setLocalDescriptionOnSuccess');
  9527. successCallback();
  9528. },
  9529. function (err) {
  9530. self.trace('setLocalDescriptionOnFailure', err);
  9531. failureCallback(err);
  9532. }
  9533. );
  9534. /*
  9535. if (this.statsinterval === null && this.maxstats > 0) {
  9536. // start gathering stats
  9537. }
  9538. */
  9539. };
  9540. TraceablePeerConnection.prototype.setRemoteDescription
  9541. = function (description, successCallback, failureCallback) {
  9542. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9543. // TODO the focus should squeze or explode the remote simulcast
  9544. description = this.simulcast.mungeRemoteDescription(description);
  9545. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9546. // if we're running on FF, transform to Plan A first.
  9547. if (RTCBrowserType.usesUnifiedPlan()) {
  9548. description = this.interop.toUnifiedPlan(description);
  9549. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9550. }
  9551. if (RTCBrowserType.usesPlanB()) {
  9552. description = normalizePlanB(description);
  9553. }
  9554. var self = this;
  9555. this.peerconnection.setRemoteDescription(description,
  9556. function () {
  9557. self.trace('setRemoteDescriptionOnSuccess');
  9558. successCallback();
  9559. },
  9560. function (err) {
  9561. self.trace('setRemoteDescriptionOnFailure', err);
  9562. failureCallback(err);
  9563. }
  9564. );
  9565. /*
  9566. if (this.statsinterval === null && this.maxstats > 0) {
  9567. // start gathering stats
  9568. }
  9569. */
  9570. };
  9571. TraceablePeerConnection.prototype.close = function () {
  9572. this.trace('stop');
  9573. if (this.statsinterval !== null) {
  9574. window.clearInterval(this.statsinterval);
  9575. this.statsinterval = null;
  9576. }
  9577. this.peerconnection.close();
  9578. };
  9579. TraceablePeerConnection.prototype.createOffer
  9580. = function (successCallback, failureCallback, constraints) {
  9581. var self = this;
  9582. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9583. this.peerconnection.createOffer(
  9584. function (offer) {
  9585. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9586. // NOTE this is not tested because in meet the focus generates the
  9587. // offer.
  9588. // if we're running on FF, transform to Plan B first.
  9589. if (RTCBrowserType.usesUnifiedPlan()) {
  9590. offer = self.interop.toPlanB(offer);
  9591. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9592. }
  9593. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9594. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9595. offer = self.simulcast.mungeLocalDescription(offer);
  9596. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9597. }
  9598. successCallback(offer);
  9599. },
  9600. function(err) {
  9601. self.trace('createOfferOnFailure', err);
  9602. failureCallback(err);
  9603. },
  9604. constraints
  9605. );
  9606. };
  9607. TraceablePeerConnection.prototype.createAnswer
  9608. = function (successCallback, failureCallback, constraints) {
  9609. var self = this;
  9610. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9611. this.peerconnection.createAnswer(
  9612. function (answer) {
  9613. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9614. // if we're running on FF, transform to Plan A first.
  9615. if (RTCBrowserType.usesUnifiedPlan()) {
  9616. answer = self.interop.toPlanB(answer);
  9617. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9618. }
  9619. // munge local video SSRC
  9620. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9621. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9622. answer = self.simulcast.mungeLocalDescription(answer);
  9623. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9624. }
  9625. successCallback(answer);
  9626. },
  9627. function(err) {
  9628. self.trace('createAnswerOnFailure', err);
  9629. failureCallback(err);
  9630. },
  9631. constraints
  9632. );
  9633. };
  9634. TraceablePeerConnection.prototype.addIceCandidate
  9635. = function (candidate, successCallback, failureCallback) {
  9636. //var self = this;
  9637. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9638. this.peerconnection.addIceCandidate(candidate);
  9639. /* maybe later
  9640. this.peerconnection.addIceCandidate(candidate,
  9641. function () {
  9642. self.trace('addIceCandidateOnSuccess');
  9643. successCallback();
  9644. },
  9645. function (err) {
  9646. self.trace('addIceCandidateOnFailure', err);
  9647. failureCallback(err);
  9648. }
  9649. );
  9650. */
  9651. };
  9652. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9653. // TODO: Is this the correct way to handle Opera, Temasys?
  9654. if (RTCBrowserType.isFirefox()) {
  9655. // ignore for now...
  9656. if(!errback)
  9657. errback = function () {};
  9658. this.peerconnection.getStats(null, callback, errback);
  9659. } else {
  9660. this.peerconnection.getStats(callback);
  9661. }
  9662. };
  9663. module.exports = TraceablePeerConnection;
  9664. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9665. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":48,"sdp-interop":66,"sdp-simulcast":69,"sdp-transform":76}],34:[function(require,module,exports){
  9666. (function (__filename){
  9667. /* global $, $iq, Promise, Strophe */
  9668. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9669. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9670. var Settings = require("../settings/Settings");
  9671. var AuthenticationEvents
  9672. = require("../../service/authentication/AuthenticationEvents");
  9673. function createExpBackoffTimer(step) {
  9674. var count = 1;
  9675. return function (reset) {
  9676. // Reset call
  9677. if (reset) {
  9678. count = 1;
  9679. return;
  9680. }
  9681. // Calculate next timeout
  9682. var timeout = Math.pow(2, count - 1);
  9683. count += 1;
  9684. return timeout * step;
  9685. };
  9686. }
  9687. function Moderator(roomName, xmpp, emitter) {
  9688. this.roomName = roomName;
  9689. this.xmppService = xmpp;
  9690. this.getNextTimeout = createExpBackoffTimer(1000);
  9691. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9692. // External authentication stuff
  9693. this.externalAuthEnabled = false;
  9694. this.settings = new Settings(roomName);
  9695. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9696. // it will be enabled automatically if focus detects the component through
  9697. // service discovery.
  9698. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  9699. this.xmppService.options.hosts.call_control !== undefined;
  9700. this.eventEmitter = emitter;
  9701. this.connection = this.xmppService.connection;
  9702. this.focusUserJid;
  9703. //FIXME:
  9704. // Message listener that talks to POPUP window
  9705. function listener(event) {
  9706. if (event.data && event.data.sessionId) {
  9707. if (event.origin !== window.location.origin) {
  9708. logger.warn("Ignoring sessionId from different origin: " +
  9709. event.origin);
  9710. return;
  9711. }
  9712. localStorage.setItem('sessionId', event.data.sessionId);
  9713. // After popup is closed we will authenticate
  9714. }
  9715. }
  9716. // Register
  9717. if (window.addEventListener) {
  9718. window.addEventListener("message", listener, false);
  9719. } else {
  9720. window.attachEvent("onmessage", listener);
  9721. }
  9722. }
  9723. Moderator.prototype.isExternalAuthEnabled = function () {
  9724. return this.externalAuthEnabled;
  9725. };
  9726. Moderator.prototype.isSipGatewayEnabled = function () {
  9727. return this.sipGatewayEnabled;
  9728. };
  9729. Moderator.prototype.onMucMemberLeft = function (jid) {
  9730. logger.info("Someone left is it focus ? " + jid);
  9731. var resource = Strophe.getResourceFromJid(jid);
  9732. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9733. logger.info(
  9734. "Focus has left the room - leaving conference");
  9735. //hangUp();
  9736. // We'd rather reload to have everything re-initialized
  9737. //FIXME: show some message before reload
  9738. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9739. }
  9740. };
  9741. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9742. if (!this.focusUserJid) {
  9743. this.focusUserJid = focusJid;
  9744. logger.info("Focus jid set to: " + this.focusUserJid);
  9745. }
  9746. };
  9747. Moderator.prototype.getFocusUserJid = function () {
  9748. return this.focusUserJid;
  9749. };
  9750. Moderator.prototype.getFocusComponent = function () {
  9751. // Get focus component address
  9752. var focusComponent = this.xmppService.options.hosts.focus;
  9753. // If not specified use default: 'focus.domain'
  9754. if (!focusComponent) {
  9755. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9756. }
  9757. return focusComponent;
  9758. };
  9759. Moderator.prototype.createConferenceIq = function () {
  9760. // Generate create conference IQ
  9761. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9762. // Session Id used for authentication
  9763. var sessionId = localStorage.getItem('sessionId');
  9764. var machineUID = this.settings.getSettings().uid;
  9765. logger.info(
  9766. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9767. elem.c('conference', {
  9768. xmlns: 'http://jitsi.org/protocol/focus',
  9769. room: this.roomName,
  9770. 'machine-uid': machineUID
  9771. });
  9772. if (sessionId) {
  9773. elem.attrs({ 'session-id': sessionId});
  9774. }
  9775. if (this.xmppService.options.hosts.bridge !== undefined) {
  9776. elem.c(
  9777. 'property', {
  9778. name: 'bridge',
  9779. value: this.xmppService.options.hosts.bridge
  9780. }).up();
  9781. }
  9782. if (this.xmppService.options.enforcedBridge !== undefined) {
  9783. elem.c(
  9784. 'property', {
  9785. name: 'enforcedBridge',
  9786. value: this.xmppService.options.enforcedBridge
  9787. }).up();
  9788. }
  9789. // Tell the focus we have Jigasi configured
  9790. if (this.xmppService.options.hosts.call_control !== undefined) {
  9791. elem.c(
  9792. 'property', {
  9793. name: 'call_control',
  9794. value: this.xmppService.options.hosts.call_control
  9795. }).up();
  9796. }
  9797. if (this.xmppService.options.channelLastN !== undefined) {
  9798. elem.c(
  9799. 'property', {
  9800. name: 'channelLastN',
  9801. value: this.xmppService.options.channelLastN
  9802. }).up();
  9803. }
  9804. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9805. elem.c(
  9806. 'property', {
  9807. name: 'adaptiveLastN',
  9808. value: this.xmppService.options.adaptiveLastN
  9809. }).up();
  9810. }
  9811. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9812. elem.c(
  9813. 'property', {
  9814. name: 'adaptiveSimulcast',
  9815. value: this.xmppService.options.adaptiveSimulcast
  9816. }).up();
  9817. }
  9818. if (this.xmppService.options.openSctp !== undefined) {
  9819. elem.c(
  9820. 'property', {
  9821. name: 'openSctp',
  9822. value: this.xmppService.options.openSctp
  9823. }).up();
  9824. }
  9825. if (this.xmppService.options.startAudioMuted !== undefined)
  9826. {
  9827. elem.c(
  9828. 'property', {
  9829. name: 'startAudioMuted',
  9830. value: this.xmppService.options.startAudioMuted
  9831. }).up();
  9832. }
  9833. if (this.xmppService.options.startVideoMuted !== undefined)
  9834. {
  9835. elem.c(
  9836. 'property', {
  9837. name: 'startVideoMuted',
  9838. value: this.xmppService.options.startVideoMuted
  9839. }).up();
  9840. }
  9841. elem.c(
  9842. 'property', {
  9843. name: 'simulcastMode',
  9844. value: 'rewriting'
  9845. }).up();
  9846. elem.up();
  9847. return elem;
  9848. };
  9849. Moderator.prototype.parseSessionId = function (resultIq) {
  9850. var sessionId = $(resultIq).find('conference').attr('session-id');
  9851. if (sessionId) {
  9852. logger.info('Received sessionId: ' + sessionId);
  9853. localStorage.setItem('sessionId', sessionId);
  9854. }
  9855. };
  9856. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9857. this.setFocusUserJid(
  9858. $(resultIq).find('conference').attr('focusjid'));
  9859. var authenticationEnabled
  9860. = $(resultIq).find(
  9861. '>conference>property' +
  9862. '[name=\'authentication\'][value=\'true\']').length > 0;
  9863. logger.info("Authentication enabled: " + authenticationEnabled);
  9864. this.externalAuthEnabled = $(resultIq).find(
  9865. '>conference>property' +
  9866. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9867. console.info(
  9868. 'External authentication enabled: ' + this.externalAuthEnabled);
  9869. if (!this.externalAuthEnabled) {
  9870. // We expect to receive sessionId in 'internal' authentication mode
  9871. this.parseSessionId(resultIq);
  9872. }
  9873. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9874. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9875. authenticationEnabled, authIdentity);
  9876. // Check if focus has auto-detected Jigasi component(this will be also
  9877. // included if we have passed our host from the config)
  9878. if ($(resultIq).find(
  9879. '>conference>property' +
  9880. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9881. this.sipGatewayEnabled = true;
  9882. }
  9883. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9884. };
  9885. // FIXME = we need to show the fact that we're waiting for the focus
  9886. // to the user(or that focus is not available)
  9887. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9888. // Try to use focus user JID from the config
  9889. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9890. // Send create conference IQ
  9891. var iq = this.createConferenceIq();
  9892. var self = this;
  9893. this.connection.sendIQ(
  9894. iq,
  9895. function (result) {
  9896. // Setup config options
  9897. self.parseConfigOptions(result);
  9898. if ('true' === $(result).find('conference').attr('ready')) {
  9899. // Reset both timers
  9900. self.getNextTimeout(true);
  9901. self.getNextErrorTimeout(true);
  9902. // Exec callback
  9903. callback();
  9904. } else {
  9905. var waitMs = self.getNextTimeout();
  9906. logger.info("Waiting for the focus... " + waitMs);
  9907. // Reset error timeout
  9908. self.getNextErrorTimeout(true);
  9909. window.setTimeout(
  9910. function () {
  9911. self.allocateConferenceFocus(callback);
  9912. }, waitMs);
  9913. }
  9914. },
  9915. function (error) {
  9916. // Invalid session ? remove and try again
  9917. // without session ID to get a new one
  9918. var invalidSession
  9919. = $(error).find('>error>session-invalid').length;
  9920. if (invalidSession) {
  9921. logger.info("Session expired! - removing");
  9922. localStorage.removeItem("sessionId");
  9923. }
  9924. if ($(error).find('>error>graceful-shutdown').length) {
  9925. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9926. return;
  9927. }
  9928. // Check for error returned by the reservation system
  9929. var reservationErr = $(error).find('>error>reservation-error');
  9930. if (reservationErr.length) {
  9931. // Trigger error event
  9932. var errorCode = reservationErr.attr('error-code');
  9933. var errorMsg;
  9934. if ($(error).find('>error>text')) {
  9935. errorMsg = $(error).find('>error>text').text();
  9936. }
  9937. self.eventEmitter.emit(
  9938. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9939. return;
  9940. }
  9941. // Not authorized to create new room
  9942. if ($(error).find('>error>not-authorized').length) {
  9943. logger.warn("Unauthorized to start the conference", error);
  9944. var toDomain
  9945. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9946. if (toDomain !==
  9947. this.xmppService.options.hosts.anonymousdomain) {
  9948. //FIXME: "is external" should come either from
  9949. // the focus or config.js
  9950. self.externalAuthEnabled = true;
  9951. }
  9952. self.eventEmitter.emit(
  9953. XMPPEvents.AUTHENTICATION_REQUIRED,
  9954. function () {
  9955. self.allocateConferenceFocus(
  9956. callback);
  9957. });
  9958. return;
  9959. }
  9960. var waitMs = self.getNextErrorTimeout();
  9961. logger.error("Focus error, retry after " + waitMs, error);
  9962. // Show message
  9963. var focusComponent = self.getFocusComponent();
  9964. var retrySec = waitMs / 1000;
  9965. //FIXME: message is duplicated ?
  9966. // Do not show in case of session invalid
  9967. // which means just a retry
  9968. if (!invalidSession) {
  9969. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9970. focusComponent, retrySec);
  9971. }
  9972. // Reset response timeout
  9973. self.getNextTimeout(true);
  9974. window.setTimeout(
  9975. function () {
  9976. self.allocateConferenceFocus(callback);
  9977. }, waitMs);
  9978. }
  9979. );
  9980. };
  9981. Moderator.prototype.authenticate = function () {
  9982. var self = this;
  9983. return new Promise(function (resolve, reject) {
  9984. self.connection.sendIQ(
  9985. self.createConferenceIq(),
  9986. function (result) {
  9987. self.parseSessionId(result);
  9988. resolve();
  9989. }, function (error) {
  9990. var code = $(error).find('>error').attr('code');
  9991. reject(error, code);
  9992. }
  9993. );
  9994. });
  9995. };
  9996. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  9997. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9998. iq.c('login-url', {
  9999. xmlns: 'http://jitsi.org/protocol/focus',
  10000. room: this.roomName,
  10001. 'machine-uid': this.settings.getSettings().uid
  10002. });
  10003. this.connection.sendIQ(
  10004. iq,
  10005. function (result) {
  10006. var url = $(result).find('login-url').attr('url');
  10007. url = url = decodeURIComponent(url);
  10008. if (url) {
  10009. logger.info("Got auth url: " + url);
  10010. urlCallback(url);
  10011. } else {
  10012. logger.error(
  10013. "Failed to get auth url from the focus", result);
  10014. failureCallback(result);
  10015. }
  10016. },
  10017. function (error) {
  10018. logger.error("Get auth url error", error);
  10019. failureCallback(error);
  10020. }
  10021. );
  10022. };
  10023. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10024. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10025. iq.c('login-url', {
  10026. xmlns: 'http://jitsi.org/protocol/focus',
  10027. room: this.roomName,
  10028. 'machine-uid': this.settings.getSettings().uid,
  10029. popup: true
  10030. });
  10031. this.connection.sendIQ(
  10032. iq,
  10033. function (result) {
  10034. var url = $(result).find('login-url').attr('url');
  10035. url = url = decodeURIComponent(url);
  10036. if (url) {
  10037. logger.info("Got POPUP auth url: " + url);
  10038. urlCallback(url);
  10039. } else {
  10040. logger.error(
  10041. "Failed to get POPUP auth url from the focus", result);
  10042. failureCallback(result);
  10043. }
  10044. },
  10045. function (error) {
  10046. logger.error('Get POPUP auth url error', error);
  10047. failureCallback(error);
  10048. }
  10049. );
  10050. };
  10051. Moderator.prototype.logout = function (callback) {
  10052. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10053. var sessionId = localStorage.getItem('sessionId');
  10054. if (!sessionId) {
  10055. callback();
  10056. return;
  10057. }
  10058. iq.c('logout', {
  10059. xmlns: 'http://jitsi.org/protocol/focus',
  10060. 'session-id': sessionId
  10061. });
  10062. this.connection.sendIQ(
  10063. iq,
  10064. function (result) {
  10065. var logoutUrl = $(result).find('logout').attr('logout-url');
  10066. if (logoutUrl) {
  10067. logoutUrl = decodeURIComponent(logoutUrl);
  10068. }
  10069. logger.info("Log out OK, url: " + logoutUrl, result);
  10070. localStorage.removeItem('sessionId');
  10071. callback(logoutUrl);
  10072. },
  10073. function (error) {
  10074. logger.error("Logout error", error);
  10075. }
  10076. );
  10077. };
  10078. module.exports = Moderator;
  10079. }).call(this,"/modules/xmpp/moderator.js")
  10080. },{"../../service/authentication/AuthenticationEvents":83,"../../service/xmpp/XMPPEvents":87,"../settings/Settings":21,"jitsi-meet-logger":48}],35:[function(require,module,exports){
  10081. (function (__filename){
  10082. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10083. Toolbar, Util, Promise */
  10084. var XMPPEvents = require("../../service/XMPP/XMPPEvents");
  10085. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10086. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10087. roomjid) {
  10088. this.eventEmitter = eventEmitter;
  10089. this.connection = connection;
  10090. this.state = "off";
  10091. this.focusMucJid = focusMucJid;
  10092. this.jirecon = jirecon;
  10093. this.url = null;
  10094. this.type = type;
  10095. this._isSupported = ((type === Recording.types.JIBRI)
  10096. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  10097. /**
  10098. * The ID of the jirecon recording session. Jirecon generates it when we
  10099. * initially start recording, and it needs to be used in subsequent requests
  10100. * to jirecon.
  10101. */
  10102. this.jireconRid = null;
  10103. this.roomjid = roomjid;
  10104. }
  10105. Recording.types = {
  10106. COLIBRI: "colibri",
  10107. JIRECON: "jirecon",
  10108. JIBRI: "jibri"
  10109. };
  10110. Recording.prototype.handleJibriPresence = function (jibri) {
  10111. var attributes = jibri.attributes;
  10112. if(!attributes)
  10113. return;
  10114. this._isSupported =
  10115. (attributes.status && attributes.status !== "undefined");
  10116. if(this._isSupported) {
  10117. this.url = attributes.url || null;
  10118. this.state = attributes.status || "off";
  10119. }
  10120. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  10121. };
  10122. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  10123. options) {
  10124. if (state == this.state){
  10125. errCallback(new Error("Invalid state!"));
  10126. }
  10127. options = options || {};
  10128. // FIXME jibri does not accept IQ without 'url' attribute set ?
  10129. var iq = $iq({to: this.focusMucJid, type: 'set'})
  10130. .c('jibri', {
  10131. "xmlns": 'http://jitsi.org/protocol/jibri',
  10132. "action": (state === 'on') ? 'start' : 'stop',
  10133. "streamid": options.streamId,
  10134. "follow-entity": options.followEntity
  10135. }).up();
  10136. logger.log('Set jibri recording: '+state, iq.nodeTree);
  10137. console.log(iq.nodeTree);
  10138. this.connection.sendIQ(
  10139. iq,
  10140. function (result) {
  10141. callback($(result).find('jibri').attr('state'),
  10142. $(result).find('jibri').attr('url'));
  10143. },
  10144. function (error) {
  10145. logger.log('Failed to start recording, error: ', error);
  10146. errCallback(error);
  10147. });
  10148. };
  10149. Recording.prototype.setRecordingJirecon =
  10150. function (state, callback, errCallback, options) {
  10151. if (state == this.state){
  10152. errCallback(new Error("Invalid state!"));
  10153. }
  10154. var iq = $iq({to: this.jirecon, type: 'set'})
  10155. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  10156. action: (state === 'on') ? 'start' : 'stop',
  10157. mucjid: this.roomjid});
  10158. if (state === 'off'){
  10159. iq.attrs({rid: this.jireconRid});
  10160. }
  10161. console.log('Start recording');
  10162. var self = this;
  10163. this.connection.sendIQ(
  10164. iq,
  10165. function (result) {
  10166. // TODO wait for an IQ with the real status, since this is
  10167. // provisional?
  10168. self.jireconRid = $(result).find('recording').attr('rid');
  10169. console.log('Recording ' +
  10170. ((state === 'on') ? 'started' : 'stopped') +
  10171. '(jirecon)' + result);
  10172. self.state = state;
  10173. if (state === 'off'){
  10174. self.jireconRid = null;
  10175. }
  10176. callback(state);
  10177. },
  10178. function (error) {
  10179. console.log('Failed to start recording, error: ', error);
  10180. errCallback(error);
  10181. });
  10182. };
  10183. // Sends a COLIBRI message which enables or disables (according to 'state')
  10184. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  10185. // with the new recording state, according to the IQ.
  10186. Recording.prototype.setRecordingColibri =
  10187. function (state, callback, errCallback, options) {
  10188. var elem = $iq({to: this.focusMucJid, type: 'set'});
  10189. elem.c('conference', {
  10190. xmlns: 'http://jitsi.org/protocol/colibri'
  10191. });
  10192. elem.c('recording', {state: state, token: options.token});
  10193. var self = this;
  10194. this.connection.sendIQ(elem,
  10195. function (result) {
  10196. console.log('Set recording "', state, '". Result:', result);
  10197. var recordingElem = $(result).find('>conference>recording');
  10198. var newState = recordingElem.attr('state');
  10199. self.state = newState;
  10200. callback(newState);
  10201. if (newState === 'pending') {
  10202. self.connection.addHandler(function(iq){
  10203. var state = $(iq).find('recording').attr('state');
  10204. if (state) {
  10205. self.state = newState;
  10206. callback(state);
  10207. }
  10208. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  10209. }
  10210. },
  10211. function (error) {
  10212. console.warn(error);
  10213. errCallback(error);
  10214. }
  10215. );
  10216. };
  10217. Recording.prototype.setRecording =
  10218. function (state, callback, errCallback, options) {
  10219. switch(this.type){
  10220. case Recording.types.JIRECON:
  10221. this.setRecordingJirecon(state, callback, errCallback, options);
  10222. break;
  10223. case Recording.types.COLIBRI:
  10224. this.setRecordingColibri(state, callback, errCallback, options);
  10225. break;
  10226. case Recording.types.JIBRI:
  10227. this.setRecordingJibri(state, callback, errCallback, options);
  10228. break;
  10229. default:
  10230. console.error("Unknown recording type!");
  10231. return;
  10232. }
  10233. };
  10234. /**
  10235. *Starts/stops the recording
  10236. * @param token token for authentication
  10237. * @param statusChangeHandler {function} receives the new status as argument.
  10238. */
  10239. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  10240. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  10241. (!options.streamId && this.type === Recording.types.JIBRI)){
  10242. statusChangeHandler("error", new Error("No token passed!"));
  10243. logger.error("No token passed!");
  10244. return;
  10245. }
  10246. var oldState = this.state;
  10247. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  10248. var self = this;
  10249. this.setRecording(newState,
  10250. function (state, url) {
  10251. logger.log("New recording state: ", state);
  10252. if (state && state !== oldState) {
  10253. self.state = state;
  10254. self.url = url;
  10255. statusChangeHandler(state);
  10256. } else {
  10257. statusChangeHandler("error", new Error("Status not changed!"));
  10258. }
  10259. }, function (error) {
  10260. statusChangeHandler("error", error);
  10261. }, options);
  10262. };
  10263. /**
  10264. * Returns true if the recording is supproted and false if not.
  10265. */
  10266. Recording.prototype.isSupported = function () {
  10267. return this._isSupported;
  10268. };
  10269. /**
  10270. * Returns null if the recording is not supported, "on" if the recording started
  10271. * and "off" if the recording is not started.
  10272. */
  10273. Recording.prototype.getState = function () {
  10274. return this.state;
  10275. };
  10276. /**
  10277. * Returns the url of the recorded video.
  10278. */
  10279. Recording.prototype.getURL = function () {
  10280. return this.url;
  10281. };
  10282. module.exports = Recording;
  10283. }).call(this,"/modules/xmpp/recording.js")
  10284. },{"../../service/XMPP/XMPPEvents":82,"jitsi-meet-logger":48}],36:[function(require,module,exports){
  10285. (function (__filename){
  10286. /* jshint -W117 */
  10287. /* a simple MUC connection plugin
  10288. * can only handle a single MUC room
  10289. */
  10290. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10291. var ChatRoom = require("./ChatRoom");
  10292. module.exports = function(XMPP) {
  10293. Strophe.addConnectionPlugin('emuc', {
  10294. connection: null,
  10295. rooms: {},//map with the rooms
  10296. init: function (conn) {
  10297. this.connection = conn;
  10298. // add handlers (just once)
  10299. this.connection.addHandler(this.onPresence.bind(this), null,
  10300. 'presence', null, null, null, null);
  10301. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  10302. null, 'presence', 'unavailable', null);
  10303. this.connection.addHandler(this.onPresenceError.bind(this), null,
  10304. 'presence', 'error', null);
  10305. this.connection.addHandler(this.onMessage.bind(this), null,
  10306. 'message', null, null);
  10307. this.connection.addHandler(this.onMute.bind(this),
  10308. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  10309. },
  10310. createRoom: function (jid, password, options) {
  10311. var roomJid = Strophe.getBareJidFromJid(jid);
  10312. if (this.rooms[roomJid]) {
  10313. logger.error("You are already in the room!");
  10314. return;
  10315. }
  10316. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  10317. return this.rooms[roomJid];
  10318. },
  10319. doLeave: function (jid) {
  10320. this.rooms[jid].doLeave();
  10321. delete this.rooms[jid];
  10322. },
  10323. onPresence: function (pres) {
  10324. var from = pres.getAttribute('from');
  10325. // What is this for? A workaround for something?
  10326. if (pres.getAttribute('type')) {
  10327. return true;
  10328. }
  10329. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10330. if(!room)
  10331. return;
  10332. // Parse status.
  10333. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  10334. room.createNonAnonymousRoom();
  10335. }
  10336. room.onPresence(pres);
  10337. return true;
  10338. },
  10339. onPresenceUnavailable: function (pres) {
  10340. var from = pres.getAttribute('from');
  10341. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10342. if(!room)
  10343. return;
  10344. room.onPresenceUnavailable(pres, from);
  10345. return true;
  10346. },
  10347. onPresenceError: function (pres) {
  10348. var from = pres.getAttribute('from');
  10349. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10350. if(!room)
  10351. return;
  10352. room.onPresenceError(pres, from);
  10353. return true;
  10354. },
  10355. onMessage: function (msg) {
  10356. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  10357. var from = msg.getAttribute('from');
  10358. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10359. if(!room)
  10360. return;
  10361. room.onMessage(msg, from);
  10362. return true;
  10363. },
  10364. setJingleSession: function (from, session) {
  10365. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10366. if(!room)
  10367. return;
  10368. room.setJingleSession(session);
  10369. },
  10370. onMute: function(iq) {
  10371. var from = iq.getAttribute('from');
  10372. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10373. if(!room)
  10374. return;
  10375. room.onMute(iq);
  10376. return true;
  10377. }
  10378. });
  10379. };
  10380. }).call(this,"/modules/xmpp/strophe.emuc.js")
  10381. },{"./ChatRoom":26,"jitsi-meet-logger":48}],37:[function(require,module,exports){
  10382. (function (__filename){
  10383. /* jshint -W117 */
  10384. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10385. var JingleSession = require("./JingleSessionPC");
  10386. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10387. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10388. module.exports = function(XMPP, eventEmitter) {
  10389. Strophe.addConnectionPlugin('jingle', {
  10390. connection: null,
  10391. sessions: {},
  10392. jid2session: {},
  10393. ice_config: {iceServers: []},
  10394. media_constraints: {
  10395. mandatory: {
  10396. 'OfferToReceiveAudio': true,
  10397. 'OfferToReceiveVideo': true
  10398. }
  10399. // MozDontOfferDataChannel: true when this is firefox
  10400. },
  10401. init: function (conn) {
  10402. this.connection = conn;
  10403. if (this.connection.disco) {
  10404. // http://xmpp.org/extensions/xep-0167.html#support
  10405. // http://xmpp.org/extensions/xep-0176.html#support
  10406. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  10407. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  10408. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  10409. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  10410. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  10411. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  10412. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  10413. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  10414. || RTCBrowserType.isTemasysPluginUsed()) {
  10415. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  10416. }
  10417. // this is dealt with by SDP O/A so we don't need to announce this
  10418. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  10419. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  10420. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  10421. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  10422. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  10423. }
  10424. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  10425. },
  10426. onJingle: function (iq) {
  10427. var sid = $(iq).find('jingle').attr('sid');
  10428. var action = $(iq).find('jingle').attr('action');
  10429. var fromJid = iq.getAttribute('from');
  10430. // send ack first
  10431. var ack = $iq({type: 'result',
  10432. to: fromJid,
  10433. id: iq.getAttribute('id')
  10434. });
  10435. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  10436. var sess = this.sessions[sid];
  10437. if ('session-initiate' != action) {
  10438. if (sess === null) {
  10439. ack.type = 'error';
  10440. ack.c('error', {type: 'cancel'})
  10441. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10442. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10443. this.connection.send(ack);
  10444. return true;
  10445. }
  10446. // local jid is not checked
  10447. if (fromJid != sess.peerjid) {
  10448. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  10449. ack.type = 'error';
  10450. ack.c('error', {type: 'cancel'})
  10451. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10452. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10453. this.connection.send(ack);
  10454. return true;
  10455. }
  10456. } else if (sess !== undefined) {
  10457. // existing session with same session id
  10458. // this might be out-of-order if the sess.peerjid is the same as from
  10459. ack.type = 'error';
  10460. ack.c('error', {type: 'cancel'})
  10461. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  10462. logger.warn('duplicate session id', sid);
  10463. this.connection.send(ack);
  10464. return true;
  10465. }
  10466. // FIXME: check for a defined action
  10467. this.connection.send(ack);
  10468. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  10469. switch (action) {
  10470. case 'session-initiate':
  10471. console.log("(TIME) received session-initiate:\t",
  10472. window.performance.now());
  10473. var startMuted = $(iq).find('jingle>startmuted');
  10474. if (startMuted && startMuted.length > 0) {
  10475. var audioMuted = startMuted.attr("audio");
  10476. var videoMuted = startMuted.attr("video");
  10477. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  10478. audioMuted === "true", videoMuted === "true");
  10479. }
  10480. sess = new JingleSession(
  10481. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  10482. this.connection, XMPP);
  10483. // configure session
  10484. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  10485. this.connection.emuc.setJingleSession(fromBareJid, sess);
  10486. sess.media_constraints = this.media_constraints;
  10487. sess.ice_config = this.ice_config;
  10488. sess.initialize(fromJid, false);
  10489. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  10490. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  10491. sess.setOffer($(iq).find('>jingle'));
  10492. this.sessions[sess.sid] = sess;
  10493. this.jid2session[sess.peerjid] = sess;
  10494. // the callback should either
  10495. // .sendAnswer and .accept
  10496. // or .sendTerminate -- not necessarily synchronous
  10497. sess.sendAnswer();
  10498. sess.accept();
  10499. break;
  10500. case 'session-accept':
  10501. sess.setAnswer($(iq).find('>jingle'));
  10502. sess.accept();
  10503. break;
  10504. case 'session-terminate':
  10505. // If this is not the focus sending the terminate, we have
  10506. // nothing more to do here.
  10507. if (Object.keys(this.sessions).length < 1
  10508. || !(this.sessions[Object.keys(this.sessions)[0]]
  10509. instanceof JingleSession))
  10510. {
  10511. break;
  10512. }
  10513. logger.log('terminating...', sess.sid);
  10514. sess.terminate();
  10515. this.terminate(sess.sid);
  10516. if ($(iq).find('>jingle>reason').length) {
  10517. $(document).trigger('callterminated.jingle', [
  10518. sess.sid,
  10519. sess.peerjid,
  10520. $(iq).find('>jingle>reason>:first')[0].tagName,
  10521. $(iq).find('>jingle>reason>text').text()
  10522. ]);
  10523. } else {
  10524. $(document).trigger('callterminated.jingle',
  10525. [sess.sid, sess.peerjid]);
  10526. }
  10527. break;
  10528. case 'transport-info':
  10529. sess.addIceCandidate($(iq).find('>jingle>content'));
  10530. break;
  10531. case 'session-info':
  10532. var affected;
  10533. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10534. $(document).trigger('ringing.jingle', [sess.sid]);
  10535. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10536. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10537. $(document).trigger('mute.jingle', [sess.sid, affected]);
  10538. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10539. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10540. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  10541. }
  10542. break;
  10543. case 'addsource': // FIXME: proprietary, un-jingleish
  10544. case 'source-add': // FIXME: proprietary
  10545. sess.addSource($(iq).find('>jingle>content'));
  10546. break;
  10547. case 'removesource': // FIXME: proprietary, un-jingleish
  10548. case 'source-remove': // FIXME: proprietary
  10549. sess.removeSource($(iq).find('>jingle>content'));
  10550. break;
  10551. default:
  10552. logger.warn('jingle action not implemented', action);
  10553. break;
  10554. }
  10555. return true;
  10556. },
  10557. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  10558. if (sid === null || sid === undefined) {
  10559. for (sid in this.sessions) {
  10560. if (this.sessions[sid].state != 'ended') {
  10561. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10562. this.sessions[sid].terminate();
  10563. }
  10564. delete this.jid2session[this.sessions[sid].peerjid];
  10565. delete this.sessions[sid];
  10566. }
  10567. } else if (this.sessions.hasOwnProperty(sid)) {
  10568. if (this.sessions[sid].state != 'ended') {
  10569. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10570. this.sessions[sid].terminate();
  10571. }
  10572. delete this.jid2session[this.sessions[sid].peerjid];
  10573. delete this.sessions[sid];
  10574. }
  10575. },
  10576. getStunAndTurnCredentials: function () {
  10577. // get stun and turn configuration from server via xep-0215
  10578. // uses time-limited credentials as described in
  10579. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  10580. //
  10581. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  10582. // for a prosody module which implements this
  10583. //
  10584. // currently, this doesn't work with updateIce and therefore credentials with a long
  10585. // validity have to be fetched before creating the peerconnection
  10586. // TODO: implement refresh via updateIce as described in
  10587. // https://code.google.com/p/webrtc/issues/detail?id=1650
  10588. var self = this;
  10589. this.connection.sendIQ(
  10590. $iq({type: 'get', to: this.connection.domain})
  10591. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  10592. function (res) {
  10593. var iceservers = [];
  10594. $(res).find('>services>service').each(function (idx, el) {
  10595. el = $(el);
  10596. var dict = {};
  10597. var type = el.attr('type');
  10598. switch (type) {
  10599. case 'stun':
  10600. dict.url = 'stun:' + el.attr('host');
  10601. if (el.attr('port')) {
  10602. dict.url += ':' + el.attr('port');
  10603. }
  10604. iceservers.push(dict);
  10605. break;
  10606. case 'turn':
  10607. case 'turns':
  10608. dict.url = type + ':';
  10609. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  10610. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  10611. dict.url += el.attr('username') + '@';
  10612. } else {
  10613. dict.username = el.attr('username'); // only works in M28
  10614. }
  10615. }
  10616. dict.url += el.attr('host');
  10617. if (el.attr('port') && el.attr('port') != '3478') {
  10618. dict.url += ':' + el.attr('port');
  10619. }
  10620. if (el.attr('transport') && el.attr('transport') != 'udp') {
  10621. dict.url += '?transport=' + el.attr('transport');
  10622. }
  10623. if (el.attr('password')) {
  10624. dict.credential = el.attr('password');
  10625. }
  10626. iceservers.push(dict);
  10627. break;
  10628. }
  10629. });
  10630. self.ice_config.iceServers = iceservers;
  10631. },
  10632. function (err) {
  10633. logger.warn('getting turn credentials failed', err);
  10634. logger.warn('is mod_turncredentials or similar installed?');
  10635. }
  10636. );
  10637. // implement push?
  10638. },
  10639. /**
  10640. * Returns the data saved in 'updateLog' in a format to be logged.
  10641. */
  10642. getLog: function () {
  10643. var data = {};
  10644. var self = this;
  10645. Object.keys(this.sessions).forEach(function (sid) {
  10646. var session = self.sessions[sid];
  10647. if (session.peerconnection && session.peerconnection.updateLog) {
  10648. // FIXME: should probably be a .dump call
  10649. data["jingle_" + session.sid] = {
  10650. updateLog: session.peerconnection.updateLog,
  10651. stats: session.peerconnection.stats,
  10652. url: window.location.href
  10653. };
  10654. }
  10655. });
  10656. return data;
  10657. }
  10658. });
  10659. };
  10660. }).call(this,"/modules/xmpp/strophe.jingle.js")
  10661. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":48}],38:[function(require,module,exports){
  10662. /* global Strophe */
  10663. module.exports = function () {
  10664. Strophe.addConnectionPlugin('logger', {
  10665. // logs raw stanzas and makes them available for download as JSON
  10666. connection: null,
  10667. log: [],
  10668. init: function (conn) {
  10669. this.connection = conn;
  10670. this.connection.rawInput = this.log_incoming.bind(this);
  10671. this.connection.rawOutput = this.log_outgoing.bind(this);
  10672. },
  10673. log_incoming: function (stanza) {
  10674. this.log.push([new Date().getTime(), 'incoming', stanza]);
  10675. },
  10676. log_outgoing: function (stanza) {
  10677. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  10678. }
  10679. });
  10680. };
  10681. },{}],39:[function(require,module,exports){
  10682. (function (__filename){
  10683. /* global $, $iq, Strophe */
  10684. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10685. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10686. /**
  10687. * Ping every 20 sec
  10688. */
  10689. var PING_INTERVAL = 20000;
  10690. /**
  10691. * Ping timeout error after 15 sec of waiting.
  10692. */
  10693. var PING_TIMEOUT = 15000;
  10694. /**
  10695. * Will close the connection after 3 consecutive ping errors.
  10696. */
  10697. var PING_THRESHOLD = 3;
  10698. /**
  10699. * XEP-0199 ping plugin.
  10700. *
  10701. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  10702. */
  10703. module.exports = function (XMPP, eventEmitter) {
  10704. Strophe.addConnectionPlugin('ping', {
  10705. connection: null,
  10706. failedPings: 0,
  10707. /**
  10708. * Initializes the plugin. Method called by Strophe.
  10709. * @param connection Strophe connection instance.
  10710. */
  10711. init: function (connection) {
  10712. this.connection = connection;
  10713. Strophe.addNamespace('PING', "urn:xmpp:ping");
  10714. },
  10715. /**
  10716. * Sends "ping" to given <tt>jid</tt>
  10717. * @param jid the JID to which ping request will be sent.
  10718. * @param success callback called on success.
  10719. * @param error callback called on error.
  10720. * @param timeout ms how long are we going to wait for the response. On
  10721. * timeout <tt>error<//t> callback is called with undefined error
  10722. * argument.
  10723. */
  10724. ping: function (jid, success, error, timeout) {
  10725. var iq = $iq({type: 'get', to: jid});
  10726. iq.c('ping', {xmlns: Strophe.NS.PING});
  10727. this.connection.sendIQ(iq, success, error, timeout);
  10728. },
  10729. /**
  10730. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  10731. * @param jid the JID to be checked for ping support.
  10732. * @param callback function with boolean argument which will be
  10733. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  10734. */
  10735. hasPingSupport: function (jid, callback) {
  10736. this.connection.disco.info(
  10737. jid, null,
  10738. function (result) {
  10739. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  10740. callback(ping.length > 0);
  10741. },
  10742. function (error) {
  10743. logger.error("Ping feature discovery error", error);
  10744. callback(false);
  10745. }
  10746. );
  10747. },
  10748. /**
  10749. * Starts to send ping in given interval to specified remote JID.
  10750. * This plugin supports only one such task and <tt>stopInterval</tt>
  10751. * must be called before starting a new one.
  10752. * @param remoteJid remote JID to which ping requests will be sent to.
  10753. * @param interval task interval in ms.
  10754. */
  10755. startInterval: function (remoteJid, interval) {
  10756. if (this.intervalId) {
  10757. logger.error("Ping task scheduled already");
  10758. return;
  10759. }
  10760. if (!interval)
  10761. interval = PING_INTERVAL;
  10762. var self = this;
  10763. this.intervalId = window.setInterval(function () {
  10764. self.ping(remoteJid,
  10765. function (result) {
  10766. // Ping OK
  10767. self.failedPings = 0;
  10768. },
  10769. function (error) {
  10770. self.failedPings += 1;
  10771. logger.error(
  10772. "Ping " + (error ? "error" : "timeout"), error);
  10773. if (self.failedPings >= PING_THRESHOLD) {
  10774. self.connection.disconnect();
  10775. }
  10776. }, PING_TIMEOUT);
  10777. }, interval);
  10778. logger.info("XMPP pings will be sent every " + interval + " ms");
  10779. },
  10780. /**
  10781. * Stops current "ping" interval task.
  10782. */
  10783. stopInterval: function () {
  10784. if (this.intervalId) {
  10785. window.clearInterval(this.intervalId);
  10786. this.intervalId = null;
  10787. this.failedPings = 0;
  10788. logger.info("Ping interval cleared");
  10789. }
  10790. }
  10791. });
  10792. };
  10793. }).call(this,"/modules/xmpp/strophe.ping.js")
  10794. },{"../../service/xmpp/XMPPEvents":87,"jitsi-meet-logger":48}],40:[function(require,module,exports){
  10795. (function (__filename){
  10796. /* jshint -W117 */
  10797. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10798. module.exports = function() {
  10799. Strophe.addConnectionPlugin('rayo',
  10800. {
  10801. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10802. connection: null,
  10803. init: function (conn) {
  10804. this.connection = conn;
  10805. if (this.connection.disco) {
  10806. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10807. }
  10808. this.connection.addHandler(
  10809. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  10810. null, null);
  10811. },
  10812. onRayo: function (iq) {
  10813. logger.info("Rayo IQ", iq);
  10814. },
  10815. dial: function (to, from, roomName, roomPass, focusMucJid) {
  10816. var self = this;
  10817. return new Promise(function (resolve, reject) {
  10818. if(!focusMucJid) {
  10819. reject(new Error("Internal error!"));
  10820. return;
  10821. }
  10822. var req = $iq(
  10823. {
  10824. type: 'set',
  10825. to: focusMucJid
  10826. }
  10827. );
  10828. req.c('dial',
  10829. {
  10830. xmlns: self.RAYO_XMLNS,
  10831. to: to,
  10832. from: from
  10833. });
  10834. req.c('header',
  10835. {
  10836. name: 'JvbRoomName',
  10837. value: roomName
  10838. }).up();
  10839. if (roomPass !== null && roomPass.length) {
  10840. req.c('header',
  10841. {
  10842. name: 'JvbRoomPassword',
  10843. value: roomPass
  10844. }).up();
  10845. }
  10846. self.connection.sendIQ(
  10847. req,
  10848. function (result) {
  10849. logger.info('Dial result ', result);
  10850. var resource = $(result).find('ref').attr('uri');
  10851. self.call_resource =
  10852. resource.substr('xmpp:'.length);
  10853. logger.info(
  10854. "Received call resource: " +
  10855. self.call_resource);
  10856. resolve();
  10857. },
  10858. function (error) {
  10859. logger.info('Dial error ', error);
  10860. reject(error);
  10861. }
  10862. );
  10863. });
  10864. },
  10865. hangup: function () {
  10866. var self = this;
  10867. return new Promise(function (resolve, reject) {
  10868. if (!self.call_resource) {
  10869. reject(new Error("No call in progress"));
  10870. logger.warn("No call in progress");
  10871. return;
  10872. }
  10873. var req = $iq(
  10874. {
  10875. type: 'set',
  10876. to: self.call_resource
  10877. }
  10878. );
  10879. req.c('hangup',
  10880. {
  10881. xmlns: self.RAYO_XMLNS
  10882. });
  10883. self.connection.sendIQ(
  10884. req,
  10885. function (result) {
  10886. logger.info('Hangup result ', result);
  10887. self.call_resource = null;
  10888. resolve();
  10889. },
  10890. function (error) {
  10891. logger.info('Hangup error ', error);
  10892. self.call_resource = null;
  10893. reject(new Error('Hangup error '));
  10894. }
  10895. );
  10896. });
  10897. }
  10898. }
  10899. );
  10900. };
  10901. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10902. },{"jitsi-meet-logger":48}],41:[function(require,module,exports){
  10903. (function (__filename){
  10904. /* global Strophe */
  10905. /**
  10906. * Strophe logger implementation. Logs from level WARN and above.
  10907. */
  10908. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10909. module.exports = function () {
  10910. Strophe.log = function (level, msg) {
  10911. switch (level) {
  10912. case Strophe.LogLevel.WARN:
  10913. logger.warn("Strophe: " + msg);
  10914. break;
  10915. case Strophe.LogLevel.ERROR:
  10916. case Strophe.LogLevel.FATAL:
  10917. logger.error("Strophe: " + msg);
  10918. break;
  10919. }
  10920. };
  10921. Strophe.getStatusString = function (status) {
  10922. switch (status) {
  10923. case Strophe.Status.ERROR:
  10924. return "ERROR";
  10925. case Strophe.Status.CONNECTING:
  10926. return "CONNECTING";
  10927. case Strophe.Status.CONNFAIL:
  10928. return "CONNFAIL";
  10929. case Strophe.Status.AUTHENTICATING:
  10930. return "AUTHENTICATING";
  10931. case Strophe.Status.AUTHFAIL:
  10932. return "AUTHFAIL";
  10933. case Strophe.Status.CONNECTED:
  10934. return "CONNECTED";
  10935. case Strophe.Status.DISCONNECTED:
  10936. return "DISCONNECTED";
  10937. case Strophe.Status.DISCONNECTING:
  10938. return "DISCONNECTING";
  10939. case Strophe.Status.ATTACHED:
  10940. return "ATTACHED";
  10941. default:
  10942. return "unknown";
  10943. }
  10944. };
  10945. };
  10946. }).call(this,"/modules/xmpp/strophe.util.js")
  10947. },{"jitsi-meet-logger":48}],42:[function(require,module,exports){
  10948. (function (__filename){
  10949. /* global $, APP, config, Strophe*/
  10950. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10951. var EventEmitter = require("events");
  10952. var Pako = require("pako");
  10953. var RTCEvents = require("../../service/RTC/RTCEvents");
  10954. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10955. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10956. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10957. var RTC = require("../RTC/RTC");
  10958. var authenticatedUser = false;
  10959. function createConnection(bosh) {
  10960. bosh = bosh || '/http-bind';
  10961. // Append token as URL param
  10962. if (this.token) {
  10963. bosh += bosh.indexOf('?') == -1 ?
  10964. '?token=' + this.token : '&token=' + this.token;
  10965. }
  10966. return new Strophe.Connection(bosh);
  10967. };
  10968. //!!!!!!!!!! FIXME: ...
  10969. function initStrophePlugins(XMPP)
  10970. {
  10971. require("./strophe.emuc")(XMPP);
  10972. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10973. // require("./strophe.moderate")(XMPP, eventEmitter);
  10974. require("./strophe.util")();
  10975. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10976. require("./strophe.rayo")();
  10977. require("./strophe.logger")();
  10978. }
  10979. //!!!!!!!!!! FIXME: ...
  10980. ///**
  10981. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10982. // * video type in MUC presence.
  10983. // * @param localStream new or modified <tt>LocalStream</tt>.
  10984. // */
  10985. //function broadcastLocalVideoType(localStream) {
  10986. // if (localStream.videoType)
  10987. // XMPP.addToPresence('videoType', localStream.videoType);
  10988. //}
  10989. //
  10990. //function registerListeners() {
  10991. // RTC.addStreamListener(
  10992. // broadcastLocalVideoType,
  10993. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10994. // );
  10995. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10996. // XMPP.addToPresence("devices", devices);
  10997. // });
  10998. //}
  10999. function XMPP(options) {
  11000. this.eventEmitter = new EventEmitter();
  11001. this.connection = null;
  11002. this.disconnectInProgress = false;
  11003. this.forceMuted = false;
  11004. this.options = options;
  11005. initStrophePlugins(this);
  11006. // registerListeners();
  11007. this.connection = createConnection(options.bosh);
  11008. }
  11009. XMPP.prototype.getConnection = function(){ return connection; };
  11010. XMPP.prototype._connect = function (jid, password) {
  11011. var self = this;
  11012. // connection.connect() starts the connection process.
  11013. //
  11014. // As the connection process proceeds, the user supplied callback will
  11015. // be triggered multiple times with status updates. The callback should
  11016. // take two arguments - the status code and the error condition.
  11017. //
  11018. // The status code will be one of the values in the Strophe.Status
  11019. // constants. The error condition will be one of the conditions defined
  11020. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11021. //
  11022. // The Parameters wait, hold and route are optional and only relevant
  11023. // for BOSH connections. Please see XEP 124 for a more detailed
  11024. // explanation of the optional parameters.
  11025. //
  11026. // Connection status constants for use by the connection handler
  11027. // callback.
  11028. //
  11029. // Status.ERROR - An error has occurred (websockets specific)
  11030. // Status.CONNECTING - The connection is currently being made
  11031. // Status.CONNFAIL - The connection attempt failed
  11032. // Status.AUTHENTICATING - The connection is authenticating
  11033. // Status.AUTHFAIL - The authentication attempt failed
  11034. // Status.CONNECTED - The connection has succeeded
  11035. // Status.DISCONNECTED - The connection has been terminated
  11036. // Status.DISCONNECTING - The connection is currently being terminated
  11037. // Status.ATTACHED - The connection has been attached
  11038. var anonymousConnectionFailed = false;
  11039. var connectionFailed = false;
  11040. var lastErrorMsg;
  11041. this.connection.connect(jid, password, function (status, msg) {
  11042. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11043. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11044. if (status === Strophe.Status.CONNECTED) {
  11045. if (self.options.useStunTurn) {
  11046. self.connection.jingle.getStunAndTurnCredentials();
  11047. }
  11048. logger.info("My Jabber ID: " + self.connection.jid);
  11049. // Schedule ping ?
  11050. var pingJid = self.connection.domain;
  11051. self.connection.ping.hasPingSupport(
  11052. pingJid,
  11053. function (hasPing) {
  11054. if (hasPing)
  11055. self.connection.ping.startInterval(pingJid);
  11056. else
  11057. logger.warn("Ping NOT supported by " + pingJid);
  11058. }
  11059. );
  11060. if (password)
  11061. authenticatedUser = true;
  11062. if (self.connection && self.connection.connected &&
  11063. Strophe.getResourceFromJid(self.connection.jid)) {
  11064. // .connected is true while connecting?
  11065. // self.connection.send($pres());
  11066. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11067. Strophe.getResourceFromJid(self.connection.jid));
  11068. }
  11069. } else if (status === Strophe.Status.CONNFAIL) {
  11070. if (msg === 'x-strophe-bad-non-anon-jid') {
  11071. anonymousConnectionFailed = true;
  11072. }
  11073. else
  11074. {
  11075. connectionFailed = true;
  11076. }
  11077. lastErrorMsg = msg;
  11078. } else if (status === Strophe.Status.DISCONNECTED) {
  11079. // Stop ping interval
  11080. self.connection.ping.stopInterval();
  11081. self.disconnectInProgress = false;
  11082. if (anonymousConnectionFailed) {
  11083. // prompt user for username and password
  11084. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11085. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11086. } else if(connectionFailed) {
  11087. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11088. JitsiConnectionErrors.OTHER_ERROR,
  11089. msg ? msg : lastErrorMsg);
  11090. } else {
  11091. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  11092. msg ? msg : lastErrorMsg);
  11093. }
  11094. } else if (status === Strophe.Status.AUTHFAIL) {
  11095. // wrong password or username, prompt user
  11096. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11097. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11098. }
  11099. });
  11100. }
  11101. XMPP.prototype.connect = function (jid, password) {
  11102. if(!jid) {
  11103. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  11104. // Force authenticated domain if room is appended with '?login=true'
  11105. if (this.options.hosts.anonymousdomain &&
  11106. window.location.search.indexOf("login=true") !== -1) {
  11107. configDomain = this.options.hosts.domain;
  11108. }
  11109. jid = configDomain || window.location.hostname;
  11110. }
  11111. return this._connect(jid, password);
  11112. };
  11113. XMPP.prototype.createRoom = function (roomName, options) {
  11114. var roomjid = roomName + '@' + this.options.hosts.muc;
  11115. if (options.useNicks) {
  11116. if (options.nick) {
  11117. roomjid += '/' + options.nick;
  11118. } else {
  11119. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  11120. }
  11121. } else {
  11122. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  11123. if(!authenticatedUser)
  11124. tmpJid = tmpJid.substr(0, 8);
  11125. roomjid += '/' + tmpJid;
  11126. }
  11127. return this.connection.emuc.createRoom(roomjid, null, options);
  11128. }
  11129. XMPP.prototype.addListener = function(type, listener) {
  11130. this.eventEmitter.on(type, listener);
  11131. };
  11132. XMPP.prototype.removeListener = function (type, listener) {
  11133. this.eventEmitter.removeListener(type, listener);
  11134. };
  11135. //FIXME: this should work with the room
  11136. XMPP.prototype.leaveRoom = function (jid) {
  11137. var handler = this.connection.jingle.jid2session[jid];
  11138. if (handler && handler.peerconnection) {
  11139. // FIXME: probably removing streams is not required and close() should
  11140. // be enough
  11141. if (RTC.localAudio) {
  11142. handler.peerconnection.removeStream(
  11143. RTC.localAudio.getOriginalStream(), true);
  11144. }
  11145. if (RTC.localVideo) {
  11146. handler.peerconnection.removeStream(
  11147. RTC.localVideo.getOriginalStream(), true);
  11148. }
  11149. handler.peerconnection.close();
  11150. }
  11151. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  11152. this.connection.emuc.doLeave(jid);
  11153. };
  11154. /**
  11155. * Sends 'data' as a log message to the focus. Returns true iff a message
  11156. * was sent.
  11157. * @param data
  11158. * @returns {boolean} true iff a message was sent.
  11159. */
  11160. XMPP.prototype.sendLogs = function (data) {
  11161. if(!this.connection.emuc.focusMucJid)
  11162. return false;
  11163. var deflate = true;
  11164. var content = JSON.stringify(data);
  11165. if (deflate) {
  11166. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  11167. }
  11168. content = Base64.encode(content);
  11169. // XEP-0337-ish
  11170. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  11171. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  11172. id: 'PeerConnectionStats'});
  11173. message.c('message').t(content).up();
  11174. if (deflate) {
  11175. message.c('tag', {name: "deflated", value: "true"}).up();
  11176. }
  11177. message.up();
  11178. this.connection.send(message);
  11179. return true;
  11180. };
  11181. // Gets the logs from strophe.jingle.
  11182. XMPP.prototype.getJingleLog = function () {
  11183. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  11184. };
  11185. // Gets the logs from strophe.
  11186. XMPP.prototype.getXmppLog = function () {
  11187. return this.connection.logger ? this.connection.logger.log : null;
  11188. };
  11189. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  11190. this.connection.rayo.dial(to, from, roomName,roomPass);
  11191. };
  11192. XMPP.prototype.setMute = function (jid, mute) {
  11193. this.connection.moderate.setMute(jid, mute);
  11194. };
  11195. XMPP.prototype.eject = function (jid) {
  11196. this.connection.moderate.eject(jid);
  11197. };
  11198. XMPP.prototype.getSessions = function () {
  11199. return this.connection.jingle.sessions;
  11200. };
  11201. XMPP.prototype.disconnect = function () {
  11202. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  11203. {
  11204. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  11205. return;
  11206. }
  11207. this.disconnectInProgress = true;
  11208. this.connection.disconnect();
  11209. };
  11210. /**
  11211. * Gets the SSRC of local media stream.
  11212. * @param mediaType the media type that tells whether we want to get
  11213. * the SSRC of local audio or video stream.
  11214. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  11215. * not available.
  11216. */
  11217. XMPP.prototype.getLocalSSRC = function (mediaType) {
  11218. if (this.connection.jingle.activecall &&
  11219. this.connection.jingle.activecall.peerconnection) {
  11220. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  11221. } else {
  11222. return null;
  11223. }
  11224. };
  11225. module.exports = XMPP;
  11226. }).call(this,"/modules/xmpp/xmpp.js")
  11227. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":80,"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"./strophe.emuc":36,"./strophe.jingle":37,"./strophe.logger":38,"./strophe.ping":39,"./strophe.rayo":40,"./strophe.util":41,"events":44,"jitsi-meet-logger":48,"pako":49}],43:[function(require,module,exports){
  11228. (function (process){
  11229. /*!
  11230. * async
  11231. * https://github.com/caolan/async
  11232. *
  11233. * Copyright 2010-2014 Caolan McMahon
  11234. * Released under the MIT license
  11235. */
  11236. /*jshint onevar: false, indent:4 */
  11237. /*global setImmediate: false, setTimeout: false, console: false */
  11238. (function () {
  11239. var async = {};
  11240. // global on the server, window in the browser
  11241. var root, previous_async;
  11242. root = this;
  11243. if (root != null) {
  11244. previous_async = root.async;
  11245. }
  11246. async.noConflict = function () {
  11247. root.async = previous_async;
  11248. return async;
  11249. };
  11250. function only_once(fn) {
  11251. var called = false;
  11252. return function() {
  11253. if (called) throw new Error("Callback was already called.");
  11254. called = true;
  11255. fn.apply(root, arguments);
  11256. }
  11257. }
  11258. //// cross-browser compatiblity functions ////
  11259. var _toString = Object.prototype.toString;
  11260. var _isArray = Array.isArray || function (obj) {
  11261. return _toString.call(obj) === '[object Array]';
  11262. };
  11263. var _each = function (arr, iterator) {
  11264. if (arr.forEach) {
  11265. return arr.forEach(iterator);
  11266. }
  11267. for (var i = 0; i < arr.length; i += 1) {
  11268. iterator(arr[i], i, arr);
  11269. }
  11270. };
  11271. var _map = function (arr, iterator) {
  11272. if (arr.map) {
  11273. return arr.map(iterator);
  11274. }
  11275. var results = [];
  11276. _each(arr, function (x, i, a) {
  11277. results.push(iterator(x, i, a));
  11278. });
  11279. return results;
  11280. };
  11281. var _reduce = function (arr, iterator, memo) {
  11282. if (arr.reduce) {
  11283. return arr.reduce(iterator, memo);
  11284. }
  11285. _each(arr, function (x, i, a) {
  11286. memo = iterator(memo, x, i, a);
  11287. });
  11288. return memo;
  11289. };
  11290. var _keys = function (obj) {
  11291. if (Object.keys) {
  11292. return Object.keys(obj);
  11293. }
  11294. var keys = [];
  11295. for (var k in obj) {
  11296. if (obj.hasOwnProperty(k)) {
  11297. keys.push(k);
  11298. }
  11299. }
  11300. return keys;
  11301. };
  11302. //// exported async module functions ////
  11303. //// nextTick implementation with browser-compatible fallback ////
  11304. if (typeof process === 'undefined' || !(process.nextTick)) {
  11305. if (typeof setImmediate === 'function') {
  11306. async.nextTick = function (fn) {
  11307. // not a direct alias for IE10 compatibility
  11308. setImmediate(fn);
  11309. };
  11310. async.setImmediate = async.nextTick;
  11311. }
  11312. else {
  11313. async.nextTick = function (fn) {
  11314. setTimeout(fn, 0);
  11315. };
  11316. async.setImmediate = async.nextTick;
  11317. }
  11318. }
  11319. else {
  11320. async.nextTick = process.nextTick;
  11321. if (typeof setImmediate !== 'undefined') {
  11322. async.setImmediate = function (fn) {
  11323. // not a direct alias for IE10 compatibility
  11324. setImmediate(fn);
  11325. };
  11326. }
  11327. else {
  11328. async.setImmediate = async.nextTick;
  11329. }
  11330. }
  11331. async.each = function (arr, iterator, callback) {
  11332. callback = callback || function () {};
  11333. if (!arr.length) {
  11334. return callback();
  11335. }
  11336. var completed = 0;
  11337. _each(arr, function (x) {
  11338. iterator(x, only_once(done) );
  11339. });
  11340. function done(err) {
  11341. if (err) {
  11342. callback(err);
  11343. callback = function () {};
  11344. }
  11345. else {
  11346. completed += 1;
  11347. if (completed >= arr.length) {
  11348. callback();
  11349. }
  11350. }
  11351. }
  11352. };
  11353. async.forEach = async.each;
  11354. async.eachSeries = function (arr, iterator, callback) {
  11355. callback = callback || function () {};
  11356. if (!arr.length) {
  11357. return callback();
  11358. }
  11359. var completed = 0;
  11360. var iterate = function () {
  11361. iterator(arr[completed], function (err) {
  11362. if (err) {
  11363. callback(err);
  11364. callback = function () {};
  11365. }
  11366. else {
  11367. completed += 1;
  11368. if (completed >= arr.length) {
  11369. callback();
  11370. }
  11371. else {
  11372. iterate();
  11373. }
  11374. }
  11375. });
  11376. };
  11377. iterate();
  11378. };
  11379. async.forEachSeries = async.eachSeries;
  11380. async.eachLimit = function (arr, limit, iterator, callback) {
  11381. var fn = _eachLimit(limit);
  11382. fn.apply(null, [arr, iterator, callback]);
  11383. };
  11384. async.forEachLimit = async.eachLimit;
  11385. var _eachLimit = function (limit) {
  11386. return function (arr, iterator, callback) {
  11387. callback = callback || function () {};
  11388. if (!arr.length || limit <= 0) {
  11389. return callback();
  11390. }
  11391. var completed = 0;
  11392. var started = 0;
  11393. var running = 0;
  11394. (function replenish () {
  11395. if (completed >= arr.length) {
  11396. return callback();
  11397. }
  11398. while (running < limit && started < arr.length) {
  11399. started += 1;
  11400. running += 1;
  11401. iterator(arr[started - 1], function (err) {
  11402. if (err) {
  11403. callback(err);
  11404. callback = function () {};
  11405. }
  11406. else {
  11407. completed += 1;
  11408. running -= 1;
  11409. if (completed >= arr.length) {
  11410. callback();
  11411. }
  11412. else {
  11413. replenish();
  11414. }
  11415. }
  11416. });
  11417. }
  11418. })();
  11419. };
  11420. };
  11421. var doParallel = function (fn) {
  11422. return function () {
  11423. var args = Array.prototype.slice.call(arguments);
  11424. return fn.apply(null, [async.each].concat(args));
  11425. };
  11426. };
  11427. var doParallelLimit = function(limit, fn) {
  11428. return function () {
  11429. var args = Array.prototype.slice.call(arguments);
  11430. return fn.apply(null, [_eachLimit(limit)].concat(args));
  11431. };
  11432. };
  11433. var doSeries = function (fn) {
  11434. return function () {
  11435. var args = Array.prototype.slice.call(arguments);
  11436. return fn.apply(null, [async.eachSeries].concat(args));
  11437. };
  11438. };
  11439. var _asyncMap = function (eachfn, arr, iterator, callback) {
  11440. arr = _map(arr, function (x, i) {
  11441. return {index: i, value: x};
  11442. });
  11443. if (!callback) {
  11444. eachfn(arr, function (x, callback) {
  11445. iterator(x.value, function (err) {
  11446. callback(err);
  11447. });
  11448. });
  11449. } else {
  11450. var results = [];
  11451. eachfn(arr, function (x, callback) {
  11452. iterator(x.value, function (err, v) {
  11453. results[x.index] = v;
  11454. callback(err);
  11455. });
  11456. }, function (err) {
  11457. callback(err, results);
  11458. });
  11459. }
  11460. };
  11461. async.map = doParallel(_asyncMap);
  11462. async.mapSeries = doSeries(_asyncMap);
  11463. async.mapLimit = function (arr, limit, iterator, callback) {
  11464. return _mapLimit(limit)(arr, iterator, callback);
  11465. };
  11466. var _mapLimit = function(limit) {
  11467. return doParallelLimit(limit, _asyncMap);
  11468. };
  11469. // reduce only has a series version, as doing reduce in parallel won't
  11470. // work in many situations.
  11471. async.reduce = function (arr, memo, iterator, callback) {
  11472. async.eachSeries(arr, function (x, callback) {
  11473. iterator(memo, x, function (err, v) {
  11474. memo = v;
  11475. callback(err);
  11476. });
  11477. }, function (err) {
  11478. callback(err, memo);
  11479. });
  11480. };
  11481. // inject alias
  11482. async.inject = async.reduce;
  11483. // foldl alias
  11484. async.foldl = async.reduce;
  11485. async.reduceRight = function (arr, memo, iterator, callback) {
  11486. var reversed = _map(arr, function (x) {
  11487. return x;
  11488. }).reverse();
  11489. async.reduce(reversed, memo, iterator, callback);
  11490. };
  11491. // foldr alias
  11492. async.foldr = async.reduceRight;
  11493. var _filter = function (eachfn, arr, iterator, callback) {
  11494. var results = [];
  11495. arr = _map(arr, function (x, i) {
  11496. return {index: i, value: x};
  11497. });
  11498. eachfn(arr, function (x, callback) {
  11499. iterator(x.value, function (v) {
  11500. if (v) {
  11501. results.push(x);
  11502. }
  11503. callback();
  11504. });
  11505. }, function (err) {
  11506. callback(_map(results.sort(function (a, b) {
  11507. return a.index - b.index;
  11508. }), function (x) {
  11509. return x.value;
  11510. }));
  11511. });
  11512. };
  11513. async.filter = doParallel(_filter);
  11514. async.filterSeries = doSeries(_filter);
  11515. // select alias
  11516. async.select = async.filter;
  11517. async.selectSeries = async.filterSeries;
  11518. var _reject = function (eachfn, arr, iterator, callback) {
  11519. var results = [];
  11520. arr = _map(arr, function (x, i) {
  11521. return {index: i, value: x};
  11522. });
  11523. eachfn(arr, function (x, callback) {
  11524. iterator(x.value, function (v) {
  11525. if (!v) {
  11526. results.push(x);
  11527. }
  11528. callback();
  11529. });
  11530. }, function (err) {
  11531. callback(_map(results.sort(function (a, b) {
  11532. return a.index - b.index;
  11533. }), function (x) {
  11534. return x.value;
  11535. }));
  11536. });
  11537. };
  11538. async.reject = doParallel(_reject);
  11539. async.rejectSeries = doSeries(_reject);
  11540. var _detect = function (eachfn, arr, iterator, main_callback) {
  11541. eachfn(arr, function (x, callback) {
  11542. iterator(x, function (result) {
  11543. if (result) {
  11544. main_callback(x);
  11545. main_callback = function () {};
  11546. }
  11547. else {
  11548. callback();
  11549. }
  11550. });
  11551. }, function (err) {
  11552. main_callback();
  11553. });
  11554. };
  11555. async.detect = doParallel(_detect);
  11556. async.detectSeries = doSeries(_detect);
  11557. async.some = function (arr, iterator, main_callback) {
  11558. async.each(arr, function (x, callback) {
  11559. iterator(x, function (v) {
  11560. if (v) {
  11561. main_callback(true);
  11562. main_callback = function () {};
  11563. }
  11564. callback();
  11565. });
  11566. }, function (err) {
  11567. main_callback(false);
  11568. });
  11569. };
  11570. // any alias
  11571. async.any = async.some;
  11572. async.every = function (arr, iterator, main_callback) {
  11573. async.each(arr, function (x, callback) {
  11574. iterator(x, function (v) {
  11575. if (!v) {
  11576. main_callback(false);
  11577. main_callback = function () {};
  11578. }
  11579. callback();
  11580. });
  11581. }, function (err) {
  11582. main_callback(true);
  11583. });
  11584. };
  11585. // all alias
  11586. async.all = async.every;
  11587. async.sortBy = function (arr, iterator, callback) {
  11588. async.map(arr, function (x, callback) {
  11589. iterator(x, function (err, criteria) {
  11590. if (err) {
  11591. callback(err);
  11592. }
  11593. else {
  11594. callback(null, {value: x, criteria: criteria});
  11595. }
  11596. });
  11597. }, function (err, results) {
  11598. if (err) {
  11599. return callback(err);
  11600. }
  11601. else {
  11602. var fn = function (left, right) {
  11603. var a = left.criteria, b = right.criteria;
  11604. return a < b ? -1 : a > b ? 1 : 0;
  11605. };
  11606. callback(null, _map(results.sort(fn), function (x) {
  11607. return x.value;
  11608. }));
  11609. }
  11610. });
  11611. };
  11612. async.auto = function (tasks, callback) {
  11613. callback = callback || function () {};
  11614. var keys = _keys(tasks);
  11615. var remainingTasks = keys.length
  11616. if (!remainingTasks) {
  11617. return callback();
  11618. }
  11619. var results = {};
  11620. var listeners = [];
  11621. var addListener = function (fn) {
  11622. listeners.unshift(fn);
  11623. };
  11624. var removeListener = function (fn) {
  11625. for (var i = 0; i < listeners.length; i += 1) {
  11626. if (listeners[i] === fn) {
  11627. listeners.splice(i, 1);
  11628. return;
  11629. }
  11630. }
  11631. };
  11632. var taskComplete = function () {
  11633. remainingTasks--
  11634. _each(listeners.slice(0), function (fn) {
  11635. fn();
  11636. });
  11637. };
  11638. addListener(function () {
  11639. if (!remainingTasks) {
  11640. var theCallback = callback;
  11641. // prevent final callback from calling itself if it errors
  11642. callback = function () {};
  11643. theCallback(null, results);
  11644. }
  11645. });
  11646. _each(keys, function (k) {
  11647. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  11648. var taskCallback = function (err) {
  11649. var args = Array.prototype.slice.call(arguments, 1);
  11650. if (args.length <= 1) {
  11651. args = args[0];
  11652. }
  11653. if (err) {
  11654. var safeResults = {};
  11655. _each(_keys(results), function(rkey) {
  11656. safeResults[rkey] = results[rkey];
  11657. });
  11658. safeResults[k] = args;
  11659. callback(err, safeResults);
  11660. // stop subsequent errors hitting callback multiple times
  11661. callback = function () {};
  11662. }
  11663. else {
  11664. results[k] = args;
  11665. async.setImmediate(taskComplete);
  11666. }
  11667. };
  11668. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  11669. var ready = function () {
  11670. return _reduce(requires, function (a, x) {
  11671. return (a && results.hasOwnProperty(x));
  11672. }, true) && !results.hasOwnProperty(k);
  11673. };
  11674. if (ready()) {
  11675. task[task.length - 1](taskCallback, results);
  11676. }
  11677. else {
  11678. var listener = function () {
  11679. if (ready()) {
  11680. removeListener(listener);
  11681. task[task.length - 1](taskCallback, results);
  11682. }
  11683. };
  11684. addListener(listener);
  11685. }
  11686. });
  11687. };
  11688. async.retry = function(times, task, callback) {
  11689. var DEFAULT_TIMES = 5;
  11690. var attempts = [];
  11691. // Use defaults if times not passed
  11692. if (typeof times === 'function') {
  11693. callback = task;
  11694. task = times;
  11695. times = DEFAULT_TIMES;
  11696. }
  11697. // Make sure times is a number
  11698. times = parseInt(times, 10) || DEFAULT_TIMES;
  11699. var wrappedTask = function(wrappedCallback, wrappedResults) {
  11700. var retryAttempt = function(task, finalAttempt) {
  11701. return function(seriesCallback) {
  11702. task(function(err, result){
  11703. seriesCallback(!err || finalAttempt, {err: err, result: result});
  11704. }, wrappedResults);
  11705. };
  11706. };
  11707. while (times) {
  11708. attempts.push(retryAttempt(task, !(times-=1)));
  11709. }
  11710. async.series(attempts, function(done, data){
  11711. data = data[data.length - 1];
  11712. (wrappedCallback || callback)(data.err, data.result);
  11713. });
  11714. }
  11715. // If a callback is passed, run this as a controll flow
  11716. return callback ? wrappedTask() : wrappedTask
  11717. };
  11718. async.waterfall = function (tasks, callback) {
  11719. callback = callback || function () {};
  11720. if (!_isArray(tasks)) {
  11721. var err = new Error('First argument to waterfall must be an array of functions');
  11722. return callback(err);
  11723. }
  11724. if (!tasks.length) {
  11725. return callback();
  11726. }
  11727. var wrapIterator = function (iterator) {
  11728. return function (err) {
  11729. if (err) {
  11730. callback.apply(null, arguments);
  11731. callback = function () {};
  11732. }
  11733. else {
  11734. var args = Array.prototype.slice.call(arguments, 1);
  11735. var next = iterator.next();
  11736. if (next) {
  11737. args.push(wrapIterator(next));
  11738. }
  11739. else {
  11740. args.push(callback);
  11741. }
  11742. async.setImmediate(function () {
  11743. iterator.apply(null, args);
  11744. });
  11745. }
  11746. };
  11747. };
  11748. wrapIterator(async.iterator(tasks))();
  11749. };
  11750. var _parallel = function(eachfn, tasks, callback) {
  11751. callback = callback || function () {};
  11752. if (_isArray(tasks)) {
  11753. eachfn.map(tasks, function (fn, callback) {
  11754. if (fn) {
  11755. fn(function (err) {
  11756. var args = Array.prototype.slice.call(arguments, 1);
  11757. if (args.length <= 1) {
  11758. args = args[0];
  11759. }
  11760. callback.call(null, err, args);
  11761. });
  11762. }
  11763. }, callback);
  11764. }
  11765. else {
  11766. var results = {};
  11767. eachfn.each(_keys(tasks), function (k, callback) {
  11768. tasks[k](function (err) {
  11769. var args = Array.prototype.slice.call(arguments, 1);
  11770. if (args.length <= 1) {
  11771. args = args[0];
  11772. }
  11773. results[k] = args;
  11774. callback(err);
  11775. });
  11776. }, function (err) {
  11777. callback(err, results);
  11778. });
  11779. }
  11780. };
  11781. async.parallel = function (tasks, callback) {
  11782. _parallel({ map: async.map, each: async.each }, tasks, callback);
  11783. };
  11784. async.parallelLimit = function(tasks, limit, callback) {
  11785. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  11786. };
  11787. async.series = function (tasks, callback) {
  11788. callback = callback || function () {};
  11789. if (_isArray(tasks)) {
  11790. async.mapSeries(tasks, function (fn, callback) {
  11791. if (fn) {
  11792. fn(function (err) {
  11793. var args = Array.prototype.slice.call(arguments, 1);
  11794. if (args.length <= 1) {
  11795. args = args[0];
  11796. }
  11797. callback.call(null, err, args);
  11798. });
  11799. }
  11800. }, callback);
  11801. }
  11802. else {
  11803. var results = {};
  11804. async.eachSeries(_keys(tasks), function (k, callback) {
  11805. tasks[k](function (err) {
  11806. var args = Array.prototype.slice.call(arguments, 1);
  11807. if (args.length <= 1) {
  11808. args = args[0];
  11809. }
  11810. results[k] = args;
  11811. callback(err);
  11812. });
  11813. }, function (err) {
  11814. callback(err, results);
  11815. });
  11816. }
  11817. };
  11818. async.iterator = function (tasks) {
  11819. var makeCallback = function (index) {
  11820. var fn = function () {
  11821. if (tasks.length) {
  11822. tasks[index].apply(null, arguments);
  11823. }
  11824. return fn.next();
  11825. };
  11826. fn.next = function () {
  11827. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11828. };
  11829. return fn;
  11830. };
  11831. return makeCallback(0);
  11832. };
  11833. async.apply = function (fn) {
  11834. var args = Array.prototype.slice.call(arguments, 1);
  11835. return function () {
  11836. return fn.apply(
  11837. null, args.concat(Array.prototype.slice.call(arguments))
  11838. );
  11839. };
  11840. };
  11841. var _concat = function (eachfn, arr, fn, callback) {
  11842. var r = [];
  11843. eachfn(arr, function (x, cb) {
  11844. fn(x, function (err, y) {
  11845. r = r.concat(y || []);
  11846. cb(err);
  11847. });
  11848. }, function (err) {
  11849. callback(err, r);
  11850. });
  11851. };
  11852. async.concat = doParallel(_concat);
  11853. async.concatSeries = doSeries(_concat);
  11854. async.whilst = function (test, iterator, callback) {
  11855. if (test()) {
  11856. iterator(function (err) {
  11857. if (err) {
  11858. return callback(err);
  11859. }
  11860. async.whilst(test, iterator, callback);
  11861. });
  11862. }
  11863. else {
  11864. callback();
  11865. }
  11866. };
  11867. async.doWhilst = function (iterator, test, callback) {
  11868. iterator(function (err) {
  11869. if (err) {
  11870. return callback(err);
  11871. }
  11872. var args = Array.prototype.slice.call(arguments, 1);
  11873. if (test.apply(null, args)) {
  11874. async.doWhilst(iterator, test, callback);
  11875. }
  11876. else {
  11877. callback();
  11878. }
  11879. });
  11880. };
  11881. async.until = function (test, iterator, callback) {
  11882. if (!test()) {
  11883. iterator(function (err) {
  11884. if (err) {
  11885. return callback(err);
  11886. }
  11887. async.until(test, iterator, callback);
  11888. });
  11889. }
  11890. else {
  11891. callback();
  11892. }
  11893. };
  11894. async.doUntil = function (iterator, test, callback) {
  11895. iterator(function (err) {
  11896. if (err) {
  11897. return callback(err);
  11898. }
  11899. var args = Array.prototype.slice.call(arguments, 1);
  11900. if (!test.apply(null, args)) {
  11901. async.doUntil(iterator, test, callback);
  11902. }
  11903. else {
  11904. callback();
  11905. }
  11906. });
  11907. };
  11908. async.queue = function (worker, concurrency) {
  11909. if (concurrency === undefined) {
  11910. concurrency = 1;
  11911. }
  11912. function _insert(q, data, pos, callback) {
  11913. if (!q.started){
  11914. q.started = true;
  11915. }
  11916. if (!_isArray(data)) {
  11917. data = [data];
  11918. }
  11919. if(data.length == 0) {
  11920. // call drain immediately if there are no tasks
  11921. return async.setImmediate(function() {
  11922. if (q.drain) {
  11923. q.drain();
  11924. }
  11925. });
  11926. }
  11927. _each(data, function(task) {
  11928. var item = {
  11929. data: task,
  11930. callback: typeof callback === 'function' ? callback : null
  11931. };
  11932. if (pos) {
  11933. q.tasks.unshift(item);
  11934. } else {
  11935. q.tasks.push(item);
  11936. }
  11937. if (q.saturated && q.tasks.length === q.concurrency) {
  11938. q.saturated();
  11939. }
  11940. async.setImmediate(q.process);
  11941. });
  11942. }
  11943. var workers = 0;
  11944. var q = {
  11945. tasks: [],
  11946. concurrency: concurrency,
  11947. saturated: null,
  11948. empty: null,
  11949. drain: null,
  11950. started: false,
  11951. paused: false,
  11952. push: function (data, callback) {
  11953. _insert(q, data, false, callback);
  11954. },
  11955. kill: function () {
  11956. q.drain = null;
  11957. q.tasks = [];
  11958. },
  11959. unshift: function (data, callback) {
  11960. _insert(q, data, true, callback);
  11961. },
  11962. process: function () {
  11963. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11964. var task = q.tasks.shift();
  11965. if (q.empty && q.tasks.length === 0) {
  11966. q.empty();
  11967. }
  11968. workers += 1;
  11969. var next = function () {
  11970. workers -= 1;
  11971. if (task.callback) {
  11972. task.callback.apply(task, arguments);
  11973. }
  11974. if (q.drain && q.tasks.length + workers === 0) {
  11975. q.drain();
  11976. }
  11977. q.process();
  11978. };
  11979. var cb = only_once(next);
  11980. worker(task.data, cb);
  11981. }
  11982. },
  11983. length: function () {
  11984. return q.tasks.length;
  11985. },
  11986. running: function () {
  11987. return workers;
  11988. },
  11989. idle: function() {
  11990. return q.tasks.length + workers === 0;
  11991. },
  11992. pause: function () {
  11993. if (q.paused === true) { return; }
  11994. q.paused = true;
  11995. q.process();
  11996. },
  11997. resume: function () {
  11998. if (q.paused === false) { return; }
  11999. q.paused = false;
  12000. q.process();
  12001. }
  12002. };
  12003. return q;
  12004. };
  12005. async.priorityQueue = function (worker, concurrency) {
  12006. function _compareTasks(a, b){
  12007. return a.priority - b.priority;
  12008. };
  12009. function _binarySearch(sequence, item, compare) {
  12010. var beg = -1,
  12011. end = sequence.length - 1;
  12012. while (beg < end) {
  12013. var mid = beg + ((end - beg + 1) >>> 1);
  12014. if (compare(item, sequence[mid]) >= 0) {
  12015. beg = mid;
  12016. } else {
  12017. end = mid - 1;
  12018. }
  12019. }
  12020. return beg;
  12021. }
  12022. function _insert(q, data, priority, callback) {
  12023. if (!q.started){
  12024. q.started = true;
  12025. }
  12026. if (!_isArray(data)) {
  12027. data = [data];
  12028. }
  12029. if(data.length == 0) {
  12030. // call drain immediately if there are no tasks
  12031. return async.setImmediate(function() {
  12032. if (q.drain) {
  12033. q.drain();
  12034. }
  12035. });
  12036. }
  12037. _each(data, function(task) {
  12038. var item = {
  12039. data: task,
  12040. priority: priority,
  12041. callback: typeof callback === 'function' ? callback : null
  12042. };
  12043. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12044. if (q.saturated && q.tasks.length === q.concurrency) {
  12045. q.saturated();
  12046. }
  12047. async.setImmediate(q.process);
  12048. });
  12049. }
  12050. // Start with a normal queue
  12051. var q = async.queue(worker, concurrency);
  12052. // Override push to accept second parameter representing priority
  12053. q.push = function (data, priority, callback) {
  12054. _insert(q, data, priority, callback);
  12055. };
  12056. // Remove unshift function
  12057. delete q.unshift;
  12058. return q;
  12059. };
  12060. async.cargo = function (worker, payload) {
  12061. var working = false,
  12062. tasks = [];
  12063. var cargo = {
  12064. tasks: tasks,
  12065. payload: payload,
  12066. saturated: null,
  12067. empty: null,
  12068. drain: null,
  12069. drained: true,
  12070. push: function (data, callback) {
  12071. if (!_isArray(data)) {
  12072. data = [data];
  12073. }
  12074. _each(data, function(task) {
  12075. tasks.push({
  12076. data: task,
  12077. callback: typeof callback === 'function' ? callback : null
  12078. });
  12079. cargo.drained = false;
  12080. if (cargo.saturated && tasks.length === payload) {
  12081. cargo.saturated();
  12082. }
  12083. });
  12084. async.setImmediate(cargo.process);
  12085. },
  12086. process: function process() {
  12087. if (working) return;
  12088. if (tasks.length === 0) {
  12089. if(cargo.drain && !cargo.drained) cargo.drain();
  12090. cargo.drained = true;
  12091. return;
  12092. }
  12093. var ts = typeof payload === 'number'
  12094. ? tasks.splice(0, payload)
  12095. : tasks.splice(0, tasks.length);
  12096. var ds = _map(ts, function (task) {
  12097. return task.data;
  12098. });
  12099. if(cargo.empty) cargo.empty();
  12100. working = true;
  12101. worker(ds, function () {
  12102. working = false;
  12103. var args = arguments;
  12104. _each(ts, function (data) {
  12105. if (data.callback) {
  12106. data.callback.apply(null, args);
  12107. }
  12108. });
  12109. process();
  12110. });
  12111. },
  12112. length: function () {
  12113. return tasks.length;
  12114. },
  12115. running: function () {
  12116. return working;
  12117. }
  12118. };
  12119. return cargo;
  12120. };
  12121. var _console_fn = function (name) {
  12122. return function (fn) {
  12123. var args = Array.prototype.slice.call(arguments, 1);
  12124. fn.apply(null, args.concat([function (err) {
  12125. var args = Array.prototype.slice.call(arguments, 1);
  12126. if (typeof console !== 'undefined') {
  12127. if (err) {
  12128. if (console.error) {
  12129. console.error(err);
  12130. }
  12131. }
  12132. else if (console[name]) {
  12133. _each(args, function (x) {
  12134. console[name](x);
  12135. });
  12136. }
  12137. }
  12138. }]));
  12139. };
  12140. };
  12141. async.log = _console_fn('log');
  12142. async.dir = _console_fn('dir');
  12143. /*async.info = _console_fn('info');
  12144. async.warn = _console_fn('warn');
  12145. async.error = _console_fn('error');*/
  12146. async.memoize = function (fn, hasher) {
  12147. var memo = {};
  12148. var queues = {};
  12149. hasher = hasher || function (x) {
  12150. return x;
  12151. };
  12152. var memoized = function () {
  12153. var args = Array.prototype.slice.call(arguments);
  12154. var callback = args.pop();
  12155. var key = hasher.apply(null, args);
  12156. if (key in memo) {
  12157. async.nextTick(function () {
  12158. callback.apply(null, memo[key]);
  12159. });
  12160. }
  12161. else if (key in queues) {
  12162. queues[key].push(callback);
  12163. }
  12164. else {
  12165. queues[key] = [callback];
  12166. fn.apply(null, args.concat([function () {
  12167. memo[key] = arguments;
  12168. var q = queues[key];
  12169. delete queues[key];
  12170. for (var i = 0, l = q.length; i < l; i++) {
  12171. q[i].apply(null, arguments);
  12172. }
  12173. }]));
  12174. }
  12175. };
  12176. memoized.memo = memo;
  12177. memoized.unmemoized = fn;
  12178. return memoized;
  12179. };
  12180. async.unmemoize = function (fn) {
  12181. return function () {
  12182. return (fn.unmemoized || fn).apply(null, arguments);
  12183. };
  12184. };
  12185. async.times = function (count, iterator, callback) {
  12186. var counter = [];
  12187. for (var i = 0; i < count; i++) {
  12188. counter.push(i);
  12189. }
  12190. return async.map(counter, iterator, callback);
  12191. };
  12192. async.timesSeries = function (count, iterator, callback) {
  12193. var counter = [];
  12194. for (var i = 0; i < count; i++) {
  12195. counter.push(i);
  12196. }
  12197. return async.mapSeries(counter, iterator, callback);
  12198. };
  12199. async.seq = function (/* functions... */) {
  12200. var fns = arguments;
  12201. return function () {
  12202. var that = this;
  12203. var args = Array.prototype.slice.call(arguments);
  12204. var callback = args.pop();
  12205. async.reduce(fns, args, function (newargs, fn, cb) {
  12206. fn.apply(that, newargs.concat([function () {
  12207. var err = arguments[0];
  12208. var nextargs = Array.prototype.slice.call(arguments, 1);
  12209. cb(err, nextargs);
  12210. }]))
  12211. },
  12212. function (err, results) {
  12213. callback.apply(that, [err].concat(results));
  12214. });
  12215. };
  12216. };
  12217. async.compose = function (/* functions... */) {
  12218. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  12219. };
  12220. var _applyEach = function (eachfn, fns /*args...*/) {
  12221. var go = function () {
  12222. var that = this;
  12223. var args = Array.prototype.slice.call(arguments);
  12224. var callback = args.pop();
  12225. return eachfn(fns, function (fn, cb) {
  12226. fn.apply(that, args.concat([cb]));
  12227. },
  12228. callback);
  12229. };
  12230. if (arguments.length > 2) {
  12231. var args = Array.prototype.slice.call(arguments, 2);
  12232. return go.apply(this, args);
  12233. }
  12234. else {
  12235. return go;
  12236. }
  12237. };
  12238. async.applyEach = doParallel(_applyEach);
  12239. async.applyEachSeries = doSeries(_applyEach);
  12240. async.forever = function (fn, callback) {
  12241. function next(err) {
  12242. if (err) {
  12243. if (callback) {
  12244. return callback(err);
  12245. }
  12246. throw err;
  12247. }
  12248. fn(next);
  12249. }
  12250. next();
  12251. };
  12252. // Node.js
  12253. if (typeof module !== 'undefined' && module.exports) {
  12254. module.exports = async;
  12255. }
  12256. // AMD / RequireJS
  12257. else if (typeof define !== 'undefined' && define.amd) {
  12258. define([], function () {
  12259. return async;
  12260. });
  12261. }
  12262. // included directly via <script> tag
  12263. else {
  12264. root.async = async;
  12265. }
  12266. }());
  12267. }).call(this,require('_process'))
  12268. },{"_process":45}],44:[function(require,module,exports){
  12269. // Copyright Joyent, Inc. and other Node contributors.
  12270. //
  12271. // Permission is hereby granted, free of charge, to any person obtaining a
  12272. // copy of this software and associated documentation files (the
  12273. // "Software"), to deal in the Software without restriction, including
  12274. // without limitation the rights to use, copy, modify, merge, publish,
  12275. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12276. // persons to whom the Software is furnished to do so, subject to the
  12277. // following conditions:
  12278. //
  12279. // The above copyright notice and this permission notice shall be included
  12280. // in all copies or substantial portions of the Software.
  12281. //
  12282. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12283. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12284. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12285. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12286. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12287. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12288. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12289. function EventEmitter() {
  12290. this._events = this._events || {};
  12291. this._maxListeners = this._maxListeners || undefined;
  12292. }
  12293. module.exports = EventEmitter;
  12294. // Backwards-compat with node 0.10.x
  12295. EventEmitter.EventEmitter = EventEmitter;
  12296. EventEmitter.prototype._events = undefined;
  12297. EventEmitter.prototype._maxListeners = undefined;
  12298. // By default EventEmitters will print a warning if more than 10 listeners are
  12299. // added to it. This is a useful default which helps finding memory leaks.
  12300. EventEmitter.defaultMaxListeners = 10;
  12301. // Obviously not all Emitters should be limited to 10. This function allows
  12302. // that to be increased. Set to zero for unlimited.
  12303. EventEmitter.prototype.setMaxListeners = function(n) {
  12304. if (!isNumber(n) || n < 0 || isNaN(n))
  12305. throw TypeError('n must be a positive number');
  12306. this._maxListeners = n;
  12307. return this;
  12308. };
  12309. EventEmitter.prototype.emit = function(type) {
  12310. var er, handler, len, args, i, listeners;
  12311. if (!this._events)
  12312. this._events = {};
  12313. // If there is no 'error' event listener then throw.
  12314. if (type === 'error') {
  12315. if (!this._events.error ||
  12316. (isObject(this._events.error) && !this._events.error.length)) {
  12317. er = arguments[1];
  12318. if (er instanceof Error) {
  12319. throw er; // Unhandled 'error' event
  12320. }
  12321. throw TypeError('Uncaught, unspecified "error" event.');
  12322. }
  12323. }
  12324. handler = this._events[type];
  12325. if (isUndefined(handler))
  12326. return false;
  12327. if (isFunction(handler)) {
  12328. switch (arguments.length) {
  12329. // fast cases
  12330. case 1:
  12331. handler.call(this);
  12332. break;
  12333. case 2:
  12334. handler.call(this, arguments[1]);
  12335. break;
  12336. case 3:
  12337. handler.call(this, arguments[1], arguments[2]);
  12338. break;
  12339. // slower
  12340. default:
  12341. len = arguments.length;
  12342. args = new Array(len - 1);
  12343. for (i = 1; i < len; i++)
  12344. args[i - 1] = arguments[i];
  12345. handler.apply(this, args);
  12346. }
  12347. } else if (isObject(handler)) {
  12348. len = arguments.length;
  12349. args = new Array(len - 1);
  12350. for (i = 1; i < len; i++)
  12351. args[i - 1] = arguments[i];
  12352. listeners = handler.slice();
  12353. len = listeners.length;
  12354. for (i = 0; i < len; i++)
  12355. listeners[i].apply(this, args);
  12356. }
  12357. return true;
  12358. };
  12359. EventEmitter.prototype.addListener = function(type, listener) {
  12360. var m;
  12361. if (!isFunction(listener))
  12362. throw TypeError('listener must be a function');
  12363. if (!this._events)
  12364. this._events = {};
  12365. // To avoid recursion in the case that type === "newListener"! Before
  12366. // adding it to the listeners, first emit "newListener".
  12367. if (this._events.newListener)
  12368. this.emit('newListener', type,
  12369. isFunction(listener.listener) ?
  12370. listener.listener : listener);
  12371. if (!this._events[type])
  12372. // Optimize the case of one listener. Don't need the extra array object.
  12373. this._events[type] = listener;
  12374. else if (isObject(this._events[type]))
  12375. // If we've already got an array, just append.
  12376. this._events[type].push(listener);
  12377. else
  12378. // Adding the second element, need to change to array.
  12379. this._events[type] = [this._events[type], listener];
  12380. // Check for listener leak
  12381. if (isObject(this._events[type]) && !this._events[type].warned) {
  12382. var m;
  12383. if (!isUndefined(this._maxListeners)) {
  12384. m = this._maxListeners;
  12385. } else {
  12386. m = EventEmitter.defaultMaxListeners;
  12387. }
  12388. if (m && m > 0 && this._events[type].length > m) {
  12389. this._events[type].warned = true;
  12390. console.error('(node) warning: possible EventEmitter memory ' +
  12391. 'leak detected. %d listeners added. ' +
  12392. 'Use emitter.setMaxListeners() to increase limit.',
  12393. this._events[type].length);
  12394. if (typeof console.trace === 'function') {
  12395. // not supported in IE 10
  12396. console.trace();
  12397. }
  12398. }
  12399. }
  12400. return this;
  12401. };
  12402. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  12403. EventEmitter.prototype.once = function(type, listener) {
  12404. if (!isFunction(listener))
  12405. throw TypeError('listener must be a function');
  12406. var fired = false;
  12407. function g() {
  12408. this.removeListener(type, g);
  12409. if (!fired) {
  12410. fired = true;
  12411. listener.apply(this, arguments);
  12412. }
  12413. }
  12414. g.listener = listener;
  12415. this.on(type, g);
  12416. return this;
  12417. };
  12418. // emits a 'removeListener' event iff the listener was removed
  12419. EventEmitter.prototype.removeListener = function(type, listener) {
  12420. var list, position, length, i;
  12421. if (!isFunction(listener))
  12422. throw TypeError('listener must be a function');
  12423. if (!this._events || !this._events[type])
  12424. return this;
  12425. list = this._events[type];
  12426. length = list.length;
  12427. position = -1;
  12428. if (list === listener ||
  12429. (isFunction(list.listener) && list.listener === listener)) {
  12430. delete this._events[type];
  12431. if (this._events.removeListener)
  12432. this.emit('removeListener', type, listener);
  12433. } else if (isObject(list)) {
  12434. for (i = length; i-- > 0;) {
  12435. if (list[i] === listener ||
  12436. (list[i].listener && list[i].listener === listener)) {
  12437. position = i;
  12438. break;
  12439. }
  12440. }
  12441. if (position < 0)
  12442. return this;
  12443. if (list.length === 1) {
  12444. list.length = 0;
  12445. delete this._events[type];
  12446. } else {
  12447. list.splice(position, 1);
  12448. }
  12449. if (this._events.removeListener)
  12450. this.emit('removeListener', type, listener);
  12451. }
  12452. return this;
  12453. };
  12454. EventEmitter.prototype.removeAllListeners = function(type) {
  12455. var key, listeners;
  12456. if (!this._events)
  12457. return this;
  12458. // not listening for removeListener, no need to emit
  12459. if (!this._events.removeListener) {
  12460. if (arguments.length === 0)
  12461. this._events = {};
  12462. else if (this._events[type])
  12463. delete this._events[type];
  12464. return this;
  12465. }
  12466. // emit removeListener for all listeners on all events
  12467. if (arguments.length === 0) {
  12468. for (key in this._events) {
  12469. if (key === 'removeListener') continue;
  12470. this.removeAllListeners(key);
  12471. }
  12472. this.removeAllListeners('removeListener');
  12473. this._events = {};
  12474. return this;
  12475. }
  12476. listeners = this._events[type];
  12477. if (isFunction(listeners)) {
  12478. this.removeListener(type, listeners);
  12479. } else {
  12480. // LIFO order
  12481. while (listeners.length)
  12482. this.removeListener(type, listeners[listeners.length - 1]);
  12483. }
  12484. delete this._events[type];
  12485. return this;
  12486. };
  12487. EventEmitter.prototype.listeners = function(type) {
  12488. var ret;
  12489. if (!this._events || !this._events[type])
  12490. ret = [];
  12491. else if (isFunction(this._events[type]))
  12492. ret = [this._events[type]];
  12493. else
  12494. ret = this._events[type].slice();
  12495. return ret;
  12496. };
  12497. EventEmitter.listenerCount = function(emitter, type) {
  12498. var ret;
  12499. if (!emitter._events || !emitter._events[type])
  12500. ret = 0;
  12501. else if (isFunction(emitter._events[type]))
  12502. ret = 1;
  12503. else
  12504. ret = emitter._events[type].length;
  12505. return ret;
  12506. };
  12507. function isFunction(arg) {
  12508. return typeof arg === 'function';
  12509. }
  12510. function isNumber(arg) {
  12511. return typeof arg === 'number';
  12512. }
  12513. function isObject(arg) {
  12514. return typeof arg === 'object' && arg !== null;
  12515. }
  12516. function isUndefined(arg) {
  12517. return arg === void 0;
  12518. }
  12519. },{}],45:[function(require,module,exports){
  12520. // shim for using process in browser
  12521. var process = module.exports = {};
  12522. var queue = [];
  12523. var draining = false;
  12524. var currentQueue;
  12525. var queueIndex = -1;
  12526. function cleanUpNextTick() {
  12527. draining = false;
  12528. if (currentQueue.length) {
  12529. queue = currentQueue.concat(queue);
  12530. } else {
  12531. queueIndex = -1;
  12532. }
  12533. if (queue.length) {
  12534. drainQueue();
  12535. }
  12536. }
  12537. function drainQueue() {
  12538. if (draining) {
  12539. return;
  12540. }
  12541. var timeout = setTimeout(cleanUpNextTick);
  12542. draining = true;
  12543. var len = queue.length;
  12544. while(len) {
  12545. currentQueue = queue;
  12546. queue = [];
  12547. while (++queueIndex < len) {
  12548. if (currentQueue) {
  12549. currentQueue[queueIndex].run();
  12550. }
  12551. }
  12552. queueIndex = -1;
  12553. len = queue.length;
  12554. }
  12555. currentQueue = null;
  12556. draining = false;
  12557. clearTimeout(timeout);
  12558. }
  12559. process.nextTick = function (fun) {
  12560. var args = new Array(arguments.length - 1);
  12561. if (arguments.length > 1) {
  12562. for (var i = 1; i < arguments.length; i++) {
  12563. args[i - 1] = arguments[i];
  12564. }
  12565. }
  12566. queue.push(new Item(fun, args));
  12567. if (queue.length === 1 && !draining) {
  12568. setTimeout(drainQueue, 0);
  12569. }
  12570. };
  12571. // v8 likes predictible objects
  12572. function Item(fun, array) {
  12573. this.fun = fun;
  12574. this.array = array;
  12575. }
  12576. Item.prototype.run = function () {
  12577. this.fun.apply(null, this.array);
  12578. };
  12579. process.title = 'browser';
  12580. process.browser = true;
  12581. process.env = {};
  12582. process.argv = [];
  12583. process.version = ''; // empty string to avoid regexp issues
  12584. process.versions = {};
  12585. function noop() {}
  12586. process.on = noop;
  12587. process.addListener = noop;
  12588. process.once = noop;
  12589. process.off = noop;
  12590. process.removeListener = noop;
  12591. process.removeAllListeners = noop;
  12592. process.emit = noop;
  12593. process.binding = function (name) {
  12594. throw new Error('process.binding is not supported');
  12595. };
  12596. process.cwd = function () { return '/' };
  12597. process.chdir = function (dir) {
  12598. throw new Error('process.chdir is not supported');
  12599. };
  12600. process.umask = function() { return 0; };
  12601. },{}],46:[function(require,module,exports){
  12602. (function (process,global){
  12603. /*!
  12604. * @overview es6-promise - a tiny implementation of Promises/A+.
  12605. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  12606. * @license Licensed under MIT license
  12607. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  12608. * @version 3.0.2
  12609. */
  12610. (function() {
  12611. "use strict";
  12612. function lib$es6$promise$utils$$objectOrFunction(x) {
  12613. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  12614. }
  12615. function lib$es6$promise$utils$$isFunction(x) {
  12616. return typeof x === 'function';
  12617. }
  12618. function lib$es6$promise$utils$$isMaybeThenable(x) {
  12619. return typeof x === 'object' && x !== null;
  12620. }
  12621. var lib$es6$promise$utils$$_isArray;
  12622. if (!Array.isArray) {
  12623. lib$es6$promise$utils$$_isArray = function (x) {
  12624. return Object.prototype.toString.call(x) === '[object Array]';
  12625. };
  12626. } else {
  12627. lib$es6$promise$utils$$_isArray = Array.isArray;
  12628. }
  12629. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  12630. var lib$es6$promise$asap$$len = 0;
  12631. var lib$es6$promise$asap$$toString = {}.toString;
  12632. var lib$es6$promise$asap$$vertxNext;
  12633. var lib$es6$promise$asap$$customSchedulerFn;
  12634. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  12635. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  12636. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  12637. lib$es6$promise$asap$$len += 2;
  12638. if (lib$es6$promise$asap$$len === 2) {
  12639. // If len is 2, that means that we need to schedule an async flush.
  12640. // If additional callbacks are queued before the queue is flushed, they
  12641. // will be processed by this flush that we are scheduling.
  12642. if (lib$es6$promise$asap$$customSchedulerFn) {
  12643. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  12644. } else {
  12645. lib$es6$promise$asap$$scheduleFlush();
  12646. }
  12647. }
  12648. }
  12649. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  12650. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  12651. }
  12652. function lib$es6$promise$asap$$setAsap(asapFn) {
  12653. lib$es6$promise$asap$$asap = asapFn;
  12654. }
  12655. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  12656. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  12657. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  12658. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  12659. // test for web worker but not in IE10
  12660. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  12661. typeof importScripts !== 'undefined' &&
  12662. typeof MessageChannel !== 'undefined';
  12663. // node
  12664. function lib$es6$promise$asap$$useNextTick() {
  12665. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  12666. // see https://github.com/cujojs/when/issues/410 for details
  12667. return function() {
  12668. process.nextTick(lib$es6$promise$asap$$flush);
  12669. };
  12670. }
  12671. // vertx
  12672. function lib$es6$promise$asap$$useVertxTimer() {
  12673. return function() {
  12674. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  12675. };
  12676. }
  12677. function lib$es6$promise$asap$$useMutationObserver() {
  12678. var iterations = 0;
  12679. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  12680. var node = document.createTextNode('');
  12681. observer.observe(node, { characterData: true });
  12682. return function() {
  12683. node.data = (iterations = ++iterations % 2);
  12684. };
  12685. }
  12686. // web worker
  12687. function lib$es6$promise$asap$$useMessageChannel() {
  12688. var channel = new MessageChannel();
  12689. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  12690. return function () {
  12691. channel.port2.postMessage(0);
  12692. };
  12693. }
  12694. function lib$es6$promise$asap$$useSetTimeout() {
  12695. return function() {
  12696. setTimeout(lib$es6$promise$asap$$flush, 1);
  12697. };
  12698. }
  12699. var lib$es6$promise$asap$$queue = new Array(1000);
  12700. function lib$es6$promise$asap$$flush() {
  12701. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  12702. var callback = lib$es6$promise$asap$$queue[i];
  12703. var arg = lib$es6$promise$asap$$queue[i+1];
  12704. callback(arg);
  12705. lib$es6$promise$asap$$queue[i] = undefined;
  12706. lib$es6$promise$asap$$queue[i+1] = undefined;
  12707. }
  12708. lib$es6$promise$asap$$len = 0;
  12709. }
  12710. function lib$es6$promise$asap$$attemptVertx() {
  12711. try {
  12712. var r = require;
  12713. var vertx = r('vertx');
  12714. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  12715. return lib$es6$promise$asap$$useVertxTimer();
  12716. } catch(e) {
  12717. return lib$es6$promise$asap$$useSetTimeout();
  12718. }
  12719. }
  12720. var lib$es6$promise$asap$$scheduleFlush;
  12721. // Decide what async method to use to triggering processing of queued callbacks:
  12722. if (lib$es6$promise$asap$$isNode) {
  12723. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  12724. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  12725. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  12726. } else if (lib$es6$promise$asap$$isWorker) {
  12727. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  12728. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  12729. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  12730. } else {
  12731. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  12732. }
  12733. function lib$es6$promise$$internal$$noop() {}
  12734. var lib$es6$promise$$internal$$PENDING = void 0;
  12735. var lib$es6$promise$$internal$$FULFILLED = 1;
  12736. var lib$es6$promise$$internal$$REJECTED = 2;
  12737. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12738. function lib$es6$promise$$internal$$selfFulfillment() {
  12739. return new TypeError("You cannot resolve a promise with itself");
  12740. }
  12741. function lib$es6$promise$$internal$$cannotReturnOwn() {
  12742. return new TypeError('A promises callback cannot return that same promise.');
  12743. }
  12744. function lib$es6$promise$$internal$$getThen(promise) {
  12745. try {
  12746. return promise.then;
  12747. } catch(error) {
  12748. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  12749. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  12750. }
  12751. }
  12752. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  12753. try {
  12754. then.call(value, fulfillmentHandler, rejectionHandler);
  12755. } catch(e) {
  12756. return e;
  12757. }
  12758. }
  12759. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  12760. lib$es6$promise$asap$$asap(function(promise) {
  12761. var sealed = false;
  12762. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  12763. if (sealed) { return; }
  12764. sealed = true;
  12765. if (thenable !== value) {
  12766. lib$es6$promise$$internal$$resolve(promise, value);
  12767. } else {
  12768. lib$es6$promise$$internal$$fulfill(promise, value);
  12769. }
  12770. }, function(reason) {
  12771. if (sealed) { return; }
  12772. sealed = true;
  12773. lib$es6$promise$$internal$$reject(promise, reason);
  12774. }, 'Settle: ' + (promise._label || ' unknown promise'));
  12775. if (!sealed && error) {
  12776. sealed = true;
  12777. lib$es6$promise$$internal$$reject(promise, error);
  12778. }
  12779. }, promise);
  12780. }
  12781. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  12782. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  12783. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  12784. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  12785. lib$es6$promise$$internal$$reject(promise, thenable._result);
  12786. } else {
  12787. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  12788. lib$es6$promise$$internal$$resolve(promise, value);
  12789. }, function(reason) {
  12790. lib$es6$promise$$internal$$reject(promise, reason);
  12791. });
  12792. }
  12793. }
  12794. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12795. if (maybeThenable.constructor === promise.constructor) {
  12796. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12797. } else {
  12798. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12799. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12800. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12801. } else if (then === undefined) {
  12802. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12803. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12804. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12805. } else {
  12806. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12807. }
  12808. }
  12809. }
  12810. function lib$es6$promise$$internal$$resolve(promise, value) {
  12811. if (promise === value) {
  12812. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12813. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12814. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12815. } else {
  12816. lib$es6$promise$$internal$$fulfill(promise, value);
  12817. }
  12818. }
  12819. function lib$es6$promise$$internal$$publishRejection(promise) {
  12820. if (promise._onerror) {
  12821. promise._onerror(promise._result);
  12822. }
  12823. lib$es6$promise$$internal$$publish(promise);
  12824. }
  12825. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12826. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12827. promise._result = value;
  12828. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12829. if (promise._subscribers.length !== 0) {
  12830. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12831. }
  12832. }
  12833. function lib$es6$promise$$internal$$reject(promise, reason) {
  12834. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12835. promise._state = lib$es6$promise$$internal$$REJECTED;
  12836. promise._result = reason;
  12837. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12838. }
  12839. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12840. var subscribers = parent._subscribers;
  12841. var length = subscribers.length;
  12842. parent._onerror = null;
  12843. subscribers[length] = child;
  12844. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12845. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12846. if (length === 0 && parent._state) {
  12847. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12848. }
  12849. }
  12850. function lib$es6$promise$$internal$$publish(promise) {
  12851. var subscribers = promise._subscribers;
  12852. var settled = promise._state;
  12853. if (subscribers.length === 0) { return; }
  12854. var child, callback, detail = promise._result;
  12855. for (var i = 0; i < subscribers.length; i += 3) {
  12856. child = subscribers[i];
  12857. callback = subscribers[i + settled];
  12858. if (child) {
  12859. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12860. } else {
  12861. callback(detail);
  12862. }
  12863. }
  12864. promise._subscribers.length = 0;
  12865. }
  12866. function lib$es6$promise$$internal$$ErrorObject() {
  12867. this.error = null;
  12868. }
  12869. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12870. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12871. try {
  12872. return callback(detail);
  12873. } catch(e) {
  12874. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12875. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12876. }
  12877. }
  12878. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12879. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12880. value, error, succeeded, failed;
  12881. if (hasCallback) {
  12882. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12883. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12884. failed = true;
  12885. error = value.error;
  12886. value = null;
  12887. } else {
  12888. succeeded = true;
  12889. }
  12890. if (promise === value) {
  12891. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12892. return;
  12893. }
  12894. } else {
  12895. value = detail;
  12896. succeeded = true;
  12897. }
  12898. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12899. // noop
  12900. } else if (hasCallback && succeeded) {
  12901. lib$es6$promise$$internal$$resolve(promise, value);
  12902. } else if (failed) {
  12903. lib$es6$promise$$internal$$reject(promise, error);
  12904. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12905. lib$es6$promise$$internal$$fulfill(promise, value);
  12906. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12907. lib$es6$promise$$internal$$reject(promise, value);
  12908. }
  12909. }
  12910. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12911. try {
  12912. resolver(function resolvePromise(value){
  12913. lib$es6$promise$$internal$$resolve(promise, value);
  12914. }, function rejectPromise(reason) {
  12915. lib$es6$promise$$internal$$reject(promise, reason);
  12916. });
  12917. } catch(e) {
  12918. lib$es6$promise$$internal$$reject(promise, e);
  12919. }
  12920. }
  12921. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12922. var enumerator = this;
  12923. enumerator._instanceConstructor = Constructor;
  12924. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12925. if (enumerator._validateInput(input)) {
  12926. enumerator._input = input;
  12927. enumerator.length = input.length;
  12928. enumerator._remaining = input.length;
  12929. enumerator._init();
  12930. if (enumerator.length === 0) {
  12931. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12932. } else {
  12933. enumerator.length = enumerator.length || 0;
  12934. enumerator._enumerate();
  12935. if (enumerator._remaining === 0) {
  12936. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12937. }
  12938. }
  12939. } else {
  12940. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12941. }
  12942. }
  12943. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12944. return lib$es6$promise$utils$$isArray(input);
  12945. };
  12946. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12947. return new Error('Array Methods must be provided an Array');
  12948. };
  12949. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12950. this._result = new Array(this.length);
  12951. };
  12952. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12953. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12954. var enumerator = this;
  12955. var length = enumerator.length;
  12956. var promise = enumerator.promise;
  12957. var input = enumerator._input;
  12958. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12959. enumerator._eachEntry(input[i], i);
  12960. }
  12961. };
  12962. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12963. var enumerator = this;
  12964. var c = enumerator._instanceConstructor;
  12965. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12966. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12967. entry._onerror = null;
  12968. enumerator._settledAt(entry._state, i, entry._result);
  12969. } else {
  12970. enumerator._willSettleAt(c.resolve(entry), i);
  12971. }
  12972. } else {
  12973. enumerator._remaining--;
  12974. enumerator._result[i] = entry;
  12975. }
  12976. };
  12977. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12978. var enumerator = this;
  12979. var promise = enumerator.promise;
  12980. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12981. enumerator._remaining--;
  12982. if (state === lib$es6$promise$$internal$$REJECTED) {
  12983. lib$es6$promise$$internal$$reject(promise, value);
  12984. } else {
  12985. enumerator._result[i] = value;
  12986. }
  12987. }
  12988. if (enumerator._remaining === 0) {
  12989. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12990. }
  12991. };
  12992. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12993. var enumerator = this;
  12994. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12995. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12996. }, function(reason) {
  12997. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12998. });
  12999. };
  13000. function lib$es6$promise$promise$all$$all(entries) {
  13001. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  13002. }
  13003. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  13004. function lib$es6$promise$promise$race$$race(entries) {
  13005. /*jshint validthis:true */
  13006. var Constructor = this;
  13007. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13008. if (!lib$es6$promise$utils$$isArray(entries)) {
  13009. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  13010. return promise;
  13011. }
  13012. var length = entries.length;
  13013. function onFulfillment(value) {
  13014. lib$es6$promise$$internal$$resolve(promise, value);
  13015. }
  13016. function onRejection(reason) {
  13017. lib$es6$promise$$internal$$reject(promise, reason);
  13018. }
  13019. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13020. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  13021. }
  13022. return promise;
  13023. }
  13024. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  13025. function lib$es6$promise$promise$resolve$$resolve(object) {
  13026. /*jshint validthis:true */
  13027. var Constructor = this;
  13028. if (object && typeof object === 'object' && object.constructor === Constructor) {
  13029. return object;
  13030. }
  13031. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13032. lib$es6$promise$$internal$$resolve(promise, object);
  13033. return promise;
  13034. }
  13035. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  13036. function lib$es6$promise$promise$reject$$reject(reason) {
  13037. /*jshint validthis:true */
  13038. var Constructor = this;
  13039. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13040. lib$es6$promise$$internal$$reject(promise, reason);
  13041. return promise;
  13042. }
  13043. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  13044. var lib$es6$promise$promise$$counter = 0;
  13045. function lib$es6$promise$promise$$needsResolver() {
  13046. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  13047. }
  13048. function lib$es6$promise$promise$$needsNew() {
  13049. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  13050. }
  13051. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  13052. /**
  13053. Promise objects represent the eventual result of an asynchronous operation. The
  13054. primary way of interacting with a promise is through its `then` method, which
  13055. registers callbacks to receive either a promise's eventual value or the reason
  13056. why the promise cannot be fulfilled.
  13057. Terminology
  13058. -----------
  13059. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  13060. - `thenable` is an object or function that defines a `then` method.
  13061. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  13062. - `exception` is a value that is thrown using the throw statement.
  13063. - `reason` is a value that indicates why a promise was rejected.
  13064. - `settled` the final resting state of a promise, fulfilled or rejected.
  13065. A promise can be in one of three states: pending, fulfilled, or rejected.
  13066. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  13067. state. Promises that are rejected have a rejection reason and are in the
  13068. rejected state. A fulfillment value is never a thenable.
  13069. Promises can also be said to *resolve* a value. If this value is also a
  13070. promise, then the original promise's settled state will match the value's
  13071. settled state. So a promise that *resolves* a promise that rejects will
  13072. itself reject, and a promise that *resolves* a promise that fulfills will
  13073. itself fulfill.
  13074. Basic Usage:
  13075. ------------
  13076. ```js
  13077. var promise = new Promise(function(resolve, reject) {
  13078. // on success
  13079. resolve(value);
  13080. // on failure
  13081. reject(reason);
  13082. });
  13083. promise.then(function(value) {
  13084. // on fulfillment
  13085. }, function(reason) {
  13086. // on rejection
  13087. });
  13088. ```
  13089. Advanced Usage:
  13090. ---------------
  13091. Promises shine when abstracting away asynchronous interactions such as
  13092. `XMLHttpRequest`s.
  13093. ```js
  13094. function getJSON(url) {
  13095. return new Promise(function(resolve, reject){
  13096. var xhr = new XMLHttpRequest();
  13097. xhr.open('GET', url);
  13098. xhr.onreadystatechange = handler;
  13099. xhr.responseType = 'json';
  13100. xhr.setRequestHeader('Accept', 'application/json');
  13101. xhr.send();
  13102. function handler() {
  13103. if (this.readyState === this.DONE) {
  13104. if (this.status === 200) {
  13105. resolve(this.response);
  13106. } else {
  13107. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  13108. }
  13109. }
  13110. };
  13111. });
  13112. }
  13113. getJSON('/posts.json').then(function(json) {
  13114. // on fulfillment
  13115. }, function(reason) {
  13116. // on rejection
  13117. });
  13118. ```
  13119. Unlike callbacks, promises are great composable primitives.
  13120. ```js
  13121. Promise.all([
  13122. getJSON('/posts'),
  13123. getJSON('/comments')
  13124. ]).then(function(values){
  13125. values[0] // => postsJSON
  13126. values[1] // => commentsJSON
  13127. return values;
  13128. });
  13129. ```
  13130. @class Promise
  13131. @param {function} resolver
  13132. Useful for tooling.
  13133. @constructor
  13134. */
  13135. function lib$es6$promise$promise$$Promise(resolver) {
  13136. this._id = lib$es6$promise$promise$$counter++;
  13137. this._state = undefined;
  13138. this._result = undefined;
  13139. this._subscribers = [];
  13140. if (lib$es6$promise$$internal$$noop !== resolver) {
  13141. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  13142. lib$es6$promise$promise$$needsResolver();
  13143. }
  13144. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  13145. lib$es6$promise$promise$$needsNew();
  13146. }
  13147. lib$es6$promise$$internal$$initializePromise(this, resolver);
  13148. }
  13149. }
  13150. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  13151. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  13152. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  13153. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  13154. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  13155. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  13156. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  13157. lib$es6$promise$promise$$Promise.prototype = {
  13158. constructor: lib$es6$promise$promise$$Promise,
  13159. /**
  13160. The primary way of interacting with a promise is through its `then` method,
  13161. which registers callbacks to receive either a promise's eventual value or the
  13162. reason why the promise cannot be fulfilled.
  13163. ```js
  13164. findUser().then(function(user){
  13165. // user is available
  13166. }, function(reason){
  13167. // user is unavailable, and you are given the reason why
  13168. });
  13169. ```
  13170. Chaining
  13171. --------
  13172. The return value of `then` is itself a promise. This second, 'downstream'
  13173. promise is resolved with the return value of the first promise's fulfillment
  13174. or rejection handler, or rejected if the handler throws an exception.
  13175. ```js
  13176. findUser().then(function (user) {
  13177. return user.name;
  13178. }, function (reason) {
  13179. return 'default name';
  13180. }).then(function (userName) {
  13181. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  13182. // will be `'default name'`
  13183. });
  13184. findUser().then(function (user) {
  13185. throw new Error('Found user, but still unhappy');
  13186. }, function (reason) {
  13187. throw new Error('`findUser` rejected and we're unhappy');
  13188. }).then(function (value) {
  13189. // never reached
  13190. }, function (reason) {
  13191. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  13192. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  13193. });
  13194. ```
  13195. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  13196. ```js
  13197. findUser().then(function (user) {
  13198. throw new PedagogicalException('Upstream error');
  13199. }).then(function (value) {
  13200. // never reached
  13201. }).then(function (value) {
  13202. // never reached
  13203. }, function (reason) {
  13204. // The `PedgagocialException` is propagated all the way down to here
  13205. });
  13206. ```
  13207. Assimilation
  13208. ------------
  13209. Sometimes the value you want to propagate to a downstream promise can only be
  13210. retrieved asynchronously. This can be achieved by returning a promise in the
  13211. fulfillment or rejection handler. The downstream promise will then be pending
  13212. until the returned promise is settled. This is called *assimilation*.
  13213. ```js
  13214. findUser().then(function (user) {
  13215. return findCommentsByAuthor(user);
  13216. }).then(function (comments) {
  13217. // The user's comments are now available
  13218. });
  13219. ```
  13220. If the assimliated promise rejects, then the downstream promise will also reject.
  13221. ```js
  13222. findUser().then(function (user) {
  13223. return findCommentsByAuthor(user);
  13224. }).then(function (comments) {
  13225. // If `findCommentsByAuthor` fulfills, we'll have the value here
  13226. }, function (reason) {
  13227. // If `findCommentsByAuthor` rejects, we'll have the reason here
  13228. });
  13229. ```
  13230. Simple Example
  13231. --------------
  13232. Synchronous Example
  13233. ```javascript
  13234. var result;
  13235. try {
  13236. result = findResult();
  13237. // success
  13238. } catch(reason) {
  13239. // failure
  13240. }
  13241. ```
  13242. Errback Example
  13243. ```js
  13244. findResult(function(result, err){
  13245. if (err) {
  13246. // failure
  13247. } else {
  13248. // success
  13249. }
  13250. });
  13251. ```
  13252. Promise Example;
  13253. ```javascript
  13254. findResult().then(function(result){
  13255. // success
  13256. }, function(reason){
  13257. // failure
  13258. });
  13259. ```
  13260. Advanced Example
  13261. --------------
  13262. Synchronous Example
  13263. ```javascript
  13264. var author, books;
  13265. try {
  13266. author = findAuthor();
  13267. books = findBooksByAuthor(author);
  13268. // success
  13269. } catch(reason) {
  13270. // failure
  13271. }
  13272. ```
  13273. Errback Example
  13274. ```js
  13275. function foundBooks(books) {
  13276. }
  13277. function failure(reason) {
  13278. }
  13279. findAuthor(function(author, err){
  13280. if (err) {
  13281. failure(err);
  13282. // failure
  13283. } else {
  13284. try {
  13285. findBoooksByAuthor(author, function(books, err) {
  13286. if (err) {
  13287. failure(err);
  13288. } else {
  13289. try {
  13290. foundBooks(books);
  13291. } catch(reason) {
  13292. failure(reason);
  13293. }
  13294. }
  13295. });
  13296. } catch(error) {
  13297. failure(err);
  13298. }
  13299. // success
  13300. }
  13301. });
  13302. ```
  13303. Promise Example;
  13304. ```javascript
  13305. findAuthor().
  13306. then(findBooksByAuthor).
  13307. then(function(books){
  13308. // found books
  13309. }).catch(function(reason){
  13310. // something went wrong
  13311. });
  13312. ```
  13313. @method then
  13314. @param {Function} onFulfilled
  13315. @param {Function} onRejected
  13316. Useful for tooling.
  13317. @return {Promise}
  13318. */
  13319. then: function(onFulfillment, onRejection) {
  13320. var parent = this;
  13321. var state = parent._state;
  13322. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  13323. return this;
  13324. }
  13325. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  13326. var result = parent._result;
  13327. if (state) {
  13328. var callback = arguments[state - 1];
  13329. lib$es6$promise$asap$$asap(function(){
  13330. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  13331. });
  13332. } else {
  13333. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  13334. }
  13335. return child;
  13336. },
  13337. /**
  13338. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  13339. as the catch block of a try/catch statement.
  13340. ```js
  13341. function findAuthor(){
  13342. throw new Error('couldn't find that author');
  13343. }
  13344. // synchronous
  13345. try {
  13346. findAuthor();
  13347. } catch(reason) {
  13348. // something went wrong
  13349. }
  13350. // async with promises
  13351. findAuthor().catch(function(reason){
  13352. // something went wrong
  13353. });
  13354. ```
  13355. @method catch
  13356. @param {Function} onRejection
  13357. Useful for tooling.
  13358. @return {Promise}
  13359. */
  13360. 'catch': function(onRejection) {
  13361. return this.then(null, onRejection);
  13362. }
  13363. };
  13364. function lib$es6$promise$polyfill$$polyfill() {
  13365. var local;
  13366. if (typeof global !== 'undefined') {
  13367. local = global;
  13368. } else if (typeof self !== 'undefined') {
  13369. local = self;
  13370. } else {
  13371. try {
  13372. local = Function('return this')();
  13373. } catch (e) {
  13374. throw new Error('polyfill failed because global object is unavailable in this environment');
  13375. }
  13376. }
  13377. var P = local.Promise;
  13378. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  13379. return;
  13380. }
  13381. local.Promise = lib$es6$promise$promise$$default;
  13382. }
  13383. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  13384. var lib$es6$promise$umd$$ES6Promise = {
  13385. 'Promise': lib$es6$promise$promise$$default,
  13386. 'polyfill': lib$es6$promise$polyfill$$default
  13387. };
  13388. /* global define:true module:true window: true */
  13389. if (typeof define === 'function' && define['amd']) {
  13390. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  13391. } else if (typeof module !== 'undefined' && module['exports']) {
  13392. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  13393. } else if (typeof this !== 'undefined') {
  13394. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  13395. }
  13396. lib$es6$promise$polyfill$$default();
  13397. }).call(this);
  13398. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13399. },{"_process":45}],47:[function(require,module,exports){
  13400. /* Copyright @ 2015 Atlassian Pty Ltd
  13401. *
  13402. * Licensed under the Apache License, Version 2.0 (the "License");
  13403. * you may not use this file except in compliance with the License.
  13404. * You may obtain a copy of the License at
  13405. *
  13406. * http://www.apache.org/licenses/LICENSE-2.0
  13407. *
  13408. * Unless required by applicable law or agreed to in writing, software
  13409. * distributed under the License is distributed on an "AS IS" BASIS,
  13410. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13411. * See the License for the specific language governing permissions and
  13412. * limitations under the License.
  13413. */
  13414. /**
  13415. * Ordered log levels.
  13416. */
  13417. var levels = {
  13418. "trace": 0,
  13419. "debug": 1,
  13420. "info": 2,
  13421. "log": 3,
  13422. "warn": 4,
  13423. "error": 5
  13424. };
  13425. /**
  13426. * Parses Error's object stack trace and extracts information about the last
  13427. * caller before the log method was called.
  13428. * @returns JS object with info about the caller - method name, file location,
  13429. * line and column.
  13430. */
  13431. function getCallerInfo() {
  13432. var callerInfo = {
  13433. methodName: "",
  13434. fileLocation: "",
  13435. line: null,
  13436. column: null
  13437. };
  13438. //gets the part of the stack without the logger wrappers
  13439. var error = new Error();
  13440. var stack = error.stack? error.stack.split("\n") : [];
  13441. if(!stack || stack.length < 1) {
  13442. return callerInfo;
  13443. }
  13444. var m = null;
  13445. if(stack[3]) {
  13446. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  13447. }
  13448. if(!m || m.length <= 4) {
  13449. //Firefox && Safari
  13450. if(stack[2].indexOf("log@") === 0){
  13451. //Safari
  13452. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  13453. } else {
  13454. //Firefox
  13455. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  13456. }
  13457. return callerInfo;
  13458. }
  13459. callerInfo.methodName = m[1];
  13460. callerInfo.fileLocation = m[2];
  13461. callerInfo.line = m[3];
  13462. callerInfo.column = m[4];
  13463. return callerInfo;
  13464. }
  13465. /**
  13466. * Logs messages using the transports and level from the logger.
  13467. * @param logger a logger instance.
  13468. * @param level the log level of the message. See the levels variable.
  13469. * @param arguments array with arguments that will be logged.
  13470. */
  13471. function log() {
  13472. var logger = arguments[0], level = arguments[1],
  13473. args = Array.prototype.slice.call(arguments, 2);
  13474. if(levels[level] <= logger.level) {
  13475. return;
  13476. }
  13477. var callerInfo = getCallerInfo();
  13478. for(var i = 0; i < logger.transports.length; i++) {
  13479. var t = logger.transports[i];
  13480. var l = t[level];
  13481. if(l && typeof(l) === "function") {
  13482. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  13483. .apply(t, args);
  13484. }
  13485. }
  13486. }
  13487. /**
  13488. *
  13489. * Constructs new logger object.
  13490. * @param level the logging level for the new logger
  13491. * @param id optional identifier for the logger instance.
  13492. * @param transports optional list of handlers(objects) for the logs.
  13493. * The handlers must support - log, warn, error, debug, info, trace.
  13494. * @param format optional (NOT implemented) string.
  13495. */
  13496. function Logger(level, id, transports, format) {
  13497. this.id = id;
  13498. this.format = format;
  13499. if(!this.transports) {
  13500. this.transports = [];
  13501. this.transports.push(Logger.consoleTransport);
  13502. }
  13503. this.level = levels[level];
  13504. var methods = Object.keys(levels);
  13505. for(var i = 0; i < methods.length; i++){
  13506. this[methods[i]] =
  13507. log.bind(null, this, methods[i]);
  13508. }
  13509. }
  13510. /**
  13511. * Sets the log level for the logger.
  13512. * @param level the new log level.
  13513. */
  13514. Logger.prototype.setLevel = function (level) {
  13515. this.level = levels[level];
  13516. };
  13517. module.exports = Logger;
  13518. /**
  13519. * The default transport - console
  13520. */
  13521. Logger.consoleTransport = console;
  13522. /**
  13523. * Enum for the supported log levels.
  13524. */
  13525. Logger.levels = {
  13526. TRACE: "trace",
  13527. DEBUG: "debug",
  13528. INFO: "info",
  13529. LOG: "log",
  13530. WARN: "warn",
  13531. ERROR: "error"
  13532. };
  13533. },{}],48:[function(require,module,exports){
  13534. /* Copyright @ 2015 Atlassian Pty Ltd
  13535. *
  13536. * Licensed under the Apache License, Version 2.0 (the "License");
  13537. * you may not use this file except in compliance with the License.
  13538. * You may obtain a copy of the License at
  13539. *
  13540. * http://www.apache.org/licenses/LICENSE-2.0
  13541. *
  13542. * Unless required by applicable law or agreed to in writing, software
  13543. * distributed under the License is distributed on an "AS IS" BASIS,
  13544. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13545. * See the License for the specific language governing permissions and
  13546. * limitations under the License.
  13547. */
  13548. var Logger = require("./Logger");
  13549. /**
  13550. * Map with the created loggers with ID.
  13551. */
  13552. var idLoggers = {};
  13553. /**
  13554. * Array with the loggers without id.
  13555. */
  13556. var loggers = [];
  13557. /**
  13558. * Log level for the lbrary.
  13559. */
  13560. var curLevel = Logger.levels.TRACE;
  13561. module.exports = {
  13562. /**
  13563. * Creates new logger.
  13564. * @arguments the same as Logger constructor
  13565. */
  13566. getLogger: function(id, transports, format) {
  13567. var logger = new Logger(curLevel, id, transports, format);
  13568. if(id) {
  13569. idLoggers[id] = idLoggers[id] || [];
  13570. idLoggers[id].push(logger);
  13571. } else {
  13572. loggers.push(logger);
  13573. }
  13574. return logger;
  13575. },
  13576. /**
  13577. * Changes the log level for the existing loggers by id.
  13578. * @param level the new log level.
  13579. * @param id if specified the level will be changed only for loggers with the
  13580. * same id. Otherwise the operation will affect all loggers that don't
  13581. * have id.
  13582. */
  13583. setLogLevelById: function(level, id) {
  13584. var l = id? (idLoggers[id] || []) : loggers;
  13585. for(var i = 0; i < l.length; i++) {
  13586. l[i].setLevel(level);
  13587. }
  13588. },
  13589. /**
  13590. * Changes the log level for all existing loggers.
  13591. * @param level the new log level.
  13592. */
  13593. setLogLevel: function (level) {
  13594. curLevel = level;
  13595. var i = 0;
  13596. for(; i < loggers.length; i++) {
  13597. loggers[i].setLevel(level);
  13598. }
  13599. for(var id in idLoggers) {
  13600. var l = idLoggers[id] || [];
  13601. for(i = 0; i < l.length; i++) {
  13602. l[i].setLevel(level);
  13603. }
  13604. }
  13605. },
  13606. /**
  13607. * The supported log levels.
  13608. */
  13609. levels: Logger.levels
  13610. };
  13611. },{"./Logger":47}],49:[function(require,module,exports){
  13612. // Top level file is just a mixin of submodules & constants
  13613. 'use strict';
  13614. var assign = require('./lib/utils/common').assign;
  13615. var deflate = require('./lib/deflate');
  13616. var inflate = require('./lib/inflate');
  13617. var constants = require('./lib/zlib/constants');
  13618. var pako = {};
  13619. assign(pako, deflate, inflate, constants);
  13620. module.exports = pako;
  13621. },{"./lib/deflate":50,"./lib/inflate":51,"./lib/utils/common":52,"./lib/zlib/constants":55}],50:[function(require,module,exports){
  13622. 'use strict';
  13623. var zlib_deflate = require('./zlib/deflate.js');
  13624. var utils = require('./utils/common');
  13625. var strings = require('./utils/strings');
  13626. var msg = require('./zlib/messages');
  13627. var zstream = require('./zlib/zstream');
  13628. var toString = Object.prototype.toString;
  13629. /* Public constants ==========================================================*/
  13630. /* ===========================================================================*/
  13631. var Z_NO_FLUSH = 0;
  13632. var Z_FINISH = 4;
  13633. var Z_OK = 0;
  13634. var Z_STREAM_END = 1;
  13635. var Z_SYNC_FLUSH = 2;
  13636. var Z_DEFAULT_COMPRESSION = -1;
  13637. var Z_DEFAULT_STRATEGY = 0;
  13638. var Z_DEFLATED = 8;
  13639. /* ===========================================================================*/
  13640. /**
  13641. * class Deflate
  13642. *
  13643. * Generic JS-style wrapper for zlib calls. If you don't need
  13644. * streaming behaviour - use more simple functions: [[deflate]],
  13645. * [[deflateRaw]] and [[gzip]].
  13646. **/
  13647. /* internal
  13648. * Deflate.chunks -> Array
  13649. *
  13650. * Chunks of output data, if [[Deflate#onData]] not overriden.
  13651. **/
  13652. /**
  13653. * Deflate.result -> Uint8Array|Array
  13654. *
  13655. * Compressed result, generated by default [[Deflate#onData]]
  13656. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  13657. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  13658. * push a chunk with explicit flush (call [[Deflate#push]] with
  13659. * `Z_SYNC_FLUSH` param).
  13660. **/
  13661. /**
  13662. * Deflate.err -> Number
  13663. *
  13664. * Error code after deflate finished. 0 (Z_OK) on success.
  13665. * You will not need it in real life, because deflate errors
  13666. * are possible only on wrong options or bad `onData` / `onEnd`
  13667. * custom handlers.
  13668. **/
  13669. /**
  13670. * Deflate.msg -> String
  13671. *
  13672. * Error message, if [[Deflate.err]] != 0
  13673. **/
  13674. /**
  13675. * new Deflate(options)
  13676. * - options (Object): zlib deflate options.
  13677. *
  13678. * Creates new deflator instance with specified params. Throws exception
  13679. * on bad params. Supported options:
  13680. *
  13681. * - `level`
  13682. * - `windowBits`
  13683. * - `memLevel`
  13684. * - `strategy`
  13685. *
  13686. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13687. * for more information on these.
  13688. *
  13689. * Additional options, for internal needs:
  13690. *
  13691. * - `chunkSize` - size of generated data chunks (16K by default)
  13692. * - `raw` (Boolean) - do raw deflate
  13693. * - `gzip` (Boolean) - create gzip wrapper
  13694. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13695. * (each char code [0..255])
  13696. * - `header` (Object) - custom header for gzip
  13697. * - `text` (Boolean) - true if compressed data believed to be text
  13698. * - `time` (Number) - modification time, unix timestamp
  13699. * - `os` (Number) - operation system code
  13700. * - `extra` (Array) - array of bytes with extra data (max 65536)
  13701. * - `name` (String) - file name (binary string)
  13702. * - `comment` (String) - comment (binary string)
  13703. * - `hcrc` (Boolean) - true if header crc should be added
  13704. *
  13705. * ##### Example:
  13706. *
  13707. * ```javascript
  13708. * var pako = require('pako')
  13709. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13710. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13711. *
  13712. * var deflate = new pako.Deflate({ level: 3});
  13713. *
  13714. * deflate.push(chunk1, false);
  13715. * deflate.push(chunk2, true); // true -> last chunk
  13716. *
  13717. * if (deflate.err) { throw new Error(deflate.err); }
  13718. *
  13719. * console.log(deflate.result);
  13720. * ```
  13721. **/
  13722. var Deflate = function(options) {
  13723. this.options = utils.assign({
  13724. level: Z_DEFAULT_COMPRESSION,
  13725. method: Z_DEFLATED,
  13726. chunkSize: 16384,
  13727. windowBits: 15,
  13728. memLevel: 8,
  13729. strategy: Z_DEFAULT_STRATEGY,
  13730. to: ''
  13731. }, options || {});
  13732. var opt = this.options;
  13733. if (opt.raw && (opt.windowBits > 0)) {
  13734. opt.windowBits = -opt.windowBits;
  13735. }
  13736. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  13737. opt.windowBits += 16;
  13738. }
  13739. this.err = 0; // error code, if happens (0 = Z_OK)
  13740. this.msg = ''; // error message
  13741. this.ended = false; // used to avoid multiple onEnd() calls
  13742. this.chunks = []; // chunks of compressed data
  13743. this.strm = new zstream();
  13744. this.strm.avail_out = 0;
  13745. var status = zlib_deflate.deflateInit2(
  13746. this.strm,
  13747. opt.level,
  13748. opt.method,
  13749. opt.windowBits,
  13750. opt.memLevel,
  13751. opt.strategy
  13752. );
  13753. if (status !== Z_OK) {
  13754. throw new Error(msg[status]);
  13755. }
  13756. if (opt.header) {
  13757. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  13758. }
  13759. };
  13760. /**
  13761. * Deflate#push(data[, mode]) -> Boolean
  13762. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  13763. * converted to utf8 byte sequence.
  13764. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13765. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13766. *
  13767. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  13768. * new compressed chunks. Returns `true` on success. The last data block must have
  13769. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13770. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13771. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  13772. *
  13773. * On fail call [[Deflate#onEnd]] with error code and return false.
  13774. *
  13775. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13776. * array format is detected automatically). Also, don't skip last param and always
  13777. * use the same type in your code (boolean or number). That will improve JS speed.
  13778. *
  13779. * For regular `Array`-s make sure all elements are [0..255].
  13780. *
  13781. * ##### Example
  13782. *
  13783. * ```javascript
  13784. * push(chunk, false); // push one of data chunks
  13785. * ...
  13786. * push(chunk, true); // push last chunk
  13787. * ```
  13788. **/
  13789. Deflate.prototype.push = function(data, mode) {
  13790. var strm = this.strm;
  13791. var chunkSize = this.options.chunkSize;
  13792. var status, _mode;
  13793. if (this.ended) { return false; }
  13794. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13795. // Convert data if needed
  13796. if (typeof data === 'string') {
  13797. // If we need to compress text, change encoding to utf8.
  13798. strm.input = strings.string2buf(data);
  13799. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13800. strm.input = new Uint8Array(data);
  13801. } else {
  13802. strm.input = data;
  13803. }
  13804. strm.next_in = 0;
  13805. strm.avail_in = strm.input.length;
  13806. do {
  13807. if (strm.avail_out === 0) {
  13808. strm.output = new utils.Buf8(chunkSize);
  13809. strm.next_out = 0;
  13810. strm.avail_out = chunkSize;
  13811. }
  13812. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13813. if (status !== Z_STREAM_END && status !== Z_OK) {
  13814. this.onEnd(status);
  13815. this.ended = true;
  13816. return false;
  13817. }
  13818. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13819. if (this.options.to === 'string') {
  13820. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13821. } else {
  13822. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13823. }
  13824. }
  13825. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13826. // Finalize on the last chunk.
  13827. if (_mode === Z_FINISH) {
  13828. status = zlib_deflate.deflateEnd(this.strm);
  13829. this.onEnd(status);
  13830. this.ended = true;
  13831. return status === Z_OK;
  13832. }
  13833. // callback interim results if Z_SYNC_FLUSH.
  13834. if (_mode === Z_SYNC_FLUSH) {
  13835. this.onEnd(Z_OK);
  13836. strm.avail_out = 0;
  13837. return true;
  13838. }
  13839. return true;
  13840. };
  13841. /**
  13842. * Deflate#onData(chunk) -> Void
  13843. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13844. * on js engine support. When string output requested, each chunk
  13845. * will be string.
  13846. *
  13847. * By default, stores data blocks in `chunks[]` property and glue
  13848. * those in `onEnd`. Override this handler, if you need another behaviour.
  13849. **/
  13850. Deflate.prototype.onData = function(chunk) {
  13851. this.chunks.push(chunk);
  13852. };
  13853. /**
  13854. * Deflate#onEnd(status) -> Void
  13855. * - status (Number): deflate status. 0 (Z_OK) on success,
  13856. * other if not.
  13857. *
  13858. * Called once after you tell deflate that the input stream is
  13859. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13860. * or if an error happened. By default - join collected chunks,
  13861. * free memory and fill `results` / `err` properties.
  13862. **/
  13863. Deflate.prototype.onEnd = function(status) {
  13864. // On success - join
  13865. if (status === Z_OK) {
  13866. if (this.options.to === 'string') {
  13867. this.result = this.chunks.join('');
  13868. } else {
  13869. this.result = utils.flattenChunks(this.chunks);
  13870. }
  13871. }
  13872. this.chunks = [];
  13873. this.err = status;
  13874. this.msg = this.strm.msg;
  13875. };
  13876. /**
  13877. * deflate(data[, options]) -> Uint8Array|Array|String
  13878. * - data (Uint8Array|Array|String): input data to compress.
  13879. * - options (Object): zlib deflate options.
  13880. *
  13881. * Compress `data` with deflate alrorythm and `options`.
  13882. *
  13883. * Supported options are:
  13884. *
  13885. * - level
  13886. * - windowBits
  13887. * - memLevel
  13888. * - strategy
  13889. *
  13890. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13891. * for more information on these.
  13892. *
  13893. * Sugar (options):
  13894. *
  13895. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13896. * negative windowBits implicitly.
  13897. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13898. * (each char code [0..255])
  13899. *
  13900. * ##### Example:
  13901. *
  13902. * ```javascript
  13903. * var pako = require('pako')
  13904. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13905. *
  13906. * console.log(pako.deflate(data));
  13907. * ```
  13908. **/
  13909. function deflate(input, options) {
  13910. var deflator = new Deflate(options);
  13911. deflator.push(input, true);
  13912. // That will never happens, if you don't cheat with options :)
  13913. if (deflator.err) { throw deflator.msg; }
  13914. return deflator.result;
  13915. }
  13916. /**
  13917. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13918. * - data (Uint8Array|Array|String): input data to compress.
  13919. * - options (Object): zlib deflate options.
  13920. *
  13921. * The same as [[deflate]], but creates raw data, without wrapper
  13922. * (header and adler32 crc).
  13923. **/
  13924. function deflateRaw(input, options) {
  13925. options = options || {};
  13926. options.raw = true;
  13927. return deflate(input, options);
  13928. }
  13929. /**
  13930. * gzip(data[, options]) -> Uint8Array|Array|String
  13931. * - data (Uint8Array|Array|String): input data to compress.
  13932. * - options (Object): zlib deflate options.
  13933. *
  13934. * The same as [[deflate]], but create gzip wrapper instead of
  13935. * deflate one.
  13936. **/
  13937. function gzip(input, options) {
  13938. options = options || {};
  13939. options.gzip = true;
  13940. return deflate(input, options);
  13941. }
  13942. exports.Deflate = Deflate;
  13943. exports.deflate = deflate;
  13944. exports.deflateRaw = deflateRaw;
  13945. exports.gzip = gzip;
  13946. },{"./utils/common":52,"./utils/strings":53,"./zlib/deflate.js":57,"./zlib/messages":62,"./zlib/zstream":64}],51:[function(require,module,exports){
  13947. 'use strict';
  13948. var zlib_inflate = require('./zlib/inflate.js');
  13949. var utils = require('./utils/common');
  13950. var strings = require('./utils/strings');
  13951. var c = require('./zlib/constants');
  13952. var msg = require('./zlib/messages');
  13953. var zstream = require('./zlib/zstream');
  13954. var gzheader = require('./zlib/gzheader');
  13955. var toString = Object.prototype.toString;
  13956. /**
  13957. * class Inflate
  13958. *
  13959. * Generic JS-style wrapper for zlib calls. If you don't need
  13960. * streaming behaviour - use more simple functions: [[inflate]]
  13961. * and [[inflateRaw]].
  13962. **/
  13963. /* internal
  13964. * inflate.chunks -> Array
  13965. *
  13966. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13967. **/
  13968. /**
  13969. * Inflate.result -> Uint8Array|Array|String
  13970. *
  13971. * Uncompressed result, generated by default [[Inflate#onData]]
  13972. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13973. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13974. * push a chunk with explicit flush (call [[Inflate#push]] with
  13975. * `Z_SYNC_FLUSH` param).
  13976. **/
  13977. /**
  13978. * Inflate.err -> Number
  13979. *
  13980. * Error code after inflate finished. 0 (Z_OK) on success.
  13981. * Should be checked if broken data possible.
  13982. **/
  13983. /**
  13984. * Inflate.msg -> String
  13985. *
  13986. * Error message, if [[Inflate.err]] != 0
  13987. **/
  13988. /**
  13989. * new Inflate(options)
  13990. * - options (Object): zlib inflate options.
  13991. *
  13992. * Creates new inflator instance with specified params. Throws exception
  13993. * on bad params. Supported options:
  13994. *
  13995. * - `windowBits`
  13996. *
  13997. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13998. * for more information on these.
  13999. *
  14000. * Additional options, for internal needs:
  14001. *
  14002. * - `chunkSize` - size of generated data chunks (16K by default)
  14003. * - `raw` (Boolean) - do raw inflate
  14004. * - `to` (String) - if equal to 'string', then result will be converted
  14005. * from utf8 to utf16 (javascript) string. When string output requested,
  14006. * chunk length can differ from `chunkSize`, depending on content.
  14007. *
  14008. * By default, when no options set, autodetect deflate/gzip data format via
  14009. * wrapper header.
  14010. *
  14011. * ##### Example:
  14012. *
  14013. * ```javascript
  14014. * var pako = require('pako')
  14015. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14016. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14017. *
  14018. * var inflate = new pako.Inflate({ level: 3});
  14019. *
  14020. * inflate.push(chunk1, false);
  14021. * inflate.push(chunk2, true); // true -> last chunk
  14022. *
  14023. * if (inflate.err) { throw new Error(inflate.err); }
  14024. *
  14025. * console.log(inflate.result);
  14026. * ```
  14027. **/
  14028. var Inflate = function(options) {
  14029. this.options = utils.assign({
  14030. chunkSize: 16384,
  14031. windowBits: 0,
  14032. to: ''
  14033. }, options || {});
  14034. var opt = this.options;
  14035. // Force window size for `raw` data, if not set directly,
  14036. // because we have no header for autodetect.
  14037. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  14038. opt.windowBits = -opt.windowBits;
  14039. if (opt.windowBits === 0) { opt.windowBits = -15; }
  14040. }
  14041. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  14042. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  14043. !(options && options.windowBits)) {
  14044. opt.windowBits += 32;
  14045. }
  14046. // Gzip header has no info about windows size, we can do autodetect only
  14047. // for deflate. So, if window size not set, force it to max when gzip possible
  14048. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  14049. // bit 3 (16) -> gzipped data
  14050. // bit 4 (32) -> autodetect gzip/deflate
  14051. if ((opt.windowBits & 15) === 0) {
  14052. opt.windowBits |= 15;
  14053. }
  14054. }
  14055. this.err = 0; // error code, if happens (0 = Z_OK)
  14056. this.msg = ''; // error message
  14057. this.ended = false; // used to avoid multiple onEnd() calls
  14058. this.chunks = []; // chunks of compressed data
  14059. this.strm = new zstream();
  14060. this.strm.avail_out = 0;
  14061. var status = zlib_inflate.inflateInit2(
  14062. this.strm,
  14063. opt.windowBits
  14064. );
  14065. if (status !== c.Z_OK) {
  14066. throw new Error(msg[status]);
  14067. }
  14068. this.header = new gzheader();
  14069. zlib_inflate.inflateGetHeader(this.strm, this.header);
  14070. };
  14071. /**
  14072. * Inflate#push(data[, mode]) -> Boolean
  14073. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  14074. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14075. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14076. *
  14077. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  14078. * new output chunks. Returns `true` on success. The last data block must have
  14079. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14080. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14081. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  14082. *
  14083. * On fail call [[Inflate#onEnd]] with error code and return false.
  14084. *
  14085. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14086. * format is detected automatically). Also, don't skip last param and always
  14087. * use the same type in your code (boolean or number). That will improve JS speed.
  14088. *
  14089. * For regular `Array`-s make sure all elements are [0..255].
  14090. *
  14091. * ##### Example
  14092. *
  14093. * ```javascript
  14094. * push(chunk, false); // push one of data chunks
  14095. * ...
  14096. * push(chunk, true); // push last chunk
  14097. * ```
  14098. **/
  14099. Inflate.prototype.push = function(data, mode) {
  14100. var strm = this.strm;
  14101. var chunkSize = this.options.chunkSize;
  14102. var status, _mode;
  14103. var next_out_utf8, tail, utf8str;
  14104. // Flag to properly process Z_BUF_ERROR on testing inflate call
  14105. // when we check that all output data was flushed.
  14106. var allowBufError = false;
  14107. if (this.ended) { return false; }
  14108. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  14109. // Convert data if needed
  14110. if (typeof data === 'string') {
  14111. // Only binary strings can be decompressed on practice
  14112. strm.input = strings.binstring2buf(data);
  14113. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14114. strm.input = new Uint8Array(data);
  14115. } else {
  14116. strm.input = data;
  14117. }
  14118. strm.next_in = 0;
  14119. strm.avail_in = strm.input.length;
  14120. do {
  14121. if (strm.avail_out === 0) {
  14122. strm.output = new utils.Buf8(chunkSize);
  14123. strm.next_out = 0;
  14124. strm.avail_out = chunkSize;
  14125. }
  14126. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  14127. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  14128. status = c.Z_OK;
  14129. allowBufError = false;
  14130. }
  14131. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  14132. this.onEnd(status);
  14133. this.ended = true;
  14134. return false;
  14135. }
  14136. if (strm.next_out) {
  14137. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  14138. if (this.options.to === 'string') {
  14139. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  14140. tail = strm.next_out - next_out_utf8;
  14141. utf8str = strings.buf2string(strm.output, next_out_utf8);
  14142. // move tail
  14143. strm.next_out = tail;
  14144. strm.avail_out = chunkSize - tail;
  14145. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  14146. this.onData(utf8str);
  14147. } else {
  14148. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14149. }
  14150. }
  14151. }
  14152. // When no more input data, we should check that internal inflate buffers
  14153. // are flushed. The only way to do it when avail_out = 0 - run one more
  14154. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  14155. // Here we set flag to process this error properly.
  14156. //
  14157. // NOTE. Deflate does not return error in this case and does not needs such
  14158. // logic.
  14159. if (strm.avail_in === 0 && strm.avail_out === 0) {
  14160. allowBufError = true;
  14161. }
  14162. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  14163. if (status === c.Z_STREAM_END) {
  14164. _mode = c.Z_FINISH;
  14165. }
  14166. // Finalize on the last chunk.
  14167. if (_mode === c.Z_FINISH) {
  14168. status = zlib_inflate.inflateEnd(this.strm);
  14169. this.onEnd(status);
  14170. this.ended = true;
  14171. return status === c.Z_OK;
  14172. }
  14173. // callback interim results if Z_SYNC_FLUSH.
  14174. if (_mode === c.Z_SYNC_FLUSH) {
  14175. this.onEnd(c.Z_OK);
  14176. strm.avail_out = 0;
  14177. return true;
  14178. }
  14179. return true;
  14180. };
  14181. /**
  14182. * Inflate#onData(chunk) -> Void
  14183. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14184. * on js engine support. When string output requested, each chunk
  14185. * will be string.
  14186. *
  14187. * By default, stores data blocks in `chunks[]` property and glue
  14188. * those in `onEnd`. Override this handler, if you need another behaviour.
  14189. **/
  14190. Inflate.prototype.onData = function(chunk) {
  14191. this.chunks.push(chunk);
  14192. };
  14193. /**
  14194. * Inflate#onEnd(status) -> Void
  14195. * - status (Number): inflate status. 0 (Z_OK) on success,
  14196. * other if not.
  14197. *
  14198. * Called either after you tell inflate that the input stream is
  14199. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14200. * or if an error happened. By default - join collected chunks,
  14201. * free memory and fill `results` / `err` properties.
  14202. **/
  14203. Inflate.prototype.onEnd = function(status) {
  14204. // On success - join
  14205. if (status === c.Z_OK) {
  14206. if (this.options.to === 'string') {
  14207. // Glue & convert here, until we teach pako to send
  14208. // utf8 alligned strings to onData
  14209. this.result = this.chunks.join('');
  14210. } else {
  14211. this.result = utils.flattenChunks(this.chunks);
  14212. }
  14213. }
  14214. this.chunks = [];
  14215. this.err = status;
  14216. this.msg = this.strm.msg;
  14217. };
  14218. /**
  14219. * inflate(data[, options]) -> Uint8Array|Array|String
  14220. * - data (Uint8Array|Array|String): input data to decompress.
  14221. * - options (Object): zlib inflate options.
  14222. *
  14223. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  14224. * format via wrapper header by default. That's why we don't provide
  14225. * separate `ungzip` method.
  14226. *
  14227. * Supported options are:
  14228. *
  14229. * - windowBits
  14230. *
  14231. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14232. * for more information.
  14233. *
  14234. * Sugar (options):
  14235. *
  14236. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14237. * negative windowBits implicitly.
  14238. * - `to` (String) - if equal to 'string', then result will be converted
  14239. * from utf8 to utf16 (javascript) string. When string output requested,
  14240. * chunk length can differ from `chunkSize`, depending on content.
  14241. *
  14242. *
  14243. * ##### Example:
  14244. *
  14245. * ```javascript
  14246. * var pako = require('pako')
  14247. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  14248. * , output;
  14249. *
  14250. * try {
  14251. * output = pako.inflate(input);
  14252. * } catch (err)
  14253. * console.log(err);
  14254. * }
  14255. * ```
  14256. **/
  14257. function inflate(input, options) {
  14258. var inflator = new Inflate(options);
  14259. inflator.push(input, true);
  14260. // That will never happens, if you don't cheat with options :)
  14261. if (inflator.err) { throw inflator.msg; }
  14262. return inflator.result;
  14263. }
  14264. /**
  14265. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  14266. * - data (Uint8Array|Array|String): input data to decompress.
  14267. * - options (Object): zlib inflate options.
  14268. *
  14269. * The same as [[inflate]], but creates raw data, without wrapper
  14270. * (header and adler32 crc).
  14271. **/
  14272. function inflateRaw(input, options) {
  14273. options = options || {};
  14274. options.raw = true;
  14275. return inflate(input, options);
  14276. }
  14277. /**
  14278. * ungzip(data[, options]) -> Uint8Array|Array|String
  14279. * - data (Uint8Array|Array|String): input data to decompress.
  14280. * - options (Object): zlib inflate options.
  14281. *
  14282. * Just shortcut to [[inflate]], because it autodetects format
  14283. * by header.content. Done for convenience.
  14284. **/
  14285. exports.Inflate = Inflate;
  14286. exports.inflate = inflate;
  14287. exports.inflateRaw = inflateRaw;
  14288. exports.ungzip = inflate;
  14289. },{"./utils/common":52,"./utils/strings":53,"./zlib/constants":55,"./zlib/gzheader":58,"./zlib/inflate.js":60,"./zlib/messages":62,"./zlib/zstream":64}],52:[function(require,module,exports){
  14290. 'use strict';
  14291. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  14292. (typeof Uint16Array !== 'undefined') &&
  14293. (typeof Int32Array !== 'undefined');
  14294. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  14295. var sources = Array.prototype.slice.call(arguments, 1);
  14296. while (sources.length) {
  14297. var source = sources.shift();
  14298. if (!source) { continue; }
  14299. if (typeof source !== 'object') {
  14300. throw new TypeError(source + 'must be non-object');
  14301. }
  14302. for (var p in source) {
  14303. if (source.hasOwnProperty(p)) {
  14304. obj[p] = source[p];
  14305. }
  14306. }
  14307. }
  14308. return obj;
  14309. };
  14310. // reduce buffer size, avoiding mem copy
  14311. exports.shrinkBuf = function (buf, size) {
  14312. if (buf.length === size) { return buf; }
  14313. if (buf.subarray) { return buf.subarray(0, size); }
  14314. buf.length = size;
  14315. return buf;
  14316. };
  14317. var fnTyped = {
  14318. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14319. if (src.subarray && dest.subarray) {
  14320. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  14321. return;
  14322. }
  14323. // Fallback to ordinary array
  14324. for (var i=0; i<len; i++) {
  14325. dest[dest_offs + i] = src[src_offs + i];
  14326. }
  14327. },
  14328. // Join array of chunks to single array.
  14329. flattenChunks: function(chunks) {
  14330. var i, l, len, pos, chunk, result;
  14331. // calculate data length
  14332. len = 0;
  14333. for (i=0, l=chunks.length; i<l; i++) {
  14334. len += chunks[i].length;
  14335. }
  14336. // join chunks
  14337. result = new Uint8Array(len);
  14338. pos = 0;
  14339. for (i=0, l=chunks.length; i<l; i++) {
  14340. chunk = chunks[i];
  14341. result.set(chunk, pos);
  14342. pos += chunk.length;
  14343. }
  14344. return result;
  14345. }
  14346. };
  14347. var fnUntyped = {
  14348. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14349. for (var i=0; i<len; i++) {
  14350. dest[dest_offs + i] = src[src_offs + i];
  14351. }
  14352. },
  14353. // Join array of chunks to single array.
  14354. flattenChunks: function(chunks) {
  14355. return [].concat.apply([], chunks);
  14356. }
  14357. };
  14358. // Enable/Disable typed arrays use, for testing
  14359. //
  14360. exports.setTyped = function (on) {
  14361. if (on) {
  14362. exports.Buf8 = Uint8Array;
  14363. exports.Buf16 = Uint16Array;
  14364. exports.Buf32 = Int32Array;
  14365. exports.assign(exports, fnTyped);
  14366. } else {
  14367. exports.Buf8 = Array;
  14368. exports.Buf16 = Array;
  14369. exports.Buf32 = Array;
  14370. exports.assign(exports, fnUntyped);
  14371. }
  14372. };
  14373. exports.setTyped(TYPED_OK);
  14374. },{}],53:[function(require,module,exports){
  14375. // String encode/decode helpers
  14376. 'use strict';
  14377. var utils = require('./common');
  14378. // Quick check if we can use fast array to bin string conversion
  14379. //
  14380. // - apply(Array) can fail on Android 2.2
  14381. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  14382. //
  14383. var STR_APPLY_OK = true;
  14384. var STR_APPLY_UIA_OK = true;
  14385. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  14386. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  14387. // Table with utf8 lengths (calculated by first byte of sequence)
  14388. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  14389. // because max possible codepoint is 0x10ffff
  14390. var _utf8len = new utils.Buf8(256);
  14391. for (var q=0; q<256; q++) {
  14392. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  14393. }
  14394. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  14395. // convert string to array (typed, when possible)
  14396. exports.string2buf = function (str) {
  14397. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  14398. // count binary size
  14399. for (m_pos = 0; m_pos < str_len; m_pos++) {
  14400. c = str.charCodeAt(m_pos);
  14401. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14402. c2 = str.charCodeAt(m_pos+1);
  14403. if ((c2 & 0xfc00) === 0xdc00) {
  14404. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14405. m_pos++;
  14406. }
  14407. }
  14408. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  14409. }
  14410. // allocate buffer
  14411. buf = new utils.Buf8(buf_len);
  14412. // convert
  14413. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  14414. c = str.charCodeAt(m_pos);
  14415. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14416. c2 = str.charCodeAt(m_pos+1);
  14417. if ((c2 & 0xfc00) === 0xdc00) {
  14418. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14419. m_pos++;
  14420. }
  14421. }
  14422. if (c < 0x80) {
  14423. /* one byte */
  14424. buf[i++] = c;
  14425. } else if (c < 0x800) {
  14426. /* two bytes */
  14427. buf[i++] = 0xC0 | (c >>> 6);
  14428. buf[i++] = 0x80 | (c & 0x3f);
  14429. } else if (c < 0x10000) {
  14430. /* three bytes */
  14431. buf[i++] = 0xE0 | (c >>> 12);
  14432. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14433. buf[i++] = 0x80 | (c & 0x3f);
  14434. } else {
  14435. /* four bytes */
  14436. buf[i++] = 0xf0 | (c >>> 18);
  14437. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  14438. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14439. buf[i++] = 0x80 | (c & 0x3f);
  14440. }
  14441. }
  14442. return buf;
  14443. };
  14444. // Helper (used in 2 places)
  14445. function buf2binstring(buf, len) {
  14446. // use fallback for big arrays to avoid stack overflow
  14447. if (len < 65537) {
  14448. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  14449. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  14450. }
  14451. }
  14452. var result = '';
  14453. for (var i=0; i < len; i++) {
  14454. result += String.fromCharCode(buf[i]);
  14455. }
  14456. return result;
  14457. }
  14458. // Convert byte array to binary string
  14459. exports.buf2binstring = function(buf) {
  14460. return buf2binstring(buf, buf.length);
  14461. };
  14462. // Convert binary string (typed, when possible)
  14463. exports.binstring2buf = function(str) {
  14464. var buf = new utils.Buf8(str.length);
  14465. for (var i=0, len=buf.length; i < len; i++) {
  14466. buf[i] = str.charCodeAt(i);
  14467. }
  14468. return buf;
  14469. };
  14470. // convert array to string
  14471. exports.buf2string = function (buf, max) {
  14472. var i, out, c, c_len;
  14473. var len = max || buf.length;
  14474. // Reserve max possible length (2 words per char)
  14475. // NB: by unknown reasons, Array is significantly faster for
  14476. // String.fromCharCode.apply than Uint16Array.
  14477. var utf16buf = new Array(len*2);
  14478. for (out=0, i=0; i<len;) {
  14479. c = buf[i++];
  14480. // quick process ascii
  14481. if (c < 0x80) { utf16buf[out++] = c; continue; }
  14482. c_len = _utf8len[c];
  14483. // skip 5 & 6 byte codes
  14484. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  14485. // apply mask on first byte
  14486. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  14487. // join the rest
  14488. while (c_len > 1 && i < len) {
  14489. c = (c << 6) | (buf[i++] & 0x3f);
  14490. c_len--;
  14491. }
  14492. // terminated by end of string?
  14493. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  14494. if (c < 0x10000) {
  14495. utf16buf[out++] = c;
  14496. } else {
  14497. c -= 0x10000;
  14498. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  14499. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  14500. }
  14501. }
  14502. return buf2binstring(utf16buf, out);
  14503. };
  14504. // Calculate max possible position in utf8 buffer,
  14505. // that will not break sequence. If that's not possible
  14506. // - (very small limits) return max size as is.
  14507. //
  14508. // buf[] - utf8 bytes array
  14509. // max - length limit (mandatory);
  14510. exports.utf8border = function(buf, max) {
  14511. var pos;
  14512. max = max || buf.length;
  14513. if (max > buf.length) { max = buf.length; }
  14514. // go back from last position, until start of sequence found
  14515. pos = max-1;
  14516. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  14517. // Fuckup - very small and broken sequence,
  14518. // return max, because we should return something anyway.
  14519. if (pos < 0) { return max; }
  14520. // If we came to start of buffer - that means vuffer is too small,
  14521. // return max too.
  14522. if (pos === 0) { return max; }
  14523. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  14524. };
  14525. },{"./common":52}],54:[function(require,module,exports){
  14526. 'use strict';
  14527. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  14528. // It doesn't worth to make additional optimizationa as in original.
  14529. // Small size is preferable.
  14530. function adler32(adler, buf, len, pos) {
  14531. var s1 = (adler & 0xffff) |0,
  14532. s2 = ((adler >>> 16) & 0xffff) |0,
  14533. n = 0;
  14534. while (len !== 0) {
  14535. // Set limit ~ twice less than 5552, to keep
  14536. // s2 in 31-bits, because we force signed ints.
  14537. // in other case %= will fail.
  14538. n = len > 2000 ? 2000 : len;
  14539. len -= n;
  14540. do {
  14541. s1 = (s1 + buf[pos++]) |0;
  14542. s2 = (s2 + s1) |0;
  14543. } while (--n);
  14544. s1 %= 65521;
  14545. s2 %= 65521;
  14546. }
  14547. return (s1 | (s2 << 16)) |0;
  14548. }
  14549. module.exports = adler32;
  14550. },{}],55:[function(require,module,exports){
  14551. module.exports = {
  14552. /* Allowed flush values; see deflate() and inflate() below for details */
  14553. Z_NO_FLUSH: 0,
  14554. Z_PARTIAL_FLUSH: 1,
  14555. Z_SYNC_FLUSH: 2,
  14556. Z_FULL_FLUSH: 3,
  14557. Z_FINISH: 4,
  14558. Z_BLOCK: 5,
  14559. Z_TREES: 6,
  14560. /* Return codes for the compression/decompression functions. Negative values
  14561. * are errors, positive values are used for special but normal events.
  14562. */
  14563. Z_OK: 0,
  14564. Z_STREAM_END: 1,
  14565. Z_NEED_DICT: 2,
  14566. Z_ERRNO: -1,
  14567. Z_STREAM_ERROR: -2,
  14568. Z_DATA_ERROR: -3,
  14569. //Z_MEM_ERROR: -4,
  14570. Z_BUF_ERROR: -5,
  14571. //Z_VERSION_ERROR: -6,
  14572. /* compression levels */
  14573. Z_NO_COMPRESSION: 0,
  14574. Z_BEST_SPEED: 1,
  14575. Z_BEST_COMPRESSION: 9,
  14576. Z_DEFAULT_COMPRESSION: -1,
  14577. Z_FILTERED: 1,
  14578. Z_HUFFMAN_ONLY: 2,
  14579. Z_RLE: 3,
  14580. Z_FIXED: 4,
  14581. Z_DEFAULT_STRATEGY: 0,
  14582. /* Possible values of the data_type field (though see inflate()) */
  14583. Z_BINARY: 0,
  14584. Z_TEXT: 1,
  14585. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  14586. Z_UNKNOWN: 2,
  14587. /* The deflate compression method */
  14588. Z_DEFLATED: 8
  14589. //Z_NULL: null // Use -1 or null inline, depending on var type
  14590. };
  14591. },{}],56:[function(require,module,exports){
  14592. 'use strict';
  14593. // Note: we can't get significant speed boost here.
  14594. // So write code to minimize size - no pregenerated tables
  14595. // and array tools dependencies.
  14596. // Use ordinary array, since untyped makes no boost here
  14597. function makeTable() {
  14598. var c, table = [];
  14599. for (var n =0; n < 256; n++) {
  14600. c = n;
  14601. for (var k =0; k < 8; k++) {
  14602. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  14603. }
  14604. table[n] = c;
  14605. }
  14606. return table;
  14607. }
  14608. // Create table on load. Just 255 signed longs. Not a problem.
  14609. var crcTable = makeTable();
  14610. function crc32(crc, buf, len, pos) {
  14611. var t = crcTable,
  14612. end = pos + len;
  14613. crc = crc ^ (-1);
  14614. for (var i = pos; i < end; i++) {
  14615. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  14616. }
  14617. return (crc ^ (-1)); // >>> 0;
  14618. }
  14619. module.exports = crc32;
  14620. },{}],57:[function(require,module,exports){
  14621. 'use strict';
  14622. var utils = require('../utils/common');
  14623. var trees = require('./trees');
  14624. var adler32 = require('./adler32');
  14625. var crc32 = require('./crc32');
  14626. var msg = require('./messages');
  14627. /* Public constants ==========================================================*/
  14628. /* ===========================================================================*/
  14629. /* Allowed flush values; see deflate() and inflate() below for details */
  14630. var Z_NO_FLUSH = 0;
  14631. var Z_PARTIAL_FLUSH = 1;
  14632. //var Z_SYNC_FLUSH = 2;
  14633. var Z_FULL_FLUSH = 3;
  14634. var Z_FINISH = 4;
  14635. var Z_BLOCK = 5;
  14636. //var Z_TREES = 6;
  14637. /* Return codes for the compression/decompression functions. Negative values
  14638. * are errors, positive values are used for special but normal events.
  14639. */
  14640. var Z_OK = 0;
  14641. var Z_STREAM_END = 1;
  14642. //var Z_NEED_DICT = 2;
  14643. //var Z_ERRNO = -1;
  14644. var Z_STREAM_ERROR = -2;
  14645. var Z_DATA_ERROR = -3;
  14646. //var Z_MEM_ERROR = -4;
  14647. var Z_BUF_ERROR = -5;
  14648. //var Z_VERSION_ERROR = -6;
  14649. /* compression levels */
  14650. //var Z_NO_COMPRESSION = 0;
  14651. //var Z_BEST_SPEED = 1;
  14652. //var Z_BEST_COMPRESSION = 9;
  14653. var Z_DEFAULT_COMPRESSION = -1;
  14654. var Z_FILTERED = 1;
  14655. var Z_HUFFMAN_ONLY = 2;
  14656. var Z_RLE = 3;
  14657. var Z_FIXED = 4;
  14658. var Z_DEFAULT_STRATEGY = 0;
  14659. /* Possible values of the data_type field (though see inflate()) */
  14660. //var Z_BINARY = 0;
  14661. //var Z_TEXT = 1;
  14662. //var Z_ASCII = 1; // = Z_TEXT
  14663. var Z_UNKNOWN = 2;
  14664. /* The deflate compression method */
  14665. var Z_DEFLATED = 8;
  14666. /*============================================================================*/
  14667. var MAX_MEM_LEVEL = 9;
  14668. /* Maximum value for memLevel in deflateInit2 */
  14669. var MAX_WBITS = 15;
  14670. /* 32K LZ77 window */
  14671. var DEF_MEM_LEVEL = 8;
  14672. var LENGTH_CODES = 29;
  14673. /* number of length codes, not counting the special END_BLOCK code */
  14674. var LITERALS = 256;
  14675. /* number of literal bytes 0..255 */
  14676. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14677. /* number of Literal or Length codes, including the END_BLOCK code */
  14678. var D_CODES = 30;
  14679. /* number of distance codes */
  14680. var BL_CODES = 19;
  14681. /* number of codes used to transfer the bit lengths */
  14682. var HEAP_SIZE = 2*L_CODES + 1;
  14683. /* maximum heap size */
  14684. var MAX_BITS = 15;
  14685. /* All codes must not exceed MAX_BITS bits */
  14686. var MIN_MATCH = 3;
  14687. var MAX_MATCH = 258;
  14688. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  14689. var PRESET_DICT = 0x20;
  14690. var INIT_STATE = 42;
  14691. var EXTRA_STATE = 69;
  14692. var NAME_STATE = 73;
  14693. var COMMENT_STATE = 91;
  14694. var HCRC_STATE = 103;
  14695. var BUSY_STATE = 113;
  14696. var FINISH_STATE = 666;
  14697. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  14698. var BS_BLOCK_DONE = 2; /* block flush performed */
  14699. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  14700. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  14701. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  14702. function err(strm, errorCode) {
  14703. strm.msg = msg[errorCode];
  14704. return errorCode;
  14705. }
  14706. function rank(f) {
  14707. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  14708. }
  14709. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14710. /* =========================================================================
  14711. * Flush as much pending output as possible. All deflate() output goes
  14712. * through this function so some applications may wish to modify it
  14713. * to avoid allocating a large strm->output buffer and copying into it.
  14714. * (See also read_buf()).
  14715. */
  14716. function flush_pending(strm) {
  14717. var s = strm.state;
  14718. //_tr_flush_bits(s);
  14719. var len = s.pending;
  14720. if (len > strm.avail_out) {
  14721. len = strm.avail_out;
  14722. }
  14723. if (len === 0) { return; }
  14724. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  14725. strm.next_out += len;
  14726. s.pending_out += len;
  14727. strm.total_out += len;
  14728. strm.avail_out -= len;
  14729. s.pending -= len;
  14730. if (s.pending === 0) {
  14731. s.pending_out = 0;
  14732. }
  14733. }
  14734. function flush_block_only (s, last) {
  14735. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  14736. s.block_start = s.strstart;
  14737. flush_pending(s.strm);
  14738. }
  14739. function put_byte(s, b) {
  14740. s.pending_buf[s.pending++] = b;
  14741. }
  14742. /* =========================================================================
  14743. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  14744. * IN assertion: the stream state is correct and there is enough room in
  14745. * pending_buf.
  14746. */
  14747. function putShortMSB(s, b) {
  14748. // put_byte(s, (Byte)(b >> 8));
  14749. // put_byte(s, (Byte)(b & 0xff));
  14750. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  14751. s.pending_buf[s.pending++] = b & 0xff;
  14752. }
  14753. /* ===========================================================================
  14754. * Read a new buffer from the current input stream, update the adler32
  14755. * and total number of bytes read. All deflate() input goes through
  14756. * this function so some applications may wish to modify it to avoid
  14757. * allocating a large strm->input buffer and copying from it.
  14758. * (See also flush_pending()).
  14759. */
  14760. function read_buf(strm, buf, start, size) {
  14761. var len = strm.avail_in;
  14762. if (len > size) { len = size; }
  14763. if (len === 0) { return 0; }
  14764. strm.avail_in -= len;
  14765. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  14766. if (strm.state.wrap === 1) {
  14767. strm.adler = adler32(strm.adler, buf, len, start);
  14768. }
  14769. else if (strm.state.wrap === 2) {
  14770. strm.adler = crc32(strm.adler, buf, len, start);
  14771. }
  14772. strm.next_in += len;
  14773. strm.total_in += len;
  14774. return len;
  14775. }
  14776. /* ===========================================================================
  14777. * Set match_start to the longest match starting at the given string and
  14778. * return its length. Matches shorter or equal to prev_length are discarded,
  14779. * in which case the result is equal to prev_length and match_start is
  14780. * garbage.
  14781. * IN assertions: cur_match is the head of the hash chain for the current
  14782. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  14783. * OUT assertion: the match length is not greater than s->lookahead.
  14784. */
  14785. function longest_match(s, cur_match) {
  14786. var chain_length = s.max_chain_length; /* max hash chain length */
  14787. var scan = s.strstart; /* current string */
  14788. var match; /* matched string */
  14789. var len; /* length of current match */
  14790. var best_len = s.prev_length; /* best match length so far */
  14791. var nice_match = s.nice_match; /* stop if match long enough */
  14792. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14793. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14794. var _win = s.window; // shortcut
  14795. var wmask = s.w_mask;
  14796. var prev = s.prev;
  14797. /* Stop when cur_match becomes <= limit. To simplify the code,
  14798. * we prevent matches with the string of window index 0.
  14799. */
  14800. var strend = s.strstart + MAX_MATCH;
  14801. var scan_end1 = _win[scan + best_len - 1];
  14802. var scan_end = _win[scan + best_len];
  14803. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14804. * It is easy to get rid of this optimization if necessary.
  14805. */
  14806. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14807. /* Do not waste too much time if we already have a good match: */
  14808. if (s.prev_length >= s.good_match) {
  14809. chain_length >>= 2;
  14810. }
  14811. /* Do not look for matches beyond the end of the input. This is necessary
  14812. * to make deflate deterministic.
  14813. */
  14814. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14815. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14816. do {
  14817. // Assert(cur_match < s->strstart, "no future");
  14818. match = cur_match;
  14819. /* Skip to next match if the match length cannot increase
  14820. * or if the match length is less than 2. Note that the checks below
  14821. * for insufficient lookahead only occur occasionally for performance
  14822. * reasons. Therefore uninitialized memory will be accessed, and
  14823. * conditional jumps will be made that depend on those values.
  14824. * However the length of the match is limited to the lookahead, so
  14825. * the output of deflate is not affected by the uninitialized values.
  14826. */
  14827. if (_win[match + best_len] !== scan_end ||
  14828. _win[match + best_len - 1] !== scan_end1 ||
  14829. _win[match] !== _win[scan] ||
  14830. _win[++match] !== _win[scan + 1]) {
  14831. continue;
  14832. }
  14833. /* The check at best_len-1 can be removed because it will be made
  14834. * again later. (This heuristic is not always a win.)
  14835. * It is not necessary to compare scan[2] and match[2] since they
  14836. * are always equal when the other bytes match, given that
  14837. * the hash keys are equal and that HASH_BITS >= 8.
  14838. */
  14839. scan += 2;
  14840. match++;
  14841. // Assert(*scan == *match, "match[2]?");
  14842. /* We check for insufficient lookahead only every 8th comparison;
  14843. * the 256th check will be made at strstart+258.
  14844. */
  14845. do {
  14846. /*jshint noempty:false*/
  14847. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14848. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14849. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14850. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14851. scan < strend);
  14852. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14853. len = MAX_MATCH - (strend - scan);
  14854. scan = strend - MAX_MATCH;
  14855. if (len > best_len) {
  14856. s.match_start = cur_match;
  14857. best_len = len;
  14858. if (len >= nice_match) {
  14859. break;
  14860. }
  14861. scan_end1 = _win[scan + best_len - 1];
  14862. scan_end = _win[scan + best_len];
  14863. }
  14864. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14865. if (best_len <= s.lookahead) {
  14866. return best_len;
  14867. }
  14868. return s.lookahead;
  14869. }
  14870. /* ===========================================================================
  14871. * Fill the window when the lookahead becomes insufficient.
  14872. * Updates strstart and lookahead.
  14873. *
  14874. * IN assertion: lookahead < MIN_LOOKAHEAD
  14875. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14876. * At least one byte has been read, or avail_in == 0; reads are
  14877. * performed for at least two bytes (required for the zip translate_eol
  14878. * option -- not supported here).
  14879. */
  14880. function fill_window(s) {
  14881. var _w_size = s.w_size;
  14882. var p, n, m, more, str;
  14883. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14884. do {
  14885. more = s.window_size - s.lookahead - s.strstart;
  14886. // JS ints have 32 bit, block below not needed
  14887. /* Deal with !@#$% 64K limit: */
  14888. //if (sizeof(int) <= 2) {
  14889. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14890. // more = wsize;
  14891. //
  14892. // } else if (more == (unsigned)(-1)) {
  14893. // /* Very unlikely, but possible on 16 bit machine if
  14894. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14895. // */
  14896. // more--;
  14897. // }
  14898. //}
  14899. /* If the window is almost full and there is insufficient lookahead,
  14900. * move the upper half to the lower one to make room in the upper half.
  14901. */
  14902. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14903. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14904. s.match_start -= _w_size;
  14905. s.strstart -= _w_size;
  14906. /* we now have strstart >= MAX_DIST */
  14907. s.block_start -= _w_size;
  14908. /* Slide the hash table (could be avoided with 32 bit values
  14909. at the expense of memory usage). We slide even when level == 0
  14910. to keep the hash table consistent if we switch back to level > 0
  14911. later. (Using level 0 permanently is not an optimal usage of
  14912. zlib, so we don't care about this pathological case.)
  14913. */
  14914. n = s.hash_size;
  14915. p = n;
  14916. do {
  14917. m = s.head[--p];
  14918. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14919. } while (--n);
  14920. n = _w_size;
  14921. p = n;
  14922. do {
  14923. m = s.prev[--p];
  14924. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14925. /* If n is not on any hash chain, prev[n] is garbage but
  14926. * its value will never be used.
  14927. */
  14928. } while (--n);
  14929. more += _w_size;
  14930. }
  14931. if (s.strm.avail_in === 0) {
  14932. break;
  14933. }
  14934. /* If there was no sliding:
  14935. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14936. * more == window_size - lookahead - strstart
  14937. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14938. * => more >= window_size - 2*WSIZE + 2
  14939. * In the BIG_MEM or MMAP case (not yet supported),
  14940. * window_size == input_size + MIN_LOOKAHEAD &&
  14941. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14942. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14943. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14944. */
  14945. //Assert(more >= 2, "more < 2");
  14946. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14947. s.lookahead += n;
  14948. /* Initialize the hash value now that we have some input: */
  14949. if (s.lookahead + s.insert >= MIN_MATCH) {
  14950. str = s.strstart - s.insert;
  14951. s.ins_h = s.window[str];
  14952. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14953. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14954. //#if MIN_MATCH != 3
  14955. // Call update_hash() MIN_MATCH-3 more times
  14956. //#endif
  14957. while (s.insert) {
  14958. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14959. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14960. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14961. s.head[s.ins_h] = str;
  14962. str++;
  14963. s.insert--;
  14964. if (s.lookahead + s.insert < MIN_MATCH) {
  14965. break;
  14966. }
  14967. }
  14968. }
  14969. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14970. * but this is not important since only literal bytes will be emitted.
  14971. */
  14972. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14973. /* If the WIN_INIT bytes after the end of the current data have never been
  14974. * written, then zero those bytes in order to avoid memory check reports of
  14975. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14976. * the longest match routines. Update the high water mark for the next
  14977. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14978. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14979. */
  14980. // if (s.high_water < s.window_size) {
  14981. // var curr = s.strstart + s.lookahead;
  14982. // var init = 0;
  14983. //
  14984. // if (s.high_water < curr) {
  14985. // /* Previous high water mark below current data -- zero WIN_INIT
  14986. // * bytes or up to end of window, whichever is less.
  14987. // */
  14988. // init = s.window_size - curr;
  14989. // if (init > WIN_INIT)
  14990. // init = WIN_INIT;
  14991. // zmemzero(s->window + curr, (unsigned)init);
  14992. // s->high_water = curr + init;
  14993. // }
  14994. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14995. // /* High water mark at or above current data, but below current data
  14996. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14997. // * to end of window, whichever is less.
  14998. // */
  14999. // init = (ulg)curr + WIN_INIT - s->high_water;
  15000. // if (init > s->window_size - s->high_water)
  15001. // init = s->window_size - s->high_water;
  15002. // zmemzero(s->window + s->high_water, (unsigned)init);
  15003. // s->high_water += init;
  15004. // }
  15005. // }
  15006. //
  15007. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15008. // "not enough room for search");
  15009. }
  15010. /* ===========================================================================
  15011. * Copy without compression as much as possible from the input stream, return
  15012. * the current block state.
  15013. * This function does not insert new strings in the dictionary since
  15014. * uncompressible data is probably not useful. This function is used
  15015. * only for the level=0 compression option.
  15016. * NOTE: this function should be optimized to avoid extra copying from
  15017. * window to pending_buf.
  15018. */
  15019. function deflate_stored(s, flush) {
  15020. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15021. * to pending_buf_size, and each stored block has a 5 byte header:
  15022. */
  15023. var max_block_size = 0xffff;
  15024. if (max_block_size > s.pending_buf_size - 5) {
  15025. max_block_size = s.pending_buf_size - 5;
  15026. }
  15027. /* Copy as much as possible from input to output: */
  15028. for (;;) {
  15029. /* Fill the window as much as possible: */
  15030. if (s.lookahead <= 1) {
  15031. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15032. // s->block_start >= (long)s->w_size, "slide too late");
  15033. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15034. // s.block_start >= s.w_size)) {
  15035. // throw new Error("slide too late");
  15036. // }
  15037. fill_window(s);
  15038. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  15039. return BS_NEED_MORE;
  15040. }
  15041. if (s.lookahead === 0) {
  15042. break;
  15043. }
  15044. /* flush the current block */
  15045. }
  15046. //Assert(s->block_start >= 0L, "block gone");
  15047. // if (s.block_start < 0) throw new Error("block gone");
  15048. s.strstart += s.lookahead;
  15049. s.lookahead = 0;
  15050. /* Emit a stored block if pending_buf will be full: */
  15051. var max_start = s.block_start + max_block_size;
  15052. if (s.strstart === 0 || s.strstart >= max_start) {
  15053. /* strstart == 0 is possible when wraparound on 16-bit machine */
  15054. s.lookahead = s.strstart - max_start;
  15055. s.strstart = max_start;
  15056. /*** FLUSH_BLOCK(s, 0); ***/
  15057. flush_block_only(s, false);
  15058. if (s.strm.avail_out === 0) {
  15059. return BS_NEED_MORE;
  15060. }
  15061. /***/
  15062. }
  15063. /* Flush if we may have to slide, otherwise block_start may become
  15064. * negative and the data will be gone:
  15065. */
  15066. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  15067. /*** FLUSH_BLOCK(s, 0); ***/
  15068. flush_block_only(s, false);
  15069. if (s.strm.avail_out === 0) {
  15070. return BS_NEED_MORE;
  15071. }
  15072. /***/
  15073. }
  15074. }
  15075. s.insert = 0;
  15076. if (flush === Z_FINISH) {
  15077. /*** FLUSH_BLOCK(s, 1); ***/
  15078. flush_block_only(s, true);
  15079. if (s.strm.avail_out === 0) {
  15080. return BS_FINISH_STARTED;
  15081. }
  15082. /***/
  15083. return BS_FINISH_DONE;
  15084. }
  15085. if (s.strstart > s.block_start) {
  15086. /*** FLUSH_BLOCK(s, 0); ***/
  15087. flush_block_only(s, false);
  15088. if (s.strm.avail_out === 0) {
  15089. return BS_NEED_MORE;
  15090. }
  15091. /***/
  15092. }
  15093. return BS_NEED_MORE;
  15094. }
  15095. /* ===========================================================================
  15096. * Compress as much as possible from the input stream, return the current
  15097. * block state.
  15098. * This function does not perform lazy evaluation of matches and inserts
  15099. * new strings in the dictionary only for unmatched strings or for short
  15100. * matches. It is used only for the fast compression options.
  15101. */
  15102. function deflate_fast(s, flush) {
  15103. var hash_head; /* head of the hash chain */
  15104. var bflush; /* set if current block must be flushed */
  15105. for (;;) {
  15106. /* Make sure that we always have enough lookahead, except
  15107. * at the end of the input file. We need MAX_MATCH bytes
  15108. * for the next match, plus MIN_MATCH bytes to insert the
  15109. * string following the next match.
  15110. */
  15111. if (s.lookahead < MIN_LOOKAHEAD) {
  15112. fill_window(s);
  15113. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15114. return BS_NEED_MORE;
  15115. }
  15116. if (s.lookahead === 0) {
  15117. break; /* flush the current block */
  15118. }
  15119. }
  15120. /* Insert the string window[strstart .. strstart+2] in the
  15121. * dictionary, and set hash_head to the head of the hash chain:
  15122. */
  15123. hash_head = 0/*NIL*/;
  15124. if (s.lookahead >= MIN_MATCH) {
  15125. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15126. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15127. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15128. s.head[s.ins_h] = s.strstart;
  15129. /***/
  15130. }
  15131. /* Find the longest match, discarding those <= prev_length.
  15132. * At this point we have always match_length < MIN_MATCH
  15133. */
  15134. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  15135. /* To simplify the code, we prevent matches with the string
  15136. * of window index 0 (in particular we have to avoid a match
  15137. * of the string with itself at the start of the input file).
  15138. */
  15139. s.match_length = longest_match(s, hash_head);
  15140. /* longest_match() sets match_start */
  15141. }
  15142. if (s.match_length >= MIN_MATCH) {
  15143. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  15144. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  15145. s.match_length - MIN_MATCH, bflush); ***/
  15146. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  15147. s.lookahead -= s.match_length;
  15148. /* Insert new strings in the hash table only if the match length
  15149. * is not too large. This saves time but degrades compression.
  15150. */
  15151. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  15152. s.match_length--; /* string at strstart already in table */
  15153. do {
  15154. s.strstart++;
  15155. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15156. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15157. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15158. s.head[s.ins_h] = s.strstart;
  15159. /***/
  15160. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  15161. * always MIN_MATCH bytes ahead.
  15162. */
  15163. } while (--s.match_length !== 0);
  15164. s.strstart++;
  15165. } else
  15166. {
  15167. s.strstart += s.match_length;
  15168. s.match_length = 0;
  15169. s.ins_h = s.window[s.strstart];
  15170. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  15171. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  15172. //#if MIN_MATCH != 3
  15173. // Call UPDATE_HASH() MIN_MATCH-3 more times
  15174. //#endif
  15175. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  15176. * matter since it will be recomputed at next deflate call.
  15177. */
  15178. }
  15179. } else {
  15180. /* No match, output a literal byte */
  15181. //Tracevv((stderr,"%c", s.window[s.strstart]));
  15182. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15183. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15184. s.lookahead--;
  15185. s.strstart++;
  15186. }
  15187. if (bflush) {
  15188. /*** FLUSH_BLOCK(s, 0); ***/
  15189. flush_block_only(s, false);
  15190. if (s.strm.avail_out === 0) {
  15191. return BS_NEED_MORE;
  15192. }
  15193. /***/
  15194. }
  15195. }
  15196. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  15197. if (flush === Z_FINISH) {
  15198. /*** FLUSH_BLOCK(s, 1); ***/
  15199. flush_block_only(s, true);
  15200. if (s.strm.avail_out === 0) {
  15201. return BS_FINISH_STARTED;
  15202. }
  15203. /***/
  15204. return BS_FINISH_DONE;
  15205. }
  15206. if (s.last_lit) {
  15207. /*** FLUSH_BLOCK(s, 0); ***/
  15208. flush_block_only(s, false);
  15209. if (s.strm.avail_out === 0) {
  15210. return BS_NEED_MORE;
  15211. }
  15212. /***/
  15213. }
  15214. return BS_BLOCK_DONE;
  15215. }
  15216. /* ===========================================================================
  15217. * Same as above, but achieves better compression. We use a lazy
  15218. * evaluation for matches: a match is finally adopted only if there is
  15219. * no better match at the next window position.
  15220. */
  15221. function deflate_slow(s, flush) {
  15222. var hash_head; /* head of hash chain */
  15223. var bflush; /* set if current block must be flushed */
  15224. var max_insert;
  15225. /* Process the input block. */
  15226. for (;;) {
  15227. /* Make sure that we always have enough lookahead, except
  15228. * at the end of the input file. We need MAX_MATCH bytes
  15229. * for the next match, plus MIN_MATCH bytes to insert the
  15230. * string following the next match.
  15231. */
  15232. if (s.lookahead < MIN_LOOKAHEAD) {
  15233. fill_window(s);
  15234. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15235. return BS_NEED_MORE;
  15236. }
  15237. if (s.lookahead === 0) { break; } /* flush the current block */
  15238. }
  15239. /* Insert the string window[strstart .. strstart+2] in the
  15240. * dictionary, and set hash_head to the head of the hash chain:
  15241. */
  15242. hash_head = 0/*NIL*/;
  15243. if (s.lookahead >= MIN_MATCH) {
  15244. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15245. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15246. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15247. s.head[s.ins_h] = s.strstart;
  15248. /***/
  15249. }
  15250. /* Find the longest match, discarding those <= prev_length.
  15251. */
  15252. s.prev_length = s.match_length;
  15253. s.prev_match = s.match_start;
  15254. s.match_length = MIN_MATCH-1;
  15255. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  15256. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  15257. /* To simplify the code, we prevent matches with the string
  15258. * of window index 0 (in particular we have to avoid a match
  15259. * of the string with itself at the start of the input file).
  15260. */
  15261. s.match_length = longest_match(s, hash_head);
  15262. /* longest_match() sets match_start */
  15263. if (s.match_length <= 5 &&
  15264. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  15265. /* If prev_match is also MIN_MATCH, match_start is garbage
  15266. * but we will ignore the current match anyway.
  15267. */
  15268. s.match_length = MIN_MATCH-1;
  15269. }
  15270. }
  15271. /* If there was a match at the previous step and the current
  15272. * match is not better, output the previous match:
  15273. */
  15274. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  15275. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  15276. /* Do not insert strings in hash table beyond this. */
  15277. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  15278. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  15279. s.prev_length - MIN_MATCH, bflush);***/
  15280. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  15281. /* Insert in hash table all strings up to the end of the match.
  15282. * strstart-1 and strstart are already inserted. If there is not
  15283. * enough lookahead, the last two strings are not inserted in
  15284. * the hash table.
  15285. */
  15286. s.lookahead -= s.prev_length-1;
  15287. s.prev_length -= 2;
  15288. do {
  15289. if (++s.strstart <= max_insert) {
  15290. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15291. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15292. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15293. s.head[s.ins_h] = s.strstart;
  15294. /***/
  15295. }
  15296. } while (--s.prev_length !== 0);
  15297. s.match_available = 0;
  15298. s.match_length = MIN_MATCH-1;
  15299. s.strstart++;
  15300. if (bflush) {
  15301. /*** FLUSH_BLOCK(s, 0); ***/
  15302. flush_block_only(s, false);
  15303. if (s.strm.avail_out === 0) {
  15304. return BS_NEED_MORE;
  15305. }
  15306. /***/
  15307. }
  15308. } else if (s.match_available) {
  15309. /* If there was no match at the previous position, output a
  15310. * single literal. If there was a match but the current match
  15311. * is longer, truncate the previous match to a single literal.
  15312. */
  15313. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15314. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15315. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15316. if (bflush) {
  15317. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  15318. flush_block_only(s, false);
  15319. /***/
  15320. }
  15321. s.strstart++;
  15322. s.lookahead--;
  15323. if (s.strm.avail_out === 0) {
  15324. return BS_NEED_MORE;
  15325. }
  15326. } else {
  15327. /* There is no previous match to compare with, wait for
  15328. * the next step to decide.
  15329. */
  15330. s.match_available = 1;
  15331. s.strstart++;
  15332. s.lookahead--;
  15333. }
  15334. }
  15335. //Assert (flush != Z_NO_FLUSH, "no flush?");
  15336. if (s.match_available) {
  15337. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15338. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15339. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15340. s.match_available = 0;
  15341. }
  15342. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  15343. if (flush === Z_FINISH) {
  15344. /*** FLUSH_BLOCK(s, 1); ***/
  15345. flush_block_only(s, true);
  15346. if (s.strm.avail_out === 0) {
  15347. return BS_FINISH_STARTED;
  15348. }
  15349. /***/
  15350. return BS_FINISH_DONE;
  15351. }
  15352. if (s.last_lit) {
  15353. /*** FLUSH_BLOCK(s, 0); ***/
  15354. flush_block_only(s, false);
  15355. if (s.strm.avail_out === 0) {
  15356. return BS_NEED_MORE;
  15357. }
  15358. /***/
  15359. }
  15360. return BS_BLOCK_DONE;
  15361. }
  15362. /* ===========================================================================
  15363. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  15364. * one. Do not maintain a hash table. (It will be regenerated if this run of
  15365. * deflate switches away from Z_RLE.)
  15366. */
  15367. function deflate_rle(s, flush) {
  15368. var bflush; /* set if current block must be flushed */
  15369. var prev; /* byte at distance one to match */
  15370. var scan, strend; /* scan goes up to strend for length of run */
  15371. var _win = s.window;
  15372. for (;;) {
  15373. /* Make sure that we always have enough lookahead, except
  15374. * at the end of the input file. We need MAX_MATCH bytes
  15375. * for the longest run, plus one for the unrolled loop.
  15376. */
  15377. if (s.lookahead <= MAX_MATCH) {
  15378. fill_window(s);
  15379. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  15380. return BS_NEED_MORE;
  15381. }
  15382. if (s.lookahead === 0) { break; } /* flush the current block */
  15383. }
  15384. /* See how many times the previous byte repeats */
  15385. s.match_length = 0;
  15386. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  15387. scan = s.strstart - 1;
  15388. prev = _win[scan];
  15389. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  15390. strend = s.strstart + MAX_MATCH;
  15391. do {
  15392. /*jshint noempty:false*/
  15393. } while (prev === _win[++scan] && prev === _win[++scan] &&
  15394. prev === _win[++scan] && prev === _win[++scan] &&
  15395. prev === _win[++scan] && prev === _win[++scan] &&
  15396. prev === _win[++scan] && prev === _win[++scan] &&
  15397. scan < strend);
  15398. s.match_length = MAX_MATCH - (strend - scan);
  15399. if (s.match_length > s.lookahead) {
  15400. s.match_length = s.lookahead;
  15401. }
  15402. }
  15403. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  15404. }
  15405. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  15406. if (s.match_length >= MIN_MATCH) {
  15407. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  15408. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  15409. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  15410. s.lookahead -= s.match_length;
  15411. s.strstart += s.match_length;
  15412. s.match_length = 0;
  15413. } else {
  15414. /* No match, output a literal byte */
  15415. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15416. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15417. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15418. s.lookahead--;
  15419. s.strstart++;
  15420. }
  15421. if (bflush) {
  15422. /*** FLUSH_BLOCK(s, 0); ***/
  15423. flush_block_only(s, false);
  15424. if (s.strm.avail_out === 0) {
  15425. return BS_NEED_MORE;
  15426. }
  15427. /***/
  15428. }
  15429. }
  15430. s.insert = 0;
  15431. if (flush === Z_FINISH) {
  15432. /*** FLUSH_BLOCK(s, 1); ***/
  15433. flush_block_only(s, true);
  15434. if (s.strm.avail_out === 0) {
  15435. return BS_FINISH_STARTED;
  15436. }
  15437. /***/
  15438. return BS_FINISH_DONE;
  15439. }
  15440. if (s.last_lit) {
  15441. /*** FLUSH_BLOCK(s, 0); ***/
  15442. flush_block_only(s, false);
  15443. if (s.strm.avail_out === 0) {
  15444. return BS_NEED_MORE;
  15445. }
  15446. /***/
  15447. }
  15448. return BS_BLOCK_DONE;
  15449. }
  15450. /* ===========================================================================
  15451. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  15452. * (It will be regenerated if this run of deflate switches away from Huffman.)
  15453. */
  15454. function deflate_huff(s, flush) {
  15455. var bflush; /* set if current block must be flushed */
  15456. for (;;) {
  15457. /* Make sure that we have a literal to write. */
  15458. if (s.lookahead === 0) {
  15459. fill_window(s);
  15460. if (s.lookahead === 0) {
  15461. if (flush === Z_NO_FLUSH) {
  15462. return BS_NEED_MORE;
  15463. }
  15464. break; /* flush the current block */
  15465. }
  15466. }
  15467. /* Output a literal byte */
  15468. s.match_length = 0;
  15469. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15470. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15471. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15472. s.lookahead--;
  15473. s.strstart++;
  15474. if (bflush) {
  15475. /*** FLUSH_BLOCK(s, 0); ***/
  15476. flush_block_only(s, false);
  15477. if (s.strm.avail_out === 0) {
  15478. return BS_NEED_MORE;
  15479. }
  15480. /***/
  15481. }
  15482. }
  15483. s.insert = 0;
  15484. if (flush === Z_FINISH) {
  15485. /*** FLUSH_BLOCK(s, 1); ***/
  15486. flush_block_only(s, true);
  15487. if (s.strm.avail_out === 0) {
  15488. return BS_FINISH_STARTED;
  15489. }
  15490. /***/
  15491. return BS_FINISH_DONE;
  15492. }
  15493. if (s.last_lit) {
  15494. /*** FLUSH_BLOCK(s, 0); ***/
  15495. flush_block_only(s, false);
  15496. if (s.strm.avail_out === 0) {
  15497. return BS_NEED_MORE;
  15498. }
  15499. /***/
  15500. }
  15501. return BS_BLOCK_DONE;
  15502. }
  15503. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  15504. * the desired pack level (0..9). The values given below have been tuned to
  15505. * exclude worst case performance for pathological files. Better values may be
  15506. * found for specific files.
  15507. */
  15508. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  15509. this.good_length = good_length;
  15510. this.max_lazy = max_lazy;
  15511. this.nice_length = nice_length;
  15512. this.max_chain = max_chain;
  15513. this.func = func;
  15514. };
  15515. var configuration_table;
  15516. configuration_table = [
  15517. /* good lazy nice chain */
  15518. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  15519. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  15520. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  15521. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  15522. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  15523. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  15524. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  15525. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  15526. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  15527. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  15528. ];
  15529. /* ===========================================================================
  15530. * Initialize the "longest match" routines for a new zlib stream
  15531. */
  15532. function lm_init(s) {
  15533. s.window_size = 2 * s.w_size;
  15534. /*** CLEAR_HASH(s); ***/
  15535. zero(s.head); // Fill with NIL (= 0);
  15536. /* Set the default configuration parameters:
  15537. */
  15538. s.max_lazy_match = configuration_table[s.level].max_lazy;
  15539. s.good_match = configuration_table[s.level].good_length;
  15540. s.nice_match = configuration_table[s.level].nice_length;
  15541. s.max_chain_length = configuration_table[s.level].max_chain;
  15542. s.strstart = 0;
  15543. s.block_start = 0;
  15544. s.lookahead = 0;
  15545. s.insert = 0;
  15546. s.match_length = s.prev_length = MIN_MATCH - 1;
  15547. s.match_available = 0;
  15548. s.ins_h = 0;
  15549. }
  15550. function DeflateState() {
  15551. this.strm = null; /* pointer back to this zlib stream */
  15552. this.status = 0; /* as the name implies */
  15553. this.pending_buf = null; /* output still pending */
  15554. this.pending_buf_size = 0; /* size of pending_buf */
  15555. this.pending_out = 0; /* next pending byte to output to the stream */
  15556. this.pending = 0; /* nb of bytes in the pending buffer */
  15557. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15558. this.gzhead = null; /* gzip header information to write */
  15559. this.gzindex = 0; /* where in extra, name, or comment */
  15560. this.method = Z_DEFLATED; /* can only be DEFLATED */
  15561. this.last_flush = -1; /* value of flush param for previous deflate call */
  15562. this.w_size = 0; /* LZ77 window size (32K by default) */
  15563. this.w_bits = 0; /* log2(w_size) (8..16) */
  15564. this.w_mask = 0; /* w_size - 1 */
  15565. this.window = null;
  15566. /* Sliding window. Input bytes are read into the second half of the window,
  15567. * and move to the first half later to keep a dictionary of at least wSize
  15568. * bytes. With this organization, matches are limited to a distance of
  15569. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  15570. * performed with a length multiple of the block size.
  15571. */
  15572. this.window_size = 0;
  15573. /* Actual size of window: 2*wSize, except when the user input buffer
  15574. * is directly used as sliding window.
  15575. */
  15576. this.prev = null;
  15577. /* Link to older string with same hash index. To limit the size of this
  15578. * array to 64K, this link is maintained only for the last 32K strings.
  15579. * An index in this array is thus a window index modulo 32K.
  15580. */
  15581. this.head = null; /* Heads of the hash chains or NIL. */
  15582. this.ins_h = 0; /* hash index of string to be inserted */
  15583. this.hash_size = 0; /* number of elements in hash table */
  15584. this.hash_bits = 0; /* log2(hash_size) */
  15585. this.hash_mask = 0; /* hash_size-1 */
  15586. this.hash_shift = 0;
  15587. /* Number of bits by which ins_h must be shifted at each input
  15588. * step. It must be such that after MIN_MATCH steps, the oldest
  15589. * byte no longer takes part in the hash key, that is:
  15590. * hash_shift * MIN_MATCH >= hash_bits
  15591. */
  15592. this.block_start = 0;
  15593. /* Window position at the beginning of the current output block. Gets
  15594. * negative when the window is moved backwards.
  15595. */
  15596. this.match_length = 0; /* length of best match */
  15597. this.prev_match = 0; /* previous match */
  15598. this.match_available = 0; /* set if previous match exists */
  15599. this.strstart = 0; /* start of string to insert */
  15600. this.match_start = 0; /* start of matching string */
  15601. this.lookahead = 0; /* number of valid bytes ahead in window */
  15602. this.prev_length = 0;
  15603. /* Length of the best match at previous step. Matches not greater than this
  15604. * are discarded. This is used in the lazy match evaluation.
  15605. */
  15606. this.max_chain_length = 0;
  15607. /* To speed up deflation, hash chains are never searched beyond this
  15608. * length. A higher limit improves compression ratio but degrades the
  15609. * speed.
  15610. */
  15611. this.max_lazy_match = 0;
  15612. /* Attempt to find a better match only when the current match is strictly
  15613. * smaller than this value. This mechanism is used only for compression
  15614. * levels >= 4.
  15615. */
  15616. // That's alias to max_lazy_match, don't use directly
  15617. //this.max_insert_length = 0;
  15618. /* Insert new strings in the hash table only if the match length is not
  15619. * greater than this length. This saves time but degrades compression.
  15620. * max_insert_length is used only for compression levels <= 3.
  15621. */
  15622. this.level = 0; /* compression level (1..9) */
  15623. this.strategy = 0; /* favor or force Huffman coding*/
  15624. this.good_match = 0;
  15625. /* Use a faster search when the previous match is longer than this */
  15626. this.nice_match = 0; /* Stop searching when current match exceeds this */
  15627. /* used by trees.c: */
  15628. /* Didn't use ct_data typedef below to suppress compiler warning */
  15629. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  15630. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  15631. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  15632. // Use flat array of DOUBLE size, with interleaved fata,
  15633. // because JS does not support effective
  15634. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  15635. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  15636. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  15637. zero(this.dyn_ltree);
  15638. zero(this.dyn_dtree);
  15639. zero(this.bl_tree);
  15640. this.l_desc = null; /* desc. for literal tree */
  15641. this.d_desc = null; /* desc. for distance tree */
  15642. this.bl_desc = null; /* desc. for bit length tree */
  15643. //ush bl_count[MAX_BITS+1];
  15644. this.bl_count = new utils.Buf16(MAX_BITS+1);
  15645. /* number of codes at each bit length for an optimal tree */
  15646. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  15647. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  15648. zero(this.heap);
  15649. this.heap_len = 0; /* number of elements in the heap */
  15650. this.heap_max = 0; /* element of largest frequency */
  15651. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15652. * The same heap array is used to build all trees.
  15653. */
  15654. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  15655. zero(this.depth);
  15656. /* Depth of each subtree used as tie breaker for trees of equal frequency
  15657. */
  15658. this.l_buf = 0; /* buffer index for literals or lengths */
  15659. this.lit_bufsize = 0;
  15660. /* Size of match buffer for literals/lengths. There are 4 reasons for
  15661. * limiting lit_bufsize to 64K:
  15662. * - frequencies can be kept in 16 bit counters
  15663. * - if compression is not successful for the first block, all input
  15664. * data is still in the window so we can still emit a stored block even
  15665. * when input comes from standard input. (This can also be done for
  15666. * all blocks if lit_bufsize is not greater than 32K.)
  15667. * - if compression is not successful for a file smaller than 64K, we can
  15668. * even emit a stored file instead of a stored block (saving 5 bytes).
  15669. * This is applicable only for zip (not gzip or zlib).
  15670. * - creating new Huffman trees less frequently may not provide fast
  15671. * adaptation to changes in the input data statistics. (Take for
  15672. * example a binary file with poorly compressible code followed by
  15673. * a highly compressible string table.) Smaller buffer sizes give
  15674. * fast adaptation but have of course the overhead of transmitting
  15675. * trees more frequently.
  15676. * - I can't count above 4
  15677. */
  15678. this.last_lit = 0; /* running index in l_buf */
  15679. this.d_buf = 0;
  15680. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  15681. * the same number of elements. To use different lengths, an extra flag
  15682. * array would be necessary.
  15683. */
  15684. this.opt_len = 0; /* bit length of current block with optimal trees */
  15685. this.static_len = 0; /* bit length of current block with static trees */
  15686. this.matches = 0; /* number of string matches in current block */
  15687. this.insert = 0; /* bytes at end of window left to insert */
  15688. this.bi_buf = 0;
  15689. /* Output buffer. bits are inserted starting at the bottom (least
  15690. * significant bits).
  15691. */
  15692. this.bi_valid = 0;
  15693. /* Number of valid bits in bi_buf. All bits above the last valid bit
  15694. * are always zero.
  15695. */
  15696. // Used for window memory init. We safely ignore it for JS. That makes
  15697. // sense only for pointers and memory check tools.
  15698. //this.high_water = 0;
  15699. /* High water mark offset in window for initialized bytes -- bytes above
  15700. * this are set to zero in order to avoid memory check warnings when
  15701. * longest match routines access bytes past the input. This is then
  15702. * updated to the new high water mark.
  15703. */
  15704. }
  15705. function deflateResetKeep(strm) {
  15706. var s;
  15707. if (!strm || !strm.state) {
  15708. return err(strm, Z_STREAM_ERROR);
  15709. }
  15710. strm.total_in = strm.total_out = 0;
  15711. strm.data_type = Z_UNKNOWN;
  15712. s = strm.state;
  15713. s.pending = 0;
  15714. s.pending_out = 0;
  15715. if (s.wrap < 0) {
  15716. s.wrap = -s.wrap;
  15717. /* was made negative by deflate(..., Z_FINISH); */
  15718. }
  15719. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  15720. strm.adler = (s.wrap === 2) ?
  15721. 0 // crc32(0, Z_NULL, 0)
  15722. :
  15723. 1; // adler32(0, Z_NULL, 0)
  15724. s.last_flush = Z_NO_FLUSH;
  15725. trees._tr_init(s);
  15726. return Z_OK;
  15727. }
  15728. function deflateReset(strm) {
  15729. var ret = deflateResetKeep(strm);
  15730. if (ret === Z_OK) {
  15731. lm_init(strm.state);
  15732. }
  15733. return ret;
  15734. }
  15735. function deflateSetHeader(strm, head) {
  15736. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15737. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  15738. strm.state.gzhead = head;
  15739. return Z_OK;
  15740. }
  15741. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  15742. if (!strm) { // === Z_NULL
  15743. return Z_STREAM_ERROR;
  15744. }
  15745. var wrap = 1;
  15746. if (level === Z_DEFAULT_COMPRESSION) {
  15747. level = 6;
  15748. }
  15749. if (windowBits < 0) { /* suppress zlib wrapper */
  15750. wrap = 0;
  15751. windowBits = -windowBits;
  15752. }
  15753. else if (windowBits > 15) {
  15754. wrap = 2; /* write gzip wrapper instead */
  15755. windowBits -= 16;
  15756. }
  15757. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  15758. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  15759. strategy < 0 || strategy > Z_FIXED) {
  15760. return err(strm, Z_STREAM_ERROR);
  15761. }
  15762. if (windowBits === 8) {
  15763. windowBits = 9;
  15764. }
  15765. /* until 256-byte window bug fixed */
  15766. var s = new DeflateState();
  15767. strm.state = s;
  15768. s.strm = strm;
  15769. s.wrap = wrap;
  15770. s.gzhead = null;
  15771. s.w_bits = windowBits;
  15772. s.w_size = 1 << s.w_bits;
  15773. s.w_mask = s.w_size - 1;
  15774. s.hash_bits = memLevel + 7;
  15775. s.hash_size = 1 << s.hash_bits;
  15776. s.hash_mask = s.hash_size - 1;
  15777. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15778. s.window = new utils.Buf8(s.w_size * 2);
  15779. s.head = new utils.Buf16(s.hash_size);
  15780. s.prev = new utils.Buf16(s.w_size);
  15781. // Don't need mem init magic for JS.
  15782. //s.high_water = 0; /* nothing written to s->window yet */
  15783. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  15784. s.pending_buf_size = s.lit_bufsize * 4;
  15785. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  15786. s.d_buf = s.lit_bufsize >> 1;
  15787. s.l_buf = (1 + 2) * s.lit_bufsize;
  15788. s.level = level;
  15789. s.strategy = strategy;
  15790. s.method = method;
  15791. return deflateReset(strm);
  15792. }
  15793. function deflateInit(strm, level) {
  15794. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15795. }
  15796. function deflate(strm, flush) {
  15797. var old_flush, s;
  15798. var beg, val; // for gzip header write only
  15799. if (!strm || !strm.state ||
  15800. flush > Z_BLOCK || flush < 0) {
  15801. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15802. }
  15803. s = strm.state;
  15804. if (!strm.output ||
  15805. (!strm.input && strm.avail_in !== 0) ||
  15806. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15807. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15808. }
  15809. s.strm = strm; /* just in case */
  15810. old_flush = s.last_flush;
  15811. s.last_flush = flush;
  15812. /* Write the header */
  15813. if (s.status === INIT_STATE) {
  15814. if (s.wrap === 2) { // GZIP header
  15815. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15816. put_byte(s, 31);
  15817. put_byte(s, 139);
  15818. put_byte(s, 8);
  15819. if (!s.gzhead) { // s->gzhead == Z_NULL
  15820. put_byte(s, 0);
  15821. put_byte(s, 0);
  15822. put_byte(s, 0);
  15823. put_byte(s, 0);
  15824. put_byte(s, 0);
  15825. put_byte(s, s.level === 9 ? 2 :
  15826. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15827. 4 : 0));
  15828. put_byte(s, OS_CODE);
  15829. s.status = BUSY_STATE;
  15830. }
  15831. else {
  15832. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15833. (s.gzhead.hcrc ? 2 : 0) +
  15834. (!s.gzhead.extra ? 0 : 4) +
  15835. (!s.gzhead.name ? 0 : 8) +
  15836. (!s.gzhead.comment ? 0 : 16)
  15837. );
  15838. put_byte(s, s.gzhead.time & 0xff);
  15839. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15840. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15841. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15842. put_byte(s, s.level === 9 ? 2 :
  15843. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15844. 4 : 0));
  15845. put_byte(s, s.gzhead.os & 0xff);
  15846. if (s.gzhead.extra && s.gzhead.extra.length) {
  15847. put_byte(s, s.gzhead.extra.length & 0xff);
  15848. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15849. }
  15850. if (s.gzhead.hcrc) {
  15851. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15852. }
  15853. s.gzindex = 0;
  15854. s.status = EXTRA_STATE;
  15855. }
  15856. }
  15857. else // DEFLATE header
  15858. {
  15859. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15860. var level_flags = -1;
  15861. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15862. level_flags = 0;
  15863. } else if (s.level < 6) {
  15864. level_flags = 1;
  15865. } else if (s.level === 6) {
  15866. level_flags = 2;
  15867. } else {
  15868. level_flags = 3;
  15869. }
  15870. header |= (level_flags << 6);
  15871. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15872. header += 31 - (header % 31);
  15873. s.status = BUSY_STATE;
  15874. putShortMSB(s, header);
  15875. /* Save the adler32 of the preset dictionary: */
  15876. if (s.strstart !== 0) {
  15877. putShortMSB(s, strm.adler >>> 16);
  15878. putShortMSB(s, strm.adler & 0xffff);
  15879. }
  15880. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15881. }
  15882. }
  15883. //#ifdef GZIP
  15884. if (s.status === EXTRA_STATE) {
  15885. if (s.gzhead.extra/* != Z_NULL*/) {
  15886. beg = s.pending; /* start of bytes to update crc */
  15887. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15888. if (s.pending === s.pending_buf_size) {
  15889. if (s.gzhead.hcrc && s.pending > beg) {
  15890. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15891. }
  15892. flush_pending(strm);
  15893. beg = s.pending;
  15894. if (s.pending === s.pending_buf_size) {
  15895. break;
  15896. }
  15897. }
  15898. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15899. s.gzindex++;
  15900. }
  15901. if (s.gzhead.hcrc && s.pending > beg) {
  15902. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15903. }
  15904. if (s.gzindex === s.gzhead.extra.length) {
  15905. s.gzindex = 0;
  15906. s.status = NAME_STATE;
  15907. }
  15908. }
  15909. else {
  15910. s.status = NAME_STATE;
  15911. }
  15912. }
  15913. if (s.status === NAME_STATE) {
  15914. if (s.gzhead.name/* != Z_NULL*/) {
  15915. beg = s.pending; /* start of bytes to update crc */
  15916. //int val;
  15917. do {
  15918. if (s.pending === s.pending_buf_size) {
  15919. if (s.gzhead.hcrc && s.pending > beg) {
  15920. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15921. }
  15922. flush_pending(strm);
  15923. beg = s.pending;
  15924. if (s.pending === s.pending_buf_size) {
  15925. val = 1;
  15926. break;
  15927. }
  15928. }
  15929. // JS specific: little magic to add zero terminator to end of string
  15930. if (s.gzindex < s.gzhead.name.length) {
  15931. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15932. } else {
  15933. val = 0;
  15934. }
  15935. put_byte(s, val);
  15936. } while (val !== 0);
  15937. if (s.gzhead.hcrc && s.pending > beg) {
  15938. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15939. }
  15940. if (val === 0) {
  15941. s.gzindex = 0;
  15942. s.status = COMMENT_STATE;
  15943. }
  15944. }
  15945. else {
  15946. s.status = COMMENT_STATE;
  15947. }
  15948. }
  15949. if (s.status === COMMENT_STATE) {
  15950. if (s.gzhead.comment/* != Z_NULL*/) {
  15951. beg = s.pending; /* start of bytes to update crc */
  15952. //int val;
  15953. do {
  15954. if (s.pending === s.pending_buf_size) {
  15955. if (s.gzhead.hcrc && s.pending > beg) {
  15956. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15957. }
  15958. flush_pending(strm);
  15959. beg = s.pending;
  15960. if (s.pending === s.pending_buf_size) {
  15961. val = 1;
  15962. break;
  15963. }
  15964. }
  15965. // JS specific: little magic to add zero terminator to end of string
  15966. if (s.gzindex < s.gzhead.comment.length) {
  15967. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15968. } else {
  15969. val = 0;
  15970. }
  15971. put_byte(s, val);
  15972. } while (val !== 0);
  15973. if (s.gzhead.hcrc && s.pending > beg) {
  15974. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15975. }
  15976. if (val === 0) {
  15977. s.status = HCRC_STATE;
  15978. }
  15979. }
  15980. else {
  15981. s.status = HCRC_STATE;
  15982. }
  15983. }
  15984. if (s.status === HCRC_STATE) {
  15985. if (s.gzhead.hcrc) {
  15986. if (s.pending + 2 > s.pending_buf_size) {
  15987. flush_pending(strm);
  15988. }
  15989. if (s.pending + 2 <= s.pending_buf_size) {
  15990. put_byte(s, strm.adler & 0xff);
  15991. put_byte(s, (strm.adler >> 8) & 0xff);
  15992. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15993. s.status = BUSY_STATE;
  15994. }
  15995. }
  15996. else {
  15997. s.status = BUSY_STATE;
  15998. }
  15999. }
  16000. //#endif
  16001. /* Flush as much pending output as possible */
  16002. if (s.pending !== 0) {
  16003. flush_pending(strm);
  16004. if (strm.avail_out === 0) {
  16005. /* Since avail_out is 0, deflate will be called again with
  16006. * more output space, but possibly with both pending and
  16007. * avail_in equal to zero. There won't be anything to do,
  16008. * but this is not an error situation so make sure we
  16009. * return OK instead of BUF_ERROR at next call of deflate:
  16010. */
  16011. s.last_flush = -1;
  16012. return Z_OK;
  16013. }
  16014. /* Make sure there is something to do and avoid duplicate consecutive
  16015. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16016. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16017. */
  16018. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16019. flush !== Z_FINISH) {
  16020. return err(strm, Z_BUF_ERROR);
  16021. }
  16022. /* User must not provide more input after the first FINISH: */
  16023. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16024. return err(strm, Z_BUF_ERROR);
  16025. }
  16026. /* Start a new block or continue the current one.
  16027. */
  16028. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16029. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16030. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16031. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16032. configuration_table[s.level].func(s, flush));
  16033. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16034. s.status = FINISH_STATE;
  16035. }
  16036. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  16037. if (strm.avail_out === 0) {
  16038. s.last_flush = -1;
  16039. /* avoid BUF_ERROR next call, see above */
  16040. }
  16041. return Z_OK;
  16042. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  16043. * of deflate should use the same flush parameter to make sure
  16044. * that the flush is complete. So we don't have to output an
  16045. * empty block here, this will be done at next call. This also
  16046. * ensures that for a very small output buffer, we emit at most
  16047. * one empty block.
  16048. */
  16049. }
  16050. if (bstate === BS_BLOCK_DONE) {
  16051. if (flush === Z_PARTIAL_FLUSH) {
  16052. trees._tr_align(s);
  16053. }
  16054. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  16055. trees._tr_stored_block(s, 0, 0, false);
  16056. /* For a full flush, this empty block will be recognized
  16057. * as a special marker by inflate_sync().
  16058. */
  16059. if (flush === Z_FULL_FLUSH) {
  16060. /*** CLEAR_HASH(s); ***/ /* forget history */
  16061. zero(s.head); // Fill with NIL (= 0);
  16062. if (s.lookahead === 0) {
  16063. s.strstart = 0;
  16064. s.block_start = 0;
  16065. s.insert = 0;
  16066. }
  16067. }
  16068. }
  16069. flush_pending(strm);
  16070. if (strm.avail_out === 0) {
  16071. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  16072. return Z_OK;
  16073. }
  16074. }
  16075. }
  16076. //Assert(strm->avail_out > 0, "bug2");
  16077. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  16078. if (flush !== Z_FINISH) { return Z_OK; }
  16079. if (s.wrap <= 0) { return Z_STREAM_END; }
  16080. /* Write the trailer */
  16081. if (s.wrap === 2) {
  16082. put_byte(s, strm.adler & 0xff);
  16083. put_byte(s, (strm.adler >> 8) & 0xff);
  16084. put_byte(s, (strm.adler >> 16) & 0xff);
  16085. put_byte(s, (strm.adler >> 24) & 0xff);
  16086. put_byte(s, strm.total_in & 0xff);
  16087. put_byte(s, (strm.total_in >> 8) & 0xff);
  16088. put_byte(s, (strm.total_in >> 16) & 0xff);
  16089. put_byte(s, (strm.total_in >> 24) & 0xff);
  16090. }
  16091. else
  16092. {
  16093. putShortMSB(s, strm.adler >>> 16);
  16094. putShortMSB(s, strm.adler & 0xffff);
  16095. }
  16096. flush_pending(strm);
  16097. /* If avail_out is zero, the application will call deflate again
  16098. * to flush the rest.
  16099. */
  16100. if (s.wrap > 0) { s.wrap = -s.wrap; }
  16101. /* write the trailer only once! */
  16102. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  16103. }
  16104. function deflateEnd(strm) {
  16105. var status;
  16106. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  16107. return Z_STREAM_ERROR;
  16108. }
  16109. status = strm.state.status;
  16110. if (status !== INIT_STATE &&
  16111. status !== EXTRA_STATE &&
  16112. status !== NAME_STATE &&
  16113. status !== COMMENT_STATE &&
  16114. status !== HCRC_STATE &&
  16115. status !== BUSY_STATE &&
  16116. status !== FINISH_STATE
  16117. ) {
  16118. return err(strm, Z_STREAM_ERROR);
  16119. }
  16120. strm.state = null;
  16121. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  16122. }
  16123. /* =========================================================================
  16124. * Copy the source state to the destination state
  16125. */
  16126. //function deflateCopy(dest, source) {
  16127. //
  16128. //}
  16129. exports.deflateInit = deflateInit;
  16130. exports.deflateInit2 = deflateInit2;
  16131. exports.deflateReset = deflateReset;
  16132. exports.deflateResetKeep = deflateResetKeep;
  16133. exports.deflateSetHeader = deflateSetHeader;
  16134. exports.deflate = deflate;
  16135. exports.deflateEnd = deflateEnd;
  16136. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  16137. /* Not implemented
  16138. exports.deflateBound = deflateBound;
  16139. exports.deflateCopy = deflateCopy;
  16140. exports.deflateSetDictionary = deflateSetDictionary;
  16141. exports.deflateParams = deflateParams;
  16142. exports.deflatePending = deflatePending;
  16143. exports.deflatePrime = deflatePrime;
  16144. exports.deflateTune = deflateTune;
  16145. */
  16146. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./messages":62,"./trees":63}],58:[function(require,module,exports){
  16147. 'use strict';
  16148. function GZheader() {
  16149. /* true if compressed data believed to be text */
  16150. this.text = 0;
  16151. /* modification time */
  16152. this.time = 0;
  16153. /* extra flags (not used when writing a gzip file) */
  16154. this.xflags = 0;
  16155. /* operating system */
  16156. this.os = 0;
  16157. /* pointer to extra field or Z_NULL if none */
  16158. this.extra = null;
  16159. /* extra field length (valid if extra != Z_NULL) */
  16160. this.extra_len = 0; // Actually, we don't need it in JS,
  16161. // but leave for few code modifications
  16162. //
  16163. // Setup limits is not necessary because in js we should not preallocate memory
  16164. // for inflate use constant limit in 65536 bytes
  16165. //
  16166. /* space at extra (only when reading header) */
  16167. // this.extra_max = 0;
  16168. /* pointer to zero-terminated file name or Z_NULL */
  16169. this.name = '';
  16170. /* space at name (only when reading header) */
  16171. // this.name_max = 0;
  16172. /* pointer to zero-terminated comment or Z_NULL */
  16173. this.comment = '';
  16174. /* space at comment (only when reading header) */
  16175. // this.comm_max = 0;
  16176. /* true if there was or will be a header crc */
  16177. this.hcrc = 0;
  16178. /* true when done reading gzip header (not used when writing a gzip file) */
  16179. this.done = false;
  16180. }
  16181. module.exports = GZheader;
  16182. },{}],59:[function(require,module,exports){
  16183. 'use strict';
  16184. // See state defs from inflate.js
  16185. var BAD = 30; /* got a data error -- remain here until reset */
  16186. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16187. /*
  16188. Decode literal, length, and distance codes and write out the resulting
  16189. literal and match bytes until either not enough input or output is
  16190. available, an end-of-block is encountered, or a data error is encountered.
  16191. When large enough input and output buffers are supplied to inflate(), for
  16192. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  16193. inflate execution time is spent in this routine.
  16194. Entry assumptions:
  16195. state.mode === LEN
  16196. strm.avail_in >= 6
  16197. strm.avail_out >= 258
  16198. start >= strm.avail_out
  16199. state.bits < 8
  16200. On return, state.mode is one of:
  16201. LEN -- ran out of enough output space or enough available input
  16202. TYPE -- reached end of block code, inflate() to interpret next block
  16203. BAD -- error in block data
  16204. Notes:
  16205. - The maximum input bits used by a length/distance pair is 15 bits for the
  16206. length code, 5 bits for the length extra, 15 bits for the distance code,
  16207. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  16208. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  16209. checking for available input while decoding.
  16210. - The maximum bytes that a single length/distance pair can output is 258
  16211. bytes, which is the maximum length that can be coded. inflate_fast()
  16212. requires strm.avail_out >= 258 for each loop to avoid checking for
  16213. output space.
  16214. */
  16215. module.exports = function inflate_fast(strm, start) {
  16216. var state;
  16217. var _in; /* local strm.input */
  16218. var last; /* have enough input while in < last */
  16219. var _out; /* local strm.output */
  16220. var beg; /* inflate()'s initial strm.output */
  16221. var end; /* while out < end, enough space available */
  16222. //#ifdef INFLATE_STRICT
  16223. var dmax; /* maximum distance from zlib header */
  16224. //#endif
  16225. var wsize; /* window size or zero if not using window */
  16226. var whave; /* valid bytes in the window */
  16227. var wnext; /* window write index */
  16228. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  16229. var s_window; /* allocated sliding window, if wsize != 0 */
  16230. var hold; /* local strm.hold */
  16231. var bits; /* local strm.bits */
  16232. var lcode; /* local strm.lencode */
  16233. var dcode; /* local strm.distcode */
  16234. var lmask; /* mask for first level of length codes */
  16235. var dmask; /* mask for first level of distance codes */
  16236. var here; /* retrieved table entry */
  16237. var op; /* code bits, operation, extra bits, or */
  16238. /* window position, window bytes to copy */
  16239. var len; /* match length, unused bytes */
  16240. var dist; /* match distance */
  16241. var from; /* where to copy match from */
  16242. var from_source;
  16243. var input, output; // JS specific, because we have no pointers
  16244. /* copy state to local variables */
  16245. state = strm.state;
  16246. //here = state.here;
  16247. _in = strm.next_in;
  16248. input = strm.input;
  16249. last = _in + (strm.avail_in - 5);
  16250. _out = strm.next_out;
  16251. output = strm.output;
  16252. beg = _out - (start - strm.avail_out);
  16253. end = _out + (strm.avail_out - 257);
  16254. //#ifdef INFLATE_STRICT
  16255. dmax = state.dmax;
  16256. //#endif
  16257. wsize = state.wsize;
  16258. whave = state.whave;
  16259. wnext = state.wnext;
  16260. s_window = state.window;
  16261. hold = state.hold;
  16262. bits = state.bits;
  16263. lcode = state.lencode;
  16264. dcode = state.distcode;
  16265. lmask = (1 << state.lenbits) - 1;
  16266. dmask = (1 << state.distbits) - 1;
  16267. /* decode literals and length/distances until end-of-block or not enough
  16268. input data or output space */
  16269. top:
  16270. do {
  16271. if (bits < 15) {
  16272. hold += input[_in++] << bits;
  16273. bits += 8;
  16274. hold += input[_in++] << bits;
  16275. bits += 8;
  16276. }
  16277. here = lcode[hold & lmask];
  16278. dolen:
  16279. for (;;) { // Goto emulation
  16280. op = here >>> 24/*here.bits*/;
  16281. hold >>>= op;
  16282. bits -= op;
  16283. op = (here >>> 16) & 0xff/*here.op*/;
  16284. if (op === 0) { /* literal */
  16285. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16286. // "inflate: literal '%c'\n" :
  16287. // "inflate: literal 0x%02x\n", here.val));
  16288. output[_out++] = here & 0xffff/*here.val*/;
  16289. }
  16290. else if (op & 16) { /* length base */
  16291. len = here & 0xffff/*here.val*/;
  16292. op &= 15; /* number of extra bits */
  16293. if (op) {
  16294. if (bits < op) {
  16295. hold += input[_in++] << bits;
  16296. bits += 8;
  16297. }
  16298. len += hold & ((1 << op) - 1);
  16299. hold >>>= op;
  16300. bits -= op;
  16301. }
  16302. //Tracevv((stderr, "inflate: length %u\n", len));
  16303. if (bits < 15) {
  16304. hold += input[_in++] << bits;
  16305. bits += 8;
  16306. hold += input[_in++] << bits;
  16307. bits += 8;
  16308. }
  16309. here = dcode[hold & dmask];
  16310. dodist:
  16311. for (;;) { // goto emulation
  16312. op = here >>> 24/*here.bits*/;
  16313. hold >>>= op;
  16314. bits -= op;
  16315. op = (here >>> 16) & 0xff/*here.op*/;
  16316. if (op & 16) { /* distance base */
  16317. dist = here & 0xffff/*here.val*/;
  16318. op &= 15; /* number of extra bits */
  16319. if (bits < op) {
  16320. hold += input[_in++] << bits;
  16321. bits += 8;
  16322. if (bits < op) {
  16323. hold += input[_in++] << bits;
  16324. bits += 8;
  16325. }
  16326. }
  16327. dist += hold & ((1 << op) - 1);
  16328. //#ifdef INFLATE_STRICT
  16329. if (dist > dmax) {
  16330. strm.msg = 'invalid distance too far back';
  16331. state.mode = BAD;
  16332. break top;
  16333. }
  16334. //#endif
  16335. hold >>>= op;
  16336. bits -= op;
  16337. //Tracevv((stderr, "inflate: distance %u\n", dist));
  16338. op = _out - beg; /* max distance in output */
  16339. if (dist > op) { /* see if copy from window */
  16340. op = dist - op; /* distance back in window */
  16341. if (op > whave) {
  16342. if (state.sane) {
  16343. strm.msg = 'invalid distance too far back';
  16344. state.mode = BAD;
  16345. break top;
  16346. }
  16347. // (!) This block is disabled in zlib defailts,
  16348. // don't enable it for binary compatibility
  16349. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16350. // if (len <= op - whave) {
  16351. // do {
  16352. // output[_out++] = 0;
  16353. // } while (--len);
  16354. // continue top;
  16355. // }
  16356. // len -= op - whave;
  16357. // do {
  16358. // output[_out++] = 0;
  16359. // } while (--op > whave);
  16360. // if (op === 0) {
  16361. // from = _out - dist;
  16362. // do {
  16363. // output[_out++] = output[from++];
  16364. // } while (--len);
  16365. // continue top;
  16366. // }
  16367. //#endif
  16368. }
  16369. from = 0; // window index
  16370. from_source = s_window;
  16371. if (wnext === 0) { /* very common case */
  16372. from += wsize - op;
  16373. if (op < len) { /* some from window */
  16374. len -= op;
  16375. do {
  16376. output[_out++] = s_window[from++];
  16377. } while (--op);
  16378. from = _out - dist; /* rest from output */
  16379. from_source = output;
  16380. }
  16381. }
  16382. else if (wnext < op) { /* wrap around window */
  16383. from += wsize + wnext - op;
  16384. op -= wnext;
  16385. if (op < len) { /* some from end of window */
  16386. len -= op;
  16387. do {
  16388. output[_out++] = s_window[from++];
  16389. } while (--op);
  16390. from = 0;
  16391. if (wnext < len) { /* some from start of window */
  16392. op = wnext;
  16393. len -= op;
  16394. do {
  16395. output[_out++] = s_window[from++];
  16396. } while (--op);
  16397. from = _out - dist; /* rest from output */
  16398. from_source = output;
  16399. }
  16400. }
  16401. }
  16402. else { /* contiguous in window */
  16403. from += wnext - op;
  16404. if (op < len) { /* some from window */
  16405. len -= op;
  16406. do {
  16407. output[_out++] = s_window[from++];
  16408. } while (--op);
  16409. from = _out - dist; /* rest from output */
  16410. from_source = output;
  16411. }
  16412. }
  16413. while (len > 2) {
  16414. output[_out++] = from_source[from++];
  16415. output[_out++] = from_source[from++];
  16416. output[_out++] = from_source[from++];
  16417. len -= 3;
  16418. }
  16419. if (len) {
  16420. output[_out++] = from_source[from++];
  16421. if (len > 1) {
  16422. output[_out++] = from_source[from++];
  16423. }
  16424. }
  16425. }
  16426. else {
  16427. from = _out - dist; /* copy direct from output */
  16428. do { /* minimum length is three */
  16429. output[_out++] = output[from++];
  16430. output[_out++] = output[from++];
  16431. output[_out++] = output[from++];
  16432. len -= 3;
  16433. } while (len > 2);
  16434. if (len) {
  16435. output[_out++] = output[from++];
  16436. if (len > 1) {
  16437. output[_out++] = output[from++];
  16438. }
  16439. }
  16440. }
  16441. }
  16442. else if ((op & 64) === 0) { /* 2nd level distance code */
  16443. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16444. continue dodist;
  16445. }
  16446. else {
  16447. strm.msg = 'invalid distance code';
  16448. state.mode = BAD;
  16449. break top;
  16450. }
  16451. break; // need to emulate goto via "continue"
  16452. }
  16453. }
  16454. else if ((op & 64) === 0) { /* 2nd level length code */
  16455. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16456. continue dolen;
  16457. }
  16458. else if (op & 32) { /* end-of-block */
  16459. //Tracevv((stderr, "inflate: end of block\n"));
  16460. state.mode = TYPE;
  16461. break top;
  16462. }
  16463. else {
  16464. strm.msg = 'invalid literal/length code';
  16465. state.mode = BAD;
  16466. break top;
  16467. }
  16468. break; // need to emulate goto via "continue"
  16469. }
  16470. } while (_in < last && _out < end);
  16471. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  16472. len = bits >> 3;
  16473. _in -= len;
  16474. bits -= len << 3;
  16475. hold &= (1 << bits) - 1;
  16476. /* update state and return */
  16477. strm.next_in = _in;
  16478. strm.next_out = _out;
  16479. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  16480. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  16481. state.hold = hold;
  16482. state.bits = bits;
  16483. return;
  16484. };
  16485. },{}],60:[function(require,module,exports){
  16486. 'use strict';
  16487. var utils = require('../utils/common');
  16488. var adler32 = require('./adler32');
  16489. var crc32 = require('./crc32');
  16490. var inflate_fast = require('./inffast');
  16491. var inflate_table = require('./inftrees');
  16492. var CODES = 0;
  16493. var LENS = 1;
  16494. var DISTS = 2;
  16495. /* Public constants ==========================================================*/
  16496. /* ===========================================================================*/
  16497. /* Allowed flush values; see deflate() and inflate() below for details */
  16498. //var Z_NO_FLUSH = 0;
  16499. //var Z_PARTIAL_FLUSH = 1;
  16500. //var Z_SYNC_FLUSH = 2;
  16501. //var Z_FULL_FLUSH = 3;
  16502. var Z_FINISH = 4;
  16503. var Z_BLOCK = 5;
  16504. var Z_TREES = 6;
  16505. /* Return codes for the compression/decompression functions. Negative values
  16506. * are errors, positive values are used for special but normal events.
  16507. */
  16508. var Z_OK = 0;
  16509. var Z_STREAM_END = 1;
  16510. var Z_NEED_DICT = 2;
  16511. //var Z_ERRNO = -1;
  16512. var Z_STREAM_ERROR = -2;
  16513. var Z_DATA_ERROR = -3;
  16514. var Z_MEM_ERROR = -4;
  16515. var Z_BUF_ERROR = -5;
  16516. //var Z_VERSION_ERROR = -6;
  16517. /* The deflate compression method */
  16518. var Z_DEFLATED = 8;
  16519. /* STATES ====================================================================*/
  16520. /* ===========================================================================*/
  16521. var HEAD = 1; /* i: waiting for magic header */
  16522. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  16523. var TIME = 3; /* i: waiting for modification time (gzip) */
  16524. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  16525. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  16526. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  16527. var NAME = 7; /* i: waiting for end of file name (gzip) */
  16528. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  16529. var HCRC = 9; /* i: waiting for header crc (gzip) */
  16530. var DICTID = 10; /* i: waiting for dictionary check value */
  16531. var DICT = 11; /* waiting for inflateSetDictionary() call */
  16532. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16533. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  16534. var STORED = 14; /* i: waiting for stored size (length and complement) */
  16535. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  16536. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  16537. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  16538. var LENLENS = 18; /* i: waiting for code length code lengths */
  16539. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  16540. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  16541. var LEN = 21; /* i: waiting for length/lit/eob code */
  16542. var LENEXT = 22; /* i: waiting for length extra bits */
  16543. var DIST = 23; /* i: waiting for distance code */
  16544. var DISTEXT = 24; /* i: waiting for distance extra bits */
  16545. var MATCH = 25; /* o: waiting for output space to copy string */
  16546. var LIT = 26; /* o: waiting for output space to write literal */
  16547. var CHECK = 27; /* i: waiting for 32-bit check value */
  16548. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  16549. var DONE = 29; /* finished check, done -- remain here until reset */
  16550. var BAD = 30; /* got a data error -- remain here until reset */
  16551. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  16552. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  16553. /* ===========================================================================*/
  16554. var ENOUGH_LENS = 852;
  16555. var ENOUGH_DISTS = 592;
  16556. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16557. var MAX_WBITS = 15;
  16558. /* 32K LZ77 window */
  16559. var DEF_WBITS = MAX_WBITS;
  16560. function ZSWAP32(q) {
  16561. return (((q >>> 24) & 0xff) +
  16562. ((q >>> 8) & 0xff00) +
  16563. ((q & 0xff00) << 8) +
  16564. ((q & 0xff) << 24));
  16565. }
  16566. function InflateState() {
  16567. this.mode = 0; /* current inflate mode */
  16568. this.last = false; /* true if processing last block */
  16569. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16570. this.havedict = false; /* true if dictionary provided */
  16571. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  16572. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  16573. this.check = 0; /* protected copy of check value */
  16574. this.total = 0; /* protected copy of output count */
  16575. // TODO: may be {}
  16576. this.head = null; /* where to save gzip header information */
  16577. /* sliding window */
  16578. this.wbits = 0; /* log base 2 of requested window size */
  16579. this.wsize = 0; /* window size or zero if not using window */
  16580. this.whave = 0; /* valid bytes in the window */
  16581. this.wnext = 0; /* window write index */
  16582. this.window = null; /* allocated sliding window, if needed */
  16583. /* bit accumulator */
  16584. this.hold = 0; /* input bit accumulator */
  16585. this.bits = 0; /* number of bits in "in" */
  16586. /* for string and stored block copying */
  16587. this.length = 0; /* literal or length of data to copy */
  16588. this.offset = 0; /* distance back to copy string from */
  16589. /* for table and code decoding */
  16590. this.extra = 0; /* extra bits needed */
  16591. /* fixed and dynamic code tables */
  16592. this.lencode = null; /* starting table for length/literal codes */
  16593. this.distcode = null; /* starting table for distance codes */
  16594. this.lenbits = 0; /* index bits for lencode */
  16595. this.distbits = 0; /* index bits for distcode */
  16596. /* dynamic table building */
  16597. this.ncode = 0; /* number of code length code lengths */
  16598. this.nlen = 0; /* number of length code lengths */
  16599. this.ndist = 0; /* number of distance code lengths */
  16600. this.have = 0; /* number of code lengths in lens[] */
  16601. this.next = null; /* next available space in codes[] */
  16602. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  16603. this.work = new utils.Buf16(288); /* work area for code table building */
  16604. /*
  16605. because we don't have pointers in js, we use lencode and distcode directly
  16606. as buffers so we don't need codes
  16607. */
  16608. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  16609. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  16610. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  16611. this.sane = 0; /* if false, allow invalid distance too far */
  16612. this.back = 0; /* bits back of last unprocessed length/lit */
  16613. this.was = 0; /* initial length of match */
  16614. }
  16615. function inflateResetKeep(strm) {
  16616. var state;
  16617. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16618. state = strm.state;
  16619. strm.total_in = strm.total_out = state.total = 0;
  16620. strm.msg = ''; /*Z_NULL*/
  16621. if (state.wrap) { /* to support ill-conceived Java test suite */
  16622. strm.adler = state.wrap & 1;
  16623. }
  16624. state.mode = HEAD;
  16625. state.last = 0;
  16626. state.havedict = 0;
  16627. state.dmax = 32768;
  16628. state.head = null/*Z_NULL*/;
  16629. state.hold = 0;
  16630. state.bits = 0;
  16631. //state.lencode = state.distcode = state.next = state.codes;
  16632. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  16633. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  16634. state.sane = 1;
  16635. state.back = -1;
  16636. //Tracev((stderr, "inflate: reset\n"));
  16637. return Z_OK;
  16638. }
  16639. function inflateReset(strm) {
  16640. var state;
  16641. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16642. state = strm.state;
  16643. state.wsize = 0;
  16644. state.whave = 0;
  16645. state.wnext = 0;
  16646. return inflateResetKeep(strm);
  16647. }
  16648. function inflateReset2(strm, windowBits) {
  16649. var wrap;
  16650. var state;
  16651. /* get the state */
  16652. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16653. state = strm.state;
  16654. /* extract wrap request from windowBits parameter */
  16655. if (windowBits < 0) {
  16656. wrap = 0;
  16657. windowBits = -windowBits;
  16658. }
  16659. else {
  16660. wrap = (windowBits >> 4) + 1;
  16661. if (windowBits < 48) {
  16662. windowBits &= 15;
  16663. }
  16664. }
  16665. /* set number of window bits, free window if different */
  16666. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  16667. return Z_STREAM_ERROR;
  16668. }
  16669. if (state.window !== null && state.wbits !== windowBits) {
  16670. state.window = null;
  16671. }
  16672. /* update state and reset the rest of it */
  16673. state.wrap = wrap;
  16674. state.wbits = windowBits;
  16675. return inflateReset(strm);
  16676. }
  16677. function inflateInit2(strm, windowBits) {
  16678. var ret;
  16679. var state;
  16680. if (!strm) { return Z_STREAM_ERROR; }
  16681. //strm.msg = Z_NULL; /* in case we return an error */
  16682. state = new InflateState();
  16683. //if (state === Z_NULL) return Z_MEM_ERROR;
  16684. //Tracev((stderr, "inflate: allocated\n"));
  16685. strm.state = state;
  16686. state.window = null/*Z_NULL*/;
  16687. ret = inflateReset2(strm, windowBits);
  16688. if (ret !== Z_OK) {
  16689. strm.state = null/*Z_NULL*/;
  16690. }
  16691. return ret;
  16692. }
  16693. function inflateInit(strm) {
  16694. return inflateInit2(strm, DEF_WBITS);
  16695. }
  16696. /*
  16697. Return state with length and distance decoding tables and index sizes set to
  16698. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  16699. If BUILDFIXED is defined, then instead this routine builds the tables the
  16700. first time it's called, and returns those tables the first time and
  16701. thereafter. This reduces the size of the code by about 2K bytes, in
  16702. exchange for a little execution time. However, BUILDFIXED should not be
  16703. used for threaded applications, since the rewriting of the tables and virgin
  16704. may not be thread-safe.
  16705. */
  16706. var virgin = true;
  16707. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  16708. function fixedtables(state) {
  16709. /* build fixed huffman tables if first call (may not be thread safe) */
  16710. if (virgin) {
  16711. var sym;
  16712. lenfix = new utils.Buf32(512);
  16713. distfix = new utils.Buf32(32);
  16714. /* literal/length table */
  16715. sym = 0;
  16716. while (sym < 144) { state.lens[sym++] = 8; }
  16717. while (sym < 256) { state.lens[sym++] = 9; }
  16718. while (sym < 280) { state.lens[sym++] = 7; }
  16719. while (sym < 288) { state.lens[sym++] = 8; }
  16720. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  16721. /* distance table */
  16722. sym = 0;
  16723. while (sym < 32) { state.lens[sym++] = 5; }
  16724. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  16725. /* do this just once */
  16726. virgin = false;
  16727. }
  16728. state.lencode = lenfix;
  16729. state.lenbits = 9;
  16730. state.distcode = distfix;
  16731. state.distbits = 5;
  16732. }
  16733. /*
  16734. Update the window with the last wsize (normally 32K) bytes written before
  16735. returning. If window does not exist yet, create it. This is only called
  16736. when a window is already in use, or when output has been written during this
  16737. inflate call, but the end of the deflate stream has not been reached yet.
  16738. It is also called to create a window for dictionary data when a dictionary
  16739. is loaded.
  16740. Providing output buffers larger than 32K to inflate() should provide a speed
  16741. advantage, since only the last 32K of output is copied to the sliding window
  16742. upon return from inflate(), and since all distances after the first 32K of
  16743. output will fall in the output data, making match copies simpler and faster.
  16744. The advantage may be dependent on the size of the processor's data caches.
  16745. */
  16746. function updatewindow(strm, src, end, copy) {
  16747. var dist;
  16748. var state = strm.state;
  16749. /* if it hasn't been done already, allocate space for the window */
  16750. if (state.window === null) {
  16751. state.wsize = 1 << state.wbits;
  16752. state.wnext = 0;
  16753. state.whave = 0;
  16754. state.window = new utils.Buf8(state.wsize);
  16755. }
  16756. /* copy state->wsize or less output bytes into the circular window */
  16757. if (copy >= state.wsize) {
  16758. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  16759. state.wnext = 0;
  16760. state.whave = state.wsize;
  16761. }
  16762. else {
  16763. dist = state.wsize - state.wnext;
  16764. if (dist > copy) {
  16765. dist = copy;
  16766. }
  16767. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16768. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  16769. copy -= dist;
  16770. if (copy) {
  16771. //zmemcpy(state->window, end - copy, copy);
  16772. utils.arraySet(state.window,src, end - copy, copy, 0);
  16773. state.wnext = copy;
  16774. state.whave = state.wsize;
  16775. }
  16776. else {
  16777. state.wnext += dist;
  16778. if (state.wnext === state.wsize) { state.wnext = 0; }
  16779. if (state.whave < state.wsize) { state.whave += dist; }
  16780. }
  16781. }
  16782. return 0;
  16783. }
  16784. function inflate(strm, flush) {
  16785. var state;
  16786. var input, output; // input/output buffers
  16787. var next; /* next input INDEX */
  16788. var put; /* next output INDEX */
  16789. var have, left; /* available input and output */
  16790. var hold; /* bit buffer */
  16791. var bits; /* bits in bit buffer */
  16792. var _in, _out; /* save starting available input and output */
  16793. var copy; /* number of stored or match bytes to copy */
  16794. var from; /* where to copy match bytes from */
  16795. var from_source;
  16796. var here = 0; /* current decoding table entry */
  16797. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16798. //var last; /* parent table entry */
  16799. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16800. var len; /* length to copy for repeats, bits to drop */
  16801. var ret; /* return code */
  16802. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16803. var opts;
  16804. var n; // temporary var for NEED_BITS
  16805. var order = /* permutation of code lengths */
  16806. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16807. if (!strm || !strm.state || !strm.output ||
  16808. (!strm.input && strm.avail_in !== 0)) {
  16809. return Z_STREAM_ERROR;
  16810. }
  16811. state = strm.state;
  16812. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16813. //--- LOAD() ---
  16814. put = strm.next_out;
  16815. output = strm.output;
  16816. left = strm.avail_out;
  16817. next = strm.next_in;
  16818. input = strm.input;
  16819. have = strm.avail_in;
  16820. hold = state.hold;
  16821. bits = state.bits;
  16822. //---
  16823. _in = have;
  16824. _out = left;
  16825. ret = Z_OK;
  16826. inf_leave: // goto emulation
  16827. for (;;) {
  16828. switch (state.mode) {
  16829. case HEAD:
  16830. if (state.wrap === 0) {
  16831. state.mode = TYPEDO;
  16832. break;
  16833. }
  16834. //=== NEEDBITS(16);
  16835. while (bits < 16) {
  16836. if (have === 0) { break inf_leave; }
  16837. have--;
  16838. hold += input[next++] << bits;
  16839. bits += 8;
  16840. }
  16841. //===//
  16842. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16843. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16844. //=== CRC2(state.check, hold);
  16845. hbuf[0] = hold & 0xff;
  16846. hbuf[1] = (hold >>> 8) & 0xff;
  16847. state.check = crc32(state.check, hbuf, 2, 0);
  16848. //===//
  16849. //=== INITBITS();
  16850. hold = 0;
  16851. bits = 0;
  16852. //===//
  16853. state.mode = FLAGS;
  16854. break;
  16855. }
  16856. state.flags = 0; /* expect zlib header */
  16857. if (state.head) {
  16858. state.head.done = false;
  16859. }
  16860. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16861. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16862. strm.msg = 'incorrect header check';
  16863. state.mode = BAD;
  16864. break;
  16865. }
  16866. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16867. strm.msg = 'unknown compression method';
  16868. state.mode = BAD;
  16869. break;
  16870. }
  16871. //--- DROPBITS(4) ---//
  16872. hold >>>= 4;
  16873. bits -= 4;
  16874. //---//
  16875. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16876. if (state.wbits === 0) {
  16877. state.wbits = len;
  16878. }
  16879. else if (len > state.wbits) {
  16880. strm.msg = 'invalid window size';
  16881. state.mode = BAD;
  16882. break;
  16883. }
  16884. state.dmax = 1 << len;
  16885. //Tracev((stderr, "inflate: zlib header ok\n"));
  16886. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16887. state.mode = hold & 0x200 ? DICTID : TYPE;
  16888. //=== INITBITS();
  16889. hold = 0;
  16890. bits = 0;
  16891. //===//
  16892. break;
  16893. case FLAGS:
  16894. //=== NEEDBITS(16); */
  16895. while (bits < 16) {
  16896. if (have === 0) { break inf_leave; }
  16897. have--;
  16898. hold += input[next++] << bits;
  16899. bits += 8;
  16900. }
  16901. //===//
  16902. state.flags = hold;
  16903. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16904. strm.msg = 'unknown compression method';
  16905. state.mode = BAD;
  16906. break;
  16907. }
  16908. if (state.flags & 0xe000) {
  16909. strm.msg = 'unknown header flags set';
  16910. state.mode = BAD;
  16911. break;
  16912. }
  16913. if (state.head) {
  16914. state.head.text = ((hold >> 8) & 1);
  16915. }
  16916. if (state.flags & 0x0200) {
  16917. //=== CRC2(state.check, hold);
  16918. hbuf[0] = hold & 0xff;
  16919. hbuf[1] = (hold >>> 8) & 0xff;
  16920. state.check = crc32(state.check, hbuf, 2, 0);
  16921. //===//
  16922. }
  16923. //=== INITBITS();
  16924. hold = 0;
  16925. bits = 0;
  16926. //===//
  16927. state.mode = TIME;
  16928. /* falls through */
  16929. case TIME:
  16930. //=== NEEDBITS(32); */
  16931. while (bits < 32) {
  16932. if (have === 0) { break inf_leave; }
  16933. have--;
  16934. hold += input[next++] << bits;
  16935. bits += 8;
  16936. }
  16937. //===//
  16938. if (state.head) {
  16939. state.head.time = hold;
  16940. }
  16941. if (state.flags & 0x0200) {
  16942. //=== CRC4(state.check, hold)
  16943. hbuf[0] = hold & 0xff;
  16944. hbuf[1] = (hold >>> 8) & 0xff;
  16945. hbuf[2] = (hold >>> 16) & 0xff;
  16946. hbuf[3] = (hold >>> 24) & 0xff;
  16947. state.check = crc32(state.check, hbuf, 4, 0);
  16948. //===
  16949. }
  16950. //=== INITBITS();
  16951. hold = 0;
  16952. bits = 0;
  16953. //===//
  16954. state.mode = OS;
  16955. /* falls through */
  16956. case OS:
  16957. //=== NEEDBITS(16); */
  16958. while (bits < 16) {
  16959. if (have === 0) { break inf_leave; }
  16960. have--;
  16961. hold += input[next++] << bits;
  16962. bits += 8;
  16963. }
  16964. //===//
  16965. if (state.head) {
  16966. state.head.xflags = (hold & 0xff);
  16967. state.head.os = (hold >> 8);
  16968. }
  16969. if (state.flags & 0x0200) {
  16970. //=== CRC2(state.check, hold);
  16971. hbuf[0] = hold & 0xff;
  16972. hbuf[1] = (hold >>> 8) & 0xff;
  16973. state.check = crc32(state.check, hbuf, 2, 0);
  16974. //===//
  16975. }
  16976. //=== INITBITS();
  16977. hold = 0;
  16978. bits = 0;
  16979. //===//
  16980. state.mode = EXLEN;
  16981. /* falls through */
  16982. case EXLEN:
  16983. if (state.flags & 0x0400) {
  16984. //=== NEEDBITS(16); */
  16985. while (bits < 16) {
  16986. if (have === 0) { break inf_leave; }
  16987. have--;
  16988. hold += input[next++] << bits;
  16989. bits += 8;
  16990. }
  16991. //===//
  16992. state.length = hold;
  16993. if (state.head) {
  16994. state.head.extra_len = hold;
  16995. }
  16996. if (state.flags & 0x0200) {
  16997. //=== CRC2(state.check, hold);
  16998. hbuf[0] = hold & 0xff;
  16999. hbuf[1] = (hold >>> 8) & 0xff;
  17000. state.check = crc32(state.check, hbuf, 2, 0);
  17001. //===//
  17002. }
  17003. //=== INITBITS();
  17004. hold = 0;
  17005. bits = 0;
  17006. //===//
  17007. }
  17008. else if (state.head) {
  17009. state.head.extra = null/*Z_NULL*/;
  17010. }
  17011. state.mode = EXTRA;
  17012. /* falls through */
  17013. case EXTRA:
  17014. if (state.flags & 0x0400) {
  17015. copy = state.length;
  17016. if (copy > have) { copy = have; }
  17017. if (copy) {
  17018. if (state.head) {
  17019. len = state.head.extra_len - state.length;
  17020. if (!state.head.extra) {
  17021. // Use untyped array for more conveniend processing later
  17022. state.head.extra = new Array(state.head.extra_len);
  17023. }
  17024. utils.arraySet(
  17025. state.head.extra,
  17026. input,
  17027. next,
  17028. // extra field is limited to 65536 bytes
  17029. // - no need for additional size check
  17030. copy,
  17031. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17032. len
  17033. );
  17034. //zmemcpy(state.head.extra + len, next,
  17035. // len + copy > state.head.extra_max ?
  17036. // state.head.extra_max - len : copy);
  17037. }
  17038. if (state.flags & 0x0200) {
  17039. state.check = crc32(state.check, input, copy, next);
  17040. }
  17041. have -= copy;
  17042. next += copy;
  17043. state.length -= copy;
  17044. }
  17045. if (state.length) { break inf_leave; }
  17046. }
  17047. state.length = 0;
  17048. state.mode = NAME;
  17049. /* falls through */
  17050. case NAME:
  17051. if (state.flags & 0x0800) {
  17052. if (have === 0) { break inf_leave; }
  17053. copy = 0;
  17054. do {
  17055. // TODO: 2 or 1 bytes?
  17056. len = input[next + copy++];
  17057. /* use constant limit because in js we should not preallocate memory */
  17058. if (state.head && len &&
  17059. (state.length < 65536 /*state.head.name_max*/)) {
  17060. state.head.name += String.fromCharCode(len);
  17061. }
  17062. } while (len && copy < have);
  17063. if (state.flags & 0x0200) {
  17064. state.check = crc32(state.check, input, copy, next);
  17065. }
  17066. have -= copy;
  17067. next += copy;
  17068. if (len) { break inf_leave; }
  17069. }
  17070. else if (state.head) {
  17071. state.head.name = null;
  17072. }
  17073. state.length = 0;
  17074. state.mode = COMMENT;
  17075. /* falls through */
  17076. case COMMENT:
  17077. if (state.flags & 0x1000) {
  17078. if (have === 0) { break inf_leave; }
  17079. copy = 0;
  17080. do {
  17081. len = input[next + copy++];
  17082. /* use constant limit because in js we should not preallocate memory */
  17083. if (state.head && len &&
  17084. (state.length < 65536 /*state.head.comm_max*/)) {
  17085. state.head.comment += String.fromCharCode(len);
  17086. }
  17087. } while (len && copy < have);
  17088. if (state.flags & 0x0200) {
  17089. state.check = crc32(state.check, input, copy, next);
  17090. }
  17091. have -= copy;
  17092. next += copy;
  17093. if (len) { break inf_leave; }
  17094. }
  17095. else if (state.head) {
  17096. state.head.comment = null;
  17097. }
  17098. state.mode = HCRC;
  17099. /* falls through */
  17100. case HCRC:
  17101. if (state.flags & 0x0200) {
  17102. //=== NEEDBITS(16); */
  17103. while (bits < 16) {
  17104. if (have === 0) { break inf_leave; }
  17105. have--;
  17106. hold += input[next++] << bits;
  17107. bits += 8;
  17108. }
  17109. //===//
  17110. if (hold !== (state.check & 0xffff)) {
  17111. strm.msg = 'header crc mismatch';
  17112. state.mode = BAD;
  17113. break;
  17114. }
  17115. //=== INITBITS();
  17116. hold = 0;
  17117. bits = 0;
  17118. //===//
  17119. }
  17120. if (state.head) {
  17121. state.head.hcrc = ((state.flags >> 9) & 1);
  17122. state.head.done = true;
  17123. }
  17124. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  17125. state.mode = TYPE;
  17126. break;
  17127. case DICTID:
  17128. //=== NEEDBITS(32); */
  17129. while (bits < 32) {
  17130. if (have === 0) { break inf_leave; }
  17131. have--;
  17132. hold += input[next++] << bits;
  17133. bits += 8;
  17134. }
  17135. //===//
  17136. strm.adler = state.check = ZSWAP32(hold);
  17137. //=== INITBITS();
  17138. hold = 0;
  17139. bits = 0;
  17140. //===//
  17141. state.mode = DICT;
  17142. /* falls through */
  17143. case DICT:
  17144. if (state.havedict === 0) {
  17145. //--- RESTORE() ---
  17146. strm.next_out = put;
  17147. strm.avail_out = left;
  17148. strm.next_in = next;
  17149. strm.avail_in = have;
  17150. state.hold = hold;
  17151. state.bits = bits;
  17152. //---
  17153. return Z_NEED_DICT;
  17154. }
  17155. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17156. state.mode = TYPE;
  17157. /* falls through */
  17158. case TYPE:
  17159. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  17160. /* falls through */
  17161. case TYPEDO:
  17162. if (state.last) {
  17163. //--- BYTEBITS() ---//
  17164. hold >>>= bits & 7;
  17165. bits -= bits & 7;
  17166. //---//
  17167. state.mode = CHECK;
  17168. break;
  17169. }
  17170. //=== NEEDBITS(3); */
  17171. while (bits < 3) {
  17172. if (have === 0) { break inf_leave; }
  17173. have--;
  17174. hold += input[next++] << bits;
  17175. bits += 8;
  17176. }
  17177. //===//
  17178. state.last = (hold & 0x01)/*BITS(1)*/;
  17179. //--- DROPBITS(1) ---//
  17180. hold >>>= 1;
  17181. bits -= 1;
  17182. //---//
  17183. switch ((hold & 0x03)/*BITS(2)*/) {
  17184. case 0: /* stored block */
  17185. //Tracev((stderr, "inflate: stored block%s\n",
  17186. // state.last ? " (last)" : ""));
  17187. state.mode = STORED;
  17188. break;
  17189. case 1: /* fixed block */
  17190. fixedtables(state);
  17191. //Tracev((stderr, "inflate: fixed codes block%s\n",
  17192. // state.last ? " (last)" : ""));
  17193. state.mode = LEN_; /* decode codes */
  17194. if (flush === Z_TREES) {
  17195. //--- DROPBITS(2) ---//
  17196. hold >>>= 2;
  17197. bits -= 2;
  17198. //---//
  17199. break inf_leave;
  17200. }
  17201. break;
  17202. case 2: /* dynamic block */
  17203. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  17204. // state.last ? " (last)" : ""));
  17205. state.mode = TABLE;
  17206. break;
  17207. case 3:
  17208. strm.msg = 'invalid block type';
  17209. state.mode = BAD;
  17210. }
  17211. //--- DROPBITS(2) ---//
  17212. hold >>>= 2;
  17213. bits -= 2;
  17214. //---//
  17215. break;
  17216. case STORED:
  17217. //--- BYTEBITS() ---// /* go to byte boundary */
  17218. hold >>>= bits & 7;
  17219. bits -= bits & 7;
  17220. //---//
  17221. //=== NEEDBITS(32); */
  17222. while (bits < 32) {
  17223. if (have === 0) { break inf_leave; }
  17224. have--;
  17225. hold += input[next++] << bits;
  17226. bits += 8;
  17227. }
  17228. //===//
  17229. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  17230. strm.msg = 'invalid stored block lengths';
  17231. state.mode = BAD;
  17232. break;
  17233. }
  17234. state.length = hold & 0xffff;
  17235. //Tracev((stderr, "inflate: stored length %u\n",
  17236. // state.length));
  17237. //=== INITBITS();
  17238. hold = 0;
  17239. bits = 0;
  17240. //===//
  17241. state.mode = COPY_;
  17242. if (flush === Z_TREES) { break inf_leave; }
  17243. /* falls through */
  17244. case COPY_:
  17245. state.mode = COPY;
  17246. /* falls through */
  17247. case COPY:
  17248. copy = state.length;
  17249. if (copy) {
  17250. if (copy > have) { copy = have; }
  17251. if (copy > left) { copy = left; }
  17252. if (copy === 0) { break inf_leave; }
  17253. //--- zmemcpy(put, next, copy); ---
  17254. utils.arraySet(output, input, next, copy, put);
  17255. //---//
  17256. have -= copy;
  17257. next += copy;
  17258. left -= copy;
  17259. put += copy;
  17260. state.length -= copy;
  17261. break;
  17262. }
  17263. //Tracev((stderr, "inflate: stored end\n"));
  17264. state.mode = TYPE;
  17265. break;
  17266. case TABLE:
  17267. //=== NEEDBITS(14); */
  17268. while (bits < 14) {
  17269. if (have === 0) { break inf_leave; }
  17270. have--;
  17271. hold += input[next++] << bits;
  17272. bits += 8;
  17273. }
  17274. //===//
  17275. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  17276. //--- DROPBITS(5) ---//
  17277. hold >>>= 5;
  17278. bits -= 5;
  17279. //---//
  17280. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  17281. //--- DROPBITS(5) ---//
  17282. hold >>>= 5;
  17283. bits -= 5;
  17284. //---//
  17285. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  17286. //--- DROPBITS(4) ---//
  17287. hold >>>= 4;
  17288. bits -= 4;
  17289. //---//
  17290. //#ifndef PKZIP_BUG_WORKAROUND
  17291. if (state.nlen > 286 || state.ndist > 30) {
  17292. strm.msg = 'too many length or distance symbols';
  17293. state.mode = BAD;
  17294. break;
  17295. }
  17296. //#endif
  17297. //Tracev((stderr, "inflate: table sizes ok\n"));
  17298. state.have = 0;
  17299. state.mode = LENLENS;
  17300. /* falls through */
  17301. case LENLENS:
  17302. while (state.have < state.ncode) {
  17303. //=== NEEDBITS(3);
  17304. while (bits < 3) {
  17305. if (have === 0) { break inf_leave; }
  17306. have--;
  17307. hold += input[next++] << bits;
  17308. bits += 8;
  17309. }
  17310. //===//
  17311. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  17312. //--- DROPBITS(3) ---//
  17313. hold >>>= 3;
  17314. bits -= 3;
  17315. //---//
  17316. }
  17317. while (state.have < 19) {
  17318. state.lens[order[state.have++]] = 0;
  17319. }
  17320. // We have separate tables & no pointers. 2 commented lines below not needed.
  17321. //state.next = state.codes;
  17322. //state.lencode = state.next;
  17323. // Switch to use dynamic table
  17324. state.lencode = state.lendyn;
  17325. state.lenbits = 7;
  17326. opts = {bits: state.lenbits};
  17327. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  17328. state.lenbits = opts.bits;
  17329. if (ret) {
  17330. strm.msg = 'invalid code lengths set';
  17331. state.mode = BAD;
  17332. break;
  17333. }
  17334. //Tracev((stderr, "inflate: code lengths ok\n"));
  17335. state.have = 0;
  17336. state.mode = CODELENS;
  17337. /* falls through */
  17338. case CODELENS:
  17339. while (state.have < state.nlen + state.ndist) {
  17340. for (;;) {
  17341. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  17342. here_bits = here >>> 24;
  17343. here_op = (here >>> 16) & 0xff;
  17344. here_val = here & 0xffff;
  17345. if ((here_bits) <= bits) { break; }
  17346. //--- PULLBYTE() ---//
  17347. if (have === 0) { break inf_leave; }
  17348. have--;
  17349. hold += input[next++] << bits;
  17350. bits += 8;
  17351. //---//
  17352. }
  17353. if (here_val < 16) {
  17354. //--- DROPBITS(here.bits) ---//
  17355. hold >>>= here_bits;
  17356. bits -= here_bits;
  17357. //---//
  17358. state.lens[state.have++] = here_val;
  17359. }
  17360. else {
  17361. if (here_val === 16) {
  17362. //=== NEEDBITS(here.bits + 2);
  17363. n = here_bits + 2;
  17364. while (bits < n) {
  17365. if (have === 0) { break inf_leave; }
  17366. have--;
  17367. hold += input[next++] << bits;
  17368. bits += 8;
  17369. }
  17370. //===//
  17371. //--- DROPBITS(here.bits) ---//
  17372. hold >>>= here_bits;
  17373. bits -= here_bits;
  17374. //---//
  17375. if (state.have === 0) {
  17376. strm.msg = 'invalid bit length repeat';
  17377. state.mode = BAD;
  17378. break;
  17379. }
  17380. len = state.lens[state.have - 1];
  17381. copy = 3 + (hold & 0x03);//BITS(2);
  17382. //--- DROPBITS(2) ---//
  17383. hold >>>= 2;
  17384. bits -= 2;
  17385. //---//
  17386. }
  17387. else if (here_val === 17) {
  17388. //=== NEEDBITS(here.bits + 3);
  17389. n = here_bits + 3;
  17390. while (bits < n) {
  17391. if (have === 0) { break inf_leave; }
  17392. have--;
  17393. hold += input[next++] << bits;
  17394. bits += 8;
  17395. }
  17396. //===//
  17397. //--- DROPBITS(here.bits) ---//
  17398. hold >>>= here_bits;
  17399. bits -= here_bits;
  17400. //---//
  17401. len = 0;
  17402. copy = 3 + (hold & 0x07);//BITS(3);
  17403. //--- DROPBITS(3) ---//
  17404. hold >>>= 3;
  17405. bits -= 3;
  17406. //---//
  17407. }
  17408. else {
  17409. //=== NEEDBITS(here.bits + 7);
  17410. n = here_bits + 7;
  17411. while (bits < n) {
  17412. if (have === 0) { break inf_leave; }
  17413. have--;
  17414. hold += input[next++] << bits;
  17415. bits += 8;
  17416. }
  17417. //===//
  17418. //--- DROPBITS(here.bits) ---//
  17419. hold >>>= here_bits;
  17420. bits -= here_bits;
  17421. //---//
  17422. len = 0;
  17423. copy = 11 + (hold & 0x7f);//BITS(7);
  17424. //--- DROPBITS(7) ---//
  17425. hold >>>= 7;
  17426. bits -= 7;
  17427. //---//
  17428. }
  17429. if (state.have + copy > state.nlen + state.ndist) {
  17430. strm.msg = 'invalid bit length repeat';
  17431. state.mode = BAD;
  17432. break;
  17433. }
  17434. while (copy--) {
  17435. state.lens[state.have++] = len;
  17436. }
  17437. }
  17438. }
  17439. /* handle error breaks in while */
  17440. if (state.mode === BAD) { break; }
  17441. /* check for end-of-block code (better have one) */
  17442. if (state.lens[256] === 0) {
  17443. strm.msg = 'invalid code -- missing end-of-block';
  17444. state.mode = BAD;
  17445. break;
  17446. }
  17447. /* build code tables -- note: do not change the lenbits or distbits
  17448. values here (9 and 6) without reading the comments in inftrees.h
  17449. concerning the ENOUGH constants, which depend on those values */
  17450. state.lenbits = 9;
  17451. opts = {bits: state.lenbits};
  17452. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  17453. // We have separate tables & no pointers. 2 commented lines below not needed.
  17454. // state.next_index = opts.table_index;
  17455. state.lenbits = opts.bits;
  17456. // state.lencode = state.next;
  17457. if (ret) {
  17458. strm.msg = 'invalid literal/lengths set';
  17459. state.mode = BAD;
  17460. break;
  17461. }
  17462. state.distbits = 6;
  17463. //state.distcode.copy(state.codes);
  17464. // Switch to use dynamic table
  17465. state.distcode = state.distdyn;
  17466. opts = {bits: state.distbits};
  17467. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  17468. // We have separate tables & no pointers. 2 commented lines below not needed.
  17469. // state.next_index = opts.table_index;
  17470. state.distbits = opts.bits;
  17471. // state.distcode = state.next;
  17472. if (ret) {
  17473. strm.msg = 'invalid distances set';
  17474. state.mode = BAD;
  17475. break;
  17476. }
  17477. //Tracev((stderr, 'inflate: codes ok\n'));
  17478. state.mode = LEN_;
  17479. if (flush === Z_TREES) { break inf_leave; }
  17480. /* falls through */
  17481. case LEN_:
  17482. state.mode = LEN;
  17483. /* falls through */
  17484. case LEN:
  17485. if (have >= 6 && left >= 258) {
  17486. //--- RESTORE() ---
  17487. strm.next_out = put;
  17488. strm.avail_out = left;
  17489. strm.next_in = next;
  17490. strm.avail_in = have;
  17491. state.hold = hold;
  17492. state.bits = bits;
  17493. //---
  17494. inflate_fast(strm, _out);
  17495. //--- LOAD() ---
  17496. put = strm.next_out;
  17497. output = strm.output;
  17498. left = strm.avail_out;
  17499. next = strm.next_in;
  17500. input = strm.input;
  17501. have = strm.avail_in;
  17502. hold = state.hold;
  17503. bits = state.bits;
  17504. //---
  17505. if (state.mode === TYPE) {
  17506. state.back = -1;
  17507. }
  17508. break;
  17509. }
  17510. state.back = 0;
  17511. for (;;) {
  17512. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  17513. here_bits = here >>> 24;
  17514. here_op = (here >>> 16) & 0xff;
  17515. here_val = here & 0xffff;
  17516. if (here_bits <= bits) { break; }
  17517. //--- PULLBYTE() ---//
  17518. if (have === 0) { break inf_leave; }
  17519. have--;
  17520. hold += input[next++] << bits;
  17521. bits += 8;
  17522. //---//
  17523. }
  17524. if (here_op && (here_op & 0xf0) === 0) {
  17525. last_bits = here_bits;
  17526. last_op = here_op;
  17527. last_val = here_val;
  17528. for (;;) {
  17529. here = state.lencode[last_val +
  17530. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17531. here_bits = here >>> 24;
  17532. here_op = (here >>> 16) & 0xff;
  17533. here_val = here & 0xffff;
  17534. if ((last_bits + here_bits) <= bits) { break; }
  17535. //--- PULLBYTE() ---//
  17536. if (have === 0) { break inf_leave; }
  17537. have--;
  17538. hold += input[next++] << bits;
  17539. bits += 8;
  17540. //---//
  17541. }
  17542. //--- DROPBITS(last.bits) ---//
  17543. hold >>>= last_bits;
  17544. bits -= last_bits;
  17545. //---//
  17546. state.back += last_bits;
  17547. }
  17548. //--- DROPBITS(here.bits) ---//
  17549. hold >>>= here_bits;
  17550. bits -= here_bits;
  17551. //---//
  17552. state.back += here_bits;
  17553. state.length = here_val;
  17554. if (here_op === 0) {
  17555. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17556. // "inflate: literal '%c'\n" :
  17557. // "inflate: literal 0x%02x\n", here.val));
  17558. state.mode = LIT;
  17559. break;
  17560. }
  17561. if (here_op & 32) {
  17562. //Tracevv((stderr, "inflate: end of block\n"));
  17563. state.back = -1;
  17564. state.mode = TYPE;
  17565. break;
  17566. }
  17567. if (here_op & 64) {
  17568. strm.msg = 'invalid literal/length code';
  17569. state.mode = BAD;
  17570. break;
  17571. }
  17572. state.extra = here_op & 15;
  17573. state.mode = LENEXT;
  17574. /* falls through */
  17575. case LENEXT:
  17576. if (state.extra) {
  17577. //=== NEEDBITS(state.extra);
  17578. n = state.extra;
  17579. while (bits < n) {
  17580. if (have === 0) { break inf_leave; }
  17581. have--;
  17582. hold += input[next++] << bits;
  17583. bits += 8;
  17584. }
  17585. //===//
  17586. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17587. //--- DROPBITS(state.extra) ---//
  17588. hold >>>= state.extra;
  17589. bits -= state.extra;
  17590. //---//
  17591. state.back += state.extra;
  17592. }
  17593. //Tracevv((stderr, "inflate: length %u\n", state.length));
  17594. state.was = state.length;
  17595. state.mode = DIST;
  17596. /* falls through */
  17597. case DIST:
  17598. for (;;) {
  17599. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  17600. here_bits = here >>> 24;
  17601. here_op = (here >>> 16) & 0xff;
  17602. here_val = here & 0xffff;
  17603. if ((here_bits) <= bits) { break; }
  17604. //--- PULLBYTE() ---//
  17605. if (have === 0) { break inf_leave; }
  17606. have--;
  17607. hold += input[next++] << bits;
  17608. bits += 8;
  17609. //---//
  17610. }
  17611. if ((here_op & 0xf0) === 0) {
  17612. last_bits = here_bits;
  17613. last_op = here_op;
  17614. last_val = here_val;
  17615. for (;;) {
  17616. here = state.distcode[last_val +
  17617. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17618. here_bits = here >>> 24;
  17619. here_op = (here >>> 16) & 0xff;
  17620. here_val = here & 0xffff;
  17621. if ((last_bits + here_bits) <= bits) { break; }
  17622. //--- PULLBYTE() ---//
  17623. if (have === 0) { break inf_leave; }
  17624. have--;
  17625. hold += input[next++] << bits;
  17626. bits += 8;
  17627. //---//
  17628. }
  17629. //--- DROPBITS(last.bits) ---//
  17630. hold >>>= last_bits;
  17631. bits -= last_bits;
  17632. //---//
  17633. state.back += last_bits;
  17634. }
  17635. //--- DROPBITS(here.bits) ---//
  17636. hold >>>= here_bits;
  17637. bits -= here_bits;
  17638. //---//
  17639. state.back += here_bits;
  17640. if (here_op & 64) {
  17641. strm.msg = 'invalid distance code';
  17642. state.mode = BAD;
  17643. break;
  17644. }
  17645. state.offset = here_val;
  17646. state.extra = (here_op) & 15;
  17647. state.mode = DISTEXT;
  17648. /* falls through */
  17649. case DISTEXT:
  17650. if (state.extra) {
  17651. //=== NEEDBITS(state.extra);
  17652. n = state.extra;
  17653. while (bits < n) {
  17654. if (have === 0) { break inf_leave; }
  17655. have--;
  17656. hold += input[next++] << bits;
  17657. bits += 8;
  17658. }
  17659. //===//
  17660. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17661. //--- DROPBITS(state.extra) ---//
  17662. hold >>>= state.extra;
  17663. bits -= state.extra;
  17664. //---//
  17665. state.back += state.extra;
  17666. }
  17667. //#ifdef INFLATE_STRICT
  17668. if (state.offset > state.dmax) {
  17669. strm.msg = 'invalid distance too far back';
  17670. state.mode = BAD;
  17671. break;
  17672. }
  17673. //#endif
  17674. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  17675. state.mode = MATCH;
  17676. /* falls through */
  17677. case MATCH:
  17678. if (left === 0) { break inf_leave; }
  17679. copy = _out - left;
  17680. if (state.offset > copy) { /* copy from window */
  17681. copy = state.offset - copy;
  17682. if (copy > state.whave) {
  17683. if (state.sane) {
  17684. strm.msg = 'invalid distance too far back';
  17685. state.mode = BAD;
  17686. break;
  17687. }
  17688. // (!) This block is disabled in zlib defailts,
  17689. // don't enable it for binary compatibility
  17690. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17691. // Trace((stderr, "inflate.c too far\n"));
  17692. // copy -= state.whave;
  17693. // if (copy > state.length) { copy = state.length; }
  17694. // if (copy > left) { copy = left; }
  17695. // left -= copy;
  17696. // state.length -= copy;
  17697. // do {
  17698. // output[put++] = 0;
  17699. // } while (--copy);
  17700. // if (state.length === 0) { state.mode = LEN; }
  17701. // break;
  17702. //#endif
  17703. }
  17704. if (copy > state.wnext) {
  17705. copy -= state.wnext;
  17706. from = state.wsize - copy;
  17707. }
  17708. else {
  17709. from = state.wnext - copy;
  17710. }
  17711. if (copy > state.length) { copy = state.length; }
  17712. from_source = state.window;
  17713. }
  17714. else { /* copy from output */
  17715. from_source = output;
  17716. from = put - state.offset;
  17717. copy = state.length;
  17718. }
  17719. if (copy > left) { copy = left; }
  17720. left -= copy;
  17721. state.length -= copy;
  17722. do {
  17723. output[put++] = from_source[from++];
  17724. } while (--copy);
  17725. if (state.length === 0) { state.mode = LEN; }
  17726. break;
  17727. case LIT:
  17728. if (left === 0) { break inf_leave; }
  17729. output[put++] = state.length;
  17730. left--;
  17731. state.mode = LEN;
  17732. break;
  17733. case CHECK:
  17734. if (state.wrap) {
  17735. //=== NEEDBITS(32);
  17736. while (bits < 32) {
  17737. if (have === 0) { break inf_leave; }
  17738. have--;
  17739. // Use '|' insdead of '+' to make sure that result is signed
  17740. hold |= input[next++] << bits;
  17741. bits += 8;
  17742. }
  17743. //===//
  17744. _out -= left;
  17745. strm.total_out += _out;
  17746. state.total += _out;
  17747. if (_out) {
  17748. strm.adler = state.check =
  17749. /*UPDATE(state.check, put - _out, _out);*/
  17750. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17751. }
  17752. _out = left;
  17753. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  17754. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  17755. strm.msg = 'incorrect data check';
  17756. state.mode = BAD;
  17757. break;
  17758. }
  17759. //=== INITBITS();
  17760. hold = 0;
  17761. bits = 0;
  17762. //===//
  17763. //Tracev((stderr, "inflate: check matches trailer\n"));
  17764. }
  17765. state.mode = LENGTH;
  17766. /* falls through */
  17767. case LENGTH:
  17768. if (state.wrap && state.flags) {
  17769. //=== NEEDBITS(32);
  17770. while (bits < 32) {
  17771. if (have === 0) { break inf_leave; }
  17772. have--;
  17773. hold += input[next++] << bits;
  17774. bits += 8;
  17775. }
  17776. //===//
  17777. if (hold !== (state.total & 0xffffffff)) {
  17778. strm.msg = 'incorrect length check';
  17779. state.mode = BAD;
  17780. break;
  17781. }
  17782. //=== INITBITS();
  17783. hold = 0;
  17784. bits = 0;
  17785. //===//
  17786. //Tracev((stderr, "inflate: length matches trailer\n"));
  17787. }
  17788. state.mode = DONE;
  17789. /* falls through */
  17790. case DONE:
  17791. ret = Z_STREAM_END;
  17792. break inf_leave;
  17793. case BAD:
  17794. ret = Z_DATA_ERROR;
  17795. break inf_leave;
  17796. case MEM:
  17797. return Z_MEM_ERROR;
  17798. case SYNC:
  17799. /* falls through */
  17800. default:
  17801. return Z_STREAM_ERROR;
  17802. }
  17803. }
  17804. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17805. /*
  17806. Return from inflate(), updating the total counts and the check value.
  17807. If there was no progress during the inflate() call, return a buffer
  17808. error. Call updatewindow() to create and/or update the window state.
  17809. Note: a memory error from inflate() is non-recoverable.
  17810. */
  17811. //--- RESTORE() ---
  17812. strm.next_out = put;
  17813. strm.avail_out = left;
  17814. strm.next_in = next;
  17815. strm.avail_in = have;
  17816. state.hold = hold;
  17817. state.bits = bits;
  17818. //---
  17819. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17820. (state.mode < CHECK || flush !== Z_FINISH))) {
  17821. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17822. state.mode = MEM;
  17823. return Z_MEM_ERROR;
  17824. }
  17825. }
  17826. _in -= strm.avail_in;
  17827. _out -= strm.avail_out;
  17828. strm.total_in += _in;
  17829. strm.total_out += _out;
  17830. state.total += _out;
  17831. if (state.wrap && _out) {
  17832. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17833. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17834. }
  17835. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17836. (state.mode === TYPE ? 128 : 0) +
  17837. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17838. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17839. ret = Z_BUF_ERROR;
  17840. }
  17841. return ret;
  17842. }
  17843. function inflateEnd(strm) {
  17844. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17845. return Z_STREAM_ERROR;
  17846. }
  17847. var state = strm.state;
  17848. if (state.window) {
  17849. state.window = null;
  17850. }
  17851. strm.state = null;
  17852. return Z_OK;
  17853. }
  17854. function inflateGetHeader(strm, head) {
  17855. var state;
  17856. /* check state */
  17857. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17858. state = strm.state;
  17859. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17860. /* save header structure */
  17861. state.head = head;
  17862. head.done = false;
  17863. return Z_OK;
  17864. }
  17865. exports.inflateReset = inflateReset;
  17866. exports.inflateReset2 = inflateReset2;
  17867. exports.inflateResetKeep = inflateResetKeep;
  17868. exports.inflateInit = inflateInit;
  17869. exports.inflateInit2 = inflateInit2;
  17870. exports.inflate = inflate;
  17871. exports.inflateEnd = inflateEnd;
  17872. exports.inflateGetHeader = inflateGetHeader;
  17873. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17874. /* Not implemented
  17875. exports.inflateCopy = inflateCopy;
  17876. exports.inflateGetDictionary = inflateGetDictionary;
  17877. exports.inflateMark = inflateMark;
  17878. exports.inflatePrime = inflatePrime;
  17879. exports.inflateSetDictionary = inflateSetDictionary;
  17880. exports.inflateSync = inflateSync;
  17881. exports.inflateSyncPoint = inflateSyncPoint;
  17882. exports.inflateUndermine = inflateUndermine;
  17883. */
  17884. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./inffast":59,"./inftrees":61}],61:[function(require,module,exports){
  17885. 'use strict';
  17886. var utils = require('../utils/common');
  17887. var MAXBITS = 15;
  17888. var ENOUGH_LENS = 852;
  17889. var ENOUGH_DISTS = 592;
  17890. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17891. var CODES = 0;
  17892. var LENS = 1;
  17893. var DISTS = 2;
  17894. var lbase = [ /* Length codes 257..285 base */
  17895. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17896. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17897. ];
  17898. var lext = [ /* Length codes 257..285 extra */
  17899. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17900. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17901. ];
  17902. var dbase = [ /* Distance codes 0..29 base */
  17903. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17904. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17905. 8193, 12289, 16385, 24577, 0, 0
  17906. ];
  17907. var dext = [ /* Distance codes 0..29 extra */
  17908. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17909. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17910. 28, 28, 29, 29, 64, 64
  17911. ];
  17912. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17913. {
  17914. var bits = opts.bits;
  17915. //here = opts.here; /* table entry for duplication */
  17916. var len = 0; /* a code's length in bits */
  17917. var sym = 0; /* index of code symbols */
  17918. var min = 0, max = 0; /* minimum and maximum code lengths */
  17919. var root = 0; /* number of index bits for root table */
  17920. var curr = 0; /* number of index bits for current table */
  17921. var drop = 0; /* code bits to drop for sub-table */
  17922. var left = 0; /* number of prefix codes available */
  17923. var used = 0; /* code entries in table used */
  17924. var huff = 0; /* Huffman code */
  17925. var incr; /* for incrementing code, index */
  17926. var fill; /* index for replicating entries */
  17927. var low; /* low bits for current root entry */
  17928. var mask; /* mask for low root bits */
  17929. var next; /* next available space in table */
  17930. var base = null; /* base value table to use */
  17931. var base_index = 0;
  17932. // var shoextra; /* extra bits table to use */
  17933. var end; /* use base and extra for symbol > end */
  17934. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17935. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17936. var extra = null;
  17937. var extra_index = 0;
  17938. var here_bits, here_op, here_val;
  17939. /*
  17940. Process a set of code lengths to create a canonical Huffman code. The
  17941. code lengths are lens[0..codes-1]. Each length corresponds to the
  17942. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17943. symbols by length from short to long, and retaining the symbol order
  17944. for codes with equal lengths. Then the code starts with all zero bits
  17945. for the first code of the shortest length, and the codes are integer
  17946. increments for the same length, and zeros are appended as the length
  17947. increases. For the deflate format, these bits are stored backwards
  17948. from their more natural integer increment ordering, and so when the
  17949. decoding tables are built in the large loop below, the integer codes
  17950. are incremented backwards.
  17951. This routine assumes, but does not check, that all of the entries in
  17952. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17953. 1..MAXBITS is interpreted as that code length. zero means that that
  17954. symbol does not occur in this code.
  17955. The codes are sorted by computing a count of codes for each length,
  17956. creating from that a table of starting indices for each length in the
  17957. sorted table, and then entering the symbols in order in the sorted
  17958. table. The sorted table is work[], with that space being provided by
  17959. the caller.
  17960. The length counts are used for other purposes as well, i.e. finding
  17961. the minimum and maximum length codes, determining if there are any
  17962. codes at all, checking for a valid set of lengths, and looking ahead
  17963. at length counts to determine sub-table sizes when building the
  17964. decoding tables.
  17965. */
  17966. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17967. for (len = 0; len <= MAXBITS; len++) {
  17968. count[len] = 0;
  17969. }
  17970. for (sym = 0; sym < codes; sym++) {
  17971. count[lens[lens_index + sym]]++;
  17972. }
  17973. /* bound code lengths, force root to be within code lengths */
  17974. root = bits;
  17975. for (max = MAXBITS; max >= 1; max--) {
  17976. if (count[max] !== 0) { break; }
  17977. }
  17978. if (root > max) {
  17979. root = max;
  17980. }
  17981. if (max === 0) { /* no symbols to code at all */
  17982. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17983. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17984. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17985. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17986. //table.op[opts.table_index] = 64;
  17987. //table.bits[opts.table_index] = 1;
  17988. //table.val[opts.table_index++] = 0;
  17989. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17990. opts.bits = 1;
  17991. return 0; /* no symbols, but wait for decoding to report error */
  17992. }
  17993. for (min = 1; min < max; min++) {
  17994. if (count[min] !== 0) { break; }
  17995. }
  17996. if (root < min) {
  17997. root = min;
  17998. }
  17999. /* check for an over-subscribed or incomplete set of lengths */
  18000. left = 1;
  18001. for (len = 1; len <= MAXBITS; len++) {
  18002. left <<= 1;
  18003. left -= count[len];
  18004. if (left < 0) {
  18005. return -1;
  18006. } /* over-subscribed */
  18007. }
  18008. if (left > 0 && (type === CODES || max !== 1)) {
  18009. return -1; /* incomplete set */
  18010. }
  18011. /* generate offsets into symbol table for each length for sorting */
  18012. offs[1] = 0;
  18013. for (len = 1; len < MAXBITS; len++) {
  18014. offs[len + 1] = offs[len] + count[len];
  18015. }
  18016. /* sort symbols by length, by symbol order within each length */
  18017. for (sym = 0; sym < codes; sym++) {
  18018. if (lens[lens_index + sym] !== 0) {
  18019. work[offs[lens[lens_index + sym]]++] = sym;
  18020. }
  18021. }
  18022. /*
  18023. Create and fill in decoding tables. In this loop, the table being
  18024. filled is at next and has curr index bits. The code being used is huff
  18025. with length len. That code is converted to an index by dropping drop
  18026. bits off of the bottom. For codes where len is less than drop + curr,
  18027. those top drop + curr - len bits are incremented through all values to
  18028. fill the table with replicated entries.
  18029. root is the number of index bits for the root table. When len exceeds
  18030. root, sub-tables are created pointed to by the root entry with an index
  18031. of the low root bits of huff. This is saved in low to check for when a
  18032. new sub-table should be started. drop is zero when the root table is
  18033. being filled, and drop is root when sub-tables are being filled.
  18034. When a new sub-table is needed, it is necessary to look ahead in the
  18035. code lengths to determine what size sub-table is needed. The length
  18036. counts are used for this, and so count[] is decremented as codes are
  18037. entered in the tables.
  18038. used keeps track of how many table entries have been allocated from the
  18039. provided *table space. It is checked for LENS and DIST tables against
  18040. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  18041. the initial root table size constants. See the comments in inftrees.h
  18042. for more information.
  18043. sym increments through all symbols, and the loop terminates when
  18044. all codes of length max, i.e. all codes, have been processed. This
  18045. routine permits incomplete codes, so another loop after this one fills
  18046. in the rest of the decoding tables with invalid code markers.
  18047. */
  18048. /* set up for code type */
  18049. // poor man optimization - use if-else instead of switch,
  18050. // to avoid deopts in old v8
  18051. if (type === CODES) {
  18052. base = extra = work; /* dummy value--not used */
  18053. end = 19;
  18054. } else if (type === LENS) {
  18055. base = lbase;
  18056. base_index -= 257;
  18057. extra = lext;
  18058. extra_index -= 257;
  18059. end = 256;
  18060. } else { /* DISTS */
  18061. base = dbase;
  18062. extra = dext;
  18063. end = -1;
  18064. }
  18065. /* initialize opts for loop */
  18066. huff = 0; /* starting code */
  18067. sym = 0; /* starting code symbol */
  18068. len = min; /* starting code length */
  18069. next = table_index; /* current table to fill in */
  18070. curr = root; /* current table index bits */
  18071. drop = 0; /* current bits to drop from code for index */
  18072. low = -1; /* trigger new sub-table when len > root */
  18073. used = 1 << root; /* use root table entries */
  18074. mask = used - 1; /* mask for comparing low */
  18075. /* check available table space */
  18076. if ((type === LENS && used > ENOUGH_LENS) ||
  18077. (type === DISTS && used > ENOUGH_DISTS)) {
  18078. return 1;
  18079. }
  18080. var i=0;
  18081. /* process all codes and make table entries */
  18082. for (;;) {
  18083. i++;
  18084. /* create table entry */
  18085. here_bits = len - drop;
  18086. if (work[sym] < end) {
  18087. here_op = 0;
  18088. here_val = work[sym];
  18089. }
  18090. else if (work[sym] > end) {
  18091. here_op = extra[extra_index + work[sym]];
  18092. here_val = base[base_index + work[sym]];
  18093. }
  18094. else {
  18095. here_op = 32 + 64; /* end of block */
  18096. here_val = 0;
  18097. }
  18098. /* replicate for those indices with low len bits equal to huff */
  18099. incr = 1 << (len - drop);
  18100. fill = 1 << curr;
  18101. min = fill; /* save offset to next table */
  18102. do {
  18103. fill -= incr;
  18104. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  18105. } while (fill !== 0);
  18106. /* backwards increment the len-bit code huff */
  18107. incr = 1 << (len - 1);
  18108. while (huff & incr) {
  18109. incr >>= 1;
  18110. }
  18111. if (incr !== 0) {
  18112. huff &= incr - 1;
  18113. huff += incr;
  18114. } else {
  18115. huff = 0;
  18116. }
  18117. /* go to next symbol, update count, len */
  18118. sym++;
  18119. if (--count[len] === 0) {
  18120. if (len === max) { break; }
  18121. len = lens[lens_index + work[sym]];
  18122. }
  18123. /* create new sub-table if needed */
  18124. if (len > root && (huff & mask) !== low) {
  18125. /* if first time, transition to sub-tables */
  18126. if (drop === 0) {
  18127. drop = root;
  18128. }
  18129. /* increment past last table */
  18130. next += min; /* here min is 1 << curr */
  18131. /* determine length of next table */
  18132. curr = len - drop;
  18133. left = 1 << curr;
  18134. while (curr + drop < max) {
  18135. left -= count[curr + drop];
  18136. if (left <= 0) { break; }
  18137. curr++;
  18138. left <<= 1;
  18139. }
  18140. /* check for enough space */
  18141. used += 1 << curr;
  18142. if ((type === LENS && used > ENOUGH_LENS) ||
  18143. (type === DISTS && used > ENOUGH_DISTS)) {
  18144. return 1;
  18145. }
  18146. /* point entry in root table to sub-table */
  18147. low = huff & mask;
  18148. /*table.op[low] = curr;
  18149. table.bits[low] = root;
  18150. table.val[low] = next - opts.table_index;*/
  18151. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  18152. }
  18153. }
  18154. /* fill in remaining table entry if code is incomplete (guaranteed to have
  18155. at most one remaining entry, since if the code is incomplete, the
  18156. maximum code length that was allowed to get this far is one bit) */
  18157. if (huff !== 0) {
  18158. //table.op[next + huff] = 64; /* invalid code marker */
  18159. //table.bits[next + huff] = len - drop;
  18160. //table.val[next + huff] = 0;
  18161. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  18162. }
  18163. /* set return parameters */
  18164. //opts.table_index += used;
  18165. opts.bits = root;
  18166. return 0;
  18167. };
  18168. },{"../utils/common":52}],62:[function(require,module,exports){
  18169. 'use strict';
  18170. module.exports = {
  18171. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  18172. '1': 'stream end', /* Z_STREAM_END 1 */
  18173. '0': '', /* Z_OK 0 */
  18174. '-1': 'file error', /* Z_ERRNO (-1) */
  18175. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  18176. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  18177. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  18178. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  18179. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  18180. };
  18181. },{}],63:[function(require,module,exports){
  18182. 'use strict';
  18183. var utils = require('../utils/common');
  18184. /* Public constants ==========================================================*/
  18185. /* ===========================================================================*/
  18186. //var Z_FILTERED = 1;
  18187. //var Z_HUFFMAN_ONLY = 2;
  18188. //var Z_RLE = 3;
  18189. var Z_FIXED = 4;
  18190. //var Z_DEFAULT_STRATEGY = 0;
  18191. /* Possible values of the data_type field (though see inflate()) */
  18192. var Z_BINARY = 0;
  18193. var Z_TEXT = 1;
  18194. //var Z_ASCII = 1; // = Z_TEXT
  18195. var Z_UNKNOWN = 2;
  18196. /*============================================================================*/
  18197. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18198. // From zutil.h
  18199. var STORED_BLOCK = 0;
  18200. var STATIC_TREES = 1;
  18201. var DYN_TREES = 2;
  18202. /* The three kinds of block type */
  18203. var MIN_MATCH = 3;
  18204. var MAX_MATCH = 258;
  18205. /* The minimum and maximum match lengths */
  18206. // From deflate.h
  18207. /* ===========================================================================
  18208. * Internal compression state.
  18209. */
  18210. var LENGTH_CODES = 29;
  18211. /* number of length codes, not counting the special END_BLOCK code */
  18212. var LITERALS = 256;
  18213. /* number of literal bytes 0..255 */
  18214. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18215. /* number of Literal or Length codes, including the END_BLOCK code */
  18216. var D_CODES = 30;
  18217. /* number of distance codes */
  18218. var BL_CODES = 19;
  18219. /* number of codes used to transfer the bit lengths */
  18220. var HEAP_SIZE = 2*L_CODES + 1;
  18221. /* maximum heap size */
  18222. var MAX_BITS = 15;
  18223. /* All codes must not exceed MAX_BITS bits */
  18224. var Buf_size = 16;
  18225. /* size of bit buffer in bi_buf */
  18226. /* ===========================================================================
  18227. * Constants
  18228. */
  18229. var MAX_BL_BITS = 7;
  18230. /* Bit length codes must not exceed MAX_BL_BITS bits */
  18231. var END_BLOCK = 256;
  18232. /* end of block literal code */
  18233. var REP_3_6 = 16;
  18234. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  18235. var REPZ_3_10 = 17;
  18236. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  18237. var REPZ_11_138 = 18;
  18238. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  18239. var extra_lbits = /* extra bits for each length code */
  18240. [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];
  18241. var extra_dbits = /* extra bits for each distance code */
  18242. [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];
  18243. var extra_blbits = /* extra bits for each bit length code */
  18244. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  18245. var bl_order =
  18246. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  18247. /* The lengths of the bit length codes are sent in order of decreasing
  18248. * probability, to avoid transmitting the lengths for unused bit length codes.
  18249. */
  18250. /* ===========================================================================
  18251. * Local data. These are initialized only once.
  18252. */
  18253. // We pre-fill arrays with 0 to avoid uninitialized gaps
  18254. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  18255. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  18256. var static_ltree = new Array((L_CODES+2) * 2);
  18257. zero(static_ltree);
  18258. /* The static literal tree. Since the bit lengths are imposed, there is no
  18259. * need for the L_CODES extra codes used during heap construction. However
  18260. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  18261. * below).
  18262. */
  18263. var static_dtree = new Array(D_CODES * 2);
  18264. zero(static_dtree);
  18265. /* The static distance tree. (Actually a trivial tree since all codes use
  18266. * 5 bits.)
  18267. */
  18268. var _dist_code = new Array(DIST_CODE_LEN);
  18269. zero(_dist_code);
  18270. /* Distance codes. The first 256 values correspond to the distances
  18271. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  18272. * the 15 bit distances.
  18273. */
  18274. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  18275. zero(_length_code);
  18276. /* length code for each normalized match length (0 == MIN_MATCH) */
  18277. var base_length = new Array(LENGTH_CODES);
  18278. zero(base_length);
  18279. /* First normalized length for each code (0 = MIN_MATCH) */
  18280. var base_dist = new Array(D_CODES);
  18281. zero(base_dist);
  18282. /* First normalized distance for each code (0 = distance of 1) */
  18283. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  18284. this.static_tree = static_tree; /* static tree or NULL */
  18285. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  18286. this.extra_base = extra_base; /* base index for extra_bits */
  18287. this.elems = elems; /* max number of elements in the tree */
  18288. this.max_length = max_length; /* max bit length for the codes */
  18289. // show if `static_tree` has data or dummy - needed for monomorphic objects
  18290. this.has_stree = static_tree && static_tree.length;
  18291. };
  18292. var static_l_desc;
  18293. var static_d_desc;
  18294. var static_bl_desc;
  18295. var TreeDesc = function(dyn_tree, stat_desc) {
  18296. this.dyn_tree = dyn_tree; /* the dynamic tree */
  18297. this.max_code = 0; /* largest code with non zero frequency */
  18298. this.stat_desc = stat_desc; /* the corresponding static tree */
  18299. };
  18300. function d_code(dist) {
  18301. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  18302. }
  18303. /* ===========================================================================
  18304. * Output a short LSB first on the stream.
  18305. * IN assertion: there is enough room in pendingBuf.
  18306. */
  18307. function put_short (s, w) {
  18308. // put_byte(s, (uch)((w) & 0xff));
  18309. // put_byte(s, (uch)((ush)(w) >> 8));
  18310. s.pending_buf[s.pending++] = (w) & 0xff;
  18311. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  18312. }
  18313. /* ===========================================================================
  18314. * Send a value on a given number of bits.
  18315. * IN assertion: length <= 16 and value fits in length bits.
  18316. */
  18317. function send_bits(s, value, length) {
  18318. if (s.bi_valid > (Buf_size - length)) {
  18319. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18320. put_short(s, s.bi_buf);
  18321. s.bi_buf = value >> (Buf_size - s.bi_valid);
  18322. s.bi_valid += length - Buf_size;
  18323. } else {
  18324. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18325. s.bi_valid += length;
  18326. }
  18327. }
  18328. function send_code(s, c, tree) {
  18329. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  18330. }
  18331. /* ===========================================================================
  18332. * Reverse the first len bits of a code, using straightforward code (a faster
  18333. * method would use a table)
  18334. * IN assertion: 1 <= len <= 15
  18335. */
  18336. function bi_reverse(code, len) {
  18337. var res = 0;
  18338. do {
  18339. res |= code & 1;
  18340. code >>>= 1;
  18341. res <<= 1;
  18342. } while (--len > 0);
  18343. return res >>> 1;
  18344. }
  18345. /* ===========================================================================
  18346. * Flush the bit buffer, keeping at most 7 bits in it.
  18347. */
  18348. function bi_flush(s) {
  18349. if (s.bi_valid === 16) {
  18350. put_short(s, s.bi_buf);
  18351. s.bi_buf = 0;
  18352. s.bi_valid = 0;
  18353. } else if (s.bi_valid >= 8) {
  18354. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  18355. s.bi_buf >>= 8;
  18356. s.bi_valid -= 8;
  18357. }
  18358. }
  18359. /* ===========================================================================
  18360. * Compute the optimal bit lengths for a tree and update the total bit length
  18361. * for the current block.
  18362. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  18363. * above are the tree nodes sorted by increasing frequency.
  18364. * OUT assertions: the field len is set to the optimal bit length, the
  18365. * array bl_count contains the frequencies for each bit length.
  18366. * The length opt_len is updated; static_len is also updated if stree is
  18367. * not null.
  18368. */
  18369. function gen_bitlen(s, desc)
  18370. // deflate_state *s;
  18371. // tree_desc *desc; /* the tree descriptor */
  18372. {
  18373. var tree = desc.dyn_tree;
  18374. var max_code = desc.max_code;
  18375. var stree = desc.stat_desc.static_tree;
  18376. var has_stree = desc.stat_desc.has_stree;
  18377. var extra = desc.stat_desc.extra_bits;
  18378. var base = desc.stat_desc.extra_base;
  18379. var max_length = desc.stat_desc.max_length;
  18380. var h; /* heap index */
  18381. var n, m; /* iterate over the tree elements */
  18382. var bits; /* bit length */
  18383. var xbits; /* extra bits */
  18384. var f; /* frequency */
  18385. var overflow = 0; /* number of elements with bit length too large */
  18386. for (bits = 0; bits <= MAX_BITS; bits++) {
  18387. s.bl_count[bits] = 0;
  18388. }
  18389. /* In a first pass, compute the optimal bit lengths (which may
  18390. * overflow in the case of the bit length tree).
  18391. */
  18392. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  18393. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  18394. n = s.heap[h];
  18395. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  18396. if (bits > max_length) {
  18397. bits = max_length;
  18398. overflow++;
  18399. }
  18400. tree[n*2 + 1]/*.Len*/ = bits;
  18401. /* We overwrite tree[n].Dad which is no longer needed */
  18402. if (n > max_code) { continue; } /* not a leaf node */
  18403. s.bl_count[bits]++;
  18404. xbits = 0;
  18405. if (n >= base) {
  18406. xbits = extra[n-base];
  18407. }
  18408. f = tree[n * 2]/*.Freq*/;
  18409. s.opt_len += f * (bits + xbits);
  18410. if (has_stree) {
  18411. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  18412. }
  18413. }
  18414. if (overflow === 0) { return; }
  18415. // Trace((stderr,"\nbit length overflow\n"));
  18416. /* This happens for example on obj2 and pic of the Calgary corpus */
  18417. /* Find the first bit length which could increase: */
  18418. do {
  18419. bits = max_length-1;
  18420. while (s.bl_count[bits] === 0) { bits--; }
  18421. s.bl_count[bits]--; /* move one leaf down the tree */
  18422. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  18423. s.bl_count[max_length]--;
  18424. /* The brother of the overflow item also moves one step up,
  18425. * but this does not affect bl_count[max_length]
  18426. */
  18427. overflow -= 2;
  18428. } while (overflow > 0);
  18429. /* Now recompute all bit lengths, scanning in increasing frequency.
  18430. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  18431. * lengths instead of fixing only the wrong ones. This idea is taken
  18432. * from 'ar' written by Haruhiko Okumura.)
  18433. */
  18434. for (bits = max_length; bits !== 0; bits--) {
  18435. n = s.bl_count[bits];
  18436. while (n !== 0) {
  18437. m = s.heap[--h];
  18438. if (m > max_code) { continue; }
  18439. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  18440. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  18441. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  18442. tree[m*2 + 1]/*.Len*/ = bits;
  18443. }
  18444. n--;
  18445. }
  18446. }
  18447. }
  18448. /* ===========================================================================
  18449. * Generate the codes for a given tree and bit counts (which need not be
  18450. * optimal).
  18451. * IN assertion: the array bl_count contains the bit length statistics for
  18452. * the given tree and the field len is set for all tree elements.
  18453. * OUT assertion: the field code is set for all tree elements of non
  18454. * zero code length.
  18455. */
  18456. function gen_codes(tree, max_code, bl_count)
  18457. // ct_data *tree; /* the tree to decorate */
  18458. // int max_code; /* largest code with non zero frequency */
  18459. // ushf *bl_count; /* number of codes at each bit length */
  18460. {
  18461. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  18462. var code = 0; /* running code value */
  18463. var bits; /* bit index */
  18464. var n; /* code index */
  18465. /* The distribution counts are first used to generate the code values
  18466. * without bit reversal.
  18467. */
  18468. for (bits = 1; bits <= MAX_BITS; bits++) {
  18469. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  18470. }
  18471. /* Check that the bit counts in bl_count are consistent. The last code
  18472. * must be all ones.
  18473. */
  18474. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  18475. // "inconsistent bit counts");
  18476. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  18477. for (n = 0; n <= max_code; n++) {
  18478. var len = tree[n*2 + 1]/*.Len*/;
  18479. if (len === 0) { continue; }
  18480. /* Now reverse the bits */
  18481. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  18482. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  18483. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  18484. }
  18485. }
  18486. /* ===========================================================================
  18487. * Initialize the various 'constant' tables.
  18488. */
  18489. function tr_static_init() {
  18490. var n; /* iterates over tree elements */
  18491. var bits; /* bit counter */
  18492. var length; /* length value */
  18493. var code; /* code value */
  18494. var dist; /* distance index */
  18495. var bl_count = new Array(MAX_BITS+1);
  18496. /* number of codes at each bit length for an optimal tree */
  18497. // do check in _tr_init()
  18498. //if (static_init_done) return;
  18499. /* For some embedded targets, global variables are not initialized: */
  18500. /*#ifdef NO_INIT_GLOBAL_POINTERS
  18501. static_l_desc.static_tree = static_ltree;
  18502. static_l_desc.extra_bits = extra_lbits;
  18503. static_d_desc.static_tree = static_dtree;
  18504. static_d_desc.extra_bits = extra_dbits;
  18505. static_bl_desc.extra_bits = extra_blbits;
  18506. #endif*/
  18507. /* Initialize the mapping length (0..255) -> length code (0..28) */
  18508. length = 0;
  18509. for (code = 0; code < LENGTH_CODES-1; code++) {
  18510. base_length[code] = length;
  18511. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  18512. _length_code[length++] = code;
  18513. }
  18514. }
  18515. //Assert (length == 256, "tr_static_init: length != 256");
  18516. /* Note that the length 255 (match length 258) can be represented
  18517. * in two different ways: code 284 + 5 bits or code 285, so we
  18518. * overwrite length_code[255] to use the best encoding:
  18519. */
  18520. _length_code[length-1] = code;
  18521. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  18522. dist = 0;
  18523. for (code = 0 ; code < 16; code++) {
  18524. base_dist[code] = dist;
  18525. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  18526. _dist_code[dist++] = code;
  18527. }
  18528. }
  18529. //Assert (dist == 256, "tr_static_init: dist != 256");
  18530. dist >>= 7; /* from now on, all distances are divided by 128 */
  18531. for (; code < D_CODES; code++) {
  18532. base_dist[code] = dist << 7;
  18533. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  18534. _dist_code[256 + dist++] = code;
  18535. }
  18536. }
  18537. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  18538. /* Construct the codes of the static literal tree */
  18539. for (bits = 0; bits <= MAX_BITS; bits++) {
  18540. bl_count[bits] = 0;
  18541. }
  18542. n = 0;
  18543. while (n <= 143) {
  18544. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18545. n++;
  18546. bl_count[8]++;
  18547. }
  18548. while (n <= 255) {
  18549. static_ltree[n*2 + 1]/*.Len*/ = 9;
  18550. n++;
  18551. bl_count[9]++;
  18552. }
  18553. while (n <= 279) {
  18554. static_ltree[n*2 + 1]/*.Len*/ = 7;
  18555. n++;
  18556. bl_count[7]++;
  18557. }
  18558. while (n <= 287) {
  18559. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18560. n++;
  18561. bl_count[8]++;
  18562. }
  18563. /* Codes 286 and 287 do not exist, but we must include them in the
  18564. * tree construction to get a canonical Huffman tree (longest code
  18565. * all ones)
  18566. */
  18567. gen_codes(static_ltree, L_CODES+1, bl_count);
  18568. /* The static distance tree is trivial: */
  18569. for (n = 0; n < D_CODES; n++) {
  18570. static_dtree[n*2 + 1]/*.Len*/ = 5;
  18571. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  18572. }
  18573. // Now data ready and we can init static trees
  18574. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  18575. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  18576. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  18577. //static_init_done = true;
  18578. }
  18579. /* ===========================================================================
  18580. * Initialize a new block.
  18581. */
  18582. function init_block(s) {
  18583. var n; /* iterates over tree elements */
  18584. /* Initialize the trees. */
  18585. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  18586. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  18587. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  18588. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  18589. s.opt_len = s.static_len = 0;
  18590. s.last_lit = s.matches = 0;
  18591. }
  18592. /* ===========================================================================
  18593. * Flush the bit buffer and align the output on a byte boundary
  18594. */
  18595. function bi_windup(s)
  18596. {
  18597. if (s.bi_valid > 8) {
  18598. put_short(s, s.bi_buf);
  18599. } else if (s.bi_valid > 0) {
  18600. //put_byte(s, (Byte)s->bi_buf);
  18601. s.pending_buf[s.pending++] = s.bi_buf;
  18602. }
  18603. s.bi_buf = 0;
  18604. s.bi_valid = 0;
  18605. }
  18606. /* ===========================================================================
  18607. * Copy a stored block, storing first the length and its
  18608. * one's complement if requested.
  18609. */
  18610. function copy_block(s, buf, len, header)
  18611. //DeflateState *s;
  18612. //charf *buf; /* the input data */
  18613. //unsigned len; /* its length */
  18614. //int header; /* true if block header must be written */
  18615. {
  18616. bi_windup(s); /* align on byte boundary */
  18617. if (header) {
  18618. put_short(s, len);
  18619. put_short(s, ~len);
  18620. }
  18621. // while (len--) {
  18622. // put_byte(s, *buf++);
  18623. // }
  18624. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  18625. s.pending += len;
  18626. }
  18627. /* ===========================================================================
  18628. * Compares to subtrees, using the tree depth as tie breaker when
  18629. * the subtrees have equal frequency. This minimizes the worst case length.
  18630. */
  18631. function smaller(tree, n, m, depth) {
  18632. var _n2 = n*2;
  18633. var _m2 = m*2;
  18634. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  18635. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  18636. }
  18637. /* ===========================================================================
  18638. * Restore the heap property by moving down the tree starting at node k,
  18639. * exchanging a node with the smallest of its two sons if necessary, stopping
  18640. * when the heap property is re-established (each father smaller than its
  18641. * two sons).
  18642. */
  18643. function pqdownheap(s, tree, k)
  18644. // deflate_state *s;
  18645. // ct_data *tree; /* the tree to restore */
  18646. // int k; /* node to move down */
  18647. {
  18648. var v = s.heap[k];
  18649. var j = k << 1; /* left son of k */
  18650. while (j <= s.heap_len) {
  18651. /* Set j to the smallest of the two sons: */
  18652. if (j < s.heap_len &&
  18653. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  18654. j++;
  18655. }
  18656. /* Exit if v is smaller than both sons */
  18657. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  18658. /* Exchange v with the smallest son */
  18659. s.heap[k] = s.heap[j];
  18660. k = j;
  18661. /* And continue down the tree, setting j to the left son of k */
  18662. j <<= 1;
  18663. }
  18664. s.heap[k] = v;
  18665. }
  18666. // inlined manually
  18667. // var SMALLEST = 1;
  18668. /* ===========================================================================
  18669. * Send the block data compressed using the given Huffman trees
  18670. */
  18671. function compress_block(s, ltree, dtree)
  18672. // deflate_state *s;
  18673. // const ct_data *ltree; /* literal tree */
  18674. // const ct_data *dtree; /* distance tree */
  18675. {
  18676. var dist; /* distance of matched string */
  18677. var lc; /* match length or unmatched char (if dist == 0) */
  18678. var lx = 0; /* running index in l_buf */
  18679. var code; /* the code to send */
  18680. var extra; /* number of extra bits to send */
  18681. if (s.last_lit !== 0) {
  18682. do {
  18683. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  18684. lc = s.pending_buf[s.l_buf + lx];
  18685. lx++;
  18686. if (dist === 0) {
  18687. send_code(s, lc, ltree); /* send a literal byte */
  18688. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18689. } else {
  18690. /* Here, lc is the match length - MIN_MATCH */
  18691. code = _length_code[lc];
  18692. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  18693. extra = extra_lbits[code];
  18694. if (extra !== 0) {
  18695. lc -= base_length[code];
  18696. send_bits(s, lc, extra); /* send the extra length bits */
  18697. }
  18698. dist--; /* dist is now the match distance - 1 */
  18699. code = d_code(dist);
  18700. //Assert (code < D_CODES, "bad d_code");
  18701. send_code(s, code, dtree); /* send the distance code */
  18702. extra = extra_dbits[code];
  18703. if (extra !== 0) {
  18704. dist -= base_dist[code];
  18705. send_bits(s, dist, extra); /* send the extra distance bits */
  18706. }
  18707. } /* literal or match pair ? */
  18708. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18709. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18710. // "pendingBuf overflow");
  18711. } while (lx < s.last_lit);
  18712. }
  18713. send_code(s, END_BLOCK, ltree);
  18714. }
  18715. /* ===========================================================================
  18716. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18717. * Update the total bit length for the current block.
  18718. * IN assertion: the field freq is set for all tree elements.
  18719. * OUT assertions: the fields len and code are set to the optimal bit length
  18720. * and corresponding code. The length opt_len is updated; static_len is
  18721. * also updated if stree is not null. The field max_code is set.
  18722. */
  18723. function build_tree(s, desc)
  18724. // deflate_state *s;
  18725. // tree_desc *desc; /* the tree descriptor */
  18726. {
  18727. var tree = desc.dyn_tree;
  18728. var stree = desc.stat_desc.static_tree;
  18729. var has_stree = desc.stat_desc.has_stree;
  18730. var elems = desc.stat_desc.elems;
  18731. var n, m; /* iterate over heap elements */
  18732. var max_code = -1; /* largest code with non zero frequency */
  18733. var node; /* new node being created */
  18734. /* Construct the initial heap, with least frequent element in
  18735. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18736. * heap[0] is not used.
  18737. */
  18738. s.heap_len = 0;
  18739. s.heap_max = HEAP_SIZE;
  18740. for (n = 0; n < elems; n++) {
  18741. if (tree[n * 2]/*.Freq*/ !== 0) {
  18742. s.heap[++s.heap_len] = max_code = n;
  18743. s.depth[n] = 0;
  18744. } else {
  18745. tree[n*2 + 1]/*.Len*/ = 0;
  18746. }
  18747. }
  18748. /* The pkzip format requires that at least one distance code exists,
  18749. * and that at least one bit should be sent even if there is only one
  18750. * possible code. So to avoid special checks later on we force at least
  18751. * two codes of non zero frequency.
  18752. */
  18753. while (s.heap_len < 2) {
  18754. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18755. tree[node * 2]/*.Freq*/ = 1;
  18756. s.depth[node] = 0;
  18757. s.opt_len--;
  18758. if (has_stree) {
  18759. s.static_len -= stree[node*2 + 1]/*.Len*/;
  18760. }
  18761. /* node is 0 or 1 so it does not have extra bits */
  18762. }
  18763. desc.max_code = max_code;
  18764. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18765. * establish sub-heaps of increasing lengths:
  18766. */
  18767. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18768. /* Construct the Huffman tree by repeatedly combining the least two
  18769. * frequent nodes.
  18770. */
  18771. node = elems; /* next internal node of the tree */
  18772. do {
  18773. //pqremove(s, tree, n); /* n = node of least frequency */
  18774. /*** pqremove ***/
  18775. n = s.heap[1/*SMALLEST*/];
  18776. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18777. pqdownheap(s, tree, 1/*SMALLEST*/);
  18778. /***/
  18779. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18780. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18781. s.heap[--s.heap_max] = m;
  18782. /* Create a new node father of n and m */
  18783. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18784. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18785. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  18786. /* and insert the new node in the heap */
  18787. s.heap[1/*SMALLEST*/] = node++;
  18788. pqdownheap(s, tree, 1/*SMALLEST*/);
  18789. } while (s.heap_len >= 2);
  18790. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18791. /* At this point, the fields freq and dad are set. We can now
  18792. * generate the bit lengths.
  18793. */
  18794. gen_bitlen(s, desc);
  18795. /* The field len is now set, we can generate the bit codes */
  18796. gen_codes(tree, max_code, s.bl_count);
  18797. }
  18798. /* ===========================================================================
  18799. * Scan a literal or distance tree to determine the frequencies of the codes
  18800. * in the bit length tree.
  18801. */
  18802. function scan_tree(s, tree, max_code)
  18803. // deflate_state *s;
  18804. // ct_data *tree; /* the tree to be scanned */
  18805. // int max_code; /* and its largest code of non zero frequency */
  18806. {
  18807. var n; /* iterates over all tree elements */
  18808. var prevlen = -1; /* last emitted length */
  18809. var curlen; /* length of current code */
  18810. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18811. var count = 0; /* repeat count of the current code */
  18812. var max_count = 7; /* max repeat count */
  18813. var min_count = 4; /* min repeat count */
  18814. if (nextlen === 0) {
  18815. max_count = 138;
  18816. min_count = 3;
  18817. }
  18818. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18819. for (n = 0; n <= max_code; n++) {
  18820. curlen = nextlen;
  18821. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18822. if (++count < max_count && curlen === nextlen) {
  18823. continue;
  18824. } else if (count < min_count) {
  18825. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18826. } else if (curlen !== 0) {
  18827. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18828. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18829. } else if (count <= 10) {
  18830. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18831. } else {
  18832. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18833. }
  18834. count = 0;
  18835. prevlen = curlen;
  18836. if (nextlen === 0) {
  18837. max_count = 138;
  18838. min_count = 3;
  18839. } else if (curlen === nextlen) {
  18840. max_count = 6;
  18841. min_count = 3;
  18842. } else {
  18843. max_count = 7;
  18844. min_count = 4;
  18845. }
  18846. }
  18847. }
  18848. /* ===========================================================================
  18849. * Send a literal or distance tree in compressed form, using the codes in
  18850. * bl_tree.
  18851. */
  18852. function send_tree(s, tree, max_code)
  18853. // deflate_state *s;
  18854. // ct_data *tree; /* the tree to be scanned */
  18855. // int max_code; /* and its largest code of non zero frequency */
  18856. {
  18857. var n; /* iterates over all tree elements */
  18858. var prevlen = -1; /* last emitted length */
  18859. var curlen; /* length of current code */
  18860. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18861. var count = 0; /* repeat count of the current code */
  18862. var max_count = 7; /* max repeat count */
  18863. var min_count = 4; /* min repeat count */
  18864. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18865. if (nextlen === 0) {
  18866. max_count = 138;
  18867. min_count = 3;
  18868. }
  18869. for (n = 0; n <= max_code; n++) {
  18870. curlen = nextlen;
  18871. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18872. if (++count < max_count && curlen === nextlen) {
  18873. continue;
  18874. } else if (count < min_count) {
  18875. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18876. } else if (curlen !== 0) {
  18877. if (curlen !== prevlen) {
  18878. send_code(s, curlen, s.bl_tree);
  18879. count--;
  18880. }
  18881. //Assert(count >= 3 && count <= 6, " 3_6?");
  18882. send_code(s, REP_3_6, s.bl_tree);
  18883. send_bits(s, count-3, 2);
  18884. } else if (count <= 10) {
  18885. send_code(s, REPZ_3_10, s.bl_tree);
  18886. send_bits(s, count-3, 3);
  18887. } else {
  18888. send_code(s, REPZ_11_138, s.bl_tree);
  18889. send_bits(s, count-11, 7);
  18890. }
  18891. count = 0;
  18892. prevlen = curlen;
  18893. if (nextlen === 0) {
  18894. max_count = 138;
  18895. min_count = 3;
  18896. } else if (curlen === nextlen) {
  18897. max_count = 6;
  18898. min_count = 3;
  18899. } else {
  18900. max_count = 7;
  18901. min_count = 4;
  18902. }
  18903. }
  18904. }
  18905. /* ===========================================================================
  18906. * Construct the Huffman tree for the bit lengths and return the index in
  18907. * bl_order of the last bit length code to send.
  18908. */
  18909. function build_bl_tree(s) {
  18910. var max_blindex; /* index of last bit length code of non zero freq */
  18911. /* Determine the bit length frequencies for literal and distance trees */
  18912. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18913. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18914. /* Build the bit length tree: */
  18915. build_tree(s, s.bl_desc);
  18916. /* opt_len now includes the length of the tree representations, except
  18917. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18918. */
  18919. /* Determine the number of bit length codes to send. The pkzip format
  18920. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18921. * 3 but the actual value used is 4.)
  18922. */
  18923. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18924. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18925. break;
  18926. }
  18927. }
  18928. /* Update opt_len to include the bit length tree and counts */
  18929. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18930. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18931. // s->opt_len, s->static_len));
  18932. return max_blindex;
  18933. }
  18934. /* ===========================================================================
  18935. * Send the header for a block using dynamic Huffman trees: the counts, the
  18936. * lengths of the bit length codes, the literal tree and the distance tree.
  18937. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18938. */
  18939. function send_all_trees(s, lcodes, dcodes, blcodes)
  18940. // deflate_state *s;
  18941. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18942. {
  18943. var rank; /* index in bl_order */
  18944. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18945. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18946. // "too many codes");
  18947. //Tracev((stderr, "\nbl counts: "));
  18948. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18949. send_bits(s, dcodes-1, 5);
  18950. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18951. for (rank = 0; rank < blcodes; rank++) {
  18952. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18953. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18954. }
  18955. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18956. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18957. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18958. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18959. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18960. }
  18961. /* ===========================================================================
  18962. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18963. * - TEXT if the two conditions below are satisfied:
  18964. * a) There are no non-portable control characters belonging to the
  18965. * "black list" (0..6, 14..25, 28..31).
  18966. * b) There is at least one printable character belonging to the
  18967. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18968. * - BINARY otherwise.
  18969. * - The following partially-portable control characters form a
  18970. * "gray list" that is ignored in this detection algorithm:
  18971. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18972. * IN assertion: the fields Freq of dyn_ltree are set.
  18973. */
  18974. function detect_data_type(s) {
  18975. /* black_mask is the bit mask of black-listed bytes
  18976. * set bits 0..6, 14..25, and 28..31
  18977. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18978. */
  18979. var black_mask = 0xf3ffc07f;
  18980. var n;
  18981. /* Check for non-textual ("black-listed") bytes. */
  18982. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18983. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18984. return Z_BINARY;
  18985. }
  18986. }
  18987. /* Check for textual ("white-listed") bytes. */
  18988. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18989. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18990. return Z_TEXT;
  18991. }
  18992. for (n = 32; n < LITERALS; n++) {
  18993. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18994. return Z_TEXT;
  18995. }
  18996. }
  18997. /* There are no "black-listed" or "white-listed" bytes:
  18998. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18999. */
  19000. return Z_BINARY;
  19001. }
  19002. var static_init_done = false;
  19003. /* ===========================================================================
  19004. * Initialize the tree data structures for a new zlib stream.
  19005. */
  19006. function _tr_init(s)
  19007. {
  19008. if (!static_init_done) {
  19009. tr_static_init();
  19010. static_init_done = true;
  19011. }
  19012. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19013. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19014. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19015. s.bi_buf = 0;
  19016. s.bi_valid = 0;
  19017. /* Initialize the first block of the first file: */
  19018. init_block(s);
  19019. }
  19020. /* ===========================================================================
  19021. * Send a stored block
  19022. */
  19023. function _tr_stored_block(s, buf, stored_len, last)
  19024. //DeflateState *s;
  19025. //charf *buf; /* input block */
  19026. //ulg stored_len; /* length of input block */
  19027. //int last; /* one if this is the last block for a file */
  19028. {
  19029. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19030. copy_block(s, buf, stored_len, true); /* with header */
  19031. }
  19032. /* ===========================================================================
  19033. * Send one empty static block to give enough lookahead for inflate.
  19034. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19035. */
  19036. function _tr_align(s) {
  19037. send_bits(s, STATIC_TREES<<1, 3);
  19038. send_code(s, END_BLOCK, static_ltree);
  19039. bi_flush(s);
  19040. }
  19041. /* ===========================================================================
  19042. * Determine the best encoding for the current block: dynamic trees, static
  19043. * trees or store, and output the encoded block to the zip file.
  19044. */
  19045. function _tr_flush_block(s, buf, stored_len, last)
  19046. //DeflateState *s;
  19047. //charf *buf; /* input block, or NULL if too old */
  19048. //ulg stored_len; /* length of input block */
  19049. //int last; /* one if this is the last block for a file */
  19050. {
  19051. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  19052. var max_blindex = 0; /* index of last bit length code of non zero freq */
  19053. /* Build the Huffman trees unless a stored block is forced */
  19054. if (s.level > 0) {
  19055. /* Check if the file is binary or text */
  19056. if (s.strm.data_type === Z_UNKNOWN) {
  19057. s.strm.data_type = detect_data_type(s);
  19058. }
  19059. /* Construct the literal and distance trees */
  19060. build_tree(s, s.l_desc);
  19061. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  19062. // s->static_len));
  19063. build_tree(s, s.d_desc);
  19064. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  19065. // s->static_len));
  19066. /* At this point, opt_len and static_len are the total bit lengths of
  19067. * the compressed block data, excluding the tree representations.
  19068. */
  19069. /* Build the bit length tree for the above two trees, and get the index
  19070. * in bl_order of the last bit length code to send.
  19071. */
  19072. max_blindex = build_bl_tree(s);
  19073. /* Determine the best encoding. Compute the block lengths in bytes. */
  19074. opt_lenb = (s.opt_len+3+7) >>> 3;
  19075. static_lenb = (s.static_len+3+7) >>> 3;
  19076. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  19077. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  19078. // s->last_lit));
  19079. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  19080. } else {
  19081. // Assert(buf != (char*)0, "lost buf");
  19082. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  19083. }
  19084. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  19085. /* 4: two words for the lengths */
  19086. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  19087. * Otherwise we can't have processed more than WSIZE input bytes since
  19088. * the last block flush, because compression would have been
  19089. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  19090. * transform a block into a stored block.
  19091. */
  19092. _tr_stored_block(s, buf, stored_len, last);
  19093. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  19094. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  19095. compress_block(s, static_ltree, static_dtree);
  19096. } else {
  19097. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  19098. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  19099. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  19100. }
  19101. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  19102. /* The above check is made mod 2^32, for files larger than 512 MB
  19103. * and uLong implemented on 32 bits.
  19104. */
  19105. init_block(s);
  19106. if (last) {
  19107. bi_windup(s);
  19108. }
  19109. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  19110. // s->compressed_len-7*last));
  19111. }
  19112. /* ===========================================================================
  19113. * Save the match info and tally the frequency counts. Return true if
  19114. * the current block must be flushed.
  19115. */
  19116. function _tr_tally(s, dist, lc)
  19117. // deflate_state *s;
  19118. // unsigned dist; /* distance of matched string */
  19119. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  19120. {
  19121. //var out_length, in_length, dcode;
  19122. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  19123. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  19124. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  19125. s.last_lit++;
  19126. if (dist === 0) {
  19127. /* lc is the unmatched char */
  19128. s.dyn_ltree[lc*2]/*.Freq*/++;
  19129. } else {
  19130. s.matches++;
  19131. /* Here, lc is the match length - MIN_MATCH */
  19132. dist--; /* dist = match distance - 1 */
  19133. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  19134. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  19135. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  19136. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  19137. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  19138. }
  19139. // (!) This block is disabled in zlib defailts,
  19140. // don't enable it for binary compatibility
  19141. //#ifdef TRUNCATE_BLOCK
  19142. // /* Try to guess if it is profitable to stop the current block here */
  19143. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  19144. // /* Compute an upper bound for the compressed length */
  19145. // out_length = s.last_lit*8;
  19146. // in_length = s.strstart - s.block_start;
  19147. //
  19148. // for (dcode = 0; dcode < D_CODES; dcode++) {
  19149. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  19150. // }
  19151. // out_length >>>= 3;
  19152. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  19153. // // s->last_lit, in_length, out_length,
  19154. // // 100L - out_length*100L/in_length));
  19155. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  19156. // return true;
  19157. // }
  19158. // }
  19159. //#endif
  19160. return (s.last_lit === s.lit_bufsize-1);
  19161. /* We avoid equality with lit_bufsize because of wraparound at 64K
  19162. * on 16 bit machines and because stored blocks are restricted to
  19163. * 64K-1 bytes.
  19164. */
  19165. }
  19166. exports._tr_init = _tr_init;
  19167. exports._tr_stored_block = _tr_stored_block;
  19168. exports._tr_flush_block = _tr_flush_block;
  19169. exports._tr_tally = _tr_tally;
  19170. exports._tr_align = _tr_align;
  19171. },{"../utils/common":52}],64:[function(require,module,exports){
  19172. 'use strict';
  19173. function ZStream() {
  19174. /* next input byte */
  19175. this.input = null; // JS specific, because we have no pointers
  19176. this.next_in = 0;
  19177. /* number of bytes available at input */
  19178. this.avail_in = 0;
  19179. /* total number of input bytes read so far */
  19180. this.total_in = 0;
  19181. /* next output byte should be put there */
  19182. this.output = null; // JS specific, because we have no pointers
  19183. this.next_out = 0;
  19184. /* remaining free space at output */
  19185. this.avail_out = 0;
  19186. /* total number of bytes output so far */
  19187. this.total_out = 0;
  19188. /* last error message, NULL if no error */
  19189. this.msg = ''/*Z_NULL*/;
  19190. /* not visible by applications */
  19191. this.state = null;
  19192. /* best guess about the data type: binary or text */
  19193. this.data_type = 2/*Z_UNKNOWN*/;
  19194. /* adler32 value of the uncompressed data */
  19195. this.adler = 0;
  19196. }
  19197. module.exports = ZStream;
  19198. },{}],65:[function(require,module,exports){
  19199. /* Copyright @ 2015 Atlassian Pty Ltd
  19200. *
  19201. * Licensed under the Apache License, Version 2.0 (the "License");
  19202. * you may not use this file except in compliance with the License.
  19203. * You may obtain a copy of the License at
  19204. *
  19205. * http://www.apache.org/licenses/LICENSE-2.0
  19206. *
  19207. * Unless required by applicable law or agreed to in writing, software
  19208. * distributed under the License is distributed on an "AS IS" BASIS,
  19209. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19210. * See the License for the specific language governing permissions and
  19211. * limitations under the License.
  19212. */
  19213. module.exports = function arrayEquals(array) {
  19214. // if the other array is a falsy value, return
  19215. if (!array)
  19216. return false;
  19217. // compare lengths - can save a lot of time
  19218. if (this.length != array.length)
  19219. return false;
  19220. for (var i = 0, l = this.length; i < l; i++) {
  19221. // Check if we have nested arrays
  19222. if (this[i] instanceof Array && array[i] instanceof Array) {
  19223. // recurse into the nested arrays
  19224. if (!arrayEquals.apply(this[i], [array[i]]))
  19225. return false;
  19226. } else if (this[i] != array[i]) {
  19227. // Warning - two different object instances will never be equal:
  19228. // {x:20} != {x:20}
  19229. return false;
  19230. }
  19231. }
  19232. return true;
  19233. };
  19234. },{}],66:[function(require,module,exports){
  19235. /* Copyright @ 2015 Atlassian Pty Ltd
  19236. *
  19237. * Licensed under the Apache License, Version 2.0 (the "License");
  19238. * you may not use this file except in compliance with the License.
  19239. * You may obtain a copy of the License at
  19240. *
  19241. * http://www.apache.org/licenses/LICENSE-2.0
  19242. *
  19243. * Unless required by applicable law or agreed to in writing, software
  19244. * distributed under the License is distributed on an "AS IS" BASIS,
  19245. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19246. * See the License for the specific language governing permissions and
  19247. * limitations under the License.
  19248. */
  19249. exports.Interop = require('./interop');
  19250. },{"./interop":67}],67:[function(require,module,exports){
  19251. /* Copyright @ 2015 Atlassian Pty Ltd
  19252. *
  19253. * Licensed under the Apache License, Version 2.0 (the "License");
  19254. * you may not use this file except in compliance with the License.
  19255. * You may obtain a copy of the License at
  19256. *
  19257. * http://www.apache.org/licenses/LICENSE-2.0
  19258. *
  19259. * Unless required by applicable law or agreed to in writing, software
  19260. * distributed under the License is distributed on an "AS IS" BASIS,
  19261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19262. * See the License for the specific language governing permissions and
  19263. * limitations under the License.
  19264. */
  19265. /* global RTCSessionDescription */
  19266. /* jshint -W097 */
  19267. "use strict";
  19268. var transform = require('./transform');
  19269. var arrayEquals = require('./array-equals');
  19270. function Interop() {
  19271. /**
  19272. * This map holds the most recent Unified Plan offer/answer SDP that was
  19273. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  19274. * the SDP string as values.
  19275. *
  19276. * @type {{}}
  19277. */
  19278. this.cache = {};
  19279. }
  19280. module.exports = Interop;
  19281. /**
  19282. * Returns the index of the first m-line with the given media type and with a
  19283. * direction which allows sending, in the last Unified Plan description with
  19284. * type "answer" converted to Plan B. Returns {null} if there is no saved
  19285. * answer, or if none of its m-lines with the given type allow sending.
  19286. * @param type the media type ("audio" or "video").
  19287. * @returns {*}
  19288. */
  19289. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  19290. if (!this.cache.answer) {
  19291. return null;
  19292. }
  19293. var session = transform.parse(this.cache.answer);
  19294. if (session && session.media && Array.isArray(session.media)){
  19295. for (var i = 0; i < session.media.length; i++) {
  19296. if (session.media[i].type == type &&
  19297. (!session.media[i].direction /* default to sendrecv */ ||
  19298. session.media[i].direction === 'sendrecv' ||
  19299. session.media[i].direction === 'sendonly')){
  19300. return i;
  19301. }
  19302. }
  19303. }
  19304. return null;
  19305. };
  19306. /**
  19307. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  19308. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  19309. * application.
  19310. *
  19311. * @param desc
  19312. * @returns {*}
  19313. */
  19314. Interop.prototype.toPlanB = function(desc) {
  19315. var self = this;
  19316. //#region Preliminary input validation.
  19317. if (typeof desc !== 'object' || desc === null ||
  19318. typeof desc.sdp !== 'string') {
  19319. console.warn('An empty description was passed as an argument.');
  19320. return desc;
  19321. }
  19322. // Objectify the SDP for easier manipulation.
  19323. var session = transform.parse(desc.sdp);
  19324. // If the SDP contains no media, there's nothing to transform.
  19325. if (typeof session.media === 'undefined' ||
  19326. !Array.isArray(session.media) || session.media.length === 0) {
  19327. console.warn('The description has no media.');
  19328. return desc;
  19329. }
  19330. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  19331. // SDP has a video, an audio and a data "channel" at most.
  19332. if (session.media.length <= 3 && session.media.every(function(m) {
  19333. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19334. })) {
  19335. console.warn('This description does not look like Unified Plan.');
  19336. return desc;
  19337. }
  19338. //#endregion
  19339. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  19340. var sdp = desc.sdp;
  19341. var rewrite = false;
  19342. for (var i = 0; i < session.media.length; i++) {
  19343. var uLine = session.media[i];
  19344. uLine.rtp.forEach(function(rtp) {
  19345. if (rtp.codec === 'NULL')
  19346. {
  19347. rewrite = true;
  19348. var offer = transform.parse(self.cache['offer']);
  19349. rtp.codec = offer.media[i].rtp[0].codec;
  19350. }
  19351. });
  19352. };
  19353. if (rewrite) {
  19354. sdp = transform.write(session);
  19355. }
  19356. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  19357. // -> Unified Plan transformation.
  19358. this.cache[desc.type] = sdp;
  19359. //#region Convert from Unified Plan to Plan B.
  19360. // We rebuild the session.media array.
  19361. var media = session.media;
  19362. session.media = [];
  19363. // Associative array that maps channel types to channel objects for fast
  19364. // access to channel objects by their type, e.g. type2bl['audio']->channel
  19365. // obj.
  19366. var type2bl = {};
  19367. // Used to build the group:BUNDLE value after the channels construction
  19368. // loop.
  19369. var types = [];
  19370. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  19371. media.forEach(function(uLine) {
  19372. // rtcp-mux is required in the Plan B SDP.
  19373. if ((typeof uLine.rtcpMux !== 'string' ||
  19374. uLine.rtcpMux !== 'rtcp-mux') &&
  19375. uLine.direction !== 'inactive') {
  19376. throw new Error('Cannot convert to Plan B because m-lines ' +
  19377. 'without the rtcp-mux attribute were found.');
  19378. }
  19379. if (uLine.type === 'application') {
  19380. session.media.push(uLine);
  19381. types.push(uLine.mid);
  19382. return;
  19383. }
  19384. // If we don't have a channel for this uLine.type, then use this
  19385. // uLine as the channel basis.
  19386. if (typeof type2bl[uLine.type] === 'undefined') {
  19387. type2bl[uLine.type] = uLine;
  19388. }
  19389. // Add sources to the channel and handle a=msid.
  19390. if (typeof uLine.sources === 'object') {
  19391. Object.keys(uLine.sources).forEach(function(ssrc) {
  19392. if (typeof type2bl[uLine.type].sources !== 'object')
  19393. type2bl[uLine.type].sources = {};
  19394. // Assign the sources to the channel.
  19395. type2bl[uLine.type].sources[ssrc] =
  19396. uLine.sources[ssrc];
  19397. if (typeof uLine.msid !== 'undefined') {
  19398. // In Plan B the msid is an SSRC attribute. Also, we don't
  19399. // care about the obsolete label and mslabel attributes.
  19400. //
  19401. // Note that it is not guaranteed that the uLine will
  19402. // have an msid. recvonly channels in particular don't have
  19403. // one.
  19404. type2bl[uLine.type].sources[ssrc].msid =
  19405. uLine.msid;
  19406. }
  19407. // NOTE ssrcs in ssrc groups will share msids, as
  19408. // draft-uberti-rtcweb-plan-00 mandates.
  19409. });
  19410. }
  19411. // Add ssrc groups to the channel.
  19412. if (typeof uLine.ssrcGroups !== 'undefined' &&
  19413. Array.isArray(uLine.ssrcGroups)) {
  19414. // Create the ssrcGroups array, if it's not defined.
  19415. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  19416. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  19417. type2bl[uLine.type].ssrcGroups = [];
  19418. }
  19419. type2bl[uLine.type].ssrcGroups =
  19420. type2bl[uLine.type].ssrcGroups.concat(
  19421. uLine.ssrcGroups);
  19422. }
  19423. if (type2bl[uLine.type] === uLine) {
  19424. // Copy ICE related stuff from the principal media line.
  19425. uLine.candidates = media[0].candidates;
  19426. uLine.iceUfrag = media[0].iceUfrag;
  19427. uLine.icePwd = media[0].icePwd;
  19428. uLine.fingerprint = media[0].fingerprint;
  19429. // Plan B mids are in ['audio', 'video', 'data']
  19430. uLine.mid = uLine.type;
  19431. // Plan B doesn't support/need the bundle-only attribute.
  19432. delete uLine.bundleOnly;
  19433. // In Plan B the msid is an SSRC attribute.
  19434. delete uLine.msid;
  19435. // Used to build the group:BUNDLE value after this loop.
  19436. types.push(uLine.type);
  19437. // Add the channel to the new media array.
  19438. session.media.push(uLine);
  19439. }
  19440. });
  19441. // We regenerate the BUNDLE group with the new mids.
  19442. session.groups.some(function(group) {
  19443. if (group.type === 'BUNDLE') {
  19444. group.mids = types.join(' ');
  19445. return true;
  19446. }
  19447. });
  19448. // msid semantic
  19449. session.msidSemantic = {
  19450. semantic: 'WMS',
  19451. token: '*'
  19452. };
  19453. var resStr = transform.write(session);
  19454. return new RTCSessionDescription({
  19455. type: desc.type,
  19456. sdp: resStr
  19457. });
  19458. //#endregion
  19459. };
  19460. /**
  19461. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  19462. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  19463. * to FF.
  19464. *
  19465. * @param desc
  19466. * @returns {*}
  19467. */
  19468. Interop.prototype.toUnifiedPlan = function(desc) {
  19469. var self = this;
  19470. //#region Preliminary input validation.
  19471. if (typeof desc !== 'object' || desc === null ||
  19472. typeof desc.sdp !== 'string') {
  19473. console.warn('An empty description was passed as an argument.');
  19474. return desc;
  19475. }
  19476. var session = transform.parse(desc.sdp);
  19477. // If the SDP contains no media, there's nothing to transform.
  19478. if (typeof session.media === 'undefined' ||
  19479. !Array.isArray(session.media) || session.media.length === 0) {
  19480. console.warn('The description has no media.');
  19481. return desc;
  19482. }
  19483. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  19484. // a video, an audio and a data "channel" at most.
  19485. if (session.media.length > 3 || !session.media.every(function(m) {
  19486. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19487. })) {
  19488. console.warn('This description does not look like Plan B.');
  19489. return desc;
  19490. }
  19491. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  19492. var mids = [];
  19493. session.media.forEach(function(m) {
  19494. mids.push(m.mid);
  19495. });
  19496. var hasBundle = false;
  19497. if (typeof session.groups !== 'undefined' &&
  19498. Array.isArray(session.groups)) {
  19499. hasBundle = session.groups.every(function(g) {
  19500. return g.type !== 'BUNDLE' ||
  19501. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  19502. });
  19503. }
  19504. if (!hasBundle) {
  19505. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  19506. " are not bundled were found.");
  19507. }
  19508. //#endregion
  19509. //#region Convert from Plan B to Unified Plan.
  19510. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  19511. // rebuild an equivalent Unified Plan offer/answer.
  19512. //
  19513. // For example, if this is a local answer (in Unified Plan style) that we
  19514. // convert to Plan B prior to handing it over to the application (the
  19515. // PeerConnection wrapper called us, for instance, after a successful
  19516. // createAnswer), we want to remember the m-line at which we've seen the
  19517. // (local) SSRC. That's because when the application wants to do call the
  19518. // SLD method, forcing us to do the inverse transformation (from Plan B to
  19519. // Unified Plan), we need to know to which m-line to assign the (local)
  19520. // SSRC. We also need to know all the other m-lines that the original
  19521. // answer had and include them in the transformed answer as well.
  19522. //
  19523. // Another example is if this is a remote offer that we convert to Plan B
  19524. // prior to giving it to the application, we want to remember the mid at
  19525. // which we've seen the (remote) SSRC.
  19526. //
  19527. // In the iteration that follows, we use the cached Unified Plan (if it
  19528. // exists) to assign mids to ssrcs.
  19529. var cached;
  19530. if (typeof this.cache[desc.type] !== 'undefined') {
  19531. cached = transform.parse(this.cache[desc.type]);
  19532. }
  19533. var recvonlySsrcs = {
  19534. audio: {},
  19535. video: {}
  19536. };
  19537. // A helper map that sends mids to m-line objects. We use it later to
  19538. // rebuild the Unified Plan style session.media array.
  19539. var mid2ul = {};
  19540. session.media.forEach(function(bLine) {
  19541. if ((typeof bLine.rtcpMux !== 'string' ||
  19542. bLine.rtcpMux !== 'rtcp-mux') &&
  19543. bLine.direction !== 'inactive') {
  19544. throw new Error("Cannot convert to Unified Plan because m-lines " +
  19545. "without the rtcp-mux attribute were found.");
  19546. }
  19547. if (bLine.type === 'application') {
  19548. mid2ul[bLine.mid] = bLine;
  19549. return;
  19550. }
  19551. // With rtcp-mux and bundle all the channels should have the same ICE
  19552. // stuff.
  19553. var sources = bLine.sources;
  19554. var ssrcGroups = bLine.ssrcGroups;
  19555. var candidates = bLine.candidates;
  19556. var iceUfrag = bLine.iceUfrag;
  19557. var icePwd = bLine.icePwd;
  19558. var fingerprint = bLine.fingerprint;
  19559. var port = bLine.port;
  19560. // We'll use the "bLine" object as a prototype for each new "mLine"
  19561. // that we create, but first we need to clean it up a bit.
  19562. delete bLine.sources;
  19563. delete bLine.ssrcGroups;
  19564. delete bLine.candidates;
  19565. delete bLine.iceUfrag;
  19566. delete bLine.icePwd;
  19567. delete bLine.fingerprint;
  19568. delete bLine.port;
  19569. delete bLine.mid;
  19570. // inverted ssrc group map
  19571. var ssrc2group = {};
  19572. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  19573. ssrcGroups.forEach(function (ssrcGroup) {
  19574. // TODO(gp) find out how to receive simulcast with FF. For the
  19575. // time being, hide it.
  19576. if (ssrcGroup.semantics === 'SIM') {
  19577. return;
  19578. }
  19579. // XXX This might brake if an SSRC is in more than one group
  19580. // for some reason.
  19581. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19582. Array.isArray(ssrcGroup.ssrcs)) {
  19583. ssrcGroup.ssrcs.forEach(function (ssrc) {
  19584. if (typeof ssrc2group[ssrc] === 'undefined') {
  19585. ssrc2group[ssrc] = [];
  19586. }
  19587. ssrc2group[ssrc].push(ssrcGroup);
  19588. });
  19589. }
  19590. });
  19591. }
  19592. // ssrc to m-line index.
  19593. var ssrc2ml = {};
  19594. if (typeof sources === 'object') {
  19595. // Explode the Plan B channel sources with one m-line per source.
  19596. Object.keys(sources).forEach(function(ssrc) {
  19597. // The (unified) m-line for this SSRC. We either create it from
  19598. // scratch or, if it's a grouped SSRC, we re-use a related
  19599. // mline. In other words, if the source is grouped with another
  19600. // source, put the two together in the same m-line.
  19601. var uLine;
  19602. // We assume here that we are the answerer in the O/A, so any
  19603. // offers which we translate come from the remote side, while
  19604. // answers are local. So the check below is to make that we
  19605. // handle receive-only SSRCs in a special way only if they come
  19606. // from the remote side.
  19607. if (desc.type==='offer') {
  19608. // We want to detect SSRCs which are used by a remote peer
  19609. // in an m-line with direction=recvonly (i.e. they are
  19610. // being used for RTCP only).
  19611. // This information would have gotten lost if the remote
  19612. // peer used Unified Plan and their local description was
  19613. // translated to Plan B. So we use the lack of an MSID
  19614. // attribute to deduce a "receive only" SSRC.
  19615. if (!sources[ssrc].msid) {
  19616. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  19617. // Receive-only SSRCs must not create new m-lines. We
  19618. // will assign them to an existing m-line later.
  19619. return;
  19620. }
  19621. }
  19622. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  19623. Array.isArray(ssrc2group[ssrc])) {
  19624. ssrc2group[ssrc].some(function (ssrcGroup) {
  19625. // ssrcGroup.ssrcs *is* an Array, no need to check
  19626. // again here.
  19627. return ssrcGroup.ssrcs.some(function (related) {
  19628. if (typeof ssrc2ml[related] === 'object') {
  19629. uLine = ssrc2ml[related];
  19630. return true;
  19631. }
  19632. });
  19633. });
  19634. }
  19635. if (typeof uLine === 'object') {
  19636. // the m-line already exists. Just add the source.
  19637. uLine.sources[ssrc] = sources[ssrc];
  19638. delete sources[ssrc].msid;
  19639. } else {
  19640. // Use the "bLine" as a prototype for the "uLine".
  19641. uLine = Object.create(bLine);
  19642. ssrc2ml[ssrc] = uLine;
  19643. if (typeof sources[ssrc].msid !== 'undefined') {
  19644. // Assign the msid of the source to the m-line. Note
  19645. // that it is not guaranteed that the source will have
  19646. // msid. In particular "recvonly" sources don't have an
  19647. // msid. Note that "recvonly" is a term only defined
  19648. // for m-lines.
  19649. uLine.msid = sources[ssrc].msid;
  19650. uLine.direction = 'sendrecv';
  19651. delete sources[ssrc].msid;
  19652. }
  19653. // We assign one SSRC per media line.
  19654. uLine.sources = {};
  19655. uLine.sources[ssrc] = sources[ssrc];
  19656. uLine.ssrcGroups = ssrc2group[ssrc];
  19657. // Use the cached Unified Plan SDP (if it exists) to assign
  19658. // SSRCs to mids.
  19659. if (typeof cached !== 'undefined' &&
  19660. typeof cached.media !== 'undefined' &&
  19661. Array.isArray(cached.media)) {
  19662. cached.media.forEach(function (m) {
  19663. if (typeof m.sources === 'object') {
  19664. Object.keys(m.sources).forEach(function (s) {
  19665. if (s === ssrc) {
  19666. uLine.mid = m.mid;
  19667. }
  19668. });
  19669. }
  19670. });
  19671. }
  19672. if (typeof uLine.mid === 'undefined') {
  19673. // If this is an SSRC that we see for the first time
  19674. // assign it a new mid. This is typically the case when
  19675. // this method is called to transform a remote
  19676. // description for the first time or when there is a
  19677. // new SSRC in the remote description because a new
  19678. // peer has joined the conference. Local SSRCs should
  19679. // have already been added to the map in the toPlanB
  19680. // method.
  19681. //
  19682. // Because FF generates answers in Unified Plan style,
  19683. // we MUST already have a cached answer with all the
  19684. // local SSRCs mapped to some m-line/mid.
  19685. if (desc.type === 'answer') {
  19686. throw new Error("An unmapped SSRC was found.");
  19687. }
  19688. uLine.mid = [bLine.type, '-', ssrc].join('');
  19689. }
  19690. // Include the candidates in the 1st media line.
  19691. uLine.candidates = candidates;
  19692. uLine.iceUfrag = iceUfrag;
  19693. uLine.icePwd = icePwd;
  19694. uLine.fingerprint = fingerprint;
  19695. uLine.port = port;
  19696. mid2ul[uLine.mid] = uLine;
  19697. }
  19698. });
  19699. }
  19700. });
  19701. // Rebuild the media array in the right order and add the missing mLines
  19702. // (missing from the Plan B SDP).
  19703. session.media = [];
  19704. mids = []; // reuse
  19705. if (desc.type === 'answer') {
  19706. // The media lines in the answer must match the media lines in the
  19707. // offer. The order is important too. Here we assume that Firefox is
  19708. // the answerer, so we merely have to use the reconstructed (unified)
  19709. // answer to update the cached (unified) answer accordingly.
  19710. //
  19711. // In the general case, one would have to use the cached (unified)
  19712. // offer to find the m-lines that are missing from the reconstructed
  19713. // answer, potentially grabbing them from the cached (unified) answer.
  19714. // One has to be careful with this approach because inactive m-lines do
  19715. // not always have an mid, making it tricky (impossible?) to find where
  19716. // exactly and which m-lines are missing from the reconstructed answer.
  19717. for (var i = 0; i < cached.media.length; i++) {
  19718. var uLine = cached.media[i];
  19719. if (typeof mid2ul[uLine.mid] === 'undefined') {
  19720. // The mid isn't in the reconstructed (unified) answer.
  19721. // This is either a (unified) m-line containing a remote
  19722. // track only, or a (unified) m-line containing a remote
  19723. // track and a local track that has been removed.
  19724. // In either case, it MUST exist in the cached
  19725. // (unified) answer.
  19726. //
  19727. // In case this is a removed local track, clean-up
  19728. // the (unified) m-line and make sure it's 'recvonly' or
  19729. // 'inactive'.
  19730. delete uLine.msid;
  19731. delete uLine.sources;
  19732. delete uLine.ssrcGroups;
  19733. if (!uLine.direction
  19734. || uLine.direction === 'sendrecv')
  19735. uLine.direction = 'recvonly';
  19736. else if (uLine.direction === 'sendonly')
  19737. uLine.direction = 'inactive';
  19738. } else {
  19739. // This is an (unified) m-line/channel that contains a local
  19740. // track (sendrecv or sendonly channel) or it's a unified
  19741. // recvonly m-line/channel. In either case, since we're
  19742. // going from PlanB -> Unified Plan this m-line MUST
  19743. // exist in the cached answer.
  19744. }
  19745. session.media.push(uLine);
  19746. if (typeof uLine.mid === 'string') {
  19747. // inactive lines don't/may not have an mid.
  19748. mids.push(uLine.mid);
  19749. }
  19750. }
  19751. } else {
  19752. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  19753. // under any circumstances. If we are no longer interested in sending a
  19754. // track, we just remove the msid and ssrc attributes and set it to
  19755. // either a=recvonly (as the reofferer, we must use recvonly if the
  19756. // other side was previously sending on the m-section, but we can also
  19757. // leave the possibility open if it wasn't previously in use), or
  19758. // a=inactive.
  19759. if (typeof cached !== 'undefined' &&
  19760. typeof cached.media !== 'undefined' &&
  19761. Array.isArray(cached.media)) {
  19762. cached.media.forEach(function(uLine) {
  19763. mids.push(uLine.mid);
  19764. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  19765. session.media.push(mid2ul[uLine.mid]);
  19766. } else {
  19767. delete uLine.msid;
  19768. delete uLine.sources;
  19769. delete uLine.ssrcGroups;
  19770. if (!uLine.direction
  19771. || uLine.direction === 'sendrecv')
  19772. uLine.direction = 'recvonly';
  19773. if (!uLine.direction
  19774. || uLine.direction === 'sendonly')
  19775. uLine.direction = 'inactive';
  19776. session.media.push(uLine);
  19777. }
  19778. });
  19779. }
  19780. // Add all the remaining (new) m-lines of the transformed SDP.
  19781. Object.keys(mid2ul).forEach(function(mid) {
  19782. if (mids.indexOf(mid) === -1) {
  19783. mids.push(mid);
  19784. if (mid2ul[mid].direction === 'recvonly') {
  19785. // This is a remote recvonly channel. Add its SSRC to the
  19786. // appropriate sendrecv or sendonly channel.
  19787. // TODO(gp) what if we don't have sendrecv/sendonly
  19788. // channel?
  19789. session.media.some(function (uLine) {
  19790. if ((uLine.direction === 'sendrecv' ||
  19791. uLine.direction === 'sendonly') &&
  19792. uLine.type === mid2ul[mid].type) {
  19793. // mid2ul[mid] shouldn't have any ssrc-groups
  19794. Object.keys(mid2ul[mid].sources).forEach(
  19795. function (ssrc) {
  19796. uLine.sources[ssrc] =
  19797. mid2ul[mid].sources[ssrc];
  19798. });
  19799. return true;
  19800. }
  19801. });
  19802. } else {
  19803. session.media.push(mid2ul[mid]);
  19804. }
  19805. }
  19806. });
  19807. }
  19808. // After we have constructed the Plan Unified m-lines we can figure out
  19809. // where (in which m-line) to place the 'recvonly SSRCs'.
  19810. // Note: we assume here that we are the answerer in the O/A, so any offers
  19811. // which we translate come from the remote side, while answers are local
  19812. // (and so our last local description is cached as an 'answer').
  19813. ["audio", "video"].forEach(function (type) {
  19814. if (!session || !session.media || !Array.isArray(session.media))
  19815. return;
  19816. var idx = null;
  19817. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19818. idx = self.getFirstSendingIndexFromAnswer(type);
  19819. if (idx === null){
  19820. // If this is the first offer we receive, we don't have a
  19821. // cached answer. Assume that we will be sending media using
  19822. // the first m-line for each media type.
  19823. for (var i = 0; i < session.media.length; i++) {
  19824. if (session.media[i].type === type) {
  19825. idx = i;
  19826. break;
  19827. }
  19828. }
  19829. }
  19830. }
  19831. if (idx && session.media.length > idx) {
  19832. var mLine = session.media[idx];
  19833. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19834. if (mLine.sources && mLine.sources[ssrc]) {
  19835. console.warn("Replacing an existing SSRC.");
  19836. }
  19837. if (!mLine.sources) {
  19838. mLine.sources = {};
  19839. }
  19840. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19841. });
  19842. }
  19843. });
  19844. // We regenerate the BUNDLE group (since we regenerated the mids)
  19845. session.groups.some(function(group) {
  19846. if (group.type === 'BUNDLE') {
  19847. group.mids = mids.join(' ');
  19848. return true;
  19849. }
  19850. });
  19851. // msid semantic
  19852. session.msidSemantic = {
  19853. semantic: 'WMS',
  19854. token: '*'
  19855. };
  19856. var resStr = transform.write(session);
  19857. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19858. // function.
  19859. this.cache[desc.type] = resStr;
  19860. return new RTCSessionDescription({
  19861. type: desc.type,
  19862. sdp: resStr
  19863. });
  19864. //#endregion
  19865. };
  19866. },{"./array-equals":65,"./transform":68}],68:[function(require,module,exports){
  19867. /* Copyright @ 2015 Atlassian Pty Ltd
  19868. *
  19869. * Licensed under the Apache License, Version 2.0 (the "License");
  19870. * you may not use this file except in compliance with the License.
  19871. * You may obtain a copy of the License at
  19872. *
  19873. * http://www.apache.org/licenses/LICENSE-2.0
  19874. *
  19875. * Unless required by applicable law or agreed to in writing, software
  19876. * distributed under the License is distributed on an "AS IS" BASIS,
  19877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19878. * See the License for the specific language governing permissions and
  19879. * limitations under the License.
  19880. */
  19881. var transform = require('sdp-transform');
  19882. exports.write = function(session, opts) {
  19883. if (typeof session !== 'undefined' &&
  19884. typeof session.media !== 'undefined' &&
  19885. Array.isArray(session.media)) {
  19886. session.media.forEach(function (mLine) {
  19887. // expand sources to ssrcs
  19888. if (typeof mLine.sources !== 'undefined' &&
  19889. Object.keys(mLine.sources).length !== 0) {
  19890. mLine.ssrcs = [];
  19891. Object.keys(mLine.sources).forEach(function (ssrc) {
  19892. var source = mLine.sources[ssrc];
  19893. Object.keys(source).forEach(function (attribute) {
  19894. mLine.ssrcs.push({
  19895. id: ssrc,
  19896. attribute: attribute,
  19897. value: source[attribute]
  19898. });
  19899. });
  19900. });
  19901. delete mLine.sources;
  19902. }
  19903. // join ssrcs in ssrc groups
  19904. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19905. Array.isArray(mLine.ssrcGroups)) {
  19906. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19907. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19908. Array.isArray(ssrcGroup.ssrcs)) {
  19909. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19910. }
  19911. });
  19912. }
  19913. });
  19914. }
  19915. // join group mids
  19916. if (typeof session !== 'undefined' &&
  19917. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19918. session.groups.forEach(function (g) {
  19919. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19920. g.mids = g.mids.join(' ');
  19921. }
  19922. });
  19923. }
  19924. return transform.write(session, opts);
  19925. };
  19926. exports.parse = function(sdp) {
  19927. var session = transform.parse(sdp);
  19928. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19929. Array.isArray(session.media)) {
  19930. session.media.forEach(function (mLine) {
  19931. // group sources attributes by ssrc
  19932. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19933. mLine.sources = {};
  19934. mLine.ssrcs.forEach(function (ssrc) {
  19935. if (!mLine.sources[ssrc.id])
  19936. mLine.sources[ssrc.id] = {};
  19937. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19938. });
  19939. delete mLine.ssrcs;
  19940. }
  19941. // split ssrcs in ssrc groups
  19942. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19943. Array.isArray(mLine.ssrcGroups)) {
  19944. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19945. if (typeof ssrcGroup.ssrcs === 'string') {
  19946. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19947. }
  19948. });
  19949. }
  19950. });
  19951. }
  19952. // split group mids
  19953. if (typeof session !== 'undefined' &&
  19954. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19955. session.groups.forEach(function (g) {
  19956. if (typeof g.mids === 'string') {
  19957. g.mids = g.mids.split(' ');
  19958. }
  19959. });
  19960. }
  19961. return session;
  19962. };
  19963. },{"sdp-transform":76}],69:[function(require,module,exports){
  19964. /* Copyright @ 2015 Atlassian Pty Ltd
  19965. *
  19966. * Licensed under the Apache License, Version 2.0 (the "License");
  19967. * you may not use this file except in compliance with the License.
  19968. * You may obtain a copy of the License at
  19969. *
  19970. * http://www.apache.org/licenses/LICENSE-2.0
  19971. *
  19972. * Unless required by applicable law or agreed to in writing, software
  19973. * distributed under the License is distributed on an "AS IS" BASIS,
  19974. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19975. * See the License for the specific language governing permissions and
  19976. * limitations under the License.
  19977. */
  19978. var transform = require('sdp-transform');
  19979. var transformUtils = require('./transform-utils');
  19980. var parseSsrcs = transformUtils.parseSsrcs;
  19981. var writeSsrcs = transformUtils.writeSsrcs;
  19982. //region Constants
  19983. var DEFAULT_NUM_OF_LAYERS = 3;
  19984. //endregion
  19985. //region Ctor
  19986. function Simulcast(options) {
  19987. this.options = options ? options : {};
  19988. if (!this.options.numOfLayers) {
  19989. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  19990. }
  19991. this.layers = [];
  19992. }
  19993. //endregion
  19994. //region Stateless private utility functions
  19995. /**
  19996. * Returns a random integer between min (included) and max (excluded)
  19997. * Using Math.round() gives a non-uniform distribution!
  19998. * @returns {number}
  19999. */
  20000. function generateSSRC() {
  20001. var min = 0, max = 0xffffffff;
  20002. return Math.floor(Math.random() * (max - min)) + min;
  20003. };
  20004. function processVideo(session, action) {
  20005. if (session == null || !Array.isArray(session.media)) {
  20006. return;
  20007. }
  20008. session.media.forEach(function (mLine) {
  20009. if (mLine.type === 'video') {
  20010. action(mLine);
  20011. }
  20012. });
  20013. }
  20014. function validateDescription(desc)
  20015. {
  20016. return desc && desc != null
  20017. && desc.type && desc.type != ''
  20018. && desc.sdp && desc.sdp != '';
  20019. }
  20020. function explodeRemoteSimulcast(mLine) {
  20021. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20022. return;
  20023. }
  20024. var sources = parseSsrcs(mLine);
  20025. var order = [];
  20026. // Find the SIM group and explode its sources.
  20027. var j = mLine.ssrcGroups.length;
  20028. while (j--) {
  20029. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  20030. continue;
  20031. }
  20032. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  20033. for (var i = 0; i < simulcastSsrcs.length; i++) {
  20034. var ssrc = simulcastSsrcs[i];
  20035. order.push(ssrc);
  20036. var parts = sources[ssrc].msid.split(' ');
  20037. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  20038. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  20039. // Remove all the groups that this SSRC participates in.
  20040. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20041. if (relatedGroup.semantics === 'SIM') {
  20042. return;
  20043. }
  20044. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20045. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20046. return;
  20047. }
  20048. // Nuke all the related SSRCs.
  20049. relatedSsrcs.forEach(function (relatedSSRC) {
  20050. sources[relatedSSRC].msid = sources[ssrc].msid;
  20051. sources[relatedSSRC].cname = sources[ssrc].cname;
  20052. if (relatedSSRC !== ssrc) {
  20053. order.push(relatedSSRC);
  20054. }
  20055. });
  20056. // Schedule the related group for nuking.
  20057. })
  20058. }
  20059. mLine.ssrcs = writeSsrcs(sources, order);
  20060. mLine.ssrcGroups.splice(j, 1);
  20061. };
  20062. }
  20063. function implodeRemoteSimulcast(mLine) {
  20064. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20065. console.debug('Halt: There are no SSRC groups in the remote ' +
  20066. 'description.');
  20067. return;
  20068. }
  20069. var sources = parseSsrcs(mLine);
  20070. // Find the SIM group and nuke it.
  20071. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  20072. if (simulcastGroup.semantics !== 'SIM') {
  20073. return;
  20074. }
  20075. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  20076. // Schedule the SIM group for nuking.
  20077. simulcastGroup.nuke = true;
  20078. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  20079. // Nuke all the higher layer SSRCs.
  20080. for (var i = 1; i < simulcastSsrcs.length; i++) {
  20081. var ssrc = simulcastSsrcs[i];
  20082. delete sources[ssrc];
  20083. // Remove all the groups that this SSRC participates in.
  20084. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20085. if (relatedGroup.semantics === 'SIM') {
  20086. return;
  20087. }
  20088. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20089. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20090. return;
  20091. }
  20092. // Nuke all the related SSRCs.
  20093. relatedSsrcs.forEach(function (relatedSSRC) {
  20094. delete sources[relatedSSRC];
  20095. });
  20096. // Schedule the related group for nuking.
  20097. relatedGroup.nuke = true;
  20098. })
  20099. }
  20100. return;
  20101. });
  20102. mLine.ssrcs = writeSsrcs(sources);
  20103. // Nuke all the scheduled groups.
  20104. var i = mLine.ssrcGroups.length;
  20105. while (i--) {
  20106. if (mLine.ssrcGroups[i].nuke) {
  20107. mLine.ssrcGroups.splice(i, 1);
  20108. }
  20109. }
  20110. }
  20111. function removeGoogConference(mLine) {
  20112. if (!mLine || !Array.isArray(mLine.invalid)) {
  20113. return;
  20114. }
  20115. var i = mLine.invalid.length;
  20116. while (i--) {
  20117. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  20118. mLine.invalid.splice(i, 1);
  20119. }
  20120. }
  20121. }
  20122. function assertGoogConference(mLine) {
  20123. if (!mLine) {
  20124. return;
  20125. }
  20126. if (!Array.isArray(mLine.invalid)) {
  20127. mLine.invalid = [];
  20128. }
  20129. if (!mLine.invalid.some(
  20130. function (i) { return i.value === 'x-google-flag:conference' })) {
  20131. mLine.invalid.push({'value': 'x-google-flag:conference'});
  20132. }
  20133. }
  20134. //endregion
  20135. //region "Private" functions
  20136. /**
  20137. *
  20138. * @param mLine
  20139. * @private
  20140. */
  20141. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  20142. if (!mLine || mLine.type !== 'video') {
  20143. return;
  20144. }
  20145. var sources = parseSsrcs(mLine);
  20146. if (Object.keys(sources).length === 0) {
  20147. // no sources, disable simulcast.
  20148. if (this.layers.length !== 0) {
  20149. this.layers = [];
  20150. }
  20151. return;
  20152. }
  20153. // find the base layer (we'll reuse its msid and cname).
  20154. var baseLayerSSRC = Object.keys(sources)[0];
  20155. var baseLayer = sources[baseLayerSSRC];
  20156. // todo(gp) handle screen sharing.
  20157. // check if base CNAME has changed and reinitialise layers.
  20158. if (this.layers.length > 0
  20159. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  20160. this.layers = [];
  20161. }
  20162. // (re)initialise layers
  20163. if (this.layers.length < 1) {
  20164. // first push the base layer.
  20165. this.layers.push({
  20166. ssrc: baseLayerSSRC,
  20167. msid: baseLayer.msid,
  20168. cname: baseLayer.cname
  20169. });
  20170. var rtx = false; // RFC 4588
  20171. if (Array.isArray(mLine.rtp)) {
  20172. rtx = mLine.rtp.some(
  20173. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  20174. }
  20175. if (rtx) {
  20176. this.layers[0].rtx = generateSSRC();
  20177. }
  20178. // now push additional layers.
  20179. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  20180. var layer = { ssrc: generateSSRC() };
  20181. if (rtx) {
  20182. layer.rtx = generateSSRC();
  20183. }
  20184. this.layers.push(layer);
  20185. }
  20186. }
  20187. };
  20188. /**
  20189. *
  20190. * @param mLine
  20191. * @private
  20192. */
  20193. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  20194. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  20195. var sources = {};
  20196. var msid = this.layers[0].msid;
  20197. var cname = this.layers[0].cname;
  20198. var simulcastSsrcs = [];
  20199. var ssrcGroups = [];
  20200. for (var i = 0; i < this.layers.length; i++) {
  20201. var layer = this.layers[i];
  20202. sources[layer.ssrc] = { msid: msid, cname: cname };
  20203. simulcastSsrcs.push(layer.ssrc);
  20204. if (layer.rtx) {
  20205. sources[layer.rtx] = {
  20206. msid: msid,
  20207. cname: cname
  20208. }
  20209. ssrcGroups.push({
  20210. semantics: 'FID',
  20211. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  20212. });
  20213. }
  20214. }
  20215. ssrcGroups.push({
  20216. semantics: 'SIM',
  20217. ssrcs: simulcastSsrcs.join(' ')
  20218. });
  20219. mLine.ssrcGroups = ssrcGroups;
  20220. mLine.ssrcs = writeSsrcs(sources);
  20221. }
  20222. }
  20223. //endregion
  20224. //region "Public" functions
  20225. Simulcast.prototype.isSupported = function () {
  20226. return window.chrome;
  20227. // TODO this needs improvements. For example I doubt that Chrome in Android
  20228. // has simulcast support. Also, only recent versions of Chromium have native
  20229. // simulcast support.
  20230. }
  20231. /**
  20232. *
  20233. * @param desc
  20234. * @returns {RTCSessionDescription}
  20235. */
  20236. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  20237. if (!validateDescription(desc)) {
  20238. return desc;
  20239. }
  20240. var session = transform.parse(desc.sdp);
  20241. var self = this;
  20242. processVideo(session, function (mLine) {
  20243. // Handle simulcast reception.
  20244. if (self.options.explodeRemoteSimulcast) {
  20245. explodeRemoteSimulcast(mLine);
  20246. } else {
  20247. implodeRemoteSimulcast(mLine);
  20248. }
  20249. // If native simulcast is enabled, we must append the x-goog-conference
  20250. // attribute to the SDP.
  20251. if (self.layers.length < 1) {
  20252. removeGoogConference(mLine);
  20253. } else {
  20254. assertGoogConference(mLine);
  20255. }
  20256. });
  20257. return new RTCSessionDescription({
  20258. type: desc.type,
  20259. sdp: transform.write(session)
  20260. });
  20261. };
  20262. /**
  20263. *
  20264. * @param desc
  20265. * @returns {RTCSessionDescription}
  20266. */
  20267. Simulcast.prototype.mungeLocalDescription = function (desc) {
  20268. if (!validateDescription(desc) || !this.isSupported()) {
  20269. return desc;
  20270. }
  20271. var session = transform.parse(desc.sdp);
  20272. var self = this;
  20273. processVideo(session, function (mLine) {
  20274. // Initialize native simulcast layers, if not already done.
  20275. self._maybeInitializeLayers(mLine);
  20276. // Update the SDP with the simulcast layers.
  20277. self._restoreSimulcastView(mLine);
  20278. });
  20279. return new RTCSessionDescription({
  20280. type: desc.type,
  20281. sdp: transform.write(session)
  20282. });
  20283. };
  20284. //endregion
  20285. module.exports = Simulcast;
  20286. },{"./transform-utils":70,"sdp-transform":72}],70:[function(require,module,exports){
  20287. /* Copyright @ 2015 Atlassian Pty Ltd
  20288. *
  20289. * Licensed under the Apache License, Version 2.0 (the "License");
  20290. * you may not use this file except in compliance with the License.
  20291. * You may obtain a copy of the License at
  20292. *
  20293. * http://www.apache.org/licenses/LICENSE-2.0
  20294. *
  20295. * Unless required by applicable law or agreed to in writing, software
  20296. * distributed under the License is distributed on an "AS IS" BASIS,
  20297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20298. * See the License for the specific language governing permissions and
  20299. * limitations under the License.
  20300. */
  20301. exports.writeSsrcs = function(sources, order) {
  20302. var ssrcs = [];
  20303. // expand sources to ssrcs
  20304. if (typeof sources !== 'undefined' &&
  20305. Object.keys(sources).length !== 0) {
  20306. if (Array.isArray(order)) {
  20307. for (var i = 0; i < order.length; i++) {
  20308. var ssrc = order[i];
  20309. var source = sources[ssrc];
  20310. Object.keys(source).forEach(function (attribute) {
  20311. ssrcs.push({
  20312. id: ssrc,
  20313. attribute: attribute,
  20314. value: source[attribute]
  20315. });
  20316. });
  20317. }
  20318. } else {
  20319. Object.keys(sources).forEach(function (ssrc) {
  20320. var source = sources[ssrc];
  20321. Object.keys(source).forEach(function (attribute) {
  20322. ssrcs.push({
  20323. id: ssrc,
  20324. attribute: attribute,
  20325. value: source[attribute]
  20326. });
  20327. });
  20328. });
  20329. }
  20330. }
  20331. return ssrcs;
  20332. };
  20333. exports.parseSsrcs = function (mLine) {
  20334. var sources = {};
  20335. // group sources attributes by ssrc.
  20336. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20337. mLine.ssrcs.forEach(function (ssrc) {
  20338. if (!sources[ssrc.id])
  20339. sources[ssrc.id] = {};
  20340. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20341. });
  20342. }
  20343. return sources;
  20344. };
  20345. },{}],71:[function(require,module,exports){
  20346. var grammar = module.exports = {
  20347. v: [{
  20348. name: 'version',
  20349. reg: /^(\d*)$/
  20350. }],
  20351. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20352. // NB: sessionId will be a String in most cases because it is huge
  20353. name: 'origin',
  20354. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20355. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20356. format: "%s %s %d %s IP%d %s"
  20357. }],
  20358. // default parsing of these only (though some of these feel outdated)
  20359. s: [{ name: 'name' }],
  20360. i: [{ name: 'description' }],
  20361. u: [{ name: 'uri' }],
  20362. e: [{ name: 'email' }],
  20363. p: [{ name: 'phone' }],
  20364. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20365. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20366. //k: [{}], // outdated thing ignored
  20367. t: [{ //t=0 0
  20368. name: 'timing',
  20369. reg: /^(\d*) (\d*)/,
  20370. names: ['start', 'stop'],
  20371. format: "%d %d"
  20372. }],
  20373. c: [{ //c=IN IP4 10.47.197.26
  20374. name: 'connection',
  20375. reg: /^IN IP(\d) (\S*)/,
  20376. names: ['version', 'ip'],
  20377. format: "IN IP%d %s"
  20378. }],
  20379. b: [{ //b=AS:4000
  20380. push: 'bandwidth',
  20381. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20382. names: ['type', 'limit'],
  20383. format: "%s:%s"
  20384. }],
  20385. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20386. // NB: special - pushes to session
  20387. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20388. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20389. names: ['type', 'port', 'protocol', 'payloads'],
  20390. format: "%s %d %s %s"
  20391. }],
  20392. a: [
  20393. { //a=rtpmap:110 opus/48000/2
  20394. push: 'rtp',
  20395. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  20396. names: ['payload', 'codec', 'rate', 'encoding'],
  20397. format: function (o) {
  20398. return (o.encoding) ?
  20399. "rtpmap:%d %s/%s/%s":
  20400. "rtpmap:%d %s/%s";
  20401. }
  20402. },
  20403. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20404. push: 'fmtp',
  20405. reg: /^fmtp:(\d*) (\S*)/,
  20406. names: ['payload', 'config'],
  20407. format: "fmtp:%d %s"
  20408. },
  20409. { //a=control:streamid=0
  20410. name: 'control',
  20411. reg: /^control:(.*)/,
  20412. format: "control:%s"
  20413. },
  20414. { //a=rtcp:65179 IN IP4 193.84.77.194
  20415. name: 'rtcp',
  20416. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20417. names: ['port', 'netType', 'ipVer', 'address'],
  20418. format: function (o) {
  20419. return (o.address != null) ?
  20420. "rtcp:%d %s IP%d %s":
  20421. "rtcp:%d";
  20422. }
  20423. },
  20424. { //a=rtcp-fb:98 trr-int 100
  20425. push: 'rtcpFbTrrInt',
  20426. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20427. names: ['payload', 'value'],
  20428. format: "rtcp-fb:%d trr-int %d"
  20429. },
  20430. { //a=rtcp-fb:98 nack rpsi
  20431. push: 'rtcpFb',
  20432. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20433. names: ['payload', 'type', 'subtype'],
  20434. format: function (o) {
  20435. return (o.subtype != null) ?
  20436. "rtcp-fb:%s %s %s":
  20437. "rtcp-fb:%s %s";
  20438. }
  20439. },
  20440. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20441. //a=extmap:1/recvonly URI-gps-string
  20442. push: 'ext',
  20443. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20444. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20445. format: function (o) {
  20446. return (o.config != null) ?
  20447. "extmap:%s %s %s":
  20448. "extmap:%s %s";
  20449. }
  20450. },
  20451. {
  20452. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20453. push: 'crypto',
  20454. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20455. names: ['id', 'suite', 'config', 'sessionConfig'],
  20456. format: function (o) {
  20457. return (o.sessionConfig != null) ?
  20458. "crypto:%d %s %s %s":
  20459. "crypto:%d %s %s";
  20460. }
  20461. },
  20462. { //a=setup:actpass
  20463. name: 'setup',
  20464. reg: /^setup:(\w*)/,
  20465. format: "setup:%s"
  20466. },
  20467. { //a=mid:1
  20468. name: 'mid',
  20469. reg: /^mid:([^\s]*)/,
  20470. format: "mid:%s"
  20471. },
  20472. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20473. name: 'msid',
  20474. reg: /^msid:(.*)/,
  20475. format: "msid:%s"
  20476. },
  20477. { //a=ptime:20
  20478. name: 'ptime',
  20479. reg: /^ptime:(\d*)/,
  20480. format: "ptime:%d"
  20481. },
  20482. { //a=maxptime:60
  20483. name: 'maxptime',
  20484. reg: /^maxptime:(\d*)/,
  20485. format: "maxptime:%d"
  20486. },
  20487. { //a=sendrecv
  20488. name: 'direction',
  20489. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20490. },
  20491. { //a=ice-lite
  20492. name: 'icelite',
  20493. reg: /^(ice-lite)/
  20494. },
  20495. { //a=ice-ufrag:F7gI
  20496. name: 'iceUfrag',
  20497. reg: /^ice-ufrag:(\S*)/,
  20498. format: "ice-ufrag:%s"
  20499. },
  20500. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20501. name: 'icePwd',
  20502. reg: /^ice-pwd:(\S*)/,
  20503. format: "ice-pwd:%s"
  20504. },
  20505. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20506. name: 'fingerprint',
  20507. reg: /^fingerprint:(\S*) (\S*)/,
  20508. names: ['type', 'hash'],
  20509. format: "fingerprint:%s %s"
  20510. },
  20511. {
  20512. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20513. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20514. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20515. push:'candidates',
  20516. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  20517. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  20518. format: function (o) {
  20519. var str = "candidate:%s %d %s %d %s %d typ %s";
  20520. // NB: candidate has two optional chunks, so %void middle one if it's missing
  20521. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20522. if (o.generation != null) {
  20523. str += " generation %d";
  20524. }
  20525. return str;
  20526. }
  20527. },
  20528. { //a=end-of-candidates (keep after the candidates line for readability)
  20529. name: 'endOfCandidates',
  20530. reg: /^(end-of-candidates)/
  20531. },
  20532. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20533. name: 'remoteCandidates',
  20534. reg: /^remote-candidates:(.*)/,
  20535. format: "remote-candidates:%s"
  20536. },
  20537. { //a=ice-options:google-ice
  20538. name: 'iceOptions',
  20539. reg: /^ice-options:(\S*)/,
  20540. format: "ice-options:%s"
  20541. },
  20542. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20543. push: "ssrcs",
  20544. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20545. names: ['id', 'attribute', 'value'],
  20546. format: "ssrc:%d %s:%s"
  20547. },
  20548. { //a=ssrc-group:FEC 1 2
  20549. push: "ssrcGroups",
  20550. reg: /^ssrc-group:(\w*) (.*)/,
  20551. names: ['semantics', 'ssrcs'],
  20552. format: "ssrc-group:%s %s"
  20553. },
  20554. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20555. name: "msidSemantic",
  20556. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20557. names: ['semantic', 'token'],
  20558. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20559. },
  20560. { //a=group:BUNDLE audio video
  20561. push: 'groups',
  20562. reg: /^group:(\w*) (.*)/,
  20563. names: ['type', 'mids'],
  20564. format: "group:%s %s"
  20565. },
  20566. { //a=rtcp-mux
  20567. name: 'rtcpMux',
  20568. reg: /^(rtcp-mux)/
  20569. },
  20570. { //a=rtcp-rsize
  20571. name: 'rtcpRsize',
  20572. reg: /^(rtcp-rsize)/
  20573. },
  20574. { // any a= that we don't understand is kepts verbatim on media.invalid
  20575. push: 'invalid',
  20576. names: ["value"]
  20577. }
  20578. ]
  20579. };
  20580. // set sensible defaults to avoid polluting the grammar with boring details
  20581. Object.keys(grammar).forEach(function (key) {
  20582. var objs = grammar[key];
  20583. objs.forEach(function (obj) {
  20584. if (!obj.reg) {
  20585. obj.reg = /(.*)/;
  20586. }
  20587. if (!obj.format) {
  20588. obj.format = "%s";
  20589. }
  20590. });
  20591. });
  20592. },{}],72:[function(require,module,exports){
  20593. var parser = require('./parser');
  20594. var writer = require('./writer');
  20595. exports.write = writer;
  20596. exports.parse = parser.parse;
  20597. exports.parseFmtpConfig = parser.parseFmtpConfig;
  20598. exports.parsePayloads = parser.parsePayloads;
  20599. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  20600. },{"./parser":73,"./writer":74}],73:[function(require,module,exports){
  20601. var toIntIfInt = function (v) {
  20602. return String(Number(v)) === v ? Number(v) : v;
  20603. };
  20604. var attachProperties = function (match, location, names, rawName) {
  20605. if (rawName && !names) {
  20606. location[rawName] = toIntIfInt(match[1]);
  20607. }
  20608. else {
  20609. for (var i = 0; i < names.length; i += 1) {
  20610. if (match[i+1] != null) {
  20611. location[names[i]] = toIntIfInt(match[i+1]);
  20612. }
  20613. }
  20614. }
  20615. };
  20616. var parseReg = function (obj, location, content) {
  20617. var needsBlank = obj.name && obj.names;
  20618. if (obj.push && !location[obj.push]) {
  20619. location[obj.push] = [];
  20620. }
  20621. else if (needsBlank && !location[obj.name]) {
  20622. location[obj.name] = {};
  20623. }
  20624. var keyLocation = obj.push ?
  20625. {} : // blank object that will be pushed
  20626. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20627. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20628. if (obj.push) {
  20629. location[obj.push].push(keyLocation);
  20630. }
  20631. };
  20632. var grammar = require('./grammar');
  20633. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20634. exports.parse = function (sdp) {
  20635. var session = {}
  20636. , media = []
  20637. , location = session; // points at where properties go under (one of the above)
  20638. // parse lines we understand
  20639. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20640. var type = l[0];
  20641. var content = l.slice(2);
  20642. if (type === 'm') {
  20643. media.push({rtp: [], fmtp: []});
  20644. location = media[media.length-1]; // point at latest media line
  20645. }
  20646. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20647. var obj = grammar[type][j];
  20648. if (obj.reg.test(content)) {
  20649. return parseReg(obj, location, content);
  20650. }
  20651. }
  20652. });
  20653. session.media = media; // link it up
  20654. return session;
  20655. };
  20656. var fmtpReducer = function (acc, expr) {
  20657. var s = expr.split('=');
  20658. if (s.length === 2) {
  20659. acc[s[0]] = toIntIfInt(s[1]);
  20660. }
  20661. return acc;
  20662. };
  20663. exports.parseFmtpConfig = function (str) {
  20664. return str.split(';').reduce(fmtpReducer, {});
  20665. };
  20666. exports.parsePayloads = function (str) {
  20667. return str.split(' ').map(Number);
  20668. };
  20669. exports.parseRemoteCandidates = function (str) {
  20670. var candidates = [];
  20671. var parts = str.split(' ').map(toIntIfInt);
  20672. for (var i = 0; i < parts.length; i += 3) {
  20673. candidates.push({
  20674. component: parts[i],
  20675. ip: parts[i + 1],
  20676. port: parts[i + 2]
  20677. });
  20678. }
  20679. return candidates;
  20680. };
  20681. },{"./grammar":71}],74:[function(require,module,exports){
  20682. var grammar = require('./grammar');
  20683. // customized util.format - discards excess arguments and can void middle ones
  20684. var formatRegExp = /%[sdv%]/g;
  20685. var format = function (formatStr) {
  20686. var i = 1;
  20687. var args = arguments;
  20688. var len = args.length;
  20689. return formatStr.replace(formatRegExp, function (x) {
  20690. if (i >= len) {
  20691. return x; // missing argument
  20692. }
  20693. var arg = args[i];
  20694. i += 1;
  20695. switch (x) {
  20696. case '%%':
  20697. return '%';
  20698. case '%s':
  20699. return String(arg);
  20700. case '%d':
  20701. return Number(arg);
  20702. case '%v':
  20703. return '';
  20704. }
  20705. });
  20706. // NB: we discard excess arguments - they are typically undefined from makeLine
  20707. };
  20708. var makeLine = function (type, obj, location) {
  20709. var str = obj.format instanceof Function ?
  20710. (obj.format(obj.push ? location : location[obj.name])) :
  20711. obj.format;
  20712. var args = [type + '=' + str];
  20713. if (obj.names) {
  20714. for (var i = 0; i < obj.names.length; i += 1) {
  20715. var n = obj.names[i];
  20716. if (obj.name) {
  20717. args.push(location[obj.name][n]);
  20718. }
  20719. else { // for mLine and push attributes
  20720. args.push(location[obj.names[i]]);
  20721. }
  20722. }
  20723. }
  20724. else {
  20725. args.push(location[obj.name]);
  20726. }
  20727. return format.apply(null, args);
  20728. };
  20729. // RFC specified order
  20730. // TODO: extend this with all the rest
  20731. var defaultOuterOrder = [
  20732. 'v', 'o', 's', 'i',
  20733. 'u', 'e', 'p', 'c',
  20734. 'b', 't', 'r', 'z', 'a'
  20735. ];
  20736. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  20737. module.exports = function (session, opts) {
  20738. opts = opts || {};
  20739. // ensure certain properties exist
  20740. if (session.version == null) {
  20741. session.version = 0; // "v=0" must be there (only defined version atm)
  20742. }
  20743. if (session.name == null) {
  20744. session.name = " "; // "s= " must be there if no meaningful name set
  20745. }
  20746. session.media.forEach(function (mLine) {
  20747. if (mLine.payloads == null) {
  20748. mLine.payloads = "";
  20749. }
  20750. });
  20751. var outerOrder = opts.outerOrder || defaultOuterOrder;
  20752. var innerOrder = opts.innerOrder || defaultInnerOrder;
  20753. var sdp = [];
  20754. // loop through outerOrder for matching properties on session
  20755. outerOrder.forEach(function (type) {
  20756. grammar[type].forEach(function (obj) {
  20757. if (obj.name in session && session[obj.name] != null) {
  20758. sdp.push(makeLine(type, obj, session));
  20759. }
  20760. else if (obj.push in session && session[obj.push] != null) {
  20761. session[obj.push].forEach(function (el) {
  20762. sdp.push(makeLine(type, obj, el));
  20763. });
  20764. }
  20765. });
  20766. });
  20767. // then for each media line, follow the innerOrder
  20768. session.media.forEach(function (mLine) {
  20769. sdp.push(makeLine('m', grammar.m[0], mLine));
  20770. innerOrder.forEach(function (type) {
  20771. grammar[type].forEach(function (obj) {
  20772. if (obj.name in mLine && mLine[obj.name] != null) {
  20773. sdp.push(makeLine(type, obj, mLine));
  20774. }
  20775. else if (obj.push in mLine && mLine[obj.push] != null) {
  20776. mLine[obj.push].forEach(function (el) {
  20777. sdp.push(makeLine(type, obj, el));
  20778. });
  20779. }
  20780. });
  20781. });
  20782. });
  20783. return sdp.join('\r\n') + '\r\n';
  20784. };
  20785. },{"./grammar":71}],75:[function(require,module,exports){
  20786. var grammar = module.exports = {
  20787. v: [{
  20788. name: 'version',
  20789. reg: /^(\d*)$/
  20790. }],
  20791. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20792. // NB: sessionId will be a String in most cases because it is huge
  20793. name: 'origin',
  20794. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20795. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20796. format: "%s %s %d %s IP%d %s"
  20797. }],
  20798. // default parsing of these only (though some of these feel outdated)
  20799. s: [{ name: 'name' }],
  20800. i: [{ name: 'description' }],
  20801. u: [{ name: 'uri' }],
  20802. e: [{ name: 'email' }],
  20803. p: [{ name: 'phone' }],
  20804. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20805. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20806. //k: [{}], // outdated thing ignored
  20807. t: [{ //t=0 0
  20808. name: 'timing',
  20809. reg: /^(\d*) (\d*)/,
  20810. names: ['start', 'stop'],
  20811. format: "%d %d"
  20812. }],
  20813. c: [{ //c=IN IP4 10.47.197.26
  20814. name: 'connection',
  20815. reg: /^IN IP(\d) (\S*)/,
  20816. names: ['version', 'ip'],
  20817. format: "IN IP%d %s"
  20818. }],
  20819. b: [{ //b=AS:4000
  20820. push: 'bandwidth',
  20821. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20822. names: ['type', 'limit'],
  20823. format: "%s:%s"
  20824. }],
  20825. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20826. // NB: special - pushes to session
  20827. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20828. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20829. names: ['type', 'port', 'protocol', 'payloads'],
  20830. format: "%s %d %s %s"
  20831. }],
  20832. a: [
  20833. { //a=rtpmap:110 opus/48000/2
  20834. push: 'rtp',
  20835. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  20836. names: ['payload', 'codec', 'rate', 'encoding'],
  20837. format: function (o) {
  20838. return (o.encoding) ?
  20839. "rtpmap:%d %s/%s/%s":
  20840. "rtpmap:%d %s/%s";
  20841. }
  20842. },
  20843. {
  20844. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20845. //a=fmtp:111 minptime=10; useinbandfec=1
  20846. push: 'fmtp',
  20847. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20848. names: ['payload', 'config'],
  20849. format: "fmtp:%d %s"
  20850. },
  20851. { //a=control:streamid=0
  20852. name: 'control',
  20853. reg: /^control:(.*)/,
  20854. format: "control:%s"
  20855. },
  20856. { //a=rtcp:65179 IN IP4 193.84.77.194
  20857. name: 'rtcp',
  20858. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20859. names: ['port', 'netType', 'ipVer', 'address'],
  20860. format: function (o) {
  20861. return (o.address != null) ?
  20862. "rtcp:%d %s IP%d %s":
  20863. "rtcp:%d";
  20864. }
  20865. },
  20866. { //a=rtcp-fb:98 trr-int 100
  20867. push: 'rtcpFbTrrInt',
  20868. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20869. names: ['payload', 'value'],
  20870. format: "rtcp-fb:%d trr-int %d"
  20871. },
  20872. { //a=rtcp-fb:98 nack rpsi
  20873. push: 'rtcpFb',
  20874. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20875. names: ['payload', 'type', 'subtype'],
  20876. format: function (o) {
  20877. return (o.subtype != null) ?
  20878. "rtcp-fb:%s %s %s":
  20879. "rtcp-fb:%s %s";
  20880. }
  20881. },
  20882. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20883. //a=extmap:1/recvonly URI-gps-string
  20884. push: 'ext',
  20885. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20886. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20887. format: function (o) {
  20888. return (o.config != null) ?
  20889. "extmap:%s %s %s":
  20890. "extmap:%s %s";
  20891. }
  20892. },
  20893. {
  20894. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20895. push: 'crypto',
  20896. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20897. names: ['id', 'suite', 'config', 'sessionConfig'],
  20898. format: function (o) {
  20899. return (o.sessionConfig != null) ?
  20900. "crypto:%d %s %s %s":
  20901. "crypto:%d %s %s";
  20902. }
  20903. },
  20904. { //a=setup:actpass
  20905. name: 'setup',
  20906. reg: /^setup:(\w*)/,
  20907. format: "setup:%s"
  20908. },
  20909. { //a=mid:1
  20910. name: 'mid',
  20911. reg: /^mid:([^\s]*)/,
  20912. format: "mid:%s"
  20913. },
  20914. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20915. name: 'msid',
  20916. reg: /^msid:(.*)/,
  20917. format: "msid:%s"
  20918. },
  20919. { //a=ptime:20
  20920. name: 'ptime',
  20921. reg: /^ptime:(\d*)/,
  20922. format: "ptime:%d"
  20923. },
  20924. { //a=maxptime:60
  20925. name: 'maxptime',
  20926. reg: /^maxptime:(\d*)/,
  20927. format: "maxptime:%d"
  20928. },
  20929. { //a=sendrecv
  20930. name: 'direction',
  20931. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20932. },
  20933. { //a=ice-lite
  20934. name: 'icelite',
  20935. reg: /^(ice-lite)/
  20936. },
  20937. { //a=ice-ufrag:F7gI
  20938. name: 'iceUfrag',
  20939. reg: /^ice-ufrag:(\S*)/,
  20940. format: "ice-ufrag:%s"
  20941. },
  20942. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20943. name: 'icePwd',
  20944. reg: /^ice-pwd:(\S*)/,
  20945. format: "ice-pwd:%s"
  20946. },
  20947. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20948. name: 'fingerprint',
  20949. reg: /^fingerprint:(\S*) (\S*)/,
  20950. names: ['type', 'hash'],
  20951. format: "fingerprint:%s %s"
  20952. },
  20953. {
  20954. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20955. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20956. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20957. push:'candidates',
  20958. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  20959. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  20960. format: function (o) {
  20961. var str = "candidate:%s %d %s %d %s %d typ %s";
  20962. // NB: candidate has two optional chunks, so %void middle one if it's missing
  20963. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20964. if (o.generation != null) {
  20965. str += " generation %d";
  20966. }
  20967. return str;
  20968. }
  20969. },
  20970. { //a=end-of-candidates (keep after the candidates line for readability)
  20971. name: 'endOfCandidates',
  20972. reg: /^(end-of-candidates)/
  20973. },
  20974. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20975. name: 'remoteCandidates',
  20976. reg: /^remote-candidates:(.*)/,
  20977. format: "remote-candidates:%s"
  20978. },
  20979. { //a=ice-options:google-ice
  20980. name: 'iceOptions',
  20981. reg: /^ice-options:(\S*)/,
  20982. format: "ice-options:%s"
  20983. },
  20984. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20985. push: "ssrcs",
  20986. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20987. names: ['id', 'attribute', 'value'],
  20988. format: "ssrc:%d %s:%s"
  20989. },
  20990. { //a=ssrc-group:FEC 1 2
  20991. push: "ssrcGroups",
  20992. reg: /^ssrc-group:(\w*) (.*)/,
  20993. names: ['semantics', 'ssrcs'],
  20994. format: "ssrc-group:%s %s"
  20995. },
  20996. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20997. name: "msidSemantic",
  20998. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20999. names: ['semantic', 'token'],
  21000. format: "msid-semantic: %s %s" // space after ":" is not accidental
  21001. },
  21002. { //a=group:BUNDLE audio video
  21003. push: 'groups',
  21004. reg: /^group:(\w*) (.*)/,
  21005. names: ['type', 'mids'],
  21006. format: "group:%s %s"
  21007. },
  21008. { //a=rtcp-mux
  21009. name: 'rtcpMux',
  21010. reg: /^(rtcp-mux)/
  21011. },
  21012. { //a=rtcp-rsize
  21013. name: 'rtcpRsize',
  21014. reg: /^(rtcp-rsize)/
  21015. },
  21016. { // any a= that we don't understand is kepts verbatim on media.invalid
  21017. push: 'invalid',
  21018. names: ["value"]
  21019. }
  21020. ]
  21021. };
  21022. // set sensible defaults to avoid polluting the grammar with boring details
  21023. Object.keys(grammar).forEach(function (key) {
  21024. var objs = grammar[key];
  21025. objs.forEach(function (obj) {
  21026. if (!obj.reg) {
  21027. obj.reg = /(.*)/;
  21028. }
  21029. if (!obj.format) {
  21030. obj.format = "%s";
  21031. }
  21032. });
  21033. });
  21034. },{}],76:[function(require,module,exports){
  21035. arguments[4][72][0].apply(exports,arguments)
  21036. },{"./parser":77,"./writer":78,"dup":72}],77:[function(require,module,exports){
  21037. var toIntIfInt = function (v) {
  21038. return String(Number(v)) === v ? Number(v) : v;
  21039. };
  21040. var attachProperties = function (match, location, names, rawName) {
  21041. if (rawName && !names) {
  21042. location[rawName] = toIntIfInt(match[1]);
  21043. }
  21044. else {
  21045. for (var i = 0; i < names.length; i += 1) {
  21046. if (match[i+1] != null) {
  21047. location[names[i]] = toIntIfInt(match[i+1]);
  21048. }
  21049. }
  21050. }
  21051. };
  21052. var parseReg = function (obj, location, content) {
  21053. var needsBlank = obj.name && obj.names;
  21054. if (obj.push && !location[obj.push]) {
  21055. location[obj.push] = [];
  21056. }
  21057. else if (needsBlank && !location[obj.name]) {
  21058. location[obj.name] = {};
  21059. }
  21060. var keyLocation = obj.push ?
  21061. {} : // blank object that will be pushed
  21062. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  21063. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  21064. if (obj.push) {
  21065. location[obj.push].push(keyLocation);
  21066. }
  21067. };
  21068. var grammar = require('./grammar');
  21069. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  21070. exports.parse = function (sdp) {
  21071. var session = {}
  21072. , media = []
  21073. , location = session; // points at where properties go under (one of the above)
  21074. // parse lines we understand
  21075. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  21076. var type = l[0];
  21077. var content = l.slice(2);
  21078. if (type === 'm') {
  21079. media.push({rtp: [], fmtp: []});
  21080. location = media[media.length-1]; // point at latest media line
  21081. }
  21082. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  21083. var obj = grammar[type][j];
  21084. if (obj.reg.test(content)) {
  21085. return parseReg(obj, location, content);
  21086. }
  21087. }
  21088. });
  21089. session.media = media; // link it up
  21090. return session;
  21091. };
  21092. var fmtpReducer = function (acc, expr) {
  21093. var s = expr.split('=');
  21094. if (s.length === 2) {
  21095. acc[s[0]] = toIntIfInt(s[1]);
  21096. }
  21097. return acc;
  21098. };
  21099. exports.parseFmtpConfig = function (str) {
  21100. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  21101. };
  21102. exports.parsePayloads = function (str) {
  21103. return str.split(' ').map(Number);
  21104. };
  21105. exports.parseRemoteCandidates = function (str) {
  21106. var candidates = [];
  21107. var parts = str.split(' ').map(toIntIfInt);
  21108. for (var i = 0; i < parts.length; i += 3) {
  21109. candidates.push({
  21110. component: parts[i],
  21111. ip: parts[i + 1],
  21112. port: parts[i + 2]
  21113. });
  21114. }
  21115. return candidates;
  21116. };
  21117. },{"./grammar":75}],78:[function(require,module,exports){
  21118. arguments[4][74][0].apply(exports,arguments)
  21119. },{"./grammar":75,"dup":74}],79:[function(require,module,exports){
  21120. var MediaStreamType = {
  21121. VIDEO_TYPE: "Video",
  21122. AUDIO_TYPE: "Audio"
  21123. };
  21124. module.exports = MediaStreamType;
  21125. },{}],80:[function(require,module,exports){
  21126. var RTCEvents = {
  21127. RTC_READY: "rtc.ready",
  21128. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  21129. LASTN_CHANGED: "rtc.lastn_changed",
  21130. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  21131. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  21132. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  21133. };
  21134. module.exports = RTCEvents;
  21135. },{}],81:[function(require,module,exports){
  21136. var Resolutions = {
  21137. "1080": {
  21138. width: 1920,
  21139. height: 1080,
  21140. order: 7
  21141. },
  21142. "fullhd": {
  21143. width: 1920,
  21144. height: 1080,
  21145. order: 7
  21146. },
  21147. "720": {
  21148. width: 1280,
  21149. height: 720,
  21150. order: 6
  21151. },
  21152. "hd": {
  21153. width: 1280,
  21154. height: 720,
  21155. order: 6
  21156. },
  21157. "960": {
  21158. width: 960,
  21159. height: 720,
  21160. order: 5
  21161. },
  21162. "640": {
  21163. width: 640,
  21164. height: 480,
  21165. order: 4
  21166. },
  21167. "vga": {
  21168. width: 640,
  21169. height: 480,
  21170. order: 4
  21171. },
  21172. "360": {
  21173. width: 640,
  21174. height: 360,
  21175. order: 3
  21176. },
  21177. "320": {
  21178. width: 320,
  21179. height: 240,
  21180. order: 2
  21181. },
  21182. "180": {
  21183. width: 320,
  21184. height: 180,
  21185. order: 1
  21186. }
  21187. };
  21188. module.exports = Resolutions;
  21189. },{}],82:[function(require,module,exports){
  21190. var XMPPEvents = {
  21191. // Designates an event indicating that the connection to the XMPP server
  21192. // failed.
  21193. CONNECTION_FAILED: "xmpp.connection.failed",
  21194. // Designates an event indicating that the media (ICE) connection was
  21195. // interrupted. This should go to the RTC module.
  21196. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  21197. // Designates an event indicating that the media (ICE) connection was
  21198. // restored. This should go to the RTC module.
  21199. CONNECTION_RESTORED: "xmpp.connection.restored",
  21200. // Designates an event indicating that an offer (e.g. Jingle
  21201. // session-initiate) was received.
  21202. CALL_INCOMING: "xmpp.callincoming.jingle",
  21203. // Designates an event indicating that we were kicked from the XMPP MUC.
  21204. KICKED: "xmpp.kicked",
  21205. // Designates an event indicating that the userID for a specific JID has
  21206. // changed.
  21207. // Note: currently this event fires every time we receive presence from
  21208. // someone (regardless of whether or not the "userID" changed).
  21209. USER_ID_CHANGED: "xmpp.user_id_changed",
  21210. // Designates an event indicating that we have joined the XMPP MUC.
  21211. MUC_JOINED: "xmpp.muc_joined",
  21212. // Designates an event indicating that a participant joined the XMPP MUC.
  21213. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  21214. // Designates an event indicating that a participant left the XMPP MUC.
  21215. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  21216. // Designates an event indicating that the MUC role of a participant has
  21217. // changed.
  21218. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  21219. // Designates an event indicating that the XMPP MUC was destroyed.
  21220. MUC_DESTROYED: "xmpp.muc_destroyed",
  21221. // Designates an event indicating that the display name of a participant
  21222. // has changed.
  21223. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  21224. // Designates an event indicating that we received statistics from a
  21225. // participant in the MUC.
  21226. REMOTE_STATS: "xmpp.remote_stats",
  21227. // Designates an event indicating that our role in the XMPP MUC has changed.
  21228. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  21229. // Designates an event indicating that the subject of the XMPP MUC has
  21230. // changed.
  21231. SUBJECT_CHANGED: "xmpp.subject_changed",
  21232. // Designates an event indicating that an XMPP message in the MUC was
  21233. // received.
  21234. MESSAGE_RECEIVED: "xmpp.message_received",
  21235. // Designates an event indicating that we sent an XMPP message to the MUC.
  21236. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  21237. // Designates an event indicating that the video type (e.g. 'camera' or
  21238. // 'screen') for a participant has changed.
  21239. // Note: currently this event fires every time we receive presence from
  21240. // someone (regardless of whether or not the "video type" changed).
  21241. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  21242. // Designates an event indicating that a participant in the XMPP MUC has
  21243. // advertised that they have audio muted (or unmuted).
  21244. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  21245. // Designates an event indicating that a participant in the XMPP MUC has
  21246. // advertised that they have video muted (or unmuted).
  21247. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  21248. // Designates an event indicating that the focus has asked us to mute our
  21249. // audio.
  21250. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  21251. // Designates an event indicating that we should join the conference with
  21252. // audio and/or video muted.
  21253. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  21254. // Designates an event indicating that a remote participant's available
  21255. // devices (whether he supports a audio and/or video) changed.
  21256. // Note: currently this event fires every time we receive presence from
  21257. // someone (regardless of whether or not the devices changed).
  21258. DEVICE_AVAILABLE: "xmpp.device_available",
  21259. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  21260. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  21261. PASSWORD_REQUIRED: "xmpp.password_required",
  21262. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  21263. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  21264. ETHERPAD: "xmpp.etherpad",
  21265. BRIDGE_DOWN: "xmpp.bridge_down",
  21266. PRESENCE_STATUS: "xmpp.presence_status",
  21267. RESERVATION_ERROR: "xmpp.room_reservation_error",
  21268. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  21269. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  21270. // TODO: only used in a hack, should probably be removed.
  21271. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  21272. // TODO: only used in a hack, should probably be removed.
  21273. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  21274. // TODO: only used in a hack, should probably be removed.
  21275. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  21276. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  21277. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  21278. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  21279. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  21280. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  21281. // xmpp is connected and obtained user media
  21282. READY_TO_JOIN: 'xmpp.ready_to_join',
  21283. FOCUS_LEFT: "xmpp.focus_left",
  21284. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  21285. /**
  21286. * Indicates that recording state changed.
  21287. */
  21288. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  21289. /**
  21290. * Indicates that phone number changed.
  21291. */
  21292. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  21293. };
  21294. module.exports = XMPPEvents;
  21295. },{}],83:[function(require,module,exports){
  21296. var AuthenticationEvents = {
  21297. /**
  21298. * Event callback arguments:
  21299. * function(authenticationEnabled, userIdentity)
  21300. * authenticationEnabled - indicates whether authentication has been enabled
  21301. * in this session
  21302. * userIdentity - if user has been logged in then it contains user name. If
  21303. * contains 'null' or 'undefined' then user is not logged in.
  21304. */
  21305. IDENTITY_UPDATED: "authentication.identity_updated"
  21306. };
  21307. module.exports = AuthenticationEvents;
  21308. },{}],84:[function(require,module,exports){
  21309. var DesktopSharingEventTypes = {
  21310. /**
  21311. * An event which indicates that the jidesha extension for Firefox is
  21312. * needed to proceed with screen sharing, and that it is not installed.
  21313. */
  21314. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  21315. };
  21316. module.exports = DesktopSharingEventTypes;
  21317. },{}],85:[function(require,module,exports){
  21318. module.exports = {
  21319. /**
  21320. * An event carrying connection statistics.
  21321. */
  21322. CONNECTION_STATS: "statistics.connectionstats",
  21323. /**
  21324. * FIXME: needs documentation.
  21325. */
  21326. AUDIO_LEVEL: "statistics.audioLevel",
  21327. /**
  21328. * FIXME: needs documentation.
  21329. */
  21330. STOP: "statistics.stop"
  21331. };
  21332. },{}],86:[function(require,module,exports){
  21333. var Constants = {
  21334. LOCAL_JID: 'local'
  21335. };
  21336. module.exports = Constants;
  21337. },{}],87:[function(require,module,exports){
  21338. arguments[4][82][0].apply(exports,arguments)
  21339. },{"dup":82}]},{},[7])(7)
  21340. });