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

lib-jitsi-meet.js 722KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var RTC = require("./modules/RTC/RTC");
  5. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  6. var StreamEventTypes = require("./service/RTC/StreamEventTypes");
  7. var RTCEvents = require("./service/RTC/RTCEvents");
  8. var EventEmitter = require("events");
  9. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  10. var JitsiParticipant = require("./JitsiParticipant");
  11. var Statistics = require("./modules/statistics/statistics");
  12. /**
  13. * Creates a JitsiConference object with the given name and properties.
  14. * Note: this constructor is not a part of the public API (objects should be
  15. * created using JitsiConnection.createConference).
  16. * @param options.config properties / settings related to the conference that will be created.
  17. * @param options.name the name of the conference
  18. * @param options.connection the JitsiConnection object for this JitsiConference.
  19. * @constructor
  20. */
  21. function JitsiConference(options) {
  22. if(!options.name || options.name.toLowerCase() !== options.name) {
  23. logger.error("Invalid conference name (no conference name passed or it"
  24. + "contains invalid characters like capital letters)!");
  25. return;
  26. }
  27. this.options = options;
  28. this.connection = this.options.connection;
  29. this.xmpp = this.connection.xmpp;
  30. this.eventEmitter = new EventEmitter();
  31. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  32. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  33. this.rtc = new RTC(this.room, options);
  34. if(!options.config.disableAudioLevels)
  35. this.statistics = new Statistics();
  36. setupListeners(this);
  37. this.participants = {};
  38. this.lastActiveSpeaker = null;
  39. }
  40. /**
  41. * Joins the conference.
  42. * @param password {string} the password
  43. */
  44. JitsiConference.prototype.join = function (password) {
  45. if(this.room)
  46. this.room.join(password, this.connection.tokenPassword);
  47. }
  48. /**
  49. * Leaves the conference.
  50. */
  51. JitsiConference.prototype.leave = function () {
  52. if(this.xmpp)
  53. this.xmpp.leaveRoom(this.room.roomjid);
  54. this.room = null;
  55. }
  56. /**
  57. * Returns the local tracks.
  58. */
  59. JitsiConference.prototype.getLocalTracks = function () {
  60. if(this.rtc)
  61. return this.rtc.localStreams;
  62. };
  63. /**
  64. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  65. * in JitsiConferenceEvents.
  66. * @param eventId the event ID.
  67. * @param handler handler for the event.
  68. *
  69. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  70. */
  71. JitsiConference.prototype.on = function (eventId, handler) {
  72. if(this.eventEmitter)
  73. this.eventEmitter.on(eventId, handler);
  74. }
  75. /**
  76. * Removes event listener
  77. * @param eventId the event ID.
  78. * @param [handler] optional, the specific handler to unbind
  79. *
  80. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  81. */
  82. JitsiConference.prototype.off = function (eventId, handler) {
  83. if(this.eventEmitter)
  84. this.eventEmitter.removeListener(eventId, listener);
  85. }
  86. // Common aliases for event emitter
  87. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  88. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  89. /**
  90. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  91. * @param command {String} the name of the command
  92. * @param handler {Function} handler for the command
  93. */
  94. JitsiConference.prototype.addCommandListener = function (command, handler) {
  95. if(this.room)
  96. this.room.addPresenceListener(command, handler);
  97. }
  98. /**
  99. * Removes command listener
  100. * @param command {String} the name of the command
  101. */
  102. JitsiConference.prototype.removeCommandListener = function (command) {
  103. if(this.room)
  104. this.room.removePresenceListener(command);
  105. }
  106. /**
  107. * Sends text message to the other participants in the conference
  108. * @param message the text message.
  109. */
  110. JitsiConference.prototype.sendTextMessage = function (message) {
  111. if(this.room)
  112. this.room.sendMessage(message);
  113. }
  114. /**
  115. * Send presence command.
  116. * @param name the name of the command.
  117. * @param values Object with keys and values that will be send.
  118. **/
  119. JitsiConference.prototype.sendCommand = function (name, values) {
  120. if(this.room) {
  121. this.room.addToPresence(name, values);
  122. this.room.sendPresence();
  123. }
  124. }
  125. /**
  126. * Send presence command one time.
  127. * @param name the name of the command.
  128. * @param values Object with keys and values that will be send.
  129. **/
  130. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  131. this.sendCommand(name, values);
  132. this.removeCommand(name);
  133. }
  134. /**
  135. * Send presence command.
  136. * @param name the name of the command.
  137. * @param values Object with keys and values that will be send.
  138. * @param persistent if false the command will be sent only one time
  139. **/
  140. JitsiConference.prototype.removeCommand = function (name) {
  141. if(this.room)
  142. this.room.removeFromPresence(name);
  143. }
  144. /**
  145. * Sets the display name for this conference.
  146. * @param name the display name to set
  147. */
  148. JitsiConference.prototype.setDisplayName = function(name) {
  149. if(this.room){
  150. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  151. this.room.sendPresence();
  152. }
  153. }
  154. /**
  155. * Adds JitsiLocalTrack object to the conference.
  156. * @param track the JitsiLocalTrack object.
  157. */
  158. JitsiConference.prototype.addTrack = function (track) {
  159. this.rtc.addLocalStream(track);
  160. this.room.addStream(track.getOriginalStream, function () {});
  161. }
  162. /**
  163. * Removes JitsiLocalTrack object to the conference.
  164. * @param track the JitsiLocalTrack object.
  165. */
  166. JitsiConference.prototype.removeTrack = function (track) {
  167. this.room.removeStream(track.getOriginalStream());
  168. this.rtc.removeLocalStream(track);
  169. }
  170. /**
  171. * Elects the participant with the given id to be the selected participant or the speaker.
  172. * @param id the identifier of the participant
  173. */
  174. JitsiConference.prototype.selectParticipant = function(participantId) {
  175. if (this.rtc) {
  176. this.rtc.selectedEndpoint(participantId);
  177. }
  178. }
  179. /**
  180. *
  181. * @param id the identifier of the participant
  182. */
  183. JitsiConference.prototype.pinParticipant = function(participantId) {
  184. if(this.rtc)
  185. this.rtc.pinEndpoint(participantId);
  186. }
  187. /**
  188. * Returns the list of participants for this conference.
  189. * @return Object a list of participant identifiers containing all conference participants.
  190. */
  191. JitsiConference.prototype.getParticipants = function() {
  192. return this.participants;
  193. }
  194. /**
  195. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  196. * null if there isn't one).
  197. * @param id the id of the participant.
  198. */
  199. JitsiConference.prototype.getParticipantById = function(id) {
  200. if(this.participants)
  201. return this.participants[id];
  202. return null;
  203. }
  204. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  205. if(this.eventEmitter)
  206. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, Strophe.getResourceFromJid(jid));
  207. // this.participants[jid] = new JitsiParticipant();
  208. }
  209. /**
  210. * Returns the local user's ID
  211. * @return {string} local user's ID
  212. */
  213. JitsiConference.prototype.myUserId = function () {
  214. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  215. }
  216. /**
  217. * Setups the listeners needed for the conference.
  218. * @param conference the conference
  219. */
  220. function setupListeners(conference) {
  221. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  222. conference.rtc.onIncommingCall(event);
  223. if(conference.statistics)
  224. conference.statistics.startRemoteStats(event.peerconnection);
  225. });
  226. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  227. conference.rtc.createRemoteStream.bind(conference.rtc));
  228. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  229. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  230. });
  231. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, function (stream) {
  232. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  233. });
  234. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  235. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  236. });
  237. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  238. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  239. });
  240. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  241. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  242. });
  243. // FIXME
  244. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  245. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  246. // });
  247. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  248. if(conference.lastActiveSpeaker !== id && conference.room
  249. && conference.myUserId() !== id) {
  250. conference.lastActiveSpeaker = id;
  251. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  252. }
  253. });
  254. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  255. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  256. });
  257. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  258. function (lastNEndpoints, endpointsEnteringLastN) {
  259. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  260. lastNEndpoints, endpointsEnteringLastN);
  261. });
  262. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  263. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT,function (jid) {
  264. conference.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, Strophe.getResourceFromJid(jid));
  265. });
  266. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (from, displayName) {
  267. conference.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  268. Strophe.getResourceFromJid(from), displayName);
  269. });
  270. if(conference.statistics) {
  271. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  272. var userId = null;
  273. if (ssrc === Statistics.LOCAL_JID) {
  274. userId = conference.myUserId();
  275. } else {
  276. var jid = conference.room.getJidBySSRC(ssrc);
  277. if (!jid)
  278. return;
  279. userId = Strophe.getResourceFromJid(jid);
  280. }
  281. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  282. userId, level);
  283. });
  284. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_CREATED, function (stream) {
  285. conference.statistics.startLocalStats(stream);
  286. });
  287. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  288. function () {
  289. conference.statistics.dispose();
  290. });
  291. RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  292. conference.room.updateDeviceAvailability(devices);
  293. });
  294. RTC.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  295. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  296. });
  297. }
  298. }
  299. module.exports = JitsiConference;
  300. }).call(this,"/JitsiConference.js")
  301. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/RTC/RTC":13,"./modules/statistics/statistics":21,"./service/RTC/RTCEvents":76,"./service/RTC/StreamEventTypes":78,"./service/xmpp/XMPPEvents":82,"events":40,"jitsi-meet-logger":44}],2:[function(require,module,exports){
  302. /**
  303. * Enumeration with the errors for the conference.
  304. * @type {{string: string}}
  305. */
  306. var JitsiConferenceErrors = {
  307. /**
  308. * Indicates that a password is required in order to join the conference.
  309. */
  310. PASSWORD_REQUIRED: "conference.passwordRequired",
  311. /**
  312. * Indicates that a connection error occurred when trying to join a conference.
  313. */
  314. CONNECTION_ERROR: "conference.connectionError",
  315. /**
  316. * Indicates that there is no available videobridge.
  317. */
  318. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  319. /**
  320. * Many more errors TBD here.
  321. */
  322. };
  323. module.exports = JitsiConferenceErrors;
  324. },{}],3:[function(require,module,exports){
  325. /**
  326. * Enumeration with the events for the conference.
  327. * @type {{string: string}}
  328. */
  329. var JitsiConferenceEvents = {
  330. /**
  331. * A new media track was added to the conference.
  332. */
  333. TRACK_ADDED: "conference.trackAdded",
  334. /**
  335. * The media track was removed to the conference.
  336. */
  337. TRACK_REMOVED: "conference.trackRemoved",
  338. /**
  339. * The active speaker was changed.
  340. */
  341. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  342. /**
  343. * A new user joinned the conference.
  344. */
  345. USER_JOINED: "conference.userJoined",
  346. /**
  347. * A user has left the conference.
  348. */
  349. USER_LEFT: "conference.userLeft",
  350. /**
  351. * New text message was received.
  352. */
  353. MESSAGE_RECEIVED: "conference.messageReceived",
  354. /**
  355. * A user has changed it display name
  356. */
  357. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  358. /**
  359. * A participant avatar has changed.
  360. */
  361. AVATAR_CHANGED: "conference.avatarChanged",
  362. /**
  363. * New connection statistics are received.
  364. */
  365. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  366. /**
  367. * The Last N set is changed.
  368. */
  369. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  370. /**
  371. * You are included / excluded in somebody's last N set
  372. */
  373. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  374. /**
  375. * A media track mute status was changed.
  376. */
  377. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  378. /**
  379. * Audio levels of a media track was changed.
  380. */
  381. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  382. /**
  383. * Indicates that the connection to the conference has been interrupted for some reason.
  384. */
  385. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  386. /**
  387. * Indicates that the connection to the conference has been restored.
  388. */
  389. CONNECTION_RESTORED: "conference.connecionRestored",
  390. /**
  391. * Indicates that conference has been joined.
  392. */
  393. CONFERENCE_JOINED: "conference.joined",
  394. /**
  395. * Indicates that conference has been left.
  396. */
  397. CONFERENCE_LEFT: "conference.left"
  398. };
  399. module.exports = JitsiConferenceEvents;
  400. },{}],4:[function(require,module,exports){
  401. var JitsiConference = require("./JitsiConference");
  402. var XMPP = require("./modules/xmpp/xmpp");
  403. var RandomUtil = require("./modules/util/RandomUtil");
  404. /**
  405. * Utility method that generates user name based on random hex values.
  406. * Eg. 12345678-1234-1234-12345678
  407. * @returns {string}
  408. */
  409. function generateUserName() {
  410. return RandomUtil.random8digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" +
  411. RandomUtil.random4digitsHex() + "-" + RandomUtil.random8digitsHex();
  412. }
  413. /**
  414. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  415. * JitsiConference interface.
  416. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  417. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  418. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  419. * The format is:
  420. * passwordToken = token + "_" + roomName + "_" + ts
  421. * See doc/tokens.md for more info on how tokens are generated.
  422. * @param options Object with properties / settings related to connection with the server.
  423. * @constructor
  424. */
  425. function JitsiConnection(appID, tokenPassword, options) {
  426. this.appID = appID;
  427. this.tokenPassword = tokenPassword;
  428. this.options = options;
  429. this.xmpp = new XMPP(options);
  430. this.conferences = {};
  431. }
  432. /**
  433. * Connect the client with the server.
  434. * @param options {object} connecting options (for example authentications parameters).
  435. */
  436. JitsiConnection.prototype.connect = function (options) {
  437. if(!options)
  438. options = {};
  439. // If we have token provided use it as a password and generate random username
  440. if (this.tokenPassword) {
  441. options.password = this.tokenPassword;
  442. if (!options.id) {
  443. options.id = generateUserName() + "@" + this.options.hosts.domain;
  444. }
  445. }
  446. this.xmpp.connect(options.id, options.password);
  447. }
  448. /**
  449. * Disconnect the client from the server.
  450. */
  451. JitsiConnection.prototype.disconnect = function () {
  452. this.xmpp.disconnect();
  453. }
  454. /**
  455. * This method allows renewal of the tokens if they are expiring.
  456. * @param token the new token.
  457. */
  458. JitsiConnection.prototype.setToken = function (token) {
  459. this.token = token;
  460. }
  461. /**
  462. * Creates and joins new conference.
  463. * @param name the name of the conference; if null - a generated name will be provided from the api
  464. * @param options Object with properties / settings related to the conference that will be created.
  465. * @returns {JitsiConference} returns the new conference object.
  466. */
  467. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  468. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  469. return this.conferences[name];
  470. }
  471. /**
  472. * Subscribes the passed listener to the event.
  473. * @param event {JitsiConnectionEvents} the connection event.
  474. * @param listener {Function} the function that will receive the event
  475. */
  476. JitsiConnection.prototype.addEventListener = function (event, listener) {
  477. this.xmpp.addListener(event, listener);
  478. }
  479. /**
  480. * Unsubscribes the passed handler.
  481. * @param event {JitsiConnectionEvents} the connection event.
  482. * @param listener {Function} the function that will receive the event
  483. */
  484. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  485. this.xmpp.removeListener(event, listener);
  486. }
  487. module.exports = JitsiConnection;
  488. },{"./JitsiConference":1,"./modules/util/RandomUtil":22,"./modules/xmpp/xmpp":38}],5:[function(require,module,exports){
  489. /**
  490. * Enumeration with the errors for the connection.
  491. * @type {{string: string}}
  492. */
  493. var JitsiConnectionErrors = {
  494. /**
  495. * Indicates that a password is required in order to join the conference.
  496. */
  497. PASSWORD_REQUIRED: "connection.passwordRequired",
  498. /**
  499. * Indicates that a connection error occurred when trying to join a conference.
  500. */
  501. CONNECTION_ERROR: "connection.connectionError",
  502. /**
  503. * Not specified errors.
  504. */
  505. OTHER_ERROR: "connection.otherError"
  506. };
  507. module.exports = JitsiConnectionErrors;
  508. },{}],6:[function(require,module,exports){
  509. /**
  510. * Enumeration with the events for the connection.
  511. * @type {{string: string}}
  512. */
  513. var JitsiConnnectionEvents = {
  514. /**
  515. * Indicates that the connection has been failed for some reason.
  516. */
  517. CONNECTION_FAILED: "connection.connecionFailed",
  518. /**
  519. * Indicates that the connection has been established.
  520. */
  521. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  522. /**
  523. * Indicates that the connection has been disconnected.
  524. */
  525. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  526. /**
  527. * Indicates that the perfomed action cannot be executed because the
  528. * connection is not in the correct state(connected, disconnected, etc.)
  529. */
  530. WRONG_STATE: "connection.wrongState"
  531. };
  532. module.exports = JitsiConnnectionEvents;
  533. },{}],7:[function(require,module,exports){
  534. var JitsiConnection = require("./JitsiConnection");
  535. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  536. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  537. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  538. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  539. var Logger = require("jitsi-meet-logger");
  540. var RTC = require("./modules/RTC/RTC");
  541. /**
  542. * Namespace for the interface of Jitsi Meet Library.
  543. */
  544. var LibJitsiMeet = {
  545. JitsiConnection: JitsiConnection,
  546. events: {
  547. conference: JitsiConferenceEvents,
  548. connection: JitsiConnectionEvents
  549. },
  550. errors: {
  551. conference: JitsiConferenceErrors,
  552. connection: JitsiConnectionErrors
  553. },
  554. logLevels: Logger.levels,
  555. init: function (options) {
  556. RTC.init(options || {});
  557. },
  558. setLogLevel: function (level) {
  559. Logger.setLogLevel(level);
  560. },
  561. /**
  562. * Creates the media tracks and returns them trough the callback.
  563. * @param options Object with properties / settings specifying the tracks which should be created.
  564. * should be created or some additional configurations about resolution for example.
  565. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  566. * or a JitsiConferenceError if rejected.
  567. */
  568. createLocalTracks: function (options) {
  569. return RTC.obtainAudioAndVideoPermissions(options || {});
  570. }
  571. };
  572. //Setups the promise object.
  573. window.Promise = window.Promise || require("es6-promise").polyfill();
  574. module.exports = LibJitsiMeet;
  575. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":13,"es6-promise":42,"jitsi-meet-logger":44}],8:[function(require,module,exports){
  576. /**
  577. * Represents a participant in (a member of) a conference.
  578. */
  579. function JitsiParticipant(id, conference, displayName){
  580. this._id = id;
  581. this._conference = conference;
  582. this._displayName = displayName;
  583. }
  584. /**
  585. * @returns {JitsiConference} The conference that this participant belongs to.
  586. */
  587. JitsiParticipant.prototype.getConference = function() {
  588. return this._conference;
  589. }
  590. /**
  591. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  592. */
  593. JitsiParticipant.prototype.getTracks = function() {
  594. }
  595. /**
  596. * @returns {String} The ID (i.e. JID) of this participant.
  597. */
  598. JitsiParticipant.prototype.getId = function() {
  599. return this._id;
  600. }
  601. /**
  602. * @returns {String} The human-readable display name of this participant.
  603. */
  604. JitsiParticipant.prototype.getDisplayName = function() {
  605. return this._displayName;
  606. }
  607. /**
  608. * @returns {Boolean} Whether this participant is a moderator or not.
  609. */
  610. JitsiParticipant.prototype.isModerator = function() {
  611. }
  612. // Gets a link to an etherpad instance advertised by the participant?
  613. //JitsiParticipant.prototype.getEtherpad = function() {
  614. //
  615. //}
  616. /*
  617. * @returns {Boolean} Whether this participant has muted their audio.
  618. */
  619. JitsiParticipant.prototype.isAudioMuted = function() {
  620. }
  621. /*
  622. * @returns {Boolean} Whether this participant has muted their video.
  623. */
  624. JitsiParticipant.prototype.isVideoMuted = function() {
  625. }
  626. /*
  627. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  628. * TODO: do we expose this or handle it internally?
  629. */
  630. JitsiParticipant.prototype.getLatestStats = function() {
  631. }
  632. /**
  633. * @returns {String} The role of this participant.
  634. */
  635. JitsiParticipant.prototype.getRole = function() {
  636. }
  637. /*
  638. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  639. */
  640. JitsiParticipant.prototype.isFocus = function() {
  641. }
  642. /*
  643. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  644. */
  645. JitsiParticipant.prototype.isRecorder = function() {
  646. }
  647. /*
  648. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  649. */
  650. JitsiParticipant.prototype.isSipGateway = function() {
  651. }
  652. /**
  653. * @returns {String} The ID for this participant's avatar.
  654. */
  655. JitsiParticipant.prototype.getAvatarId = function() {
  656. }
  657. /**
  658. * @returns {Boolean} Whether this participant is currently sharing their screen.
  659. */
  660. JitsiParticipant.prototype.isScreenSharing = function() {
  661. }
  662. /**
  663. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  664. */
  665. JitsiParticipant.prototype.getUserAgent = function() {
  666. }
  667. /**
  668. * Kicks the participant from the conference (requires certain privileges).
  669. */
  670. JitsiParticipant.prototype.kick = function() {
  671. }
  672. /**
  673. * Asks this participant to mute themselves.
  674. */
  675. JitsiParticipant.prototype.askToMute = function() {
  676. }
  677. module.exports = JitsiParticipant();
  678. },{}],9:[function(require,module,exports){
  679. (function (__filename){
  680. /* global config, APP, Strophe */
  681. // cache datachannels to avoid garbage collection
  682. // https://code.google.com/p/chromium/issues/detail?id=405545
  683. var logger = require("jitsi-meet-logger").getLogger(__filename);
  684. var RTCEvents = require("../../service/RTC/RTCEvents");
  685. /**
  686. * Binds "ondatachannel" event listener to given PeerConnection instance.
  687. * @param peerConnection WebRTC peer connection instance.
  688. */
  689. function DataChannels(peerConnection, emitter) {
  690. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  691. this.eventEmitter = emitter;
  692. this._dataChannels = [];
  693. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  694. // Although it's not a requirement to open separate channels from both bridge
  695. // and peer as single channel can be used for sending and receiving data.
  696. // So either channel opened by the bridge or the one opened here is enough
  697. // for communication with the bridge.
  698. /*var dataChannelOptions =
  699. {
  700. reliable: true
  701. };
  702. var dataChannel
  703. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  704. // Can be used only when is in open state
  705. dataChannel.onopen = function ()
  706. {
  707. dataChannel.send("My channel !!!");
  708. };
  709. dataChannel.onmessage = function (event)
  710. {
  711. var msgData = event.data;
  712. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  713. };*/
  714. };
  715. /**
  716. * Callback triggered by PeerConnection when new data channel is opened
  717. * on the bridge.
  718. * @param event the event info object.
  719. */
  720. DataChannels.prototype.onDataChannel = function (event) {
  721. var dataChannel = event.channel;
  722. var self = this;
  723. dataChannel.onopen = function () {
  724. logger.info("Data channel opened by the Videobridge!", dataChannel);
  725. // Code sample for sending string and/or binary data
  726. // Sends String message to the bridge
  727. //dataChannel.send("Hello bridge!");
  728. // Sends 12 bytes binary message to the bridge
  729. //dataChannel.send(new ArrayBuffer(12));
  730. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  731. };
  732. dataChannel.onerror = function (error) {
  733. logger.error("Data Channel Error:", error, dataChannel);
  734. };
  735. dataChannel.onmessage = function (event) {
  736. var data = event.data;
  737. // JSON
  738. var obj;
  739. try {
  740. obj = JSON.parse(data);
  741. }
  742. catch (e) {
  743. logger.error(
  744. "Failed to parse data channel message as JSON: ",
  745. data,
  746. dataChannel);
  747. }
  748. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  749. var colibriClass = obj.colibriClass;
  750. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  751. // Endpoint ID from the Videobridge.
  752. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  753. logger.info(
  754. "Data channel new dominant speaker event: ",
  755. dominantSpeakerEndpoint);
  756. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  757. }
  758. else if ("InLastNChangeEvent" === colibriClass) {
  759. var oldValue = obj.oldValue;
  760. var newValue = obj.newValue;
  761. // Make sure that oldValue and newValue are of type boolean.
  762. var type;
  763. if ((type = typeof oldValue) !== 'boolean') {
  764. if (type === 'string') {
  765. oldValue = (oldValue == "true");
  766. } else {
  767. oldValue = new Boolean(oldValue).valueOf();
  768. }
  769. }
  770. if ((type = typeof newValue) !== 'boolean') {
  771. if (type === 'string') {
  772. newValue = (newValue == "true");
  773. } else {
  774. newValue = new Boolean(newValue).valueOf();
  775. }
  776. }
  777. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  778. }
  779. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  780. // The new/latest list of last-n endpoint IDs.
  781. var lastNEndpoints = obj.lastNEndpoints;
  782. // The list of endpoint IDs which are entering the list of
  783. // last-n at this time i.e. were not in the old list of last-n
  784. // endpoint IDs.
  785. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  786. logger.log(
  787. "Data channel new last-n event: ",
  788. lastNEndpoints, endpointsEnteringLastN, obj);
  789. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  790. lastNEndpoints, endpointsEnteringLastN, obj);
  791. }
  792. else {
  793. logger.debug("Data channel JSON-formatted message: ", obj);
  794. }
  795. }
  796. };
  797. dataChannel.onclose = function () {
  798. logger.info("The Data Channel closed", dataChannel);
  799. var idx = self._dataChannels.indexOf(dataChannel);
  800. if (idx > -1)
  801. self._dataChannels = self._dataChannels.splice(idx, 1);
  802. };
  803. this._dataChannels.push(dataChannel);
  804. };
  805. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  806. logger.log('selected endpoint changed: ', userResource);
  807. if (this._dataChannels && this._dataChannels.length != 0) {
  808. this._dataChannels.some(function (dataChannel) {
  809. if (dataChannel.readyState == 'open') {
  810. logger.log('sending selected endpoint changed ' +
  811. 'notification to the bridge: ', userResource);
  812. dataChannel.send(JSON.stringify({
  813. 'colibriClass': 'SelectedEndpointChangedEvent',
  814. 'selectedEndpoint':
  815. (!userResource || userResource === null)?
  816. null : userResource
  817. }));
  818. return true;
  819. }
  820. });
  821. }
  822. }
  823. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  824. logger.log('pinned endpoint changed: ', userResource);
  825. if (this._dataChannels && this._dataChannels.length != 0) {
  826. this._dataChannels.some(function (dataChannel) {
  827. if (dataChannel.readyState == 'open') {
  828. dataChannel.send(JSON.stringify({
  829. 'colibriClass': 'PinnedEndpointChangedEvent',
  830. 'pinnedEndpoint':
  831. (!userResource || userResource == null)?
  832. null : userResource
  833. }));
  834. return true;
  835. }
  836. });
  837. }
  838. }
  839. module.exports = DataChannels;
  840. }).call(this,"/modules/RTC/DataChannels.js")
  841. },{"../../service/RTC/RTCEvents":76,"jitsi-meet-logger":44}],10:[function(require,module,exports){
  842. var JitsiTrack = require("./JitsiTrack");
  843. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  844. var RTCBrowserType = require("./RTCBrowserType");
  845. /**
  846. * Represents a single media track (either audio or video).
  847. * @constructor
  848. */
  849. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType,
  850. resolution)
  851. {
  852. JitsiTrack.call(this, RTC, stream);
  853. this.eventEmitter = eventEmitter;
  854. this.videoType = videoType;
  855. this.dontFireRemoveEvent = false;
  856. this.resolution = resolution;
  857. var self = this;
  858. this.stream.onended = function () {
  859. if(!self.dontFireRemoveEvent)
  860. self.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  861. self.dontFireRemoveEvent = false;
  862. };
  863. }
  864. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  865. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  866. /**
  867. * Mutes / unmutes the track.
  868. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  869. */
  870. JitsiLocalTrack.prototype._setMute = function (mute) {
  871. if(!this.rtc) {
  872. console.error("Mute is not supported for streams not attached to conference!");
  873. return;
  874. }
  875. var isAudio = this.type === JitsiTrack.AUDIO;
  876. this.dontFireRemoveEvent = false;
  877. if ((window.location.protocol != "https:") ||
  878. (isAudio) || this.videoType === "screen" ||
  879. // FIXME FF does not support 'removeStream' method used to mute
  880. RTCBrowserType.isFirefox()) {
  881. var tracks = this._getTracks();
  882. for (var idx = 0; idx < tracks.length; idx++) {
  883. tracks[idx].enabled = !mute;
  884. }
  885. if(isAudio)
  886. this.rtc.room.setAudioMute(mute);
  887. else
  888. this.rtc.room.setVideoMute(mute);
  889. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  890. } else {
  891. if (mute) {
  892. this.dontFireRemoveEvent = true;
  893. this.rtc.room.removeStream(this.stream);
  894. this.stream.stop();
  895. if(isAudio)
  896. this.rtc.room.setAudioMute(mute);
  897. else
  898. this.rtc.room.setVideoMute(mute);
  899. this.stream = null;
  900. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  901. //FIXME: Maybe here we should set the SRC for the containers to something
  902. } else {
  903. var self = this;
  904. var RTC = require("./RTCUtils");
  905. RTC.obtainAudioAndVideoPermissions(
  906. (isAudio ? ["audio"] : ["video"]),
  907. self.resolution, true)
  908. .then(function (streams) {
  909. var stream = null;
  910. for(var i = 0; i < streams.length; i++) {
  911. stream = streams[i];
  912. if(stream.type === self.type) {
  913. self.stream = stream.stream;
  914. self.videoType = stream.videoType;
  915. break;
  916. }
  917. }
  918. if(!stream)
  919. return;
  920. for(var i = 0; i < self.containers.length; i++)
  921. {
  922. RTC.attachMediaStream(self.containers[i], self.stream);
  923. }
  924. self.rtc.room.addStream(stream.stream,
  925. function () {
  926. if(isAudio)
  927. self.rtc.room.setAudioMute(mute);
  928. else
  929. self.rtc.room.setVideoMute(mute);
  930. self.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  931. });
  932. });
  933. }
  934. }
  935. }
  936. /**
  937. * Stops sending the media track. And removes it from the HTML.
  938. * NOTE: Works for local tracks only.
  939. */
  940. JitsiLocalTrack.prototype.stop = function () {
  941. if(!this.stream)
  942. return;
  943. if(this.rtc)
  944. this.rtc.room.removeStream(this.stream);
  945. this.stream.stop();
  946. this.detach();
  947. }
  948. /**
  949. * Returns <tt>true</tt> - if the stream is muted
  950. * and <tt>false</tt> otherwise.
  951. * @returns {boolean} <tt>true</tt> - if the stream is muted
  952. * and <tt>false</tt> otherwise.
  953. */
  954. JitsiLocalTrack.prototype.isMuted = function () {
  955. if (!this.stream)
  956. return true;
  957. var tracks = [];
  958. var isAudio = this.type === JitsiTrack.AUDIO;
  959. if (isAudio) {
  960. tracks = this.stream.getAudioTracks();
  961. } else {
  962. if (this.stream.ended)
  963. return true;
  964. tracks = this.stream.getVideoTracks();
  965. }
  966. for (var idx = 0; idx < tracks.length; idx++) {
  967. if(tracks[idx].enabled)
  968. return false;
  969. }
  970. return true;
  971. };
  972. /**
  973. * Private method. Updates rtc property of the track.
  974. * @param rtc the rtc instance.
  975. */
  976. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  977. this.rtc = rtc;
  978. };
  979. module.exports = JitsiLocalTrack;
  980. },{"../../service/RTC/StreamEventTypes":78,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils":15}],11:[function(require,module,exports){
  981. var JitsiTrack = require("./JitsiTrack");
  982. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  983. /**
  984. * Represents a single media track (either audio or video).
  985. * @param RTC the rtc instance.
  986. * @param data object with the stream and some details about it(participant id, video type, etc.)
  987. * @param sid sid for the Media Stream
  988. * @param ssrc ssrc for the Media Stream
  989. * @param eventEmitter the event emitter
  990. * @constructor
  991. */
  992. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  993. JitsiTrack.call(this, RTC, data.stream);
  994. this.rtc = RTC;
  995. this.sid = sid;
  996. this.stream = data.stream;
  997. this.peerjid = data.peerjid;
  998. this.videoType = data.videoType;
  999. this.ssrc = ssrc;
  1000. this.muted = false;
  1001. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1002. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1003. this.muted = true
  1004. }
  1005. this.eventEmitter = eventEmitter;
  1006. var self = this;
  1007. if(this.stream)
  1008. this.stream.onended = function () {
  1009. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  1010. }
  1011. }
  1012. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1013. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1014. /**
  1015. * Sets current muted status and fires an events for the change.
  1016. * @param value the muted status.
  1017. */
  1018. JitsiRemoteTrack.prototype.setMute = function (value) {
  1019. this.stream.muted = value;
  1020. this.muted = value;
  1021. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1022. };
  1023. /**
  1024. * Returns the current muted status of the track.
  1025. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1026. */
  1027. JitsiRemoteTrack.prototype.isMuted = function () {
  1028. return this.muted;
  1029. }
  1030. /**
  1031. * Returns the participant id which owns the track.
  1032. * @returns {string} the id of the participants.
  1033. */
  1034. JitsiRemoteTrack.prototype.getParitcipantId = function() {
  1035. return Strophe.getResourceFromJid(this.peerjid);
  1036. };
  1037. delete JitsiRemoteTrack.prototype.stop;
  1038. delete JitsiRemoteTrack.prototype.start;
  1039. module.exports = JitsiRemoteTrack;
  1040. },{"../../service/RTC/StreamEventTypes":78,"./JitsiTrack":12}],12:[function(require,module,exports){
  1041. var RTCBrowserType = require("./RTCBrowserType");
  1042. /**
  1043. * This implements 'onended' callback normally fired by WebRTC after the stream
  1044. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1045. * @param stream original WebRTC stream object to which 'onended' handling
  1046. * will be added.
  1047. */
  1048. function implementOnEndedHandling(stream) {
  1049. var originalStop = stream.stop;
  1050. stream.stop = function () {
  1051. originalStop.apply(stream);
  1052. if (!stream.ended) {
  1053. stream.ended = true;
  1054. stream.onended();
  1055. }
  1056. };
  1057. }
  1058. /**
  1059. * Represents a single media track (either audio or video).
  1060. * @constructor
  1061. */
  1062. function JitsiTrack(rtc, stream)
  1063. {
  1064. /**
  1065. * Array with the HTML elements that are displaying the streams.
  1066. * @type {Array}
  1067. */
  1068. this.containers = [];
  1069. this.rtc = rtc;
  1070. this.stream = stream;
  1071. this.type = (this.stream.getVideoTracks().length > 0)?
  1072. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1073. if(this.type == "audio") {
  1074. this._getTracks = function () {
  1075. return this.stream.getAudioTracks();
  1076. }.bind(this);
  1077. } else {
  1078. this._getTracks = function () {
  1079. return this.stream.getVideoTracks();
  1080. }.bind(this);
  1081. }
  1082. if (RTCBrowserType.isFirefox() && this.stream) {
  1083. implementOnEndedHandling(this.stream);
  1084. }
  1085. }
  1086. /**
  1087. * JitsiTrack video type.
  1088. * @type {string}
  1089. */
  1090. JitsiTrack.VIDEO = "video";
  1091. /**
  1092. * JitsiTrack audio type.
  1093. * @type {string}
  1094. */
  1095. JitsiTrack.AUDIO = "audio";
  1096. /**
  1097. * Returns the type (audio or video) of this track.
  1098. */
  1099. JitsiTrack.prototype.getType = function() {
  1100. return this.type;
  1101. };
  1102. /**
  1103. * Returns the RTCMediaStream from the browser (?).
  1104. */
  1105. JitsiTrack.prototype.getOriginalStream = function() {
  1106. return this.stream;
  1107. }
  1108. /**
  1109. * Mutes the track.
  1110. */
  1111. JitsiTrack.prototype.mute = function () {
  1112. this._setMute(true);
  1113. }
  1114. /**
  1115. * Unmutes the stream.
  1116. */
  1117. JitsiTrack.prototype.unmute = function () {
  1118. this._setMute(false);
  1119. }
  1120. /**
  1121. * Attaches the MediaStream of this track to an HTML container (?).
  1122. * Adds the container to the list of containers that are displaying the track.
  1123. * @param container the HTML container
  1124. */
  1125. JitsiTrack.prototype.attach = function (container) {
  1126. if(this.stream)
  1127. require("./RTCUtils").attachMediaStream(container, this.stream);
  1128. this.containers.push(container);
  1129. }
  1130. /**
  1131. * Removes the track from the passed HTML container.
  1132. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1133. */
  1134. JitsiTrack.prototype.detach = function (container) {
  1135. for(var i = 0; i < this.containers.length; i++)
  1136. {
  1137. if(this.containers[i].is(container))
  1138. {
  1139. this.containers.splice(i,1);
  1140. }
  1141. if(!container)
  1142. {
  1143. this.containers[i].find(">video").remove();
  1144. }
  1145. }
  1146. if(container)
  1147. $(container).find(">video").remove();
  1148. }
  1149. /**
  1150. * Stops sending the media track. And removes it from the HTML.
  1151. * NOTE: Works for local tracks only.
  1152. */
  1153. JitsiTrack.prototype.stop = function () {
  1154. }
  1155. /**
  1156. * Returns true if this is a video track and the source of the video is a
  1157. * screen capture as opposed to a camera.
  1158. */
  1159. JitsiTrack.prototype.isScreenSharing = function(){
  1160. }
  1161. /**
  1162. * Returns id of the track.
  1163. * @returns {string} id of the track or null if this is fake track.
  1164. */
  1165. JitsiTrack.prototype.getId = function () {
  1166. var tracks = this.stream.getTracks();
  1167. if(!tracks || tracks.length === 0)
  1168. return null;
  1169. return tracks[0].id;
  1170. };
  1171. module.exports = JitsiTrack;
  1172. },{"./RTCBrowserType":14,"./RTCUtils":15}],13:[function(require,module,exports){
  1173. /* global APP */
  1174. var EventEmitter = require("events");
  1175. var RTCBrowserType = require("./RTCBrowserType");
  1176. var RTCUtils = require("./RTCUtils.js");
  1177. var JitsiTrack = require("./JitsiTrack");
  1178. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1179. var DataChannels = require("./DataChannels");
  1180. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1181. var DesktopSharingEventTypes
  1182. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1183. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1184. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1185. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1186. var desktopsharing = require("../desktopsharing/desktopsharing");
  1187. function RTC(room, options) {
  1188. this.room = room;
  1189. this.localStreams = [];
  1190. this.remoteStreams = {};
  1191. this.localAudio = null;
  1192. this.localVideo = null;
  1193. this.eventEmitter = new EventEmitter();
  1194. var self = this;
  1195. this.options = options || {};
  1196. desktopsharing.addListener(
  1197. function (stream, isUsingScreenStream, callback) {
  1198. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1199. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1200. room.addPresenceListener("videomuted", function (values, from) {
  1201. if(self.remoteStreams[from])
  1202. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1203. });
  1204. room.addPresenceListener("audiomuted", function (values, from) {
  1205. if(self.remoteStreams[from])
  1206. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1207. });
  1208. }
  1209. /**
  1210. * Creates the local MediaStreams.
  1211. * @param options object for options (NOTE: currently only list of devices and resolution are supported)
  1212. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1213. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1214. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1215. * @returns {*} Promise object that will receive the new JitsiTracks
  1216. */
  1217. RTC.obtainAudioAndVideoPermissions = function (options, dontCreateJitsiTrack) {
  1218. return RTCUtils.obtainAudioAndVideoPermissions(
  1219. options.devices, options.resolution, dontCreateJitsiTrack);
  1220. }
  1221. RTC.prototype.onIncommingCall = function(event) {
  1222. if(this.options.config.openSctp)
  1223. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1224. for(var i = 0; i < this.localStreams.length; i++)
  1225. if(this.localStreams[i])
  1226. {
  1227. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1228. }
  1229. }
  1230. RTC.prototype.selectedEndpoint = function (id) {
  1231. if(this.dataChannels)
  1232. this.dataChannels.handleSelectedEndpointEvent(id);
  1233. }
  1234. RTC.prototype.pinEndpoint = function (id) {
  1235. if(this.dataChannels)
  1236. this.dataChannels.handlePinnedEndpointEvent(id);
  1237. }
  1238. RTC.prototype.addListener = function (type, listener) {
  1239. this.eventEmitter.on(type, listener);
  1240. };
  1241. RTC.prototype.removeListener = function (eventType, listener) {
  1242. this.eventEmitter.removeListener(eventType, listener);
  1243. };
  1244. RTC.addListener = function (eventType, listener) {
  1245. RTCUtils.addListener(eventType, listener);
  1246. }
  1247. RTC.removeListener = function (eventType, listener) {
  1248. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1249. RTCUtils.removeListener(eventType, listener)
  1250. }
  1251. RTC.isRTCReady = function () {
  1252. return RTCUtils.isRTCReady();
  1253. }
  1254. RTC.init = function (options) {
  1255. RTCUtils.init(options || {});
  1256. }
  1257. RTC.getDeviceAvailability = function () {
  1258. return RTCUtils.getDeviceAvailability();
  1259. }
  1260. RTC.prototype.addLocalStream = function (stream) {
  1261. this.localStreams.push(stream);
  1262. stream._setRTC(this);
  1263. if (stream.type == "audio") {
  1264. this.localAudio = stream;
  1265. } else {
  1266. this.localVideo = stream;
  1267. }
  1268. };
  1269. RTC.prototype.removeLocalStream = function (stream) {
  1270. for(var i = 0; i < this.localStreams.length; i++) {
  1271. if(this.localStreams[i].getOriginalStream() === stream) {
  1272. delete this.localStreams[i];
  1273. return;
  1274. }
  1275. }
  1276. };
  1277. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1278. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1279. this.eventEmitter);
  1280. if(!data.peerjid)
  1281. return;
  1282. var jid = data.peerjid;
  1283. if(!this.remoteStreams[jid]) {
  1284. this.remoteStreams[jid] = {};
  1285. }
  1286. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1287. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1288. return remoteStream;
  1289. };
  1290. RTC.getPCConstraints = function () {
  1291. return RTCUtils.pc_constraints;
  1292. };
  1293. RTC.getUserMediaWithConstraints = function(um, success_callback,
  1294. failure_callback, resolution,
  1295. bandwidth, fps, desktopStream)
  1296. {
  1297. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  1298. failure_callback, resolution, bandwidth, fps, desktopStream);
  1299. };
  1300. RTC.attachMediaStream = function (elSelector, stream) {
  1301. RTCUtils.attachMediaStream(elSelector, stream);
  1302. };
  1303. RTC.getStreamID = function (stream) {
  1304. return RTCUtils.getStreamID(stream);
  1305. };
  1306. RTC.getVideoSrc = function (element) {
  1307. return RTCUtils.getVideoSrc(element);
  1308. };
  1309. RTC.setVideoSrc = function (element, src) {
  1310. RTCUtils.setVideoSrc(element, src);
  1311. };
  1312. RTC.prototype.getVideoElementName = function () {
  1313. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1314. };
  1315. RTC.prototype.dispose = function() {
  1316. };
  1317. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1318. var stream;
  1319. if(this.remoteStreams[jid] &&
  1320. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1321. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1322. }
  1323. if(!stream)
  1324. return true;
  1325. if (value != stream.muted) {
  1326. stream.setMute(value);
  1327. return true;
  1328. }
  1329. return false;
  1330. };
  1331. RTC.prototype.switchVideoStreams = function (new_stream) {
  1332. this.localVideo.stream = new_stream;
  1333. this.localStreams = [];
  1334. //in firefox we have only one stream object
  1335. if (this.localAudio.getOriginalStream() != new_stream)
  1336. this.localStreams.push(this.localAudio);
  1337. this.localStreams.push(this.localVideo);
  1338. };
  1339. /**
  1340. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local video.
  1341. * The method also handles the sdp changes.
  1342. * @param stream the new MediaStream received by the browser.
  1343. * @param isUsingScreenStream <tt>true</tt> if the stream is for desktop stream.
  1344. * @param callback - function that will be called after the operation is completed.
  1345. */
  1346. RTC.prototype.changeLocalVideo = function (stream, isUsingScreenStream, callback) {
  1347. var oldStream = this.localVideo.getOriginalStream();
  1348. var type = (isUsingScreenStream ? "screen" : "camera");
  1349. var localCallback = callback;
  1350. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1351. localCallback = function() {
  1352. this.room.setVideoMute(false, function(mute) {
  1353. this.eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1354. }.bind(this));
  1355. callback();
  1356. };
  1357. }
  1358. // FIXME: Workaround for FF/IE/Safari
  1359. if (stream && stream.videoStream) {
  1360. stream = stream.videoStream;
  1361. }
  1362. var videoStream = RTCUtils.createStream(stream, true);
  1363. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1364. // Stop the stream to trigger onended event for old stream
  1365. oldStream.stop();
  1366. this.switchVideoStreams(videoStream, oldStream);
  1367. this.room.switchStreams(videoStream, oldStream,localCallback);
  1368. };
  1369. /**
  1370. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local audio.
  1371. * The method also handles the sdp changes.
  1372. * @param stream the new MediaStream received by the browser.
  1373. * @param callback - function that will be called after the operation is completed.
  1374. */
  1375. RTC.prototype.changeLocalAudio = function (stream, callback) {
  1376. var oldStream = this.localAudio.getOriginalStream();
  1377. var newStream = RTCUtils.createStream(stream);
  1378. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1379. // Stop the stream to trigger onended event for old stream
  1380. oldStream.stop();
  1381. this.room.switchStreams(newStream, oldStream, callback, true);
  1382. };
  1383. RTC.prototype.isVideoMuted = function (jid) {
  1384. if (jid === APP.xmpp.myJid()) {
  1385. var localVideo = APP.RTC.localVideo;
  1386. return (!localVideo || localVideo.isMuted());
  1387. } else {
  1388. if (!this.remoteStreams[jid] ||
  1389. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1390. return null;
  1391. }
  1392. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1393. }
  1394. };
  1395. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1396. if (!this.localVideo)
  1397. return;
  1398. if (mute == this.localVideo.isMuted())
  1399. {
  1400. APP.xmpp.sendVideoInfoPresence(mute);
  1401. if (callback)
  1402. callback(mute);
  1403. }
  1404. else
  1405. {
  1406. this.localVideo.setMute(mute);
  1407. this.room.setVideoMute(
  1408. mute,
  1409. callback,
  1410. options);
  1411. }
  1412. };
  1413. module.exports = RTC;
  1414. },{"../../service/RTC/MediaStreamTypes":75,"../../service/RTC/RTCEvents.js":76,"../../service/RTC/StreamEventTypes.js":78,"../../service/desktopsharing/DesktopSharingEventTypes":80,"../desktopsharing/desktopsharing":17,"./DataChannels":9,"./JitsiLocalTrack.js":10,"./JitsiRemoteTrack.js":11,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils.js":15,"events":40}],14:[function(require,module,exports){
  1415. var currentBrowser;
  1416. var browserVersion;
  1417. var isAndroid;
  1418. var RTCBrowserType = {
  1419. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1420. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1421. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1422. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1423. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1424. getBrowserType: function () {
  1425. return currentBrowser;
  1426. },
  1427. isChrome: function () {
  1428. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1429. },
  1430. isOpera: function () {
  1431. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1432. },
  1433. isFirefox: function () {
  1434. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1435. },
  1436. isIExplorer: function () {
  1437. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1438. },
  1439. isSafari: function () {
  1440. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1441. },
  1442. isTemasysPluginUsed: function () {
  1443. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1444. },
  1445. getFirefoxVersion: function () {
  1446. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1447. },
  1448. getChromeVersion: function () {
  1449. return RTCBrowserType.isChrome() ? browserVersion : null;
  1450. },
  1451. usesPlanB: function() {
  1452. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1453. RTCBrowserType.isTemasysPluginUsed();
  1454. },
  1455. usesUnifiedPlan: function() {
  1456. return RTCBrowserType.isFirefox();
  1457. },
  1458. /**
  1459. * Whether the browser is running on an android device.
  1460. */
  1461. isAndroid: function() {
  1462. return isAndroid;
  1463. }
  1464. // Add version getters for other browsers when needed
  1465. };
  1466. // detectOpera() must be called before detectChrome() !!!
  1467. // otherwise Opera wil be detected as Chrome
  1468. function detectChrome() {
  1469. if (navigator.webkitGetUserMedia) {
  1470. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1471. var userAgent = navigator.userAgent.toLowerCase();
  1472. // We can assume that user agent is chrome, because it's
  1473. // enforced when 'ext' streaming method is set
  1474. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1475. console.log("This appears to be Chrome, ver: " + ver);
  1476. return ver;
  1477. }
  1478. return null;
  1479. }
  1480. function detectOpera() {
  1481. var userAgent = navigator.userAgent;
  1482. if (userAgent.match(/Opera|OPR/)) {
  1483. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1484. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1485. console.info("This appears to be Opera, ver: " + version);
  1486. return version;
  1487. }
  1488. return null;
  1489. }
  1490. function detectFirefox() {
  1491. if (navigator.mozGetUserMedia) {
  1492. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1493. var version = parseInt(
  1494. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1495. console.log('This appears to be Firefox, ver: ' + version);
  1496. return version;
  1497. }
  1498. return null;
  1499. }
  1500. function detectSafari() {
  1501. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1502. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1503. console.info("This appears to be Safari");
  1504. // FIXME detect Safari version when needed
  1505. return 1;
  1506. }
  1507. return null;
  1508. }
  1509. function detectIE() {
  1510. var version;
  1511. var ua = window.navigator.userAgent;
  1512. var msie = ua.indexOf('MSIE ');
  1513. if (msie > 0) {
  1514. // IE 10 or older => return version number
  1515. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1516. }
  1517. var trident = ua.indexOf('Trident/');
  1518. if (!version && trident > 0) {
  1519. // IE 11 => return version number
  1520. var rv = ua.indexOf('rv:');
  1521. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1522. }
  1523. var edge = ua.indexOf('Edge/');
  1524. if (!version && edge > 0) {
  1525. // IE 12 => return version number
  1526. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1527. }
  1528. if (version) {
  1529. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1530. console.info("This appears to be IExplorer, ver: " + version);
  1531. }
  1532. return version;
  1533. }
  1534. function detectBrowser() {
  1535. var version;
  1536. var detectors = [
  1537. detectOpera,
  1538. detectChrome,
  1539. detectFirefox,
  1540. detectIE,
  1541. detectSafari
  1542. ];
  1543. // Try all browser detectors
  1544. for (var i = 0; i < detectors.length; i++) {
  1545. version = detectors[i]();
  1546. if (version)
  1547. return version;
  1548. }
  1549. console.error("Failed to detect browser type");
  1550. return undefined;
  1551. }
  1552. browserVersion = detectBrowser();
  1553. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1554. module.exports = RTCBrowserType;
  1555. },{}],15:[function(require,module,exports){
  1556. (function (__filename){
  1557. /* global config, require, attachMediaStream, getUserMedia */
  1558. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1559. var RTCBrowserType = require("./RTCBrowserType");
  1560. var Resolutions = require("../../service/RTC/Resolutions");
  1561. var RTCEvents = require("../../service/RTC/RTCEvents");
  1562. var AdapterJS = require("./adapter.screenshare");
  1563. var SDPUtil = require("../xmpp/SDPUtil");
  1564. var EventEmitter = require("events");
  1565. var JitsiLocalTrack = require("./JitsiLocalTrack");
  1566. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1567. var eventEmitter = new EventEmitter();
  1568. var devices = {
  1569. audio: true,
  1570. video: true
  1571. };
  1572. var rtcReady = false;
  1573. function DummyMediaStream(id) {
  1574. this.id = id;
  1575. this.label = id;
  1576. this.stop = function() { };
  1577. this.getAudioTracks = function() { return []; };
  1578. this.getVideoTracks = function() { return []; };
  1579. }
  1580. function getPreviousResolution(resolution) {
  1581. if(!Resolutions[resolution])
  1582. return null;
  1583. var order = Resolutions[resolution].order;
  1584. var res = null;
  1585. var resName = null;
  1586. for(var i in Resolutions) {
  1587. var tmp = Resolutions[i];
  1588. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1589. resName = i;
  1590. res = tmp;
  1591. }
  1592. }
  1593. return resName;
  1594. }
  1595. function setResolutionConstraints(constraints, resolution) {
  1596. var isAndroid = RTCBrowserType.isAndroid();
  1597. if (Resolutions[resolution]) {
  1598. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1599. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1600. }
  1601. else if (isAndroid) {
  1602. // FIXME can't remember if the purpose of this was to always request
  1603. // low resolution on Android ? if yes it should be moved up front
  1604. constraints.video.mandatory.minWidth = 320;
  1605. constraints.video.mandatory.minHeight = 240;
  1606. constraints.video.mandatory.maxFrameRate = 15;
  1607. }
  1608. if (constraints.video.mandatory.minWidth)
  1609. constraints.video.mandatory.maxWidth =
  1610. constraints.video.mandatory.minWidth;
  1611. if (constraints.video.mandatory.minHeight)
  1612. constraints.video.mandatory.maxHeight =
  1613. constraints.video.mandatory.minHeight;
  1614. }
  1615. function getConstraints(um, resolution, bandwidth, fps, desktopStream) {
  1616. var constraints = {audio: false, video: false};
  1617. if (um.indexOf('video') >= 0) {
  1618. // same behaviour as true
  1619. constraints.video = { mandatory: {}, optional: [] };
  1620. constraints.video.optional.push({ googLeakyBucket: true });
  1621. setResolutionConstraints(constraints, resolution);
  1622. }
  1623. if (um.indexOf('audio') >= 0) {
  1624. if (!RTCBrowserType.isFirefox()) {
  1625. // same behaviour as true
  1626. constraints.audio = { mandatory: {}, optional: []};
  1627. // if it is good enough for hangouts...
  1628. constraints.audio.optional.push(
  1629. {googEchoCancellation: true},
  1630. {googAutoGainControl: true},
  1631. {googNoiseSupression: true},
  1632. {googHighpassFilter: true},
  1633. {googNoisesuppression2: true},
  1634. {googEchoCancellation2: true},
  1635. {googAutoGainControl2: true}
  1636. );
  1637. } else {
  1638. constraints.audio = true;
  1639. }
  1640. }
  1641. if (um.indexOf('screen') >= 0) {
  1642. if (RTCBrowserType.isChrome()) {
  1643. constraints.video = {
  1644. mandatory: {
  1645. chromeMediaSource: "screen",
  1646. googLeakyBucket: true,
  1647. maxWidth: window.screen.width,
  1648. maxHeight: window.screen.height,
  1649. maxFrameRate: 3
  1650. },
  1651. optional: []
  1652. };
  1653. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1654. constraints.video = {
  1655. optional: [
  1656. {
  1657. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1658. }
  1659. ]
  1660. };
  1661. } else {
  1662. logger.error(
  1663. "'screen' WebRTC media source is supported only in Chrome" +
  1664. " and with Temasys plugin");
  1665. }
  1666. }
  1667. if (um.indexOf('desktop') >= 0) {
  1668. constraints.video = {
  1669. mandatory: {
  1670. chromeMediaSource: "desktop",
  1671. chromeMediaSourceId: desktopStream,
  1672. googLeakyBucket: true,
  1673. maxWidth: window.screen.width,
  1674. maxHeight: window.screen.height,
  1675. maxFrameRate: 3
  1676. },
  1677. optional: []
  1678. };
  1679. }
  1680. if (bandwidth) {
  1681. if (!constraints.video) {
  1682. //same behaviour as true
  1683. constraints.video = {mandatory: {}, optional: []};
  1684. }
  1685. constraints.video.optional.push({bandwidth: bandwidth});
  1686. }
  1687. if (fps) {
  1688. // for some cameras it might be necessary to request 30fps
  1689. // so they choose 30fps mjpg over 10fps yuy2
  1690. if (!constraints.video) {
  1691. // same behaviour as true;
  1692. constraints.video = {mandatory: {}, optional: []};
  1693. }
  1694. constraints.video.mandatory.minFrameRate = fps;
  1695. }
  1696. return constraints;
  1697. }
  1698. function setAvailableDevices(um, available) {
  1699. var devices = {};
  1700. if (um.indexOf("video") != -1) {
  1701. devices.video = available;
  1702. }
  1703. if (um.indexOf("audio") != -1) {
  1704. devices.audio = available;
  1705. }
  1706. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  1707. }
  1708. // In case of IE we continue from 'onReady' callback
  1709. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1710. // once it is initialized.
  1711. function onReady () {
  1712. rtcReady = true;
  1713. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1714. };
  1715. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1716. var RTCUtils = {
  1717. init: function (options) {
  1718. var self = this;
  1719. if (RTCBrowserType.isFirefox()) {
  1720. var FFversion = RTCBrowserType.getFirefoxVersion();
  1721. if (FFversion >= 40) {
  1722. this.peerconnection = mozRTCPeerConnection;
  1723. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1724. this.pc_constraints = {};
  1725. this.attachMediaStream = function (element, stream) {
  1726. // srcObject is being standardized and FF will eventually
  1727. // support that unprefixed. FF also supports the
  1728. // "element.src = URL.createObjectURL(...)" combo, but that
  1729. // will be deprecated in favour of srcObject.
  1730. //
  1731. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1732. // https://github.com/webrtc/samples/issues/302
  1733. if (!element[0])
  1734. return;
  1735. element[0].mozSrcObject = stream;
  1736. element[0].play();
  1737. };
  1738. this.getStreamID = function (stream) {
  1739. var id = stream.id;
  1740. if (!id) {
  1741. var tracks = stream.getVideoTracks();
  1742. if (!tracks || tracks.length === 0) {
  1743. tracks = stream.getAudioTracks();
  1744. }
  1745. id = tracks[0].id;
  1746. }
  1747. return SDPUtil.filter_special_chars(id);
  1748. };
  1749. this.getVideoSrc = function (element) {
  1750. if (!element)
  1751. return null;
  1752. return element.mozSrcObject;
  1753. };
  1754. this.setVideoSrc = function (element, src) {
  1755. if (element)
  1756. element.mozSrcObject = src;
  1757. };
  1758. RTCSessionDescription = mozRTCSessionDescription;
  1759. RTCIceCandidate = mozRTCIceCandidate;
  1760. } else {
  1761. logger.error(
  1762. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1763. window.location.href = 'unsupported_browser.html';
  1764. return;
  1765. }
  1766. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1767. this.peerconnection = webkitRTCPeerConnection;
  1768. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1769. this.attachMediaStream = function (element, stream) {
  1770. element.attr('src', webkitURL.createObjectURL(stream));
  1771. };
  1772. this.getStreamID = function (stream) {
  1773. // streams from FF endpoints have the characters '{' and '}'
  1774. // that make jQuery choke.
  1775. return SDPUtil.filter_special_chars(stream.id);
  1776. };
  1777. this.getVideoSrc = function (element) {
  1778. if (!element)
  1779. return null;
  1780. return element.getAttribute("src");
  1781. };
  1782. this.setVideoSrc = function (element, src) {
  1783. if (element)
  1784. element.setAttribute("src", src);
  1785. };
  1786. // DTLS should now be enabled by default but..
  1787. this.pc_constraints = {'optional': [
  1788. {'DtlsSrtpKeyAgreement': 'true'}
  1789. ]};
  1790. if (options.useIPv6) {
  1791. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1792. this.pc_constraints.optional.push({googIPv6: true});
  1793. }
  1794. if (RTCBrowserType.isAndroid()) {
  1795. this.pc_constraints = {}; // disable DTLS on Android
  1796. }
  1797. if (!webkitMediaStream.prototype.getVideoTracks) {
  1798. webkitMediaStream.prototype.getVideoTracks = function () {
  1799. return this.videoTracks;
  1800. };
  1801. }
  1802. if (!webkitMediaStream.prototype.getAudioTracks) {
  1803. webkitMediaStream.prototype.getAudioTracks = function () {
  1804. return this.audioTracks;
  1805. };
  1806. }
  1807. }
  1808. // Detect IE/Safari
  1809. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1810. //AdapterJS.WebRTCPlugin.setLogLevel(
  1811. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1812. AdapterJS.webRTCReady(function (isPlugin) {
  1813. self.peerconnection = RTCPeerConnection;
  1814. self.getUserMedia = getUserMedia;
  1815. self.attachMediaStream = function (elSel, stream) {
  1816. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1817. return;
  1818. }
  1819. attachMediaStream(elSel[0], stream);
  1820. };
  1821. self.getStreamID = function (stream) {
  1822. var id = SDPUtil.filter_special_chars(stream.label);
  1823. return id;
  1824. };
  1825. self.getVideoSrc = function (element) {
  1826. if (!element) {
  1827. logger.warn("Attempt to get video SRC of null element");
  1828. return null;
  1829. }
  1830. var children = element.children;
  1831. for (var i = 0; i !== children.length; ++i) {
  1832. if (children[i].name === 'streamId') {
  1833. return children[i].value;
  1834. }
  1835. }
  1836. //logger.info(element.id + " SRC: " + src);
  1837. return null;
  1838. };
  1839. self.setVideoSrc = function (element, src) {
  1840. //logger.info("Set video src: ", element, src);
  1841. if (!src) {
  1842. logger.warn("Not attaching video stream, 'src' is null");
  1843. return;
  1844. }
  1845. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1846. var stream = AdapterJS.WebRTCPlugin.plugin
  1847. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1848. attachMediaStream(element, stream);
  1849. };
  1850. onReady(isPlugin);
  1851. });
  1852. } else {
  1853. try {
  1854. logger.error('Browser does not appear to be WebRTC-capable');
  1855. } catch (e) {
  1856. }
  1857. return;
  1858. }
  1859. // Call onReady() if Temasys plugin is not used
  1860. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1861. onReady();
  1862. }
  1863. },
  1864. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  1865. var constraints = getConstraints(
  1866. um, resolution, bandwidth, fps, desktopStream);
  1867. logger.info("Get media constraints", constraints);
  1868. try {
  1869. this.getUserMedia(constraints,
  1870. function (stream) {
  1871. logger.log('onUserMediaSuccess');
  1872. setAvailableDevices(um, true);
  1873. success_callback(stream);
  1874. },
  1875. function (error) {
  1876. setAvailableDevices(um, false);
  1877. logger.warn('Failed to get access to local media. Error ',
  1878. error, constraints);
  1879. if (failure_callback) {
  1880. failure_callback(error, resolution);
  1881. }
  1882. });
  1883. } catch (e) {
  1884. logger.error('GUM failed: ', e);
  1885. if (failure_callback) {
  1886. failure_callback(e);
  1887. }
  1888. }
  1889. },
  1890. /**
  1891. * Creates the local MediaStreams.
  1892. * @param devices the devices that will be requested
  1893. * @param resolution resolution constraints
  1894. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1895. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1896. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1897. * @returns {*} Promise object that will receive the new JitsiTracks
  1898. */
  1899. obtainAudioAndVideoPermissions: function (devices, resolution, dontCreateJitsiTracks) {
  1900. var self = this;
  1901. // Get AV
  1902. return new Promise(function (resolve, reject) {
  1903. var successCallback = function (stream) {
  1904. var streams = self.successCallback(stream, resolution);
  1905. resolve(dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  1906. };
  1907. if (!devices)
  1908. devices = ['audio', 'video'];
  1909. if (devices.length === 0) {
  1910. successCallback();
  1911. return;
  1912. }
  1913. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1914. // With FF/IE we can't split the stream into audio and video because FF
  1915. // doesn't support media stream constructors. So, we need to get the
  1916. // audio stream separately from the video stream using two distinct GUM
  1917. // calls. Not very user friendly :-( but we don't have many other
  1918. // options neither.
  1919. //
  1920. // Note that we pack those 2 streams in a single object and pass it to
  1921. // the successCallback method.
  1922. var obtainVideo = function (audioStream) {
  1923. self.getUserMediaWithConstraints(
  1924. ['video'],
  1925. function (videoStream) {
  1926. return successCallback({
  1927. audioStream: audioStream,
  1928. videoStream: videoStream
  1929. });
  1930. },
  1931. function (error, resolution) {
  1932. logger.error(
  1933. 'failed to obtain video stream - stop', error);
  1934. self.errorCallback(error, resolve, resolution, dontCreateJitsiTracks);
  1935. },
  1936. resolution || '360');
  1937. };
  1938. var obtainAudio = function () {
  1939. self.getUserMediaWithConstraints(
  1940. ['audio'],
  1941. function (audioStream) {
  1942. if (devices.indexOf('video') !== -1)
  1943. obtainVideo(audioStream);
  1944. },
  1945. function (error) {
  1946. logger.error(
  1947. 'failed to obtain audio stream - stop', error);
  1948. self.errorCallback(error, resolve, null, dontCreateJitsiTracks);
  1949. }
  1950. );
  1951. };
  1952. if (devices.indexOf('audio') !== -1) {
  1953. obtainAudio();
  1954. } else {
  1955. obtainVideo(null);
  1956. }
  1957. } else {
  1958. this.getUserMediaWithConstraints(
  1959. devices,
  1960. function (stream) {
  1961. successCallback(stream);
  1962. },
  1963. function (error, resolution) {
  1964. self.errorCallback(error, resolve, resolution, dontCreateJitsiTracks);
  1965. },
  1966. resolution || '360');
  1967. }
  1968. }.bind(this));
  1969. },
  1970. /**
  1971. * Successful callback called from GUM.
  1972. * @param stream the new MediaStream
  1973. * @param resolution the resolution of the video stream.
  1974. * @returns {*}
  1975. */
  1976. successCallback: function (stream, resolution) {
  1977. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1978. // it's an object with two properties: audioStream, videoStream.
  1979. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1980. logger.log('got', stream, stream.getAudioTracks().length,
  1981. stream.getVideoTracks().length);
  1982. return this.handleLocalStream(stream, resolution);
  1983. },
  1984. /**
  1985. * Error callback called from GUM. Retries the GUM call with different resolutions.
  1986. * @param error the error
  1987. * @param resolve the resolve funtion that will be called on success.
  1988. * @param currentResolution the last resolution used for GUM.
  1989. * @param dontCreateJitsiTracks if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1990. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1991. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1992. */
  1993. errorCallback: function (error, resolve, currentResolution, dontCreateJitsiTracks) {
  1994. var self = this;
  1995. logger.error('failed to obtain audio/video stream - trying audio only', error);
  1996. var resolution = getPreviousResolution(currentResolution);
  1997. if (typeof error == "object" && error.constraintName && error.name
  1998. && (error.name == "ConstraintNotSatisfiedError" ||
  1999. error.name == "OverconstrainedError") &&
  2000. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  2001. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  2002. && resolution != null) {
  2003. self.getUserMediaWithConstraints(['audio', 'video'],
  2004. function (stream) {
  2005. var streams = self.successCallback(stream, resolution);
  2006. resolve(dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2007. }, function (error, resolution) {
  2008. return self.errorCallback(error, resolve, resolution, dontCreateJitsiTracks);
  2009. }, resolution);
  2010. }
  2011. else {
  2012. self.getUserMediaWithConstraints(
  2013. ['audio'],
  2014. function (stream) {
  2015. var streams = self.successCallback(stream, resolution);
  2016. resolve(dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2017. },
  2018. function (error) {
  2019. logger.error('failed to obtain audio/video stream - stop',
  2020. error);
  2021. var streams = self.successCallback(null);
  2022. resolve(dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2023. }
  2024. );
  2025. }
  2026. },
  2027. /**
  2028. * Handles the newly created Media Streams.
  2029. * @param stream the new Media Streams
  2030. * @param resolution the resolution of the video stream.
  2031. * @returns {*[]} Promise object with the new Media Streams.
  2032. */
  2033. handleLocalStream: function (stream, resolution) {
  2034. var audioStream, videoStream;
  2035. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2036. // an object with two properties: audioStream, videoStream.
  2037. if (window.webkitMediaStream) {
  2038. audioStream = new webkitMediaStream();
  2039. videoStream = new webkitMediaStream();
  2040. if (stream) {
  2041. var audioTracks = stream.getAudioTracks();
  2042. for (var i = 0; i < audioTracks.length; i++) {
  2043. audioStream.addTrack(audioTracks[i]);
  2044. }
  2045. var videoTracks = stream.getVideoTracks();
  2046. for (i = 0; i < videoTracks.length; i++) {
  2047. videoStream.addTrack(videoTracks[i]);
  2048. }
  2049. }
  2050. }
  2051. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2052. if (stream && stream.audioStream)
  2053. audioStream = stream.audioStream;
  2054. else
  2055. audioStream = new DummyMediaStream("dummyAudio");
  2056. if (stream && stream.videoStream)
  2057. videoStream = stream.videoStream;
  2058. else
  2059. videoStream = new DummyMediaStream("dummyVideo");
  2060. }
  2061. return [
  2062. {stream: audioStream, type: "audio", videoType: null},
  2063. {stream: videoStream, type: "video", videoType: "camera",
  2064. resolution: resolution}
  2065. ];
  2066. },
  2067. createStream: function (stream, isVideo) {
  2068. var newStream = null;
  2069. if (window.webkitMediaStream) {
  2070. newStream = new webkitMediaStream();
  2071. if (newStream) {
  2072. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  2073. for (var i = 0; i < tracks.length; i++) {
  2074. newStream.addTrack(tracks[i]);
  2075. }
  2076. }
  2077. } else {
  2078. // FIXME: this is duplicated with 'handleLocalStream' !!!
  2079. if (stream) {
  2080. newStream = stream;
  2081. } else {
  2082. newStream =
  2083. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  2084. }
  2085. }
  2086. return newStream;
  2087. },
  2088. addListener: function (eventType, listener) {
  2089. eventEmitter.on(eventType, listener);
  2090. },
  2091. removeListener: function (eventType, listener) {
  2092. eventEmitter.removeListener(eventType, listener);
  2093. },
  2094. getDeviceAvailability: function () {
  2095. return devices;
  2096. },
  2097. isRTCReady: function () {
  2098. return rtcReady;
  2099. },
  2100. createLocalTracks: function (streams) {
  2101. var newStreams = []
  2102. for (var i = 0; i < streams.length; i++) {
  2103. var localStream = new JitsiLocalTrack(null, streams[i].stream,
  2104. eventEmitter, streams[i].videoType, streams[i].resolution);
  2105. newStreams.push(localStream);
  2106. if (streams[i].isMuted === true)
  2107. localStream.setMute(true);
  2108. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  2109. eventEmitter.emit(eventType, localStream);
  2110. }
  2111. return newStreams;
  2112. }
  2113. }
  2114. module.exports = RTCUtils;
  2115. }).call(this,"/modules/RTC/RTCUtils.js")
  2116. },{"../../service/RTC/RTCEvents":76,"../../service/RTC/Resolutions":77,"../../service/RTC/StreamEventTypes.js":78,"../xmpp/SDPUtil":29,"./JitsiLocalTrack":10,"./RTCBrowserType":14,"./adapter.screenshare":16,"events":40,"jitsi-meet-logger":44}],16:[function(require,module,exports){
  2117. (function (__filename){
  2118. /*! adapterjs - v0.12.0 - 2015-09-04 */
  2119. var console = require("jitsi-meet-logger").getLogger(__filename);
  2120. // Adapter's interface.
  2121. var AdapterJS = AdapterJS || {};
  2122. // Browserify compatibility
  2123. if(typeof exports !== 'undefined') {
  2124. module.exports = AdapterJS;
  2125. }
  2126. AdapterJS.options = AdapterJS.options || {};
  2127. // uncomment to get virtual webcams
  2128. // AdapterJS.options.getAllCams = true;
  2129. // uncomment to prevent the install prompt when the plugin in not yet installed
  2130. // AdapterJS.options.hidePluginInstallPrompt = true;
  2131. // AdapterJS version
  2132. AdapterJS.VERSION = '0.12.0';
  2133. // This function will be called when the WebRTC API is ready to be used
  2134. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2135. // the plugin
  2136. // You may Override this function to synchronise the start of your application
  2137. // with the WebRTC API being ready.
  2138. // If you decide not to override use this synchronisation, it may result in
  2139. // an extensive CPU usage on the plugin start (once per tab loaded)
  2140. // Params:
  2141. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2142. //
  2143. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2144. // The WebRTC API is ready.
  2145. // Override me and do whatever you want here
  2146. };
  2147. // Sets a callback function to be called when the WebRTC interface is ready.
  2148. // The first argument is the function to callback.\
  2149. // Throws an error if the first argument is not a function
  2150. AdapterJS.webRTCReady = function (callback) {
  2151. if (typeof callback !== 'function') {
  2152. throw new Error('Callback provided is not a function');
  2153. }
  2154. if (true === AdapterJS.onwebrtcreadyDone) {
  2155. // All WebRTC interfaces are ready, just call the callback
  2156. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2157. } else {
  2158. // will be triggered automatically when your browser/plugin is ready.
  2159. AdapterJS.onwebrtcready = callback;
  2160. }
  2161. };
  2162. // Plugin namespace
  2163. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2164. // The object to store plugin information
  2165. AdapterJS.WebRTCPlugin.pluginInfo = {
  2166. prefix : 'Tem',
  2167. plugName : 'TemWebRTCPlugin',
  2168. pluginId : 'plugin0',
  2169. type : 'application/x-temwebrtcplugin',
  2170. onload : '__TemWebRTCReady0',
  2171. portalLink : 'http://skylink.io/plugin/',
  2172. downloadLink : null, //set below
  2173. companyName: 'Temasys'
  2174. };
  2175. if(!!navigator.platform.match(/^Mac/i)) {
  2176. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2177. }
  2178. else if(!!navigator.platform.match(/^Win/i)) {
  2179. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2180. }
  2181. AdapterJS.WebRTCPlugin.TAGS = {
  2182. NONE : 'none',
  2183. AUDIO : 'audio',
  2184. VIDEO : 'video'
  2185. };
  2186. // Unique identifier of each opened page
  2187. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2188. // Use this whenever you want to call the plugin.
  2189. AdapterJS.WebRTCPlugin.plugin = null;
  2190. // Set log level for the plugin once it is ready.
  2191. // The different values are
  2192. // This is an asynchronous function that will run when the plugin is ready
  2193. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2194. // Defines webrtc's JS interface according to the plugin's implementation.
  2195. // Define plugin Browsers as WebRTC Interface.
  2196. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2197. // This function detects whether or not a plugin is installed.
  2198. // Checks if Not IE (firefox, for example), else if it's IE,
  2199. // we're running IE and do something. If not it is not supported.
  2200. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2201. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2202. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2203. // Inject the HTML DOM object element into the page.
  2204. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2205. // States of readiness that the plugin goes through when
  2206. // being injected and stated
  2207. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2208. NONE : 0, // no plugin use
  2209. INITIALIZING : 1, // Detected need for plugin
  2210. INJECTING : 2, // Injecting plugin
  2211. INJECTED: 3, // Plugin element injected but not usable yet
  2212. READY: 4 // Plugin ready to be used
  2213. };
  2214. // Current state of the plugin. You cannot use the plugin before this is
  2215. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2216. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2217. // True is AdapterJS.onwebrtcready was already called, false otherwise
  2218. // Used to make sure AdapterJS.onwebrtcready is only called once
  2219. AdapterJS.onwebrtcreadyDone = false;
  2220. // Log levels for the plugin.
  2221. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  2222. /*
  2223. Log outputs are prefixed in some cases.
  2224. INFO: Information reported by the plugin.
  2225. ERROR: Errors originating from within the plugin.
  2226. WEBRTC: Error originating from within the libWebRTC library
  2227. */
  2228. // From the least verbose to the most verbose
  2229. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  2230. NONE : 'NONE',
  2231. ERROR : 'ERROR',
  2232. WARNING : 'WARNING',
  2233. INFO: 'INFO',
  2234. VERBOSE: 'VERBOSE',
  2235. SENSITIVE: 'SENSITIVE'
  2236. };
  2237. // Does a waiting check before proceeding to load the plugin.
  2238. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  2239. // This methid will use an interval to wait for the plugin to be ready.
  2240. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  2241. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  2242. // This function will be called when plugin is ready. It sends necessary
  2243. // details to the plugin.
  2244. // The function will wait for the document to be ready and the set the
  2245. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2246. // indicating that it can start being requested.
  2247. // This function is not in the IE/Safari condition brackets so that
  2248. // TemPluginLoaded function might be called on Chrome/Firefox.
  2249. // This function is the only private function that is not encapsulated to
  2250. // allow the plugin method to be called.
  2251. __TemWebRTCReady0 = function () {
  2252. if (document.readyState === 'complete') {
  2253. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2254. AdapterJS.maybeThroughWebRTCReady();
  2255. } else {
  2256. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2257. if (document.readyState === 'complete') {
  2258. // TODO: update comments, we wait for the document to be ready
  2259. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2260. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2261. AdapterJS.maybeThroughWebRTCReady();
  2262. }
  2263. }, 100);
  2264. }
  2265. };
  2266. AdapterJS.maybeThroughWebRTCReady = function() {
  2267. if (!AdapterJS.onwebrtcreadyDone) {
  2268. AdapterJS.onwebrtcreadyDone = true;
  2269. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2270. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2271. }
  2272. }
  2273. };
  2274. // Text namespace
  2275. AdapterJS.TEXT = {
  2276. PLUGIN: {
  2277. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2278. 'to work on this browser.',
  2279. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2280. BUTTON: 'Install Now'
  2281. },
  2282. REFRESH: {
  2283. REQUIRE_REFRESH: 'Please refresh page',
  2284. BUTTON: 'Refresh Page'
  2285. }
  2286. };
  2287. // The result of ice connection states.
  2288. // - starting: Ice connection is starting.
  2289. // - checking: Ice connection is checking.
  2290. // - connected Ice connection is connected.
  2291. // - completed Ice connection is connected.
  2292. // - done Ice connection has been completed.
  2293. // - disconnected Ice connection has been disconnected.
  2294. // - failed Ice connection has failed.
  2295. // - closed Ice connection is closed.
  2296. AdapterJS._iceConnectionStates = {
  2297. starting : 'starting',
  2298. checking : 'checking',
  2299. connected : 'connected',
  2300. completed : 'connected',
  2301. done : 'completed',
  2302. disconnected : 'disconnected',
  2303. failed : 'failed',
  2304. closed : 'closed'
  2305. };
  2306. //The IceConnection states that has been fired for each peer.
  2307. AdapterJS._iceConnectionFiredStates = [];
  2308. // Check if WebRTC Interface is defined.
  2309. AdapterJS.isDefined = null;
  2310. // This function helps to retrieve the webrtc detected browser information.
  2311. // This sets:
  2312. // - webrtcDetectedBrowser: The browser agent name.
  2313. // - webrtcDetectedVersion: The browser version.
  2314. // - webrtcDetectedType: The types of webRTC support.
  2315. // - 'moz': Mozilla implementation of webRTC.
  2316. // - 'webkit': WebKit implementation of webRTC.
  2317. // - 'plugin': Using the plugin implementation.
  2318. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2319. var hasMatch, checkMatch = navigator.userAgent.match(
  2320. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2321. if (/trident/i.test(checkMatch[1])) {
  2322. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2323. webrtcDetectedBrowser = 'IE';
  2324. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2325. } else if (checkMatch[1] === 'Chrome') {
  2326. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2327. if (hasMatch !== null) {
  2328. webrtcDetectedBrowser = 'opera';
  2329. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2330. }
  2331. }
  2332. if (navigator.userAgent.indexOf('Safari')) {
  2333. if (typeof InstallTrigger !== 'undefined') {
  2334. webrtcDetectedBrowser = 'firefox';
  2335. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2336. webrtcDetectedBrowser = 'IE';
  2337. } else if (
  2338. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2339. webrtcDetectedBrowser = 'safari';
  2340. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2341. webrtcDetectedBrowser = 'opera';
  2342. } else if (!!window.chrome) {
  2343. webrtcDetectedBrowser = 'chrome';
  2344. }
  2345. }
  2346. if (!webrtcDetectedBrowser) {
  2347. webrtcDetectedVersion = checkMatch[1];
  2348. }
  2349. if (!webrtcDetectedVersion) {
  2350. try {
  2351. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2352. [navigator.appName, navigator.appVersion, '-?'];
  2353. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2354. checkMatch.splice(1, 1, hasMatch[1]);
  2355. }
  2356. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2357. } catch (error) { }
  2358. }
  2359. };
  2360. // To fix configuration as some browsers does not support
  2361. // the 'urls' attribute.
  2362. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2363. if (pcConfig === null) {
  2364. return;
  2365. }
  2366. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2367. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2368. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2369. delete pcConfig.iceServers[i].urls;
  2370. }
  2371. }
  2372. };
  2373. AdapterJS.addEvent = function(elem, evnt, func) {
  2374. if (elem.addEventListener) { // W3C DOM
  2375. elem.addEventListener(evnt, func, false);
  2376. } else if (elem.attachEvent) {// OLD IE DOM
  2377. elem.attachEvent('on'+evnt, func);
  2378. } else { // No much to do
  2379. elem[evnt] = func;
  2380. }
  2381. };
  2382. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2383. // only inject once the page is ready
  2384. if (document.readyState !== 'complete') {
  2385. return;
  2386. }
  2387. var w = window;
  2388. var i = document.createElement('iframe');
  2389. i.style.position = 'fixed';
  2390. i.style.top = '-41px';
  2391. i.style.left = 0;
  2392. i.style.right = 0;
  2393. i.style.width = '100%';
  2394. i.style.height = '40px';
  2395. i.style.backgroundColor = '#ffffe1';
  2396. i.style.border = 'none';
  2397. i.style.borderBottom = '1px solid #888888';
  2398. i.style.zIndex = '9999999';
  2399. if(typeof i.style.webkitTransition === 'string') {
  2400. i.style.webkitTransition = 'all .5s ease-out';
  2401. } else if(typeof i.style.transition === 'string') {
  2402. i.style.transition = 'all .5s ease-out';
  2403. }
  2404. document.body.appendChild(i);
  2405. c = (i.contentWindow) ? i.contentWindow :
  2406. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2407. c.document.open();
  2408. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2409. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2410. 'middle; cursor: default;">' + text + '</span>');
  2411. if(buttonText && buttonLink) {
  2412. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  2413. c.document.close();
  2414. // On click on okay
  2415. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2416. if (!!displayRefreshBar) {
  2417. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2418. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2419. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2420. }
  2421. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2422. e.preventDefault();
  2423. try {
  2424. event.cancelBubble = true;
  2425. } catch(error) { }
  2426. var pluginInstallInterval = setInterval(function(){
  2427. if(! isIE) {
  2428. navigator.plugins.refresh(false);
  2429. }
  2430. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2431. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2432. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2433. function() { // plugin now installed
  2434. clearInterval(pluginInstallInterval);
  2435. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2436. },
  2437. function() {
  2438. // still no plugin detected, nothing to do
  2439. });
  2440. } , 500);
  2441. });
  2442. // On click on Cancel
  2443. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  2444. w.document.body.removeChild(i);
  2445. });
  2446. } else {
  2447. c.document.close();
  2448. }
  2449. setTimeout(function() {
  2450. if(typeof i.style.webkitTransform === 'string') {
  2451. i.style.webkitTransform = 'translateY(40px)';
  2452. } else if(typeof i.style.transform === 'string') {
  2453. i.style.transform = 'translateY(40px)';
  2454. } else {
  2455. i.style.top = '0px';
  2456. }
  2457. }, 300);
  2458. };
  2459. // -----------------------------------------------------------
  2460. // Detected webrtc implementation. Types are:
  2461. // - 'moz': Mozilla implementation of webRTC.
  2462. // - 'webkit': WebKit implementation of webRTC.
  2463. // - 'plugin': Using the plugin implementation.
  2464. webrtcDetectedType = null;
  2465. // Detected webrtc datachannel support. Types are:
  2466. // - 'SCTP': SCTP datachannel support.
  2467. // - 'RTP': RTP datachannel support.
  2468. webrtcDetectedDCSupport = null;
  2469. // Set the settings for creating DataChannels, MediaStream for
  2470. // Cross-browser compability.
  2471. // - This is only for SCTP based support browsers.
  2472. // the 'urls' attribute.
  2473. checkMediaDataChannelSettings =
  2474. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2475. if (typeof callback !== 'function') {
  2476. return;
  2477. }
  2478. var beOfferer = true;
  2479. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2480. // Nightly version does not require MozDontOfferDataChannel for interop
  2481. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2482. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2483. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2484. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2485. // Resends an updated version of constraints for MozDataChannel to work
  2486. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2487. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2488. try {
  2489. delete constraints.mandatory.MozDontOfferDataChannel;
  2490. } catch (error) {
  2491. console.error('Failed deleting MozDontOfferDataChannel');
  2492. console.error(error);
  2493. }
  2494. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2495. constraints.mandatory.MozDontOfferDataChannel = true;
  2496. }
  2497. if (!isLocalFirefox) {
  2498. // temporary measure to remove Moz* constraints in non Firefox browsers
  2499. for (var prop in constraints.mandatory) {
  2500. if (constraints.mandatory.hasOwnProperty(prop)) {
  2501. if (prop.indexOf('Moz') !== -1) {
  2502. delete constraints.mandatory[prop];
  2503. }
  2504. }
  2505. }
  2506. }
  2507. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2508. // interopability of the media stream
  2509. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2510. beOfferer = false;
  2511. }
  2512. callback(beOfferer, constraints);
  2513. };
  2514. // Handles the differences for all browsers ice connection state output.
  2515. // - Tested outcomes are:
  2516. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2517. // - Chrome (answerer) : 'checking' > 'connected'
  2518. // - Firefox (offerer) : 'checking' > 'connected'
  2519. // - Firefox (answerer): 'checking' > 'connected'
  2520. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2521. if (typeof callback !== 'function') {
  2522. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2523. return;
  2524. }
  2525. peerId = (peerId) ? peerId : 'peer';
  2526. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2527. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2528. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2529. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2530. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2531. }
  2532. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2533. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2534. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2535. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2536. setTimeout(function () {
  2537. AdapterJS._iceConnectionFiredStates[peerId]
  2538. .push(AdapterJS._iceConnectionStates.done);
  2539. callback(AdapterJS._iceConnectionStates.done);
  2540. }, 1000);
  2541. }
  2542. callback(iceConnectionState);
  2543. }
  2544. return;
  2545. };
  2546. // Firefox:
  2547. // - Creates iceServer from the url for Firefox.
  2548. // - Create iceServer with stun url.
  2549. // - Create iceServer with turn url.
  2550. // - Ignore the transport parameter from TURN url for FF version <=27.
  2551. // - Return null for createIceServer if transport=tcp.
  2552. // - FF 27 and above supports transport parameters in TURN url,
  2553. // - So passing in the full url to create iceServer.
  2554. // Chrome:
  2555. // - Creates iceServer from the url for Chrome M33 and earlier.
  2556. // - Create iceServer with stun url.
  2557. // - Chrome M28 & above uses below TURN format.
  2558. // Plugin:
  2559. // - Creates Ice Server for Plugin Browsers
  2560. // - If Stun - Create iceServer with stun url.
  2561. // - Else - Create iceServer with turn url
  2562. // - This is a WebRTC Function
  2563. createIceServer = null;
  2564. // Firefox:
  2565. // - Creates IceServers for Firefox
  2566. // - Use .url for FireFox.
  2567. // - Multiple Urls support
  2568. // Chrome:
  2569. // - Creates iceServers from the urls for Chrome M34 and above.
  2570. // - .urls is supported since Chrome M34.
  2571. // - Multiple Urls support
  2572. // Plugin:
  2573. // - Creates Ice Servers for Plugin Browsers
  2574. // - Multiple Urls support
  2575. // - This is a WebRTC Function
  2576. createIceServers = null;
  2577. //------------------------------------------------------------
  2578. //The RTCPeerConnection object.
  2579. RTCPeerConnection = null;
  2580. // Creates RTCSessionDescription object for Plugin Browsers
  2581. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2582. RTCSessionDescription : null;
  2583. // Creates RTCIceCandidate object for Plugin Browsers
  2584. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2585. RTCIceCandidate : null;
  2586. // Get UserMedia (only difference is the prefix).
  2587. // Code from Adam Barth.
  2588. getUserMedia = null;
  2589. // Attach a media stream to an element.
  2590. attachMediaStream = null;
  2591. // Re-attach a media stream to an element.
  2592. reattachMediaStream = null;
  2593. // Detected browser agent name. Types are:
  2594. // - 'firefox': Firefox browser.
  2595. // - 'chrome': Chrome browser.
  2596. // - 'opera': Opera browser.
  2597. // - 'safari': Safari browser.
  2598. // - 'IE' - Internet Explorer browser.
  2599. webrtcDetectedBrowser = null;
  2600. // Detected browser version.
  2601. webrtcDetectedVersion = null;
  2602. // Check for browser types and react accordingly
  2603. if (navigator.mozGetUserMedia) {
  2604. webrtcDetectedBrowser = 'firefox';
  2605. webrtcDetectedVersion = parseInt(navigator
  2606. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2607. webrtcDetectedType = 'moz';
  2608. webrtcDetectedDCSupport = 'SCTP';
  2609. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2610. AdapterJS.maybeFixConfiguration(pcConfig);
  2611. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2612. };
  2613. // The RTCSessionDescription object.
  2614. RTCSessionDescription = mozRTCSessionDescription;
  2615. window.RTCSessionDescription = RTCSessionDescription;
  2616. // The RTCIceCandidate object.
  2617. RTCIceCandidate = mozRTCIceCandidate;
  2618. window.RTCIceCandidate = RTCIceCandidate;
  2619. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2620. navigator.getUserMedia = window.getUserMedia;
  2621. // Shim for MediaStreamTrack.getSources.
  2622. MediaStreamTrack.getSources = function(successCb) {
  2623. setTimeout(function() {
  2624. var infos = [
  2625. { kind: 'audio', id: 'default', label:'', facing:'' },
  2626. { kind: 'video', id: 'default', label:'', facing:'' }
  2627. ];
  2628. successCb(infos);
  2629. }, 0);
  2630. };
  2631. createIceServer = function (url, username, password) {
  2632. var iceServer = null;
  2633. var url_parts = url.split(':');
  2634. if (url_parts[0].indexOf('stun') === 0) {
  2635. iceServer = { url : url };
  2636. } else if (url_parts[0].indexOf('turn') === 0) {
  2637. if (webrtcDetectedVersion < 27) {
  2638. var turn_url_parts = url.split('?');
  2639. if (turn_url_parts.length === 1 ||
  2640. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2641. iceServer = {
  2642. url : turn_url_parts[0],
  2643. credential : password,
  2644. username : username
  2645. };
  2646. }
  2647. } else {
  2648. iceServer = {
  2649. url : url,
  2650. credential : password,
  2651. username : username
  2652. };
  2653. }
  2654. }
  2655. return iceServer;
  2656. };
  2657. createIceServers = function (urls, username, password) {
  2658. var iceServers = [];
  2659. for (i = 0; i < urls.length; i++) {
  2660. var iceServer = createIceServer(urls[i], username, password);
  2661. if (iceServer !== null) {
  2662. iceServers.push(iceServer);
  2663. }
  2664. }
  2665. return iceServers;
  2666. };
  2667. attachMediaStream = function (element, stream) {
  2668. element.mozSrcObject = stream;
  2669. if (stream !== null)
  2670. element.play();
  2671. return element;
  2672. };
  2673. reattachMediaStream = function (to, from) {
  2674. to.mozSrcObject = from.mozSrcObject;
  2675. to.play();
  2676. return to;
  2677. };
  2678. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2679. if (!callback) {
  2680. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2681. ': 1 argument required, but only 0 present.');
  2682. }
  2683. return callback([]);
  2684. };
  2685. // Fake get{Video,Audio}Tracks
  2686. if (!MediaStream.prototype.getVideoTracks) {
  2687. MediaStream.prototype.getVideoTracks = function () {
  2688. return [];
  2689. };
  2690. }
  2691. if (!MediaStream.prototype.getAudioTracks) {
  2692. MediaStream.prototype.getAudioTracks = function () {
  2693. return [];
  2694. };
  2695. }
  2696. AdapterJS.maybeThroughWebRTCReady();
  2697. } else if (navigator.webkitGetUserMedia) {
  2698. webrtcDetectedBrowser = 'chrome';
  2699. webrtcDetectedType = 'webkit';
  2700. webrtcDetectedVersion = parseInt(navigator
  2701. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2702. // check if browser is opera 20+
  2703. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2704. if (checkIfOpera !== null) {
  2705. webrtcDetectedBrowser = 'opera';
  2706. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2707. }
  2708. // check browser datachannel support
  2709. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2710. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2711. webrtcDetectedDCSupport = 'SCTP';
  2712. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2713. webrtcDetectedVersion > 24) {
  2714. webrtcDetectedDCSupport = 'RTP';
  2715. } else {
  2716. webrtcDetectedDCSupport = '';
  2717. }
  2718. createIceServer = function (url, username, password) {
  2719. var iceServer = null;
  2720. var url_parts = url.split(':');
  2721. if (url_parts[0].indexOf('stun') === 0) {
  2722. iceServer = { 'url' : url };
  2723. } else if (url_parts[0].indexOf('turn') === 0) {
  2724. iceServer = {
  2725. 'url' : url,
  2726. 'credential' : password,
  2727. 'username' : username
  2728. };
  2729. }
  2730. return iceServer;
  2731. };
  2732. createIceServers = function (urls, username, password) {
  2733. var iceServers = [];
  2734. if (webrtcDetectedVersion >= 34) {
  2735. iceServers = {
  2736. 'urls' : urls,
  2737. 'credential' : password,
  2738. 'username' : username
  2739. };
  2740. } else {
  2741. for (i = 0; i < urls.length; i++) {
  2742. var iceServer = createIceServer(urls[i], username, password);
  2743. if (iceServer !== null) {
  2744. iceServers.push(iceServer);
  2745. }
  2746. }
  2747. }
  2748. return iceServers;
  2749. };
  2750. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2751. if (webrtcDetectedVersion < 34) {
  2752. AdapterJS.maybeFixConfiguration(pcConfig);
  2753. }
  2754. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2755. };
  2756. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2757. navigator.getUserMedia = window.getUserMedia;
  2758. attachMediaStream = function (element, stream) {
  2759. if (typeof element.srcObject !== 'undefined') {
  2760. element.srcObject = stream;
  2761. } else if (typeof element.mozSrcObject !== 'undefined') {
  2762. element.mozSrcObject = stream;
  2763. } else if (typeof element.src !== 'undefined') {
  2764. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2765. } else {
  2766. console.log('Error attaching stream to element.');
  2767. }
  2768. return element;
  2769. };
  2770. reattachMediaStream = function (to, from) {
  2771. to.src = from.src;
  2772. return to;
  2773. };
  2774. AdapterJS.maybeThroughWebRTCReady();
  2775. } else if (navigator.mediaDevices && navigator.userAgent.match(
  2776. /Edge\/(\d+).(\d+)$/)) {
  2777. webrtcDetectedBrowser = 'edge';
  2778. webrtcDetectedVersion =
  2779. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  2780. // the minimum version still supported by adapter.
  2781. webrtcMinimumVersion = 12;
  2782. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  2783. attachMediaStream = function(element, stream) {
  2784. element.srcObject = stream;
  2785. return element;
  2786. };
  2787. reattachMediaStream = function(to, from) {
  2788. to.srcObject = from.srcObject;
  2789. return to;
  2790. };
  2791. AdapterJS.maybeThroughWebRTCReady();
  2792. } else { // TRY TO USE PLUGIN
  2793. // IE 9 is not offering an implementation of console.log until you open a console
  2794. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2795. /* jshint -W020 */
  2796. console = {} || console;
  2797. // Implemented based on console specs from MDN
  2798. // You may override these functions
  2799. console.log = function (arg) {};
  2800. console.info = function (arg) {};
  2801. console.error = function (arg) {};
  2802. console.dir = function (arg) {};
  2803. console.exception = function (arg) {};
  2804. console.trace = function (arg) {};
  2805. console.warn = function (arg) {};
  2806. console.count = function (arg) {};
  2807. console.debug = function (arg) {};
  2808. console.count = function (arg) {};
  2809. console.time = function (arg) {};
  2810. console.timeEnd = function (arg) {};
  2811. console.group = function (arg) {};
  2812. console.groupCollapsed = function (arg) {};
  2813. console.groupEnd = function (arg) {};
  2814. /* jshint +W020 */
  2815. }
  2816. webrtcDetectedType = 'plugin';
  2817. webrtcDetectedDCSupport = 'plugin';
  2818. AdapterJS.parseWebrtcDetectedBrowser();
  2819. isIE = webrtcDetectedBrowser === 'IE';
  2820. /* jshint -W035 */
  2821. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2822. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2823. /* empty because it needs to prevent the function from running. */
  2824. }
  2825. };
  2826. /* jshint +W035 */
  2827. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2828. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2829. // Call immediately if possible
  2830. // Once the plugin is set, the code will always take this path
  2831. callback();
  2832. } else {
  2833. // otherwise start a 100ms interval
  2834. var checkPluginReadyState = setInterval(function () {
  2835. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2836. clearInterval(checkPluginReadyState);
  2837. callback();
  2838. }
  2839. }, 100);
  2840. }
  2841. };
  2842. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2843. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2844. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2845. });
  2846. };
  2847. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2848. // only inject once the page is ready
  2849. if (document.readyState !== 'complete') {
  2850. return;
  2851. }
  2852. // Prevent multiple injections
  2853. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2854. return;
  2855. }
  2856. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2857. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2858. var frag = document.createDocumentFragment();
  2859. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2860. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2861. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2862. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2863. '<param name="pluginId" value="' +
  2864. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2865. '<param name="windowless" value="false" /> ' +
  2866. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2867. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  2868. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  2869. // uncomment to be able to use virtual cams
  2870. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2871. '</object>';
  2872. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2873. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2874. }
  2875. document.body.appendChild(frag);
  2876. // Need to re-fetch the plugin
  2877. AdapterJS.WebRTCPlugin.plugin =
  2878. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2879. } else {
  2880. // Load Plugin
  2881. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2882. AdapterJS.WebRTCPlugin.plugin.id =
  2883. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2884. // IE will only start the plugin if it's ACTUALLY visible
  2885. if (isIE) {
  2886. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2887. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2888. } else { // The size of the plugin on Safari should be 0x0px
  2889. // so that the autorisation prompt is at the top
  2890. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2891. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2892. }
  2893. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2894. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2895. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2896. '<param name="pluginId" value="' +
  2897. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2898. '<param name="windowless" value="false" /> ' +
  2899. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2900. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  2901. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  2902. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2903. }
  2904. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2905. };
  2906. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2907. function (comName, plugName, installedCb, notInstalledCb) {
  2908. if (!isIE) {
  2909. var pluginArray = navigator.plugins;
  2910. for (var i = 0; i < pluginArray.length; i++) {
  2911. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2912. installedCb();
  2913. return;
  2914. }
  2915. }
  2916. notInstalledCb();
  2917. } else {
  2918. try {
  2919. var axo = new ActiveXObject(comName + '.' + plugName);
  2920. } catch (e) {
  2921. notInstalledCb();
  2922. return;
  2923. }
  2924. installedCb();
  2925. }
  2926. };
  2927. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2928. if (AdapterJS.WebRTCPlugin.pluginState ===
  2929. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2930. console.error("AdapterJS - WebRTC interface has already been defined");
  2931. return;
  2932. }
  2933. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2934. AdapterJS.isDefined = function (variable) {
  2935. return variable !== null && variable !== undefined;
  2936. };
  2937. createIceServer = function (url, username, password) {
  2938. var iceServer = null;
  2939. var url_parts = url.split(':');
  2940. if (url_parts[0].indexOf('stun') === 0) {
  2941. iceServer = {
  2942. 'url' : url,
  2943. 'hasCredentials' : false
  2944. };
  2945. } else if (url_parts[0].indexOf('turn') === 0) {
  2946. iceServer = {
  2947. 'url' : url,
  2948. 'hasCredentials' : true,
  2949. 'credential' : password,
  2950. 'username' : username
  2951. };
  2952. }
  2953. return iceServer;
  2954. };
  2955. createIceServers = function (urls, username, password) {
  2956. var iceServers = [];
  2957. for (var i = 0; i < urls.length; ++i) {
  2958. iceServers.push(createIceServer(urls[i], username, password));
  2959. }
  2960. return iceServers;
  2961. };
  2962. RTCSessionDescription = function (info) {
  2963. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2964. return AdapterJS.WebRTCPlugin.plugin.
  2965. ConstructSessionDescription(info.type, info.sdp);
  2966. };
  2967. RTCPeerConnection = function (servers, constraints) {
  2968. var iceServers = null;
  2969. if (servers) {
  2970. iceServers = servers.iceServers;
  2971. for (var i = 0; i < iceServers.length; i++) {
  2972. if (iceServers[i].urls && !iceServers[i].url) {
  2973. iceServers[i].url = iceServers[i].urls;
  2974. }
  2975. iceServers[i].hasCredentials = AdapterJS.
  2976. isDefined(iceServers[i].username) &&
  2977. AdapterJS.isDefined(iceServers[i].credential);
  2978. }
  2979. }
  2980. var mandatory = (constraints && constraints.mandatory) ?
  2981. constraints.mandatory : null;
  2982. var optional = (constraints && constraints.optional) ?
  2983. constraints.optional : null;
  2984. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2985. return AdapterJS.WebRTCPlugin.plugin.
  2986. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2987. iceServers, mandatory, optional);
  2988. };
  2989. MediaStreamTrack = {};
  2990. MediaStreamTrack.getSources = function (callback) {
  2991. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2992. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2993. });
  2994. };
  2995. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2996. constraints.audio = constraints.audio || false;
  2997. constraints.video = constraints.video || false;
  2998. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2999. AdapterJS.WebRTCPlugin.plugin.
  3000. getUserMedia(constraints, successCallback, failureCallback);
  3001. });
  3002. };
  3003. window.navigator.getUserMedia = window.getUserMedia;
  3004. attachMediaStream = function (element, stream) {
  3005. if (!element || !element.parentNode) {
  3006. return;
  3007. }
  3008. var streamId
  3009. if (stream === null) {
  3010. streamId = '';
  3011. }
  3012. else {
  3013. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  3014. streamId = stream.id;
  3015. }
  3016. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  3017. var nodeName = element.nodeName.toLowerCase();
  3018. if (nodeName !== 'object') { // not a plugin <object> tag yet
  3019. var tag;
  3020. switch(nodeName) {
  3021. case 'audio':
  3022. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  3023. break;
  3024. case 'video':
  3025. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  3026. break;
  3027. default:
  3028. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  3029. }
  3030. var frag = document.createDocumentFragment();
  3031. var temp = document.createElement('div');
  3032. var classHTML = '';
  3033. if (element.className) {
  3034. classHTML = 'class="' + element.className + '" ';
  3035. } else if (element.attributes && element.attributes['class']) {
  3036. classHTML = 'class="' + element.attributes['class'].value + '" ';
  3037. }
  3038. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  3039. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  3040. '<param name="pluginId" value="' + elementId + '" /> ' +
  3041. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3042. '<param name="windowless" value="true" /> ' +
  3043. '<param name="streamId" value="' + streamId + '" /> ' +
  3044. '<param name="tag" value="' + tag + '" /> ' +
  3045. '</object>';
  3046. while (temp.firstChild) {
  3047. frag.appendChild(temp.firstChild);
  3048. }
  3049. var height = '';
  3050. var width = '';
  3051. if (element.getBoundingClientRect) {
  3052. var rectObject = element.getBoundingClientRect();
  3053. width = rectObject.width + 'px';
  3054. height = rectObject.height + 'px';
  3055. }
  3056. else if (element.width) {
  3057. width = element.width;
  3058. height = element.height;
  3059. } else {
  3060. // TODO: What scenario could bring us here?
  3061. }
  3062. element.parentNode.insertBefore(frag, element);
  3063. frag = document.getElementById(elementId);
  3064. frag.width = width;
  3065. frag.height = height;
  3066. element.parentNode.removeChild(element);
  3067. } else { // already an <object> tag, just change the stream id
  3068. var children = element.children;
  3069. for (var i = 0; i !== children.length; ++i) {
  3070. if (children[i].name === 'streamId') {
  3071. children[i].value = streamId;
  3072. break;
  3073. }
  3074. }
  3075. element.setStreamId(streamId);
  3076. }
  3077. var newElement = document.getElementById(elementId);
  3078. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  3079. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  3080. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  3081. if (isIE) { // on IE the event needs to be plugged manually
  3082. newElement.attachEvent('onplaying', newElement.onplaying);
  3083. newElement.attachEvent('onplay', newElement.onplay);
  3084. newElement._TemOnClick = function (id) {
  3085. var arg = {
  3086. srcElement : document.getElementById(id)
  3087. };
  3088. newElement.onclick(arg);
  3089. };
  3090. }
  3091. return newElement;
  3092. };
  3093. reattachMediaStream = function (to, from) {
  3094. var stream = null;
  3095. var children = from.children;
  3096. for (var i = 0; i !== children.length; ++i) {
  3097. if (children[i].name === 'streamId') {
  3098. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3099. stream = AdapterJS.WebRTCPlugin.plugin
  3100. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  3101. break;
  3102. }
  3103. }
  3104. if (stream !== null) {
  3105. return attachMediaStream(to, stream);
  3106. } else {
  3107. console.log('Could not find the stream associated with this element');
  3108. }
  3109. };
  3110. RTCIceCandidate = function (candidate) {
  3111. if (!candidate.sdpMid) {
  3112. candidate.sdpMid = '';
  3113. }
  3114. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3115. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  3116. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  3117. );
  3118. };
  3119. // inject plugin
  3120. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  3121. AdapterJS.WebRTCPlugin.injectPlugin();
  3122. };
  3123. // This function will be called if the plugin is needed (browser different
  3124. // from Chrome or Firefox), but the plugin is not installed.
  3125. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  3126. function() {
  3127. AdapterJS.addEvent(document,
  3128. 'readystatechange',
  3129. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  3130. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  3131. };
  3132. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  3133. if (AdapterJS.options.hidePluginInstallPrompt) {
  3134. return;
  3135. }
  3136. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3137. if(downloadLink) { // if download link
  3138. var popupString;
  3139. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3140. popupString = 'This website requires you to install the ' +
  3141. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3142. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3143. ' WebRTC Plugin</a>' +
  3144. ' to work on this browser.';
  3145. } else { // no portal link, just print a generic explanation
  3146. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3147. }
  3148. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3149. } else { // no download link, just print a generic explanation
  3150. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3151. }
  3152. };
  3153. // Try to detect the plugin and act accordingly
  3154. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3155. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3156. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3157. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3158. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3159. }
  3160. }).call(this,"/modules/RTC/adapter.screenshare.js")
  3161. },{"jitsi-meet-logger":44}],17:[function(require,module,exports){
  3162. (function (__filename){
  3163. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  3164. getUserMediaWithConstraints */
  3165. /**
  3166. * Indicates that desktop stream is currently in use(for toggle purpose).
  3167. * @type {boolean}
  3168. */
  3169. var isUsingScreenStream = false;
  3170. /**
  3171. * Indicates that switch stream operation is in progress and prevent from
  3172. * triggering new events.
  3173. * @type {boolean}
  3174. */
  3175. var switchInProgress = false;
  3176. /**
  3177. * Method used to get screen sharing stream.
  3178. *
  3179. * @type {function (stream_callback, failure_callback}
  3180. */
  3181. var obtainDesktopStream = null;
  3182. /**
  3183. * Indicates whether desktop sharing extension is installed.
  3184. * @type {boolean}
  3185. */
  3186. var extInstalled = false;
  3187. /**
  3188. * Indicates whether update of desktop sharing extension is required.
  3189. * @type {boolean}
  3190. */
  3191. var extUpdateRequired = false;
  3192. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3193. var AdapterJS = require("../RTC/adapter.screenshare");
  3194. var EventEmitter = require("events");
  3195. var eventEmitter = new EventEmitter();
  3196. var DesktopSharingEventTypes
  3197. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3198. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3199. var RTCEvents = require("../../service/RTC/RTCEvents");
  3200. /**
  3201. * Method obtains desktop stream from WebRTC 'screen' source.
  3202. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  3203. */
  3204. function obtainWebRTCScreen(streamCallback, failCallback) {
  3205. APP.RTC.getUserMediaWithConstraints(
  3206. ['screen'],
  3207. streamCallback,
  3208. failCallback
  3209. );
  3210. }
  3211. /**
  3212. * Constructs inline install URL for Chrome desktop streaming extension.
  3213. * The 'chromeExtensionId' must be defined in config.js.
  3214. * @returns {string}
  3215. */
  3216. function getWebStoreInstallUrl()
  3217. {
  3218. return "https://chrome.google.com/webstore/detail/" +
  3219. config.chromeExtensionId;
  3220. }
  3221. /**
  3222. * Checks whether extension update is required.
  3223. * @param minVersion minimal required version
  3224. * @param extVersion current extension version
  3225. * @returns {boolean}
  3226. */
  3227. function isUpdateRequired(minVersion, extVersion)
  3228. {
  3229. try
  3230. {
  3231. var s1 = minVersion.split('.');
  3232. var s2 = extVersion.split('.');
  3233. var len = Math.max(s1.length, s2.length);
  3234. for (var i = 0; i < len; i++)
  3235. {
  3236. var n1 = 0,
  3237. n2 = 0;
  3238. if (i < s1.length)
  3239. n1 = parseInt(s1[i]);
  3240. if (i < s2.length)
  3241. n2 = parseInt(s2[i]);
  3242. if (isNaN(n1) || isNaN(n2))
  3243. {
  3244. return true;
  3245. }
  3246. else if (n1 !== n2)
  3247. {
  3248. return n1 > n2;
  3249. }
  3250. }
  3251. // will happen if boths version has identical numbers in
  3252. // their components (even if one of them is longer, has more components)
  3253. return false;
  3254. }
  3255. catch (e)
  3256. {
  3257. logger.error("Failed to parse extension version", e);
  3258. APP.UI.messageHandler.showError("dialog.error",
  3259. "dialog.detectext");
  3260. return true;
  3261. }
  3262. }
  3263. function checkChromeExtInstalled(callback) {
  3264. if (!chrome.runtime) {
  3265. // No API, so no extension for sure
  3266. callback(false, false);
  3267. return;
  3268. }
  3269. chrome.runtime.sendMessage(
  3270. config.chromeExtensionId,
  3271. { getVersion: true },
  3272. function (response) {
  3273. if (!response || !response.version) {
  3274. // Communication failure - assume that no endpoint exists
  3275. logger.warn(
  3276. "Extension not installed?: ", chrome.runtime.lastError);
  3277. callback(false, false);
  3278. return;
  3279. }
  3280. // Check installed extension version
  3281. var extVersion = response.version;
  3282. logger.log('Extension version is: ' + extVersion);
  3283. var updateRequired
  3284. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  3285. callback(!updateRequired, updateRequired);
  3286. }
  3287. );
  3288. }
  3289. function doGetStreamFromExtension(streamCallback, failCallback) {
  3290. // Sends 'getStream' msg to the extension.
  3291. // Extension id must be defined in the config.
  3292. chrome.runtime.sendMessage(
  3293. config.chromeExtensionId,
  3294. { getStream: true, sources: config.desktopSharingSources },
  3295. function (response) {
  3296. if (!response) {
  3297. failCallback(chrome.runtime.lastError);
  3298. return;
  3299. }
  3300. logger.log("Response from extension: " + response);
  3301. if (response.streamId) {
  3302. APP.RTC.getUserMediaWithConstraints(
  3303. ['desktop'],
  3304. function (stream) {
  3305. streamCallback(stream);
  3306. },
  3307. failCallback,
  3308. null, null, null,
  3309. response.streamId);
  3310. } else {
  3311. failCallback("Extension failed to get the stream");
  3312. }
  3313. }
  3314. );
  3315. }
  3316. /**
  3317. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3318. * stream for returned stream token.
  3319. */
  3320. function obtainScreenFromExtension(streamCallback, failCallback) {
  3321. if (extInstalled) {
  3322. doGetStreamFromExtension(streamCallback, failCallback);
  3323. } else {
  3324. if (extUpdateRequired) {
  3325. alert(
  3326. 'Jitsi Desktop Streamer requires update. ' +
  3327. 'Changes will take effect after next Chrome restart.');
  3328. }
  3329. chrome.webstore.install(
  3330. getWebStoreInstallUrl(),
  3331. function (arg) {
  3332. logger.log("Extension installed successfully", arg);
  3333. extInstalled = true;
  3334. // We need to give a moment for the endpoint to become available
  3335. window.setTimeout(function () {
  3336. doGetStreamFromExtension(streamCallback, failCallback);
  3337. }, 500);
  3338. },
  3339. function (arg) {
  3340. logger.log("Failed to install the extension", arg);
  3341. failCallback(arg);
  3342. APP.UI.messageHandler.showError("dialog.error",
  3343. "dialog.failtoinstall");
  3344. }
  3345. );
  3346. }
  3347. }
  3348. /**
  3349. * Call this method to toggle desktop sharing feature.
  3350. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  3351. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  3352. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  3353. * enabled), pass any other string or nothing in order to disable this
  3354. * feature completely.
  3355. */
  3356. function setDesktopSharing(method) {
  3357. obtainDesktopStream = null;
  3358. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  3359. // care about 'method' parameter
  3360. if (RTCBrowserType.isTemasysPluginUsed()) {
  3361. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3362. logger.info("Screensharing not supported by this plugin version");
  3363. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3364. logger.info(
  3365. "Screensharing not available with Temasys plugin on this site");
  3366. } else {
  3367. obtainDesktopStream = obtainWebRTCScreen;
  3368. logger.info("Using Temasys plugin for desktop sharing");
  3369. }
  3370. } else if (RTCBrowserType.isChrome()) {
  3371. if (method == "ext") {
  3372. if (RTCBrowserType.getChromeVersion() >= 34) {
  3373. obtainDesktopStream = obtainScreenFromExtension;
  3374. logger.info("Using Chrome extension for desktop sharing");
  3375. initChromeExtension();
  3376. } else {
  3377. logger.info("Chrome extension not supported until ver 34");
  3378. }
  3379. } else if (method == "webrtc") {
  3380. obtainDesktopStream = obtainWebRTCScreen;
  3381. logger.info("Using Chrome WebRTC for desktop sharing");
  3382. }
  3383. }
  3384. if (!obtainDesktopStream) {
  3385. logger.info("Desktop sharing disabled");
  3386. }
  3387. }
  3388. /**
  3389. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3390. * config.js to support inline installs. Host site must be selected as main
  3391. * website of published extension.
  3392. */
  3393. function initInlineInstalls()
  3394. {
  3395. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3396. }
  3397. function initChromeExtension() {
  3398. // Initialize Chrome extension inline installs
  3399. initInlineInstalls();
  3400. // Check if extension is installed
  3401. checkChromeExtInstalled(function (installed, updateRequired) {
  3402. extInstalled = installed;
  3403. extUpdateRequired = updateRequired;
  3404. logger.info(
  3405. "Chrome extension installed: " + extInstalled +
  3406. " updateRequired: " + extUpdateRequired);
  3407. });
  3408. }
  3409. function getVideoStreamFailed(error) {
  3410. logger.error("Failed to obtain the stream to switch to", error);
  3411. switchInProgress = false;
  3412. isUsingScreenStream = false;
  3413. newStreamCreated(null);
  3414. }
  3415. function getDesktopStreamFailed(error) {
  3416. logger.error("Failed to obtain the stream to switch to", error);
  3417. switchInProgress = false;
  3418. }
  3419. function streamSwitchDone() {
  3420. switchInProgress = false;
  3421. eventEmitter.emit(
  3422. DesktopSharingEventTypes.SWITCHING_DONE,
  3423. isUsingScreenStream);
  3424. }
  3425. function newStreamCreated(stream)
  3426. {
  3427. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3428. stream, isUsingScreenStream, streamSwitchDone);
  3429. }
  3430. function onEndedHandler(stream) {
  3431. if (!switchInProgress && isUsingScreenStream) {
  3432. APP.desktopsharing.toggleScreenSharing();
  3433. }
  3434. //FIXME: to be verified
  3435. if (stream.removeEventListener) {
  3436. stream.removeEventListener('ended', onEndedHandler);
  3437. } else {
  3438. stream.detachEvent('ended', onEndedHandler);
  3439. }
  3440. }
  3441. // Called when RTC finishes initialization
  3442. function onWebRtcReady() {
  3443. setDesktopSharing(config.desktopSharing);
  3444. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3445. }
  3446. module.exports = {
  3447. isUsingScreenStream: function () {
  3448. return isUsingScreenStream;
  3449. },
  3450. /**
  3451. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3452. * and enabled.
  3453. */
  3454. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  3455. init: function () {
  3456. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  3457. },
  3458. addListener: function (listener, type)
  3459. {
  3460. eventEmitter.on(type, listener);
  3461. },
  3462. removeListener: function (listener, type) {
  3463. eventEmitter.removeListener(type, listener);
  3464. },
  3465. /*
  3466. * Toggles screen sharing.
  3467. */
  3468. toggleScreenSharing: function () {
  3469. if (switchInProgress || !obtainDesktopStream) {
  3470. logger.warn("Switch in progress or no method defined");
  3471. return;
  3472. }
  3473. switchInProgress = true;
  3474. if (!isUsingScreenStream)
  3475. {
  3476. // Switch to desktop stream
  3477. obtainDesktopStream(
  3478. function (stream) {
  3479. // We now use screen stream
  3480. isUsingScreenStream = true;
  3481. // Hook 'ended' event to restore camera
  3482. // when screen stream stops
  3483. //FIXME: to be verified
  3484. if (stream.addEventListener) {
  3485. stream.addEventListener('ended', function () {
  3486. onEndedHandler(stream);
  3487. });
  3488. } else {
  3489. stream.attachEvent('ended', function () {
  3490. onEndedHandler(stream);
  3491. });
  3492. }
  3493. newStreamCreated(stream);
  3494. },
  3495. getDesktopStreamFailed);
  3496. } else {
  3497. // Disable screen stream
  3498. APP.RTC.getUserMediaWithConstraints(
  3499. ['video'],
  3500. function (stream) {
  3501. // We are now using camera stream
  3502. isUsingScreenStream = false;
  3503. newStreamCreated(stream);
  3504. },
  3505. getVideoStreamFailed, config.resolution || '360'
  3506. );
  3507. }
  3508. }
  3509. };
  3510. }).call(this,"/modules/desktopsharing/desktopsharing.js")
  3511. },{"../../service/RTC/RTCEvents":76,"../../service/desktopsharing/DesktopSharingEventTypes":80,"../RTC/RTCBrowserType":14,"../RTC/adapter.screenshare":16,"events":40,"jitsi-meet-logger":44}],18:[function(require,module,exports){
  3512. (function (__filename){
  3513. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3514. function supportsLocalStorage() {
  3515. try {
  3516. return 'localStorage' in window && window.localStorage !== null;
  3517. } catch (e) {
  3518. logger.log("localstorage is not supported");
  3519. return false;
  3520. }
  3521. }
  3522. function generateUniqueId() {
  3523. function _p8() {
  3524. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3525. }
  3526. return _p8() + _p8() + _p8() + _p8();
  3527. }
  3528. function Settings(conferenceID) {
  3529. this.email = '';
  3530. this.displayName = '';
  3531. this.userId;
  3532. this.language = null;
  3533. this.confSettings = null;
  3534. this.conferenceID = conferenceID;
  3535. if (supportsLocalStorage()) {
  3536. if(!window.localStorage.getItem(conferenceID))
  3537. this.confSettings = {};
  3538. else
  3539. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3540. if(!this.confSettings.jitsiMeetId) {
  3541. this.confSettings.jitsiMeetId = generateUniqueId();
  3542. logger.log("generated id",
  3543. this.confSettings.jitsiMeetId);
  3544. this.save();
  3545. }
  3546. this.userId = this.confSettings.jitsiMeetId || '';
  3547. this.email = this.confSettings.email || '';
  3548. this.displayName = this.confSettings.displayname || '';
  3549. this.language = this.confSettings.language;
  3550. } else {
  3551. logger.log("local storage is not supported");
  3552. this.userId = generateUniqueId();
  3553. }
  3554. }
  3555. Settings.prototype.save = function () {
  3556. if(!supportsLocalStorage())
  3557. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3558. }
  3559. Settings.prototype.setDisplayName = function (newDisplayName) {
  3560. this.displayName = newDisplayName;
  3561. if(this.confSettings != null)
  3562. this.confSettings.displayname = displayName;
  3563. this.save();
  3564. return this.displayName;
  3565. },
  3566. Settings.prototype.setEmail = function (newEmail) {
  3567. this.email = newEmail;
  3568. if(this.confSettings != null)
  3569. this.confSettings.email = newEmail;
  3570. this.save();
  3571. return this.email;
  3572. },
  3573. Settings.prototype.getSettings = function () {
  3574. return {
  3575. email: this.email,
  3576. displayName: this.displayName,
  3577. uid: this.userId,
  3578. language: this.language
  3579. };
  3580. },
  3581. Settings.prototype.setLanguage = function (lang) {
  3582. this.language = lang;
  3583. if(this.confSettings != null)
  3584. this.confSettings.language = lang;
  3585. this.save();
  3586. }
  3587. module.exports = Settings;
  3588. }).call(this,"/modules/settings/Settings.js")
  3589. },{"jitsi-meet-logger":44}],19:[function(require,module,exports){
  3590. /* global config */
  3591. /**
  3592. * Provides statistics for the local stream.
  3593. */
  3594. var RTCBrowserType = require('../RTC/RTCBrowserType');
  3595. var LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  3596. /**
  3597. * Size of the webaudio analyzer buffer.
  3598. * @type {number}
  3599. */
  3600. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  3601. /**
  3602. * Value of the webaudio analyzer smoothing time parameter.
  3603. * @type {number}
  3604. */
  3605. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  3606. /**
  3607. * Converts time domain data array to audio level.
  3608. * @param samples the time domain data array.
  3609. * @returns {number} the audio level
  3610. */
  3611. function timeDomainDataToAudioLevel(samples) {
  3612. var maxVolume = 0;
  3613. var length = samples.length;
  3614. for (var i = 0; i < length; i++) {
  3615. if (maxVolume < samples[i])
  3616. maxVolume = samples[i];
  3617. }
  3618. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  3619. }
  3620. /**
  3621. * Animates audio level change
  3622. * @param newLevel the new audio level
  3623. * @param lastLevel the last audio level
  3624. * @returns {Number} the audio level to be set
  3625. */
  3626. function animateLevel(newLevel, lastLevel) {
  3627. var value = 0;
  3628. var diff = lastLevel - newLevel;
  3629. if(diff > 0.2) {
  3630. value = lastLevel - 0.2;
  3631. }
  3632. else if(diff < -0.4) {
  3633. value = lastLevel + 0.4;
  3634. }
  3635. else {
  3636. value = newLevel;
  3637. }
  3638. return parseFloat(value.toFixed(3));
  3639. }
  3640. /**
  3641. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  3642. *
  3643. * @param stream the local stream
  3644. * @param interval stats refresh interval given in ms.
  3645. * @constructor
  3646. */
  3647. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  3648. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  3649. this.stream = stream;
  3650. this.intervalId = null;
  3651. this.intervalMilis = interval;
  3652. this.eventEmitter = eventEmitter;
  3653. this.audioLevel = 0;
  3654. this.statisticsService = statisticsService;
  3655. }
  3656. /**
  3657. * Starts the collecting the statistics.
  3658. */
  3659. LocalStatsCollector.prototype.start = function () {
  3660. if (!window.AudioContext ||
  3661. RTCBrowserType.isTemasysPluginUsed())
  3662. return;
  3663. var context = new AudioContext();
  3664. var analyser = context.createAnalyser();
  3665. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  3666. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  3667. var source = context.createMediaStreamSource(this.stream);
  3668. source.connect(analyser);
  3669. var self = this;
  3670. this.intervalId = setInterval(
  3671. function () {
  3672. var array = new Uint8Array(analyser.frequencyBinCount);
  3673. analyser.getByteTimeDomainData(array);
  3674. var audioLevel = timeDomainDataToAudioLevel(array);
  3675. if (audioLevel != self.audioLevel) {
  3676. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  3677. self.eventEmitter.emit(
  3678. "statistics.audioLevel",
  3679. LOCAL_JID,
  3680. self.audioLevel);
  3681. }
  3682. },
  3683. this.intervalMilis
  3684. );
  3685. };
  3686. /**
  3687. * Stops collecting the statistics.
  3688. */
  3689. LocalStatsCollector.prototype.stop = function () {
  3690. if (this.intervalId) {
  3691. clearInterval(this.intervalId);
  3692. this.intervalId = null;
  3693. }
  3694. };
  3695. module.exports = LocalStatsCollector;
  3696. },{"../../service/statistics/constants":81,"../RTC/RTCBrowserType":14}],20:[function(require,module,exports){
  3697. (function (__filename){
  3698. /* global require, ssrc2jid */
  3699. /* jshint -W117 */
  3700. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3701. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3702. /* Whether we support the browser we are running into for logging statistics */
  3703. var browserSupported = RTCBrowserType.isChrome() ||
  3704. RTCBrowserType.isOpera();
  3705. var keyMap = {};
  3706. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  3707. "ssrc": "ssrc",
  3708. "packetsReceived": "packetsReceived",
  3709. "packetsLost": "packetsLost",
  3710. "packetsSent": "packetsSent",
  3711. "bytesReceived": "bytesReceived",
  3712. "bytesSent": "bytesSent"
  3713. };
  3714. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  3715. "receiveBandwidth": "googAvailableReceiveBandwidth",
  3716. "sendBandwidth": "googAvailableSendBandwidth",
  3717. "remoteAddress": "googRemoteAddress",
  3718. "transportType": "googTransportType",
  3719. "localAddress": "googLocalAddress",
  3720. "activeConnection": "googActiveConnection",
  3721. "ssrc": "ssrc",
  3722. "packetsReceived": "packetsReceived",
  3723. "packetsSent": "packetsSent",
  3724. "packetsLost": "packetsLost",
  3725. "bytesReceived": "bytesReceived",
  3726. "bytesSent": "bytesSent",
  3727. "googFrameHeightReceived": "googFrameHeightReceived",
  3728. "googFrameWidthReceived": "googFrameWidthReceived",
  3729. "googFrameHeightSent": "googFrameHeightSent",
  3730. "googFrameWidthSent": "googFrameWidthSent",
  3731. "audioInputLevel": "audioInputLevel",
  3732. "audioOutputLevel": "audioOutputLevel"
  3733. };
  3734. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  3735. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  3736. /**
  3737. * Calculates packet lost percent using the number of lost packets and the
  3738. * number of all packet.
  3739. * @param lostPackets the number of lost packets
  3740. * @param totalPackets the number of all packets.
  3741. * @returns {number} packet loss percent
  3742. */
  3743. function calculatePacketLoss(lostPackets, totalPackets) {
  3744. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  3745. return 0;
  3746. return Math.round((lostPackets/totalPackets)*100);
  3747. }
  3748. function getStatValue(item, name) {
  3749. var browserType = RTCBrowserType.getBrowserType();
  3750. if (!keyMap[browserType][name])
  3751. throw "The property isn't supported!";
  3752. var key = keyMap[browserType][name];
  3753. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  3754. item.stat(key) : item[key];
  3755. }
  3756. function formatAudioLevel(audioLevel) {
  3757. return Math.min(Math.max(audioLevel, 0), 1);
  3758. }
  3759. /**
  3760. * Checks whether a certain record should be included in the logged statistics.
  3761. */
  3762. function acceptStat(reportId, reportType, statName) {
  3763. if (reportType == "googCandidatePair" && statName == "googChannelId")
  3764. return false;
  3765. if (reportType == "ssrc") {
  3766. if (statName == "googTrackId" ||
  3767. statName == "transportId" ||
  3768. statName == "ssrc")
  3769. return false;
  3770. }
  3771. return true;
  3772. }
  3773. /**
  3774. * Checks whether a certain record should be included in the logged statistics.
  3775. */
  3776. function acceptReport(id, type) {
  3777. if (id.substring(0, 15) == "googCertificate" ||
  3778. id.substring(0, 9) == "googTrack" ||
  3779. id.substring(0, 20) == "googLibjingleSession")
  3780. return false;
  3781. if (type == "googComponent")
  3782. return false;
  3783. return true;
  3784. }
  3785. /**
  3786. * Peer statistics data holder.
  3787. * @constructor
  3788. */
  3789. function PeerStats()
  3790. {
  3791. this.ssrc2Loss = {};
  3792. this.ssrc2AudioLevel = {};
  3793. this.ssrc2bitrate = {};
  3794. this.ssrc2resolution = {};
  3795. }
  3796. /**
  3797. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  3798. * represented by this instance.
  3799. * @param lossRate new packet loss rate value to be set.
  3800. */
  3801. PeerStats.prototype.setSsrcLoss = function (lossRate)
  3802. {
  3803. this.ssrc2Loss = lossRate;
  3804. };
  3805. /**
  3806. * Sets resolution that belong to the ssrc
  3807. * represented by this instance.
  3808. * @param resolution new resolution value to be set.
  3809. */
  3810. PeerStats.prototype.setSsrcResolution = function (resolution)
  3811. {
  3812. if(resolution === null && this.ssrc2resolution[ssrc])
  3813. {
  3814. delete this.ssrc2resolution[ssrc];
  3815. }
  3816. else if(resolution !== null)
  3817. this.ssrc2resolution[ssrc] = resolution;
  3818. };
  3819. /**
  3820. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  3821. * represented by this instance.
  3822. * @param ssrc audio or video RTP stream SSRC.
  3823. * @param bitrate new bitrate value to be set.
  3824. */
  3825. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  3826. {
  3827. if(this.ssrc2bitrate[ssrc])
  3828. {
  3829. this.ssrc2bitrate[ssrc].download += bitrate.download;
  3830. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  3831. }
  3832. else {
  3833. this.ssrc2bitrate[ssrc] = bitrate;
  3834. }
  3835. };
  3836. /**
  3837. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  3838. * the stream which belongs to the peer represented by this instance.
  3839. * @param ssrc RTP stream SSRC for which current audio level value will be
  3840. * updated.
  3841. * @param audioLevel the new audio level value to be set. Value is truncated to
  3842. * fit the range from 0 to 1.
  3843. */
  3844. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  3845. {
  3846. // Range limit 0 - 1
  3847. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  3848. };
  3849. function ConferenceStats() {
  3850. /**
  3851. * The bandwidth
  3852. * @type {{}}
  3853. */
  3854. this.bandwidth = {};
  3855. /**
  3856. * The bit rate
  3857. * @type {{}}
  3858. */
  3859. this.bitrate = {};
  3860. /**
  3861. * The packet loss rate
  3862. * @type {{}}
  3863. */
  3864. this.packetLoss = null;
  3865. /**
  3866. * Array with the transport information.
  3867. * @type {Array}
  3868. */
  3869. this.transport = [];
  3870. }
  3871. /**
  3872. * <tt>StatsCollector</tt> registers for stats updates of given
  3873. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  3874. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  3875. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  3876. * instance as an event source.
  3877. *
  3878. * @param peerconnection webRTC peer connection object.
  3879. * @param interval stats refresh interval given in ms.
  3880. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  3881. * called on stats update.
  3882. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  3883. * @constructor
  3884. */
  3885. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  3886. {
  3887. this.peerconnection = peerconnection;
  3888. this.baselineAudioLevelsReport = null;
  3889. this.currentAudioLevelsReport = null;
  3890. this.currentStatsReport = null;
  3891. this.baselineStatsReport = null;
  3892. this.audioLevelsIntervalId = null;
  3893. this.eventEmitter = eventEmitter;
  3894. this.config = config || {};
  3895. this.conferenceStats = new ConferenceStats();
  3896. /**
  3897. * Gather PeerConnection stats once every this many milliseconds.
  3898. */
  3899. this.GATHER_INTERVAL = 15000;
  3900. /**
  3901. * Log stats via the focus once every this many milliseconds.
  3902. */
  3903. this.LOG_INTERVAL = 60000;
  3904. /**
  3905. * Gather stats and store them in this.statsToBeLogged.
  3906. */
  3907. this.gatherStatsIntervalId = null;
  3908. /**
  3909. * Send the stats already saved in this.statsToBeLogged to be logged via
  3910. * the focus.
  3911. */
  3912. this.logStatsIntervalId = null;
  3913. /**
  3914. * Stores the statistics which will be send to the focus to be logged.
  3915. */
  3916. this.statsToBeLogged =
  3917. {
  3918. timestamps: [],
  3919. stats: {}
  3920. };
  3921. // Updates stats interval
  3922. this.audioLevelsIntervalMilis = audioLevelsInterval;
  3923. this.statsIntervalId = null;
  3924. this.statsIntervalMilis = statsInterval;
  3925. // Map of ssrcs to PeerStats
  3926. this.ssrc2stats = {};
  3927. }
  3928. module.exports = StatsCollector;
  3929. /**
  3930. * Stops stats updates.
  3931. */
  3932. StatsCollector.prototype.stop = function () {
  3933. if (this.audioLevelsIntervalId) {
  3934. clearInterval(this.audioLevelsIntervalId);
  3935. this.audioLevelsIntervalId = null;
  3936. }
  3937. if (this.statsIntervalId)
  3938. {
  3939. clearInterval(this.statsIntervalId);
  3940. this.statsIntervalId = null;
  3941. }
  3942. if(this.logStatsIntervalId)
  3943. {
  3944. clearInterval(this.logStatsIntervalId);
  3945. this.logStatsIntervalId = null;
  3946. }
  3947. if(this.gatherStatsIntervalId)
  3948. {
  3949. clearInterval(this.gatherStatsIntervalId);
  3950. this.gatherStatsIntervalId = null;
  3951. }
  3952. };
  3953. /**
  3954. * Callback passed to <tt>getStats</tt> method.
  3955. * @param error an error that occurred on <tt>getStats</tt> call.
  3956. */
  3957. StatsCollector.prototype.errorCallback = function (error)
  3958. {
  3959. logger.error("Get stats error", error);
  3960. this.stop();
  3961. };
  3962. /**
  3963. * Starts stats updates.
  3964. */
  3965. StatsCollector.prototype.start = function ()
  3966. {
  3967. var self = this;
  3968. this.audioLevelsIntervalId = setInterval(
  3969. function () {
  3970. // Interval updates
  3971. self.peerconnection.getStats(
  3972. function (report) {
  3973. var results = null;
  3974. if (!report || !report.result ||
  3975. typeof report.result != 'function') {
  3976. results = report;
  3977. }
  3978. else {
  3979. results = report.result();
  3980. }
  3981. //logger.error("Got interval report", results);
  3982. self.currentAudioLevelsReport = results;
  3983. self.processAudioLevelReport();
  3984. self.baselineAudioLevelsReport =
  3985. self.currentAudioLevelsReport;
  3986. },
  3987. self.errorCallback
  3988. );
  3989. },
  3990. self.audioLevelsIntervalMilis
  3991. );
  3992. // if (!this.config.disableStats && browserSupported) {
  3993. // this.statsIntervalId = setInterval(
  3994. // function () {
  3995. // // Interval updates
  3996. // self.peerconnection.getStats(
  3997. // function (report) {
  3998. // var results = null;
  3999. // if (!report || !report.result ||
  4000. // typeof report.result != 'function') {
  4001. // //firefox
  4002. // results = report;
  4003. // }
  4004. // else {
  4005. // //chrome
  4006. // results = report.result();
  4007. // }
  4008. // //logger.error("Got interval report", results);
  4009. // self.currentStatsReport = results;
  4010. // try {
  4011. // self.processStatsReport();
  4012. // }
  4013. // catch (e) {
  4014. // logger.error("Unsupported key:" + e, e);
  4015. // }
  4016. //
  4017. // self.baselineStatsReport = self.currentStatsReport;
  4018. // },
  4019. // self.errorCallback
  4020. // );
  4021. // },
  4022. // self.statsIntervalMilis
  4023. // );
  4024. // }
  4025. //
  4026. // if (this.config.logStats && browserSupported) {
  4027. // this.gatherStatsIntervalId = setInterval(
  4028. // function () {
  4029. // self.peerconnection.getStats(
  4030. // function (report) {
  4031. // self.addStatsToBeLogged(report.result());
  4032. // },
  4033. // function () {
  4034. // }
  4035. // );
  4036. // },
  4037. // this.GATHER_INTERVAL
  4038. // );
  4039. //
  4040. // this.logStatsIntervalId = setInterval(
  4041. // function() { self.logStats(); },
  4042. // this.LOG_INTERVAL);
  4043. // }
  4044. };
  4045. /**
  4046. * Converts the stats to the format used for logging, and saves the data in
  4047. * this.statsToBeLogged.
  4048. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4049. */
  4050. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4051. var self = this;
  4052. var num_records = this.statsToBeLogged.timestamps.length;
  4053. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4054. reports.map(function (report) {
  4055. if (!acceptReport(report.id, report.type))
  4056. return;
  4057. var stat = self.statsToBeLogged.stats[report.id];
  4058. if (!stat) {
  4059. stat = self.statsToBeLogged.stats[report.id] = {};
  4060. }
  4061. stat.type = report.type;
  4062. report.names().map(function (name) {
  4063. if (!acceptStat(report.id, report.type, name))
  4064. return;
  4065. var values = stat[name];
  4066. if (!values) {
  4067. values = stat[name] = [];
  4068. }
  4069. while (values.length < num_records) {
  4070. values.push(null);
  4071. }
  4072. values.push(report.stat(name));
  4073. });
  4074. });
  4075. };
  4076. //FIXME:
  4077. //StatsCollector.prototype.logStats = function () {
  4078. //
  4079. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4080. // return;
  4081. // // Reset the stats
  4082. // this.statsToBeLogged.stats = {};
  4083. // this.statsToBeLogged.timestamps = [];
  4084. //};
  4085. /**
  4086. * Stats processing logic.
  4087. */
  4088. StatsCollector.prototype.processStatsReport = function () {
  4089. if (!this.baselineStatsReport) {
  4090. return;
  4091. }
  4092. for (var idx in this.currentStatsReport) {
  4093. var now = this.currentStatsReport[idx];
  4094. try {
  4095. if (getStatValue(now, 'receiveBandwidth') ||
  4096. getStatValue(now, 'sendBandwidth')) {
  4097. this.conferenceStats.bandwidth = {
  4098. "download": Math.round(
  4099. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4100. "upload": Math.round(
  4101. (getStatValue(now, 'sendBandwidth')) / 1000)
  4102. };
  4103. }
  4104. }
  4105. catch(e){/*not supported*/}
  4106. if(now.type == 'googCandidatePair')
  4107. {
  4108. var ip, type, localIP, active;
  4109. try {
  4110. ip = getStatValue(now, 'remoteAddress');
  4111. type = getStatValue(now, "transportType");
  4112. localIP = getStatValue(now, "localAddress");
  4113. active = getStatValue(now, "activeConnection");
  4114. }
  4115. catch(e){/*not supported*/}
  4116. if(!ip || !type || !localIP || active != "true")
  4117. continue;
  4118. var addressSaved = false;
  4119. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4120. {
  4121. if(this.conferenceStats.transport[i].ip == ip &&
  4122. this.conferenceStats.transport[i].type == type &&
  4123. this.conferenceStats.transport[i].localip == localIP)
  4124. {
  4125. addressSaved = true;
  4126. }
  4127. }
  4128. if(addressSaved)
  4129. continue;
  4130. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4131. continue;
  4132. }
  4133. if(now.type == "candidatepair")
  4134. {
  4135. if(now.state == "succeeded")
  4136. continue;
  4137. var local = this.currentStatsReport[now.localCandidateId];
  4138. var remote = this.currentStatsReport[now.remoteCandidateId];
  4139. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4140. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4141. }
  4142. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4143. now.type != "inboundrtp") {
  4144. continue;
  4145. }
  4146. var before = this.baselineStatsReport[idx];
  4147. if (!before) {
  4148. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4149. continue;
  4150. }
  4151. var ssrc = getStatValue(now, 'ssrc');
  4152. if(!ssrc)
  4153. continue;
  4154. var ssrcStats = this.ssrc2stats[ssrc];
  4155. if (!ssrcStats) {
  4156. ssrcStats = new PeerStats();
  4157. this.ssrc2stats[ssrc] = ssrcStats;
  4158. }
  4159. var isDownloadStream = true;
  4160. var key = 'packetsReceived';
  4161. if (!getStatValue(now, key))
  4162. {
  4163. isDownloadStream = false;
  4164. key = 'packetsSent';
  4165. if (!getStatValue(now, key))
  4166. {
  4167. logger.warn("No packetsReceived nor packetSent stat found");
  4168. continue;
  4169. }
  4170. }
  4171. var packetsNow = getStatValue(now, key);
  4172. if(!packetsNow || packetsNow < 0)
  4173. packetsNow = 0;
  4174. var packetsBefore = getStatValue(before, key);
  4175. if(!packetsBefore || packetsBefore < 0)
  4176. packetsBefore = 0;
  4177. var packetRate = packetsNow - packetsBefore;
  4178. if(!packetRate || packetRate < 0)
  4179. packetRate = 0;
  4180. var currentLoss = getStatValue(now, 'packetsLost');
  4181. if(!currentLoss || currentLoss < 0)
  4182. currentLoss = 0;
  4183. var previousLoss = getStatValue(before, 'packetsLost');
  4184. if(!previousLoss || previousLoss < 0)
  4185. previousLoss = 0;
  4186. var lossRate = currentLoss - previousLoss;
  4187. if(!lossRate || lossRate < 0)
  4188. lossRate = 0;
  4189. var packetsTotal = (packetRate + lossRate);
  4190. ssrcStats.setSsrcLoss(ssrc,
  4191. {"packetsTotal": packetsTotal,
  4192. "packetsLost": lossRate,
  4193. "isDownloadStream": isDownloadStream});
  4194. var bytesReceived = 0, bytesSent = 0;
  4195. if(getStatValue(now, "bytesReceived"))
  4196. {
  4197. bytesReceived = getStatValue(now, "bytesReceived") -
  4198. getStatValue(before, "bytesReceived");
  4199. }
  4200. if(getStatValue(now, "bytesSent"))
  4201. {
  4202. bytesSent = getStatValue(now, "bytesSent") -
  4203. getStatValue(before, "bytesSent");
  4204. }
  4205. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4206. if(bytesReceived <= 0 || time <= 0)
  4207. {
  4208. bytesReceived = 0;
  4209. }
  4210. else
  4211. {
  4212. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4213. }
  4214. if(bytesSent <= 0 || time <= 0)
  4215. {
  4216. bytesSent = 0;
  4217. }
  4218. else
  4219. {
  4220. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4221. }
  4222. ssrcStats.setSsrcBitrate(ssrc, {
  4223. "download": bytesReceived,
  4224. "upload": bytesSent});
  4225. var resolution = {height: null, width: null};
  4226. try {
  4227. if (getStatValue(now, "googFrameHeightReceived") &&
  4228. getStatValue(now, "googFrameWidthReceived")) {
  4229. resolution.height = getStatValue(now, "googFrameHeightReceived");
  4230. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4231. }
  4232. else if (getStatValue(now, "googFrameHeightSent") &&
  4233. getStatValue(now, "googFrameWidthSent")) {
  4234. resolution.height = getStatValue(now, "googFrameHeightSent");
  4235. resolution.width = getStatValue(now, "googFrameWidthSent");
  4236. }
  4237. }
  4238. catch(e){/*not supported*/}
  4239. if(resolution.height && resolution.width)
  4240. {
  4241. ssrcStats.setSsrcResolution(ssrc, resolution);
  4242. }
  4243. else
  4244. {
  4245. ssrcStats.setSsrcResolution(ssrc, null);
  4246. }
  4247. }
  4248. var self = this;
  4249. // Jid stats
  4250. var totalPackets = {download: 0, upload: 0};
  4251. var lostPackets = {download: 0, upload: 0};
  4252. var bitrateDownload = 0;
  4253. var bitrateUpload = 0;
  4254. var resolutions = {};
  4255. Object.keys(this.ssrc2stats).forEach(
  4256. function (jid)
  4257. {
  4258. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4259. function (ssrc)
  4260. {
  4261. var type = "upload";
  4262. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4263. type = "download";
  4264. totalPackets[type] +=
  4265. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4266. lostPackets[type] +=
  4267. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4268. }
  4269. );
  4270. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4271. function (ssrc) {
  4272. bitrateDownload +=
  4273. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4274. bitrateUpload +=
  4275. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4276. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4277. }
  4278. );
  4279. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4280. }
  4281. );
  4282. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4283. this.conferenceStats.packetLoss = {
  4284. total:
  4285. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4286. totalPackets.download + totalPackets.upload),
  4287. download:
  4288. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4289. upload:
  4290. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4291. };
  4292. this.eventEmitter.emit("statistics.connectionstats",
  4293. {
  4294. "bitrate": this.conferenceStats.bitrate,
  4295. "packetLoss": this.conferenceStats.packetLoss,
  4296. "bandwidth": this.conferenceStats.bandwidth,
  4297. "resolution": resolutions,
  4298. "transport": this.conferenceStats.transport
  4299. });
  4300. this.conferenceStats.transport = [];
  4301. };
  4302. /**
  4303. * Stats processing logic.
  4304. */
  4305. StatsCollector.prototype.processAudioLevelReport = function () {
  4306. if (!this.baselineAudioLevelsReport) {
  4307. return;
  4308. }
  4309. for (var idx in this.currentAudioLevelsReport) {
  4310. var now = this.currentAudioLevelsReport[idx];
  4311. //if we don't have "packetsReceived" this is local stream
  4312. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4313. continue;
  4314. }
  4315. var before = this.baselineAudioLevelsReport[idx];
  4316. if (!before) {
  4317. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4318. continue;
  4319. }
  4320. var ssrc = getStatValue(now, 'ssrc');
  4321. if (!ssrc) {
  4322. if((Date.now() - now.timestamp) < 3000)
  4323. logger.warn("No ssrc: ");
  4324. continue;
  4325. }
  4326. var ssrcStats = this.ssrc2stats[ssrc];
  4327. if (!ssrcStats) {
  4328. ssrcStats = new PeerStats();
  4329. this.ssrc2stats[ssrc] = ssrcStats;
  4330. }
  4331. // Audio level
  4332. var audioLevel = null;
  4333. try {
  4334. audioLevel = getStatValue(now, 'audioInputLevel');
  4335. if (!audioLevel)
  4336. audioLevel = getStatValue(now, 'audioOutputLevel');
  4337. }
  4338. catch(e) {/*not supported*/
  4339. logger.warn("Audio Levels are not available in the statistics.");
  4340. clearInterval(this.audioLevelsIntervalId);
  4341. return;
  4342. }
  4343. if (audioLevel) {
  4344. // TODO: can't find specs about what this value really is,
  4345. // but it seems to vary between 0 and around 32k.
  4346. audioLevel = audioLevel / 32767;
  4347. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4348. this.eventEmitter.emit("statistics.audioLevel", ssrc, audioLevel);
  4349. }
  4350. }
  4351. };
  4352. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4353. },{"../RTC/RTCBrowserType":14,"jitsi-meet-logger":44}],21:[function(require,module,exports){
  4354. /* global require, APP */
  4355. var LocalStats = require("./LocalStatsCollector.js");
  4356. var RTPStats = require("./RTPStatsCollector.js");
  4357. var EventEmitter = require("events");
  4358. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4359. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4360. //var CallStats = require("./CallStats");
  4361. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4362. //
  4363. //function onDisposeConference(onUnload) {
  4364. // CallStats.sendTerminateEvent();
  4365. // stopRemote();
  4366. // if(onUnload) {
  4367. // stopLocal();
  4368. // eventEmitter.removeAllListeners();
  4369. // }
  4370. //}
  4371. function Statistics() {
  4372. this.localStats = null;
  4373. this.rtpStats = null;
  4374. this.eventEmitter = new EventEmitter();
  4375. }
  4376. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4377. if (this.rtpStats) {
  4378. this.rtpStats.stop();
  4379. }
  4380. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4381. this.rtpStats.start();
  4382. }
  4383. Statistics.prototype.startLocalStats = function (stream) {
  4384. if(stream.getType() !== "audio")
  4385. return;
  4386. this.localStats = new LocalStats(stream.getOriginalStream(), 200, this,
  4387. this.eventEmitter);
  4388. this.localStats.start();
  4389. }
  4390. Statistics.prototype.addAudioLevelListener = function(listener)
  4391. {
  4392. this.eventEmitter.on("statistics.audioLevel", listener);
  4393. }
  4394. Statistics.prototype.removeAudioLevelListener = function(listener)
  4395. {
  4396. this.eventEmitter.removeListener("statistics.audioLevel", listener);
  4397. }
  4398. Statistics.prototype.dispose = function () {
  4399. this.stopLocal();
  4400. this.stopRemote();
  4401. if(this.eventEmitter)
  4402. {
  4403. this.eventEmitter.removeAllListeners();
  4404. }
  4405. }
  4406. Statistics.prototype.stopLocal = function () {
  4407. if (this.localStats) {
  4408. this.localStats.stop();
  4409. this.localStats = null;
  4410. }
  4411. }
  4412. Statistics.prototype.stopRemote = function () {
  4413. if (this.rtpStats) {
  4414. this.rtpStats.stop();
  4415. this.eventEmitter.emit("statistics.stop");
  4416. this.rtpStats = null;
  4417. }
  4418. }
  4419. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  4420. //
  4421. //var statistics = {
  4422. // /**
  4423. // * Indicates that this audio level is for local jid.
  4424. // * @type {string}
  4425. // */
  4426. // LOCAL_JID: 'local',
  4427. //
  4428. // addConnectionStatsListener: function(listener)
  4429. // {
  4430. // eventEmitter.on("statistics.connectionstats", listener);
  4431. // },
  4432. //
  4433. // removeConnectionStatsListener: function(listener)
  4434. // {
  4435. // eventEmitter.removeListener("statistics.connectionstats", listener);
  4436. // },
  4437. //
  4438. //
  4439. // addRemoteStatsStopListener: function(listener)
  4440. // {
  4441. // eventEmitter.on("statistics.stop", listener);
  4442. // },
  4443. //
  4444. // removeRemoteStatsStopListener: function(listener)
  4445. // {
  4446. // eventEmitter.removeListener("statistics.stop", listener);
  4447. // },
  4448. //
  4449. //
  4450. // stopRemoteStatistics: function()
  4451. // {
  4452. // stopRemote();
  4453. // },
  4454. //
  4455. //// Already implemented with the constructor
  4456. // start: function () {
  4457. // APP.RTC.addStreamListener(onStreamCreated,
  4458. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  4459. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  4460. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  4461. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  4462. // startRemoteStats(event.peerconnection);
  4463. //// CallStats.init(event);
  4464. // });
  4465. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  4466. //// CallStats.init(session);
  4467. //// });
  4468. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4469. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  4470. //// CallStats.sendMuteEvent(mute, "audio");
  4471. //// });
  4472. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  4473. //// CallStats.sendSetupFailedEvent();
  4474. //// });
  4475. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4476. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  4477. //// CallStats.sendMuteEvent(mute, "video");
  4478. //// });
  4479. // }
  4480. //};
  4481. module.exports = Statistics;
  4482. },{"../../service/statistics/constants":81,"./LocalStatsCollector.js":19,"./RTPStatsCollector.js":20,"events":40}],22:[function(require,module,exports){
  4483. /**
  4484. * Generates random hex number within the range [min, max]
  4485. * @param max the maximum value for the generated number
  4486. * @param min the minimum value for the generated number
  4487. * @returns random hex number
  4488. */
  4489. function rangeRandomHex(min, max)
  4490. {
  4491. return Math.floor(Math.random() * (max - min) + min).toString(16);
  4492. }
  4493. /**
  4494. * Exported interface.
  4495. */
  4496. var RandomUtil = {
  4497. /**
  4498. * Generates hex number with length 4
  4499. */
  4500. random4digitsHex: function() {
  4501. return rangeRandomHex(4096, 65535);
  4502. },
  4503. /**
  4504. * Generates hex number with length 8
  4505. */
  4506. random8digitsHex: function() {
  4507. return rangeRandomHex(268435456, 4294967295);
  4508. },
  4509. /**
  4510. * Generates hex number with length 12
  4511. */
  4512. random12digitsHex: function() {
  4513. return rangeRandomHex(17592186044416, 281474976710655);
  4514. }
  4515. };
  4516. module.exports = RandomUtil;
  4517. },{}],23:[function(require,module,exports){
  4518. (function (__filename){
  4519. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4520. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4521. var Moderator = require("./moderator");
  4522. var EventEmitter = require("events");
  4523. var parser = {
  4524. packet2JSON: function (packet, nodes) {
  4525. var self = this;
  4526. $(packet).children().each(function (index) {
  4527. var tagName = $(this).prop("tagName");
  4528. var node = {}
  4529. node["tagName"] = tagName;
  4530. node.attributes = {};
  4531. $($(this)[0].attributes).each(function( index, attr ) {
  4532. node.attributes[ attr.name ] = attr.value;
  4533. } );
  4534. var text = Strophe.getText($(this)[0]);
  4535. if(text)
  4536. node.value = text;
  4537. node.children = [];
  4538. nodes.push(node);
  4539. self.packet2JSON($(this), node.children);
  4540. })
  4541. },
  4542. JSON2packet: function (nodes, packet) {
  4543. for(var i = 0; i < nodes.length; i++)
  4544. {
  4545. var node = nodes[i];
  4546. if(!node || node === null){
  4547. continue;
  4548. }
  4549. packet.c(node.tagName, node.attributes);
  4550. if(node.value)
  4551. packet.t(node.value);
  4552. if(node.children)
  4553. this.JSON2packet(node.children, packet);
  4554. packet.up();
  4555. }
  4556. // packet.up();
  4557. }
  4558. };
  4559. /**
  4560. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  4561. * @param pres the presence JSON
  4562. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  4563. */
  4564. function filterNodeFromPresenceJSON(pres, nodeName){
  4565. var res = [];
  4566. for(var i = 0; i < pres.length; i++)
  4567. if(pres[i].tagName === nodeName)
  4568. res.push(pres[i]);
  4569. return res;
  4570. }
  4571. function ChatRoom(connection, jid, password, XMPP, options) {
  4572. this.eventEmitter = new EventEmitter();
  4573. this.xmpp = XMPP;
  4574. this.connection = connection;
  4575. this.roomjid = Strophe.getBareJidFromJid(jid);
  4576. this.myroomjid = jid;
  4577. this.password = password;
  4578. logger.info("Joined MUC as " + this.myroomjid);
  4579. this.members = {};
  4580. this.presMap = {};
  4581. this.presHandlers = {};
  4582. this.joined = false;
  4583. this.role = null;
  4584. this.focusMucJid = null;
  4585. this.bridgeIsDown = false;
  4586. this.options = options || {};
  4587. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  4588. this.initPresenceMap();
  4589. this.session = null;
  4590. var self = this;
  4591. this.lastPresences = {};
  4592. }
  4593. ChatRoom.prototype.initPresenceMap = function () {
  4594. this.presMap['to'] = this.myroomjid;
  4595. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  4596. this.presMap["nodes"] = [];
  4597. this.presMap["nodes"].push( {
  4598. "tagName": "user-agent",
  4599. "value": navigator.userAgent,
  4600. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  4601. });
  4602. };
  4603. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  4604. this.presMap["nodes"].push( {
  4605. "tagName": "devices",
  4606. "children": [
  4607. {
  4608. "tagName": "audio",
  4609. "value": devices.audio,
  4610. },
  4611. {
  4612. "tagName": "video",
  4613. "value": devices.video,
  4614. }
  4615. ]
  4616. });
  4617. }
  4618. ChatRoom.prototype.join = function (password, tokenPassword) {
  4619. if(password)
  4620. this.password = password;
  4621. var self = this;
  4622. this.moderator.allocateConferenceFocus(function()
  4623. {
  4624. self.sendPresence(tokenPassword);
  4625. }.bind(this));
  4626. };
  4627. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  4628. if (!this.presMap['to']) {
  4629. // Too early to send presence - not initialized
  4630. return;
  4631. }
  4632. var pres = $pres({to: this.presMap['to'] });
  4633. pres.c('x', {xmlns: this.presMap['xns']});
  4634. if (this.password) {
  4635. pres.c('password').t(this.password).up();
  4636. }
  4637. pres.up();
  4638. // Send XEP-0115 'c' stanza that contains our capabilities info
  4639. if (this.connection.caps) {
  4640. this.connection.caps.node = this.xmpp.options.clientNode;
  4641. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  4642. }
  4643. if (tokenPassword) {
  4644. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  4645. .t(tokenPassword).up();
  4646. }
  4647. parser.JSON2packet(this.presMap.nodes, pres);
  4648. this.connection.send(pres);
  4649. };
  4650. ChatRoom.prototype.doLeave = function () {
  4651. logger.log("do leave", this.myroomjid);
  4652. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  4653. this.presMap.length = 0;
  4654. this.connection.send(pres);
  4655. };
  4656. ChatRoom.prototype.createNonAnonymousRoom = function () {
  4657. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  4658. var getForm = $iq({type: 'get', to: this.roomjid})
  4659. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  4660. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  4661. var self = this;
  4662. this.connection.sendIQ(getForm, function (form) {
  4663. if (!$(form).find(
  4664. '>query>x[xmlns="jabber:x:data"]' +
  4665. '>field[var="muc#roomconfig_whois"]').length) {
  4666. logger.error('non-anonymous rooms not supported');
  4667. return;
  4668. }
  4669. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  4670. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  4671. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  4672. formSubmit.c('field', {'var': 'FORM_TYPE'})
  4673. .c('value')
  4674. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  4675. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  4676. .c('value').t('anyone').up().up();
  4677. self.connection.sendIQ(formSubmit);
  4678. }, function (error) {
  4679. logger.error("Error getting room configuration form");
  4680. });
  4681. };
  4682. ChatRoom.prototype.onPresence = function (pres) {
  4683. var from = pres.getAttribute('from');
  4684. // Parse roles.
  4685. var member = {};
  4686. member.show = $(pres).find('>show').text();
  4687. member.status = $(pres).find('>status').text();
  4688. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  4689. member.affiliation = tmp.attr('affiliation');
  4690. member.role = tmp.attr('role');
  4691. // Focus recognition
  4692. member.jid = tmp.attr('jid');
  4693. member.isFocus = false;
  4694. if (member.jid
  4695. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  4696. member.isFocus = true;
  4697. }
  4698. $(pres).find(">x").remove();
  4699. var nodes = [];
  4700. parser.packet2JSON(pres, nodes);
  4701. this.lastPresences[from] = nodes;
  4702. for(var i = 0; i < nodes.length; i++)
  4703. {
  4704. var node = nodes[i];
  4705. switch(node.tagName)
  4706. {
  4707. case "nick":
  4708. member.nick = node.value;
  4709. if(!member.isFocus) {
  4710. var displayName = !this.xmpp.options.displayJids
  4711. ? member.nick : Strophe.getResourceFromJid(from);
  4712. if (displayName && displayName.length > 0) {
  4713. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  4714. }
  4715. logger.info("Display name: " + displayName, pres);
  4716. }
  4717. break;
  4718. case "userId":
  4719. member.id = node.value;
  4720. break;
  4721. case "email":
  4722. member.email = node.value;
  4723. break;
  4724. case "bridgeIsDown":
  4725. if(!this.bridgeIsDown) {
  4726. this.bridgeIsDown = true;
  4727. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  4728. }
  4729. break;
  4730. default :
  4731. this.processNode(node, from);
  4732. }
  4733. }
  4734. if (from == this.myroomjid) {
  4735. if (member.affiliation == 'owner')
  4736. if (this.role !== member.role) {
  4737. this.role = member.role;
  4738. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  4739. member, this.isModerator());
  4740. }
  4741. if (!this.joined) {
  4742. this.joined = true;
  4743. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  4744. }
  4745. } else if (this.members[from] === undefined) {
  4746. // new participant
  4747. this.members[from] = member;
  4748. logger.log('entered', from, member);
  4749. if (member.isFocus) {
  4750. this.focusMucJid = from;
  4751. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  4752. }
  4753. else {
  4754. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  4755. }
  4756. } else {
  4757. // Presence update for existing participant
  4758. // Watch role change:
  4759. if (this.members[from].role != member.role) {
  4760. this.members[from].role = member.role;
  4761. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  4762. member.role, member.nick);
  4763. }
  4764. }
  4765. if(!member.isFocus)
  4766. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  4767. // Trigger status message update
  4768. if (member.status) {
  4769. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  4770. }
  4771. };
  4772. ChatRoom.prototype.processNode = function (node, from) {
  4773. if(this.presHandlers[node.tagName])
  4774. this.presHandlers[node.tagName](node, from);
  4775. };
  4776. ChatRoom.prototype.sendMessage = function (body, nickname) {
  4777. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  4778. msg.c('body', body).up();
  4779. if (nickname) {
  4780. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  4781. }
  4782. this.connection.send(msg);
  4783. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  4784. };
  4785. ChatRoom.prototype.setSubject = function (subject) {
  4786. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  4787. msg.c('subject', subject);
  4788. this.connection.send(msg);
  4789. logger.log("topic changed to " + subject);
  4790. };
  4791. ChatRoom.prototype.onParticipantLeft = function (jid) {
  4792. delete this.lastPresences[jid];
  4793. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  4794. this.moderator.onMucMemberLeft(jid);
  4795. };
  4796. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  4797. // room destroyed ?
  4798. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  4799. '>destroy').length) {
  4800. var reason;
  4801. var reasonSelect = $(pres).find(
  4802. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  4803. '>destroy>reason');
  4804. if (reasonSelect.length) {
  4805. reason = reasonSelect.text();
  4806. }
  4807. this.xmpp.disposeConference(false);
  4808. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  4809. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  4810. return true;
  4811. }
  4812. // Status code 110 indicates that this notification is "self-presence".
  4813. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  4814. delete this.members[from];
  4815. this.onParticipantLeft(from);
  4816. }
  4817. // If the status code is 110 this means we're leaving and we would like
  4818. // to remove everyone else from our view, so we trigger the event.
  4819. else if (Object.keys(this.members).length > 1) {
  4820. for (var i in this.members) {
  4821. var member = this.members[i];
  4822. delete this.members[i];
  4823. this.onParticipantLeft(member);
  4824. }
  4825. }
  4826. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  4827. if (this.myroomjid === from) {
  4828. this.xmpp.disposeConference(false);
  4829. this.eventEmitter.emit(XMPPEvents.KICKED);
  4830. }
  4831. }
  4832. };
  4833. ChatRoom.prototype.onMessage = function (msg, from) {
  4834. var nick =
  4835. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  4836. .text() ||
  4837. Strophe.getResourceFromJid(from);
  4838. var txt = $(msg).find('>body').text();
  4839. var type = msg.getAttribute("type");
  4840. if (type == "error") {
  4841. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  4842. $(msg).find('>text').text(), txt);
  4843. return true;
  4844. }
  4845. var subject = $(msg).find('>subject');
  4846. if (subject.length) {
  4847. var subjectText = subject.text();
  4848. if (subjectText || subjectText == "") {
  4849. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  4850. logger.log("Subject is changed to " + subjectText);
  4851. }
  4852. }
  4853. // xep-0203 delay
  4854. var stamp = $(msg).find('>delay').attr('stamp');
  4855. if (!stamp) {
  4856. // or xep-0091 delay, UTC timestamp
  4857. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  4858. if (stamp) {
  4859. // the format is CCYYMMDDThh:mm:ss
  4860. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  4861. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  4862. }
  4863. }
  4864. if (txt) {
  4865. logger.log('chat', nick, txt);
  4866. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  4867. from, nick, txt, this.myroomjid, stamp);
  4868. }
  4869. }
  4870. ChatRoom.prototype.onPresenceError = function (pres, from) {
  4871. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  4872. logger.log('on password required', from);
  4873. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  4874. } else if ($(pres).find(
  4875. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  4876. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  4877. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  4878. // enter the room by replying with 'not-authorized'. This would
  4879. // result in reconnection from authorized domain.
  4880. // We're either missing Jicofo/Prosody config for anonymous
  4881. // domains or something is wrong.
  4882. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  4883. } else {
  4884. logger.warn('onPresError ', pres);
  4885. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  4886. }
  4887. } else {
  4888. logger.warn('onPresError ', pres);
  4889. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  4890. }
  4891. };
  4892. ChatRoom.prototype.kick = function (jid) {
  4893. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  4894. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  4895. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  4896. .c('reason').t('You have been kicked.').up().up().up();
  4897. this.connection.sendIQ(
  4898. kickIQ,
  4899. function (result) {
  4900. logger.log('Kick participant with jid: ', jid, result);
  4901. },
  4902. function (error) {
  4903. logger.log('Kick participant error: ', error);
  4904. });
  4905. };
  4906. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  4907. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  4908. var ob = this;
  4909. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  4910. function (res) {
  4911. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  4912. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  4913. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  4914. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  4915. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  4916. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  4917. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  4918. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  4919. ob.connection.sendIQ(formsubmit,
  4920. onSuccess,
  4921. onError);
  4922. } else {
  4923. onNotSupported();
  4924. }
  4925. }, onError);
  4926. };
  4927. ChatRoom.prototype.addToPresence = function (key, values) {
  4928. values.tagName = key;
  4929. this.presMap["nodes"].push(values);
  4930. };
  4931. ChatRoom.prototype.removeFromPresence = function (key) {
  4932. for(var i = 0; i < this.presMap.nodes.length; i++)
  4933. {
  4934. if(key === this.presMap.nodes[i].tagName)
  4935. this.presMap.nodes.splice(i, 1);
  4936. }
  4937. };
  4938. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  4939. this.presHandlers[name] = handler;
  4940. }
  4941. ChatRoom.prototype.removePresenceListener = function (name) {
  4942. delete this.presHandlers[name];
  4943. }
  4944. ChatRoom.prototype.isModerator = function (jid) {
  4945. return this.role === 'moderator';
  4946. };
  4947. ChatRoom.prototype.getMemberRole = function (peerJid) {
  4948. if (this.members[peerJid]) {
  4949. return this.members[peerJid].role;
  4950. }
  4951. return null;
  4952. };
  4953. ChatRoom.prototype.setJingleSession = function(session){
  4954. this.session = session;
  4955. this.session.room = this;
  4956. };
  4957. ChatRoom.prototype.removeStream = function (stream) {
  4958. if(!this.session)
  4959. return;
  4960. this.session.peerconnection.removeStream(stream)
  4961. }
  4962. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  4963. if(this.session) {
  4964. // FIXME: will block switchInProgress on true value in case of exception
  4965. this.session.switchStreams(stream, oldStream, callback, isAudio);
  4966. } else {
  4967. // We are done immediately
  4968. logger.warn("No conference handler or conference not started yet");
  4969. callback();
  4970. }
  4971. };
  4972. ChatRoom.prototype.addStream = function (stream, callback) {
  4973. if(this.session) {
  4974. // FIXME: will block switchInProgress on true value in case of exception
  4975. this.session.addStream(stream, callback);
  4976. } else {
  4977. // We are done immediately
  4978. logger.warn("No conference handler or conference not started yet");
  4979. callback();
  4980. }
  4981. }
  4982. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  4983. var self = this;
  4984. var localCallback = function (mute) {
  4985. self.sendVideoInfoPresence(mute);
  4986. if(callback)
  4987. callback(mute)
  4988. };
  4989. if(this.session)
  4990. {
  4991. this.session.setVideoMute(
  4992. mute, localCallback, options);
  4993. }
  4994. else {
  4995. localCallback(mute);
  4996. }
  4997. };
  4998. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  4999. //This will be for remote streams only
  5000. // if (this.forceMuted && !mute) {
  5001. // logger.info("Asking focus for unmute");
  5002. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5003. // // FIXME: wait for result before resetting muted status
  5004. // this.forceMuted = false;
  5005. // }
  5006. return this.sendAudioInfoPresence(mute, callback);
  5007. };
  5008. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5009. this.removeFromPresence("audiomuted");
  5010. this.addToPresence("audiomuted",
  5011. {attributes:
  5012. {"audions": "http://jitsi.org/jitmeet/audio"},
  5013. value: mute.toString()});
  5014. }
  5015. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5016. this.addAudioInfoToPresence(mute);
  5017. if(this.connection) {
  5018. this.sendPresence();
  5019. }
  5020. if(callback)
  5021. callback();
  5022. };
  5023. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5024. this.removeFromPresence("videomuted");
  5025. this.addToPresence("videomuted",
  5026. {attributes:
  5027. {"videons": "http://jitsi.org/jitmeet/video"},
  5028. value: mute.toString()});
  5029. }
  5030. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5031. this.addVideoInfoToPresence(mute);
  5032. if(!this.connection)
  5033. return;
  5034. this.sendPresence();
  5035. };
  5036. ChatRoom.prototype.addListener = function(type, listener) {
  5037. this.eventEmitter.on(type, listener);
  5038. };
  5039. ChatRoom.prototype.removeListener = function (type, listener) {
  5040. this.eventEmitter.removeListener(type, listener);
  5041. };
  5042. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5043. if(this.lastPresences[data.peerjid])
  5044. {
  5045. var pres = this.lastPresences[data.peerjid];
  5046. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5047. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5048. data.videomuted = ((videomuted.length > 0
  5049. && videomuted[0]
  5050. && videomuted[0]["value"] === "true")? true : false);
  5051. data.audiomuted = ((audiomuted.length > 0
  5052. && audiomuted[0]
  5053. && audiomuted[0]["value"] === "true")? true : false);
  5054. }
  5055. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5056. }
  5057. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5058. if (!this.session)
  5059. return null;
  5060. return this.session.getSsrcOwner(ssrc);
  5061. };
  5062. module.exports = ChatRoom;
  5063. }).call(this,"/modules/xmpp/ChatRoom.js")
  5064. },{"../../service/xmpp/XMPPEvents":82,"./moderator":31,"events":40,"jitsi-meet-logger":44}],24:[function(require,module,exports){
  5065. (function (__filename){
  5066. /*
  5067. * JingleSession provides an API to manage a single Jingle session. We will
  5068. * have different implementations depending on the underlying interface used
  5069. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5070. */
  5071. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5072. function JingleSession(me, sid, connection, service, eventEmitter) {
  5073. /**
  5074. * Our JID.
  5075. */
  5076. this.me = me;
  5077. /**
  5078. * The Jingle session identifier.
  5079. */
  5080. this.sid = sid;
  5081. /**
  5082. * The XMPP connection.
  5083. */
  5084. this.connection = connection;
  5085. /**
  5086. * The XMPP service.
  5087. */
  5088. this.service = service;
  5089. /**
  5090. * The event emitter.
  5091. */
  5092. this.eventEmitter = eventEmitter;
  5093. /**
  5094. * Whether to use dripping or not. Dripping is sending trickle candidates
  5095. * not one-by-one.
  5096. * Note: currently we do not support 'false'.
  5097. */
  5098. this.usedrip = true;
  5099. /**
  5100. * When dripping is used, stores ICE candidates which are to be sent.
  5101. */
  5102. this.drip_container = [];
  5103. // Media constraints. Is this WebRTC only?
  5104. this.media_constraints = null;
  5105. // ICE servers config (RTCConfiguration?).
  5106. this.ice_config = {};
  5107. // The chat room instance associated with the session.
  5108. this.room = null;
  5109. }
  5110. /**
  5111. * Prepares this object to initiate a session.
  5112. * @param peerjid the JID of the remote peer.
  5113. * @param isInitiator whether we will be the Jingle initiator.
  5114. * @param media_constraints
  5115. * @param ice_config
  5116. */
  5117. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5118. media_constraints, ice_config) {
  5119. this.media_constraints = media_constraints;
  5120. this.ice_config = ice_config;
  5121. if (this.state !== null) {
  5122. logger.error('attempt to initiate on session ' + this.sid +
  5123. 'in state ' + this.state);
  5124. return;
  5125. }
  5126. this.state = 'pending';
  5127. this.initiator = isInitiator ? this.me : peerjid;
  5128. this.responder = !isInitiator ? this.me : peerjid;
  5129. this.peerjid = peerjid;
  5130. this.doInitialize();
  5131. };
  5132. /**
  5133. * Finishes initialization.
  5134. */
  5135. JingleSession.prototype.doInitialize = function() {};
  5136. /**
  5137. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5138. * Note: currently only used on transport-info
  5139. */
  5140. JingleSession.prototype.addIceCandidates = function(contents) {};
  5141. /**
  5142. * Handles an 'add-source' event.
  5143. *
  5144. * @param contents an array of Jingle 'content' elements.
  5145. */
  5146. JingleSession.prototype.addSources = function(contents) {};
  5147. /**
  5148. * Handles a 'remove-source' event.
  5149. *
  5150. * @param contents an array of Jingle 'content' elements.
  5151. */
  5152. JingleSession.prototype.removeSources = function(contents) {};
  5153. /**
  5154. * Terminates this Jingle session (stops sending media and closes the streams?)
  5155. */
  5156. JingleSession.prototype.terminate = function() {};
  5157. /**
  5158. * Sends a Jingle session-terminate message to the peer and terminates the
  5159. * session.
  5160. * @param reason
  5161. * @param text
  5162. */
  5163. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5164. /**
  5165. * Handles an offer from the remote peer (prepares to accept a session).
  5166. * @param jingle the 'jingle' XML element.
  5167. */
  5168. JingleSession.prototype.setOffer = function(jingle) {};
  5169. /**
  5170. * Handles an answer from the remote peer (prepares to accept a session).
  5171. * @param jingle the 'jingle' XML element.
  5172. */
  5173. JingleSession.prototype.setAnswer = function(jingle) {};
  5174. module.exports = JingleSession;
  5175. }).call(this,"/modules/xmpp/JingleSession.js")
  5176. },{"jitsi-meet-logger":44}],25:[function(require,module,exports){
  5177. (function (__filename){
  5178. /* jshint -W117 */
  5179. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5180. var JingleSession = require("./JingleSession");
  5181. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5182. var SDPDiffer = require("./SDPDiffer");
  5183. var SDPUtil = require("./SDPUtil");
  5184. var SDP = require("./SDP");
  5185. var async = require("async");
  5186. var transform = require("sdp-transform");
  5187. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5188. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5189. var SSRCReplacement = require("./LocalSSRCReplacement");
  5190. var RTC = require("../RTC/RTC");
  5191. // Jingle stuff
  5192. function JingleSessionPC(me, sid, connection, service) {
  5193. JingleSession.call(this, me, sid, connection, service);
  5194. this.initiator = null;
  5195. this.responder = null;
  5196. this.peerjid = null;
  5197. this.state = null;
  5198. this.localSDP = null;
  5199. this.remoteSDP = null;
  5200. this.relayedStreams = [];
  5201. this.usetrickle = true;
  5202. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5203. this.hadstuncandidate = false;
  5204. this.hadturncandidate = false;
  5205. this.lasticecandidate = false;
  5206. this.statsinterval = null;
  5207. this.reason = null;
  5208. this.addssrc = [];
  5209. this.removessrc = [];
  5210. this.pendingop = null;
  5211. this.switchstreams = false;
  5212. this.addingStreams = false;
  5213. this.wait = true;
  5214. this.localStreamsSSRC = null;
  5215. this.ssrcOwners = {};
  5216. this.ssrcVideoTypes = {};
  5217. /**
  5218. * The indicator which determines whether the (local) video has been muted
  5219. * in response to a user command in contrast to an automatic decision made
  5220. * by the application logic.
  5221. */
  5222. this.videoMuteByUser = false;
  5223. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5224. // We start with the queue paused. We resume it when the signaling state is
  5225. // stable and the ice connection state is connected.
  5226. this.modifySourcesQueue.pause();
  5227. }
  5228. JingleSessionPC.prototype = JingleSession.prototype;
  5229. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5230. JingleSessionPC.prototype.setOffer = function(offer) {
  5231. this.setRemoteDescription(offer, 'offer');
  5232. };
  5233. JingleSessionPC.prototype.setAnswer = function(answer) {
  5234. this.setRemoteDescription(answer, 'answer');
  5235. };
  5236. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5237. var signalingState = this.peerconnection.signalingState;
  5238. var iceConnectionState = this.peerconnection.iceConnectionState;
  5239. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5240. this.modifySourcesQueue.resume();
  5241. } else {
  5242. this.modifySourcesQueue.pause();
  5243. }
  5244. };
  5245. JingleSessionPC.prototype.doInitialize = function () {
  5246. var self = this;
  5247. this.hadstuncandidate = false;
  5248. this.hadturncandidate = false;
  5249. this.lasticecandidate = false;
  5250. // True if reconnect is in progress
  5251. this.isreconnect = false;
  5252. // Set to true if the connection was ever stable
  5253. this.wasstable = false;
  5254. this.peerconnection = new TraceablePeerConnection(
  5255. this.connection.jingle.ice_config,
  5256. RTC.getPCConstraints(),
  5257. this);
  5258. this.peerconnection.onicecandidate = function (event) {
  5259. self.sendIceCandidate(event.candidate);
  5260. };
  5261. this.peerconnection.onaddstream = function (event) {
  5262. if (event.stream.id !== 'default') {
  5263. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5264. self.remoteStreamAdded(event);
  5265. } else {
  5266. // This is a recvonly stream. Clients that implement Unified Plan,
  5267. // such as Firefox use recvonly "streams/channels/tracks" for
  5268. // receiving remote stream/tracks, as opposed to Plan B where there
  5269. // are only 3 channels: audio, video and data.
  5270. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5271. }
  5272. };
  5273. this.peerconnection.onremovestream = function (event) {
  5274. // Remove the stream from remoteStreams
  5275. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5276. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5277. };
  5278. this.peerconnection.onsignalingstatechange = function (event) {
  5279. if (!(self && self.peerconnection)) return;
  5280. if (self.peerconnection.signalingState === 'stable') {
  5281. self.wasstable = true;
  5282. }
  5283. self.updateModifySourcesQueue();
  5284. };
  5285. /**
  5286. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  5287. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  5288. * RTCPeerConnection.iceConnectionState changes.
  5289. *
  5290. * @param event the event containing information about the change
  5291. */
  5292. this.peerconnection.oniceconnectionstatechange = function (event) {
  5293. if (!(self && self.peerconnection)) return;
  5294. self.updateModifySourcesQueue();
  5295. switch (self.peerconnection.iceConnectionState) {
  5296. case 'connected':
  5297. // Informs interested parties that the connection has been restored.
  5298. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  5299. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  5300. self.isreconnect = false;
  5301. break;
  5302. case 'disconnected':
  5303. self.isreconnect = true;
  5304. // Informs interested parties that the connection has been interrupted.
  5305. if (self.wasstable)
  5306. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  5307. break;
  5308. case 'failed':
  5309. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5310. break;
  5311. }
  5312. onIceConnectionStateChange(self.sid, self);
  5313. };
  5314. this.peerconnection.onnegotiationneeded = function (event) {
  5315. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  5316. };
  5317. this.relayedStreams.forEach(function(stream) {
  5318. self.peerconnection.addStream(stream);
  5319. });
  5320. };
  5321. function onIceConnectionStateChange(sid, session) {
  5322. switch (session.peerconnection.iceConnectionState) {
  5323. case 'checking':
  5324. session.timeChecking = (new Date()).getTime();
  5325. session.firstconnect = true;
  5326. break;
  5327. case 'completed': // on caller side
  5328. case 'connected':
  5329. if (session.firstconnect) {
  5330. session.firstconnect = false;
  5331. var metadata = {};
  5332. metadata.setupTime
  5333. = (new Date()).getTime() - session.timeChecking;
  5334. session.peerconnection.getStats(function (res) {
  5335. if(res && res.result) {
  5336. res.result().forEach(function (report) {
  5337. if (report.type == 'googCandidatePair' &&
  5338. report.stat('googActiveConnection') == 'true') {
  5339. metadata.localCandidateType
  5340. = report.stat('googLocalCandidateType');
  5341. metadata.remoteCandidateType
  5342. = report.stat('googRemoteCandidateType');
  5343. // log pair as well so we can get nice pie
  5344. // charts
  5345. metadata.candidatePair
  5346. = report.stat('googLocalCandidateType') +
  5347. ';' +
  5348. report.stat('googRemoteCandidateType');
  5349. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  5350. {
  5351. metadata.ipv6 = true;
  5352. }
  5353. }
  5354. });
  5355. }
  5356. });
  5357. }
  5358. break;
  5359. }
  5360. }
  5361. JingleSessionPC.prototype.accept = function () {
  5362. this.state = 'active';
  5363. var pranswer = this.peerconnection.localDescription;
  5364. if (!pranswer || pranswer.type != 'pranswer') {
  5365. return;
  5366. }
  5367. logger.log('going from pranswer to answer');
  5368. if (this.usetrickle) {
  5369. // remove candidates already sent from session-accept
  5370. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  5371. for (var i = 0; i < lines.length; i++) {
  5372. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  5373. }
  5374. }
  5375. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  5376. // FIXME: change any inactive to sendrecv or whatever they were originally
  5377. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  5378. }
  5379. var prsdp = new SDP(pranswer.sdp);
  5380. var accept = $iq({to: this.peerjid,
  5381. type: 'set'})
  5382. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5383. action: 'session-accept',
  5384. initiator: this.initiator,
  5385. responder: this.responder,
  5386. sid: this.sid });
  5387. // FIXME why do we generate session-accept in 3 different places ?
  5388. prsdp.toJingle(
  5389. accept,
  5390. this.initiator == this.me ? 'initiator' : 'responder',
  5391. this.localStreamsSSRC);
  5392. var sdp = this.peerconnection.localDescription.sdp;
  5393. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  5394. // FIXME: change any inactive to sendrecv or whatever they were originally
  5395. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  5396. }
  5397. var self = this;
  5398. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  5399. function () {
  5400. //logger.log('setLocalDescription success');
  5401. self.setLocalDescription();
  5402. SSRCReplacement.processSessionInit(accept);
  5403. self.connection.sendIQ(accept,
  5404. function () {
  5405. var ack = {};
  5406. ack.source = 'answer';
  5407. $(document).trigger('ack.jingle', [self.sid, ack]);
  5408. },
  5409. function (stanza) {
  5410. var error = ($(stanza).find('error').length) ? {
  5411. code: $(stanza).find('error').attr('code'),
  5412. reason: $(stanza).find('error :first')[0].tagName
  5413. }:{};
  5414. error.source = 'answer';
  5415. JingleSessionPC.onJingleError(self.sid, error);
  5416. },
  5417. 10000);
  5418. },
  5419. function (e) {
  5420. logger.error('setLocalDescription failed', e);
  5421. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5422. }
  5423. );
  5424. };
  5425. JingleSessionPC.prototype.terminate = function (reason) {
  5426. this.state = 'ended';
  5427. this.reason = reason;
  5428. this.peerconnection.close();
  5429. if (this.statsinterval !== null) {
  5430. window.clearInterval(this.statsinterval);
  5431. this.statsinterval = null;
  5432. }
  5433. };
  5434. JingleSessionPC.prototype.active = function () {
  5435. return this.state == 'active';
  5436. };
  5437. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  5438. var self = this;
  5439. if (candidate && !this.lasticecandidate) {
  5440. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  5441. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  5442. if (!(ice && jcand)) {
  5443. logger.error('failed to get ice && jcand');
  5444. return;
  5445. }
  5446. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5447. if (jcand.type === 'srflx') {
  5448. this.hadstuncandidate = true;
  5449. } else if (jcand.type === 'relay') {
  5450. this.hadturncandidate = true;
  5451. }
  5452. if (this.usetrickle) {
  5453. if (this.usedrip) {
  5454. if (this.drip_container.length === 0) {
  5455. // start 20ms callout
  5456. window.setTimeout(function () {
  5457. if (self.drip_container.length === 0) return;
  5458. self.sendIceCandidates(self.drip_container);
  5459. self.drip_container = [];
  5460. }, 20);
  5461. }
  5462. this.drip_container.push(candidate);
  5463. return;
  5464. } else {
  5465. self.sendIceCandidate([candidate]);
  5466. }
  5467. }
  5468. } else {
  5469. //logger.log('sendIceCandidate: last candidate.');
  5470. if (!this.usetrickle) {
  5471. //logger.log('should send full offer now...');
  5472. //FIXME why do we generate session-accept in 3 different places ?
  5473. var init = $iq({to: this.peerjid,
  5474. type: 'set'})
  5475. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5476. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  5477. initiator: this.initiator,
  5478. sid: this.sid});
  5479. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  5480. var sendJingle = function (ssrc) {
  5481. if(!ssrc)
  5482. ssrc = {};
  5483. self.localSDP.toJingle(
  5484. init,
  5485. self.initiator == self.me ? 'initiator' : 'responder',
  5486. ssrc);
  5487. SSRCReplacement.processSessionInit(init);
  5488. self.connection.sendIQ(init,
  5489. function () {
  5490. //logger.log('session initiate ack');
  5491. var ack = {};
  5492. ack.source = 'offer';
  5493. $(document).trigger('ack.jingle', [self.sid, ack]);
  5494. },
  5495. function (stanza) {
  5496. self.state = 'error';
  5497. self.peerconnection.close();
  5498. var error = ($(stanza).find('error').length) ? {
  5499. code: $(stanza).find('error').attr('code'),
  5500. reason: $(stanza).find('error :first')[0].tagName,
  5501. }:{};
  5502. error.source = 'offer';
  5503. JingleSessionPC.onJingleError(self.sid, error);
  5504. },
  5505. 10000);
  5506. };
  5507. sendJingle();
  5508. }
  5509. this.lasticecandidate = true;
  5510. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  5511. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  5512. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  5513. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  5514. }
  5515. }
  5516. };
  5517. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  5518. logger.log('sendIceCandidates', candidates);
  5519. var cand = $iq({to: this.peerjid, type: 'set'})
  5520. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5521. action: 'transport-info',
  5522. initiator: this.initiator,
  5523. sid: this.sid});
  5524. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  5525. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  5526. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  5527. if (cands.length > 0) {
  5528. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  5529. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5530. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  5531. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  5532. }).c('transport', ice);
  5533. for (var i = 0; i < cands.length; i++) {
  5534. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  5535. }
  5536. // add fingerprint
  5537. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  5538. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  5539. tmp.required = true;
  5540. cand.c(
  5541. 'fingerprint',
  5542. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  5543. .t(tmp.fingerprint);
  5544. delete tmp.fingerprint;
  5545. cand.attrs(tmp);
  5546. cand.up();
  5547. }
  5548. cand.up(); // transport
  5549. cand.up(); // content
  5550. }
  5551. }
  5552. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  5553. //logger.log('was this the last candidate', this.lasticecandidate);
  5554. this.connection.sendIQ(cand,
  5555. function () {
  5556. var ack = {};
  5557. ack.source = 'transportinfo';
  5558. $(document).trigger('ack.jingle', [this.sid, ack]);
  5559. },
  5560. function (stanza) {
  5561. var error = ($(stanza).find('error').length) ? {
  5562. code: $(stanza).find('error').attr('code'),
  5563. reason: $(stanza).find('error :first')[0].tagName,
  5564. }:{};
  5565. error.source = 'transportinfo';
  5566. JingleSessionPC.onJingleError(this.sid, error);
  5567. },
  5568. 10000);
  5569. };
  5570. JingleSessionPC.prototype.sendOffer = function () {
  5571. //logger.log('sendOffer...');
  5572. var self = this;
  5573. this.peerconnection.createOffer(function (sdp) {
  5574. self.createdOffer(sdp);
  5575. },
  5576. function (e) {
  5577. logger.error('createOffer failed', e);
  5578. },
  5579. this.media_constraints
  5580. );
  5581. };
  5582. // FIXME createdOffer is never used in jitsi-meet
  5583. JingleSessionPC.prototype.createdOffer = function (sdp) {
  5584. //logger.log('createdOffer', sdp);
  5585. var self = this;
  5586. this.localSDP = new SDP(sdp.sdp);
  5587. //this.localSDP.mangle();
  5588. var sendJingle = function () {
  5589. var init = $iq({to: this.peerjid,
  5590. type: 'set'})
  5591. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5592. action: 'session-initiate',
  5593. initiator: this.initiator,
  5594. sid: this.sid});
  5595. self.localSDP.toJingle(
  5596. init,
  5597. this.initiator == this.me ? 'initiator' : 'responder',
  5598. this.localStreamsSSRC);
  5599. SSRCReplacement.processSessionInit(init);
  5600. self.connection.sendIQ(init,
  5601. function () {
  5602. var ack = {};
  5603. ack.source = 'offer';
  5604. $(document).trigger('ack.jingle', [self.sid, ack]);
  5605. },
  5606. function (stanza) {
  5607. self.state = 'error';
  5608. self.peerconnection.close();
  5609. var error = ($(stanza).find('error').length) ? {
  5610. code: $(stanza).find('error').attr('code'),
  5611. reason: $(stanza).find('error :first')[0].tagName,
  5612. }:{};
  5613. error.source = 'offer';
  5614. JingleSessionPC.onJingleError(self.sid, error);
  5615. },
  5616. 10000);
  5617. }
  5618. sdp.sdp = this.localSDP.raw;
  5619. this.peerconnection.setLocalDescription(sdp,
  5620. function () {
  5621. if(self.usetrickle)
  5622. {
  5623. sendJingle();
  5624. }
  5625. self.setLocalDescription();
  5626. //logger.log('setLocalDescription success');
  5627. },
  5628. function (e) {
  5629. logger.error('setLocalDescription failed', e);
  5630. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5631. }
  5632. );
  5633. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  5634. for (var i = 0; i < cands.length; i++) {
  5635. var cand = SDPUtil.parse_icecandidate(cands[i]);
  5636. if (cand.type == 'srflx') {
  5637. this.hadstuncandidate = true;
  5638. } else if (cand.type == 'relay') {
  5639. this.hadturncandidate = true;
  5640. }
  5641. }
  5642. };
  5643. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  5644. var self = this;
  5645. $(contents).each(function (idx, content) {
  5646. var name = $(content).attr('name');
  5647. var mediaType = this.getAttribute('name');
  5648. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  5649. ssrcs.each(function () {
  5650. var ssrc = this.getAttribute('ssrc');
  5651. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  5652. function () {
  5653. var owner = this.getAttribute('owner');
  5654. self.ssrcOwners[ssrc] = owner;
  5655. }
  5656. );
  5657. });
  5658. });
  5659. };
  5660. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  5661. return this.ssrcOwners[ssrc];
  5662. };
  5663. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  5664. //logger.log('setting remote description... ', desctype);
  5665. this.remoteSDP = new SDP('');
  5666. this.remoteSDP.fromJingle(elem);
  5667. this.readSsrcInfo($(elem).find(">content"));
  5668. if (this.peerconnection.remoteDescription !== null) {
  5669. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  5670. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  5671. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  5672. for (var i = 0; i < pranswer.media.length; i++) {
  5673. // make sure we have ice ufrag and pwd
  5674. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  5675. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  5676. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  5677. } else {
  5678. logger.warn('no ice ufrag?');
  5679. }
  5680. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  5681. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  5682. } else {
  5683. logger.warn('no ice pwd?');
  5684. }
  5685. }
  5686. // copy over candidates
  5687. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  5688. for (var j = 0; j < lines.length; j++) {
  5689. this.remoteSDP.media[i] += lines[j] + '\r\n';
  5690. }
  5691. }
  5692. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  5693. }
  5694. }
  5695. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  5696. this.peerconnection.setRemoteDescription(remotedesc,
  5697. function () {
  5698. //logger.log('setRemoteDescription success');
  5699. },
  5700. function (e) {
  5701. logger.error('setRemoteDescription error', e);
  5702. JingleSessionPC.onJingleFatalError(self, e);
  5703. }
  5704. );
  5705. };
  5706. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  5707. var self = this;
  5708. if (this.peerconnection.signalingState == 'closed') {
  5709. return;
  5710. }
  5711. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  5712. logger.log('trickle ice candidate arriving before session accept...');
  5713. // create a PRANSWER for setRemoteDescription
  5714. if (!this.remoteSDP) {
  5715. var cobbled = 'v=0\r\n' +
  5716. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  5717. 's=-\r\n' +
  5718. 't=0 0\r\n';
  5719. // first, take some things from the local description
  5720. for (var i = 0; i < this.localSDP.media.length; i++) {
  5721. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  5722. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  5723. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  5724. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  5725. }
  5726. cobbled += 'a=inactive\r\n';
  5727. }
  5728. this.remoteSDP = new SDP(cobbled);
  5729. }
  5730. // then add things like ice and dtls from remote candidate
  5731. elem.each(function () {
  5732. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  5733. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  5734. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  5735. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  5736. var tmp = $(this).find('transport');
  5737. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  5738. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  5739. tmp = $(this).find('transport>fingerprint');
  5740. if (tmp.length) {
  5741. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  5742. } else {
  5743. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  5744. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  5745. }
  5746. break;
  5747. }
  5748. }
  5749. }
  5750. });
  5751. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  5752. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  5753. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  5754. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  5755. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  5756. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  5757. }).length == this.remoteSDP.media.length;
  5758. if (iscomplete) {
  5759. logger.log('setting pranswer');
  5760. try {
  5761. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  5762. function() {
  5763. },
  5764. function(e) {
  5765. logger.log('setRemoteDescription pranswer failed', e.toString());
  5766. });
  5767. } catch (e) {
  5768. logger.error('setting pranswer failed', e);
  5769. }
  5770. } else {
  5771. //logger.log('not yet setting pranswer');
  5772. }
  5773. }
  5774. // operate on each content element
  5775. elem.each(function () {
  5776. // would love to deactivate this, but firefox still requires it
  5777. var idx = -1;
  5778. var i;
  5779. for (i = 0; i < self.remoteSDP.media.length; i++) {
  5780. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  5781. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  5782. idx = i;
  5783. break;
  5784. }
  5785. }
  5786. if (idx == -1) { // fall back to localdescription
  5787. for (i = 0; i < self.localSDP.media.length; i++) {
  5788. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  5789. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  5790. idx = i;
  5791. break;
  5792. }
  5793. }
  5794. }
  5795. var name = $(this).attr('name');
  5796. // TODO: check ice-pwd and ice-ufrag?
  5797. $(this).find('transport>candidate').each(function () {
  5798. var line, candidate;
  5799. line = SDPUtil.candidateFromJingle(this);
  5800. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  5801. sdpMid: name,
  5802. candidate: line});
  5803. try {
  5804. self.peerconnection.addIceCandidate(candidate);
  5805. } catch (e) {
  5806. logger.error('addIceCandidate failed', e.toString(), line);
  5807. }
  5808. });
  5809. });
  5810. };
  5811. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  5812. //logger.log('createAnswer', provisional);
  5813. var self = this;
  5814. this.peerconnection.createAnswer(
  5815. function (sdp) {
  5816. self.createdAnswer(sdp, provisional);
  5817. },
  5818. function (e) {
  5819. logger.error('createAnswer failed', e);
  5820. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5821. },
  5822. this.media_constraints
  5823. );
  5824. };
  5825. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  5826. //logger.log('createAnswer callback');
  5827. var self = this;
  5828. this.localSDP = new SDP(sdp.sdp);
  5829. //this.localSDP.mangle();
  5830. this.usepranswer = provisional === true;
  5831. if (this.usetrickle) {
  5832. if (this.usepranswer) {
  5833. sdp.type = 'pranswer';
  5834. for (var i = 0; i < this.localSDP.media.length; i++) {
  5835. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  5836. }
  5837. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  5838. }
  5839. }
  5840. var self = this;
  5841. var sendJingle = function (ssrcs) {
  5842. // FIXME why do we generate session-accept in 3 different places ?
  5843. var accept = $iq({to: self.peerjid,
  5844. type: 'set'})
  5845. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5846. action: 'session-accept',
  5847. initiator: self.initiator,
  5848. responder: self.responder,
  5849. sid: self.sid });
  5850. self.localSDP.toJingle(
  5851. accept,
  5852. self.initiator == self.me ? 'initiator' : 'responder',
  5853. ssrcs);
  5854. SSRCReplacement.processSessionInit(accept);
  5855. self.connection.sendIQ(accept,
  5856. function () {
  5857. var ack = {};
  5858. ack.source = 'answer';
  5859. $(document).trigger('ack.jingle', [self.sid, ack]);
  5860. },
  5861. function (stanza) {
  5862. var error = ($(stanza).find('error').length) ? {
  5863. code: $(stanza).find('error').attr('code'),
  5864. reason: $(stanza).find('error :first')[0].tagName,
  5865. }:{};
  5866. error.source = 'answer';
  5867. JingleSessionPC.onJingleError(self.sid, error);
  5868. },
  5869. 10000);
  5870. }
  5871. sdp.sdp = this.localSDP.raw;
  5872. this.peerconnection.setLocalDescription(sdp,
  5873. function () {
  5874. //logger.log('setLocalDescription success');
  5875. if (self.usetrickle && !self.usepranswer) {
  5876. sendJingle();
  5877. }
  5878. self.setLocalDescription();
  5879. },
  5880. function (e) {
  5881. logger.error('setLocalDescription failed', e);
  5882. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5883. }
  5884. );
  5885. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  5886. for (var j = 0; j < cands.length; j++) {
  5887. var cand = SDPUtil.parse_icecandidate(cands[j]);
  5888. if (cand.type == 'srflx') {
  5889. this.hadstuncandidate = true;
  5890. } else if (cand.type == 'relay') {
  5891. this.hadturncandidate = true;
  5892. }
  5893. }
  5894. };
  5895. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  5896. var self = this,
  5897. term = $iq({to: this.peerjid,
  5898. type: 'set'})
  5899. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5900. action: 'session-terminate',
  5901. initiator: this.initiator,
  5902. sid: this.sid})
  5903. .c('reason')
  5904. .c(reason || 'success');
  5905. if (text) {
  5906. term.up().c('text').t(text);
  5907. }
  5908. this.connection.sendIQ(term,
  5909. function () {
  5910. self.peerconnection.close();
  5911. self.peerconnection = null;
  5912. self.terminate();
  5913. var ack = {};
  5914. ack.source = 'terminate';
  5915. $(document).trigger('ack.jingle', [self.sid, ack]);
  5916. },
  5917. function (stanza) {
  5918. var error = ($(stanza).find('error').length) ? {
  5919. code: $(stanza).find('error').attr('code'),
  5920. reason: $(stanza).find('error :first')[0].tagName,
  5921. }:{};
  5922. $(document).trigger('ack.jingle', [self.sid, error]);
  5923. },
  5924. 10000);
  5925. if (this.statsinterval !== null) {
  5926. window.clearInterval(this.statsinterval);
  5927. this.statsinterval = null;
  5928. }
  5929. };
  5930. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  5931. var self = this;
  5932. // FIXME: dirty waiting
  5933. if (!this.peerconnection.localDescription)
  5934. {
  5935. logger.warn("addSource - localDescription not ready yet")
  5936. setTimeout(function()
  5937. {
  5938. self.addSource(elem, fromJid);
  5939. },
  5940. 200
  5941. );
  5942. return;
  5943. }
  5944. logger.log('addssrc', new Date().getTime());
  5945. logger.log('ice', this.peerconnection.iceConnectionState);
  5946. this.readSsrcInfo(elem);
  5947. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5948. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  5949. $(elem).each(function (idx, content) {
  5950. var name = $(content).attr('name');
  5951. var lines = '';
  5952. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5953. var semantics = this.getAttribute('semantics');
  5954. var ssrcs = $(this).find('>source').map(function () {
  5955. return this.getAttribute('ssrc');
  5956. }).get();
  5957. if (ssrcs.length != 0) {
  5958. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5959. }
  5960. });
  5961. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  5962. tmp.each(function () {
  5963. var ssrc = $(this).attr('ssrc');
  5964. if(mySdp.containsSSRC(ssrc)){
  5965. /**
  5966. * This happens when multiple participants change their streams at the same time and
  5967. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  5968. * addssrc are scheduled for update IQ. See
  5969. */
  5970. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  5971. return;
  5972. }
  5973. if (sdp.containsSSRC(ssrc)) {
  5974. logger.warn("Source-add request for existing SSRC: " + ssrc);
  5975. return;
  5976. }
  5977. $(this).find('>parameter').each(function () {
  5978. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5979. if ($(this).attr('value') && $(this).attr('value').length)
  5980. lines += ':' + $(this).attr('value');
  5981. lines += '\r\n';
  5982. });
  5983. });
  5984. sdp.media.forEach(function(media, idx) {
  5985. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5986. return;
  5987. sdp.media[idx] += lines;
  5988. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  5989. self.addssrc[idx] += lines;
  5990. });
  5991. sdp.raw = sdp.session + sdp.media.join('');
  5992. });
  5993. this.modifySourcesQueue.push(function() {
  5994. // When a source is added and if this is FF, a new channel is allocated
  5995. // for receiving the added source. We need to diffuse the SSRC of this
  5996. // new recvonly channel to the rest of the peers.
  5997. logger.log('modify sources done');
  5998. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5999. logger.log("SDPs", mySdp, newSdp);
  6000. self.notifyMySSRCUpdate(mySdp, newSdp);
  6001. });
  6002. };
  6003. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  6004. var self = this;
  6005. // FIXME: dirty waiting
  6006. if (!this.peerconnection.localDescription)
  6007. {
  6008. logger.warn("removeSource - localDescription not ready yet")
  6009. setTimeout(function()
  6010. {
  6011. self.removeSource(elem, fromJid);
  6012. },
  6013. 200
  6014. );
  6015. return;
  6016. }
  6017. logger.log('removessrc', new Date().getTime());
  6018. logger.log('ice', this.peerconnection.iceConnectionState);
  6019. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6020. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6021. $(elem).each(function (idx, content) {
  6022. var name = $(content).attr('name');
  6023. var lines = '';
  6024. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6025. var semantics = this.getAttribute('semantics');
  6026. var ssrcs = $(this).find('>source').map(function () {
  6027. return this.getAttribute('ssrc');
  6028. }).get();
  6029. if (ssrcs.length != 0) {
  6030. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6031. }
  6032. });
  6033. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6034. tmp.each(function () {
  6035. var ssrc = $(this).attr('ssrc');
  6036. // This should never happen, but can be useful for bug detection
  6037. if(mySdp.containsSSRC(ssrc)){
  6038. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6039. return;
  6040. }
  6041. $(this).find('>parameter').each(function () {
  6042. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6043. if ($(this).attr('value') && $(this).attr('value').length)
  6044. lines += ':' + $(this).attr('value');
  6045. lines += '\r\n';
  6046. });
  6047. });
  6048. sdp.media.forEach(function(media, idx) {
  6049. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6050. return;
  6051. sdp.media[idx] += lines;
  6052. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6053. self.removessrc[idx] += lines;
  6054. });
  6055. sdp.raw = sdp.session + sdp.media.join('');
  6056. });
  6057. this.modifySourcesQueue.push(function() {
  6058. // When a source is removed and if this is FF, the recvonly channel that
  6059. // receives the remote stream is deactivated . We need to diffuse the
  6060. // recvonly SSRC removal to the rest of the peers.
  6061. logger.log('modify sources done');
  6062. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6063. logger.log("SDPs", mySdp, newSdp);
  6064. self.notifyMySSRCUpdate(mySdp, newSdp);
  6065. });
  6066. };
  6067. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6068. var self = this;
  6069. if (this.peerconnection.signalingState == 'closed') return;
  6070. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6071. || this.switchstreams || this.addingStreams)){
  6072. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6073. this.setLocalDescription();
  6074. if(successCallback){
  6075. successCallback();
  6076. }
  6077. queueCallback();
  6078. return;
  6079. }
  6080. // Reset switch streams flags
  6081. this.switchstreams = false;
  6082. this.addingStreams = false;
  6083. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6084. // add sources
  6085. this.addssrc.forEach(function(lines, idx) {
  6086. sdp.media[idx] += lines;
  6087. });
  6088. this.addssrc = [];
  6089. // remove sources
  6090. this.removessrc.forEach(function(lines, idx) {
  6091. lines = lines.split('\r\n');
  6092. lines.pop(); // remove empty last element;
  6093. lines.forEach(function(line) {
  6094. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6095. });
  6096. });
  6097. this.removessrc = [];
  6098. sdp.raw = sdp.session + sdp.media.join('');
  6099. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6100. function() {
  6101. if(self.signalingState == 'closed') {
  6102. logger.error("createAnswer attempt on closed state");
  6103. queueCallback("createAnswer attempt on closed state");
  6104. return;
  6105. }
  6106. self.peerconnection.createAnswer(
  6107. function(modifiedAnswer) {
  6108. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6109. if (self.pendingop !== null) {
  6110. var sdp = new SDP(modifiedAnswer.sdp);
  6111. if (sdp.media.length > 1) {
  6112. switch(self.pendingop) {
  6113. case 'mute':
  6114. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6115. break;
  6116. case 'unmute':
  6117. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6118. break;
  6119. }
  6120. sdp.raw = sdp.session + sdp.media.join('');
  6121. modifiedAnswer.sdp = sdp.raw;
  6122. }
  6123. self.pendingop = null;
  6124. }
  6125. // FIXME: pushing down an answer while ice connection state
  6126. // is still checking is bad...
  6127. //logger.log(self.peerconnection.iceConnectionState);
  6128. // trying to work around another chrome bug
  6129. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6130. self.peerconnection.setLocalDescription(modifiedAnswer,
  6131. function() {
  6132. //logger.log('modified setLocalDescription ok');
  6133. self.setLocalDescription();
  6134. if(successCallback){
  6135. successCallback();
  6136. }
  6137. queueCallback();
  6138. },
  6139. function(error) {
  6140. logger.error('modified setLocalDescription failed', error);
  6141. queueCallback(error);
  6142. }
  6143. );
  6144. },
  6145. function(error) {
  6146. logger.error('modified answer failed', error);
  6147. queueCallback(error);
  6148. }
  6149. );
  6150. },
  6151. function(error) {
  6152. logger.error('modify failed', error);
  6153. queueCallback(error);
  6154. }
  6155. );
  6156. };
  6157. /**
  6158. * Switches video streams.
  6159. * @param new_stream new stream that will be used as video of this session.
  6160. * @param oldStream old video stream of this session.
  6161. * @param success_callback callback executed after successful stream switch.
  6162. */
  6163. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  6164. var self = this;
  6165. // Remember SDP to figure out added/removed SSRCs
  6166. var oldSdp = null;
  6167. if(self.peerconnection) {
  6168. if(self.peerconnection.localDescription) {
  6169. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6170. }
  6171. self.peerconnection.removeStream(oldStream, true);
  6172. if(new_stream)
  6173. self.peerconnection.addStream(new_stream);
  6174. }
  6175. // Conference is not active
  6176. if(!oldSdp || !self.peerconnection) {
  6177. success_callback();
  6178. return;
  6179. }
  6180. self.switchstreams = true;
  6181. self.modifySourcesQueue.push(function() {
  6182. logger.log('modify sources done');
  6183. success_callback();
  6184. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6185. logger.log("SDPs", oldSdp, newSdp);
  6186. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6187. });
  6188. };
  6189. /**
  6190. * Adds streams.
  6191. * @param stream new stream that will be added.
  6192. * @param success_callback callback executed after successful stream addition.
  6193. */
  6194. JingleSessionPC.prototype.addStream = function (stream, callback) {
  6195. var self = this;
  6196. // Remember SDP to figure out added/removed SSRCs
  6197. var oldSdp = null;
  6198. if(this.peerconnection) {
  6199. if(this.peerconnection.localDescription) {
  6200. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  6201. }
  6202. if(stream)
  6203. this.peerconnection.addStream(stream);
  6204. }
  6205. // Conference is not active
  6206. if(!oldSdp || !this.peerconnection) {
  6207. callback();
  6208. return;
  6209. }
  6210. this.addingStreams = true;
  6211. this.modifySourcesQueue.push(function() {
  6212. logger.log('modify sources done');
  6213. callback();
  6214. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6215. logger.log("SDPs", oldSdp, newSdp);
  6216. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6217. });
  6218. }
  6219. /**
  6220. * Figures out added/removed ssrcs and send update IQs.
  6221. * @param old_sdp SDP object for old description.
  6222. * @param new_sdp SDP object for new description.
  6223. */
  6224. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  6225. if (!(this.peerconnection.signalingState == 'stable' &&
  6226. this.peerconnection.iceConnectionState == 'connected')){
  6227. logger.log("Too early to send updates");
  6228. return;
  6229. }
  6230. // send source-remove IQ.
  6231. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  6232. var remove = $iq({to: this.peerjid, type: 'set'})
  6233. .c('jingle', {
  6234. xmlns: 'urn:xmpp:jingle:1',
  6235. action: 'source-remove',
  6236. initiator: this.initiator,
  6237. sid: this.sid
  6238. }
  6239. );
  6240. var removed = sdpDiffer.toJingle(remove);
  6241. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  6242. // it in the current form
  6243. if (removed)
  6244. remove = SSRCReplacement.processSourceRemove(remove);
  6245. if (removed && remove) {
  6246. logger.info("Sending source-remove", remove);
  6247. this.connection.sendIQ(remove,
  6248. function (res) {
  6249. logger.info('got remove result', res);
  6250. },
  6251. function (err) {
  6252. logger.error('got remove error', err);
  6253. }
  6254. );
  6255. } else {
  6256. logger.log('removal not necessary');
  6257. }
  6258. // send source-add IQ.
  6259. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  6260. var add = $iq({to: this.peerjid, type: 'set'})
  6261. .c('jingle', {
  6262. xmlns: 'urn:xmpp:jingle:1',
  6263. action: 'source-add',
  6264. initiator: this.initiator,
  6265. sid: this.sid
  6266. }
  6267. );
  6268. var added = sdpDiffer.toJingle(add);
  6269. // Let 'source-add' IQ through the hack and see if we're allowed to send
  6270. // it in the current form
  6271. if (added)
  6272. add = SSRCReplacement.processSourceAdd(add);
  6273. if (added && add) {
  6274. logger.info("Sending source-add", add);
  6275. this.connection.sendIQ(add,
  6276. function (res) {
  6277. logger.info('got add result', res);
  6278. },
  6279. function (err) {
  6280. logger.error('got add error', err);
  6281. }
  6282. );
  6283. } else {
  6284. logger.log('addition not necessary');
  6285. }
  6286. };
  6287. /**
  6288. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  6289. *
  6290. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  6291. * tracks; otherwise, <tt>false</tt>
  6292. * @param callback a function to be invoked with <tt>mute</tt> after all video
  6293. * tracks have been enabled/disabled. The function may, optionally, return
  6294. * another function which is to be invoked after the whole mute/unmute operation
  6295. * has completed successfully.
  6296. * @param options an object which specifies optional arguments such as the
  6297. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  6298. * specifies whether the method was initiated in response to a user command (in
  6299. * contrast to an automatic decision made by the application logic)
  6300. */
  6301. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  6302. var byUser;
  6303. if (options) {
  6304. byUser = options.byUser;
  6305. if (typeof byUser === 'undefined') {
  6306. byUser = true;
  6307. }
  6308. } else {
  6309. byUser = true;
  6310. }
  6311. // The user's command to mute the (local) video takes precedence over any
  6312. // automatic decision made by the application logic.
  6313. if (byUser) {
  6314. this.videoMuteByUser = mute;
  6315. } else if (this.videoMuteByUser) {
  6316. return;
  6317. }
  6318. this.hardMuteVideo(mute);
  6319. var self = this;
  6320. var oldSdp = null;
  6321. if(self.peerconnection) {
  6322. if(self.peerconnection.localDescription) {
  6323. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6324. }
  6325. }
  6326. this.modifySourcesQueue.push(function() {
  6327. logger.log('modify sources done');
  6328. callback(mute);
  6329. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6330. logger.log("SDPs", oldSdp, newSdp);
  6331. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6332. });
  6333. };
  6334. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  6335. this.pendingop = muted ? 'mute' : 'unmute';
  6336. };
  6337. JingleSessionPC.prototype.sendMute = function (muted, content) {
  6338. var info = $iq({to: this.peerjid,
  6339. type: 'set'})
  6340. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6341. action: 'session-info',
  6342. initiator: this.initiator,
  6343. sid: this.sid });
  6344. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6345. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  6346. if (content) {
  6347. info.attrs({'name': content});
  6348. }
  6349. this.connection.send(info);
  6350. };
  6351. JingleSessionPC.prototype.sendRinging = function () {
  6352. var info = $iq({to: this.peerjid,
  6353. type: 'set'})
  6354. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6355. action: 'session-info',
  6356. initiator: this.initiator,
  6357. sid: this.sid });
  6358. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6359. this.connection.send(info);
  6360. };
  6361. JingleSessionPC.prototype.getStats = function (interval) {
  6362. var self = this;
  6363. var recv = {audio: 0, video: 0};
  6364. var lost = {audio: 0, video: 0};
  6365. var lastrecv = {audio: 0, video: 0};
  6366. var lastlost = {audio: 0, video: 0};
  6367. var loss = {audio: 0, video: 0};
  6368. var delta = {audio: 0, video: 0};
  6369. this.statsinterval = window.setInterval(function () {
  6370. if (self && self.peerconnection && self.peerconnection.getStats) {
  6371. self.peerconnection.getStats(function (stats) {
  6372. var results = stats.result();
  6373. // TODO: there are so much statistics you can get from this..
  6374. for (var i = 0; i < results.length; ++i) {
  6375. if (results[i].type == 'ssrc') {
  6376. var packetsrecv = results[i].stat('packetsReceived');
  6377. var packetslost = results[i].stat('packetsLost');
  6378. if (packetsrecv && packetslost) {
  6379. packetsrecv = parseInt(packetsrecv, 10);
  6380. packetslost = parseInt(packetslost, 10);
  6381. if (results[i].stat('googFrameRateReceived')) {
  6382. lastlost.video = lost.video;
  6383. lastrecv.video = recv.video;
  6384. recv.video = packetsrecv;
  6385. lost.video = packetslost;
  6386. } else {
  6387. lastlost.audio = lost.audio;
  6388. lastrecv.audio = recv.audio;
  6389. recv.audio = packetsrecv;
  6390. lost.audio = packetslost;
  6391. }
  6392. }
  6393. }
  6394. }
  6395. delta.audio = recv.audio - lastrecv.audio;
  6396. delta.video = recv.video - lastrecv.video;
  6397. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  6398. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  6399. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  6400. });
  6401. }
  6402. }, interval || 3000);
  6403. return this.statsinterval;
  6404. };
  6405. JingleSessionPC.onJingleError = function (session, error)
  6406. {
  6407. logger.error("Jingle error", error);
  6408. }
  6409. JingleSessionPC.onJingleFatalError = function (session, error)
  6410. {
  6411. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6412. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  6413. }
  6414. JingleSessionPC.prototype.setLocalDescription = function () {
  6415. var self = this;
  6416. var newssrcs = [];
  6417. var session = transform.parse(this.peerconnection.localDescription.sdp);
  6418. session.media.forEach(function (media) {
  6419. if (media.ssrcs != null && media.ssrcs.length > 0) {
  6420. // TODO(gp) maybe exclude FID streams?
  6421. media.ssrcs.forEach(function (ssrc) {
  6422. if (ssrc.attribute !== 'cname') {
  6423. return;
  6424. }
  6425. newssrcs.push({
  6426. 'ssrc': ssrc.id,
  6427. 'type': media.type
  6428. });
  6429. });
  6430. }
  6431. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  6432. {
  6433. newssrcs.push({
  6434. 'ssrc': self.localStreamsSSRC[media.type],
  6435. 'type': media.type
  6436. });
  6437. }
  6438. });
  6439. logger.log('new ssrcs', newssrcs);
  6440. // Bind us as local SSRCs owner
  6441. if (newssrcs.length > 0) {
  6442. for (var i = 1; i <= newssrcs.length; i ++) {
  6443. var ssrc = newssrcs[i-1].ssrc;
  6444. var myJid = self.connection.emuc.myroomjid;
  6445. self.ssrcOwners[ssrc] = myJid;
  6446. }
  6447. }
  6448. }
  6449. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  6450. JingleSessionPC.prototype.sendKeyframe = function () {
  6451. var pc = this.peerconnection;
  6452. logger.log('sendkeyframe', pc.iceConnectionState);
  6453. if (pc.iceConnectionState !== 'connected') return; // safe...
  6454. var self = this;
  6455. pc.setRemoteDescription(
  6456. pc.remoteDescription,
  6457. function () {
  6458. pc.createAnswer(
  6459. function (modifiedAnswer) {
  6460. pc.setLocalDescription(
  6461. modifiedAnswer,
  6462. function () {
  6463. // noop
  6464. },
  6465. function (error) {
  6466. logger.log('triggerKeyframe setLocalDescription failed', error);
  6467. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  6468. }
  6469. );
  6470. },
  6471. function (error) {
  6472. logger.log('triggerKeyframe createAnswer failed', error);
  6473. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  6474. }
  6475. );
  6476. },
  6477. function (error) {
  6478. logger.log('triggerKeyframe setRemoteDescription failed', error);
  6479. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  6480. }
  6481. );
  6482. }
  6483. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  6484. var self = this;
  6485. var thessrc;
  6486. var streamId = RTC.getStreamID(data.stream);
  6487. // look up an associated JID for a stream id
  6488. if (!streamId) {
  6489. logger.error("No stream ID for", data.stream);
  6490. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  6491. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  6492. var ssrclines
  6493. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  6494. ssrclines = ssrclines.filter(function (line) {
  6495. // NOTE(gp) previously we filtered on the mslabel, but that property
  6496. // is not always present.
  6497. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  6498. if (RTCBrowserType.isTemasysPluginUsed()) {
  6499. return ((line.indexOf('mslabel:' + streamId) !== -1));
  6500. } else {
  6501. return ((line.indexOf('msid:' + streamId) !== -1));
  6502. }
  6503. });
  6504. if (ssrclines.length) {
  6505. thessrc = ssrclines[0].substring(7).split(' ')[0];
  6506. if (!self.ssrcOwners[thessrc]) {
  6507. logger.error("No SSRC owner known for: " + thessrc);
  6508. return;
  6509. }
  6510. data.peerjid = self.ssrcOwners[thessrc];
  6511. logger.log('associated jid', self.ssrcOwners[thessrc]);
  6512. } else {
  6513. logger.error("No SSRC lines for ", streamId);
  6514. }
  6515. }
  6516. this.room.remoteStreamAdded(data, this.sid, thessrc);
  6517. var isVideo = data.stream.getVideoTracks().length > 0;
  6518. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  6519. if (isVideo &&
  6520. data.peerjid && this.peerjid === data.peerjid &&
  6521. data.stream.getVideoTracks().length === 0 &&
  6522. RTC.localVideo.getTracks().length > 0) {
  6523. window.setTimeout(function () {
  6524. self.sendKeyframe();
  6525. }, 3000);
  6526. }
  6527. }
  6528. module.exports = JingleSessionPC;
  6529. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  6530. },{"../../service/xmpp/XMPPEvents":82,"../RTC/RTC":13,"../RTC/RTCBrowserType":14,"./JingleSession":24,"./LocalSSRCReplacement":26,"./SDP":27,"./SDPDiffer":28,"./SDPUtil":29,"./TraceablePeerConnection":30,"async":39,"jitsi-meet-logger":44,"sdp-transform":72}],26:[function(require,module,exports){
  6531. (function (__filename){
  6532. /* global $ */
  6533. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6534. /*
  6535. Here we do modifications of local video SSRCs. There are 2 situations we have
  6536. to handle:
  6537. 1. We generate SSRC for local recvonly video stream. This is the case when we
  6538. have no local camera and it is not generated automatically, but SSRC=1 is
  6539. used implicitly. If that happens RTCP packets will be dropped by the JVB
  6540. and we won't be able to request video key frames correctly.
  6541. 2. A hack to re-use SSRC of the first video stream for any new stream created
  6542. in future. It turned out that Chrome may keep on using the SSRC of removed
  6543. video stream in RTCP even though a new one has been created. So we just
  6544. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  6545. notifications are blocked once first video SSRC is advertised to the focus.
  6546. What this hack does:
  6547. 1. Stores the SSRC of the first video stream created by
  6548. a) scanning Jingle session-accept/session-invite for existing video SSRC
  6549. b) watching for 'source-add' for new video stream if it has not been
  6550. created in step a)
  6551. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  6552. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  6553. returned to the other parts of the application.
  6554. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  6555. blocks those notifications. This makes Jicofo and all participants think
  6556. that it exists all the time even if the video stream has been removed or
  6557. replaced locally. Thanks to that there is no additional signaling activity
  6558. on video mute or when switching to the desktop stream.
  6559. */
  6560. var SDP = require('./SDP');
  6561. var RandomUtil = require('../util/RandomUtil');
  6562. var RTCBrowserType = require('../RTC/RTCBrowserType');
  6563. /**
  6564. * The hack is enabled on all browsers except FF by default
  6565. * FIXME finish the hack once removeStream method is implemented in FF
  6566. * @type {boolean}
  6567. */
  6568. var isEnabled = !RTCBrowserType.isFirefox();
  6569. /**
  6570. * Stored SSRC of local video stream.
  6571. */
  6572. var localVideoSSRC;
  6573. /**
  6574. * SSRC, msid, mslabel, label used for recvonly video stream when we have no local camera.
  6575. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  6576. * instead of 1.
  6577. */
  6578. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  6579. /**
  6580. * cname for <tt>localRecvOnlySSRC</tt>
  6581. */
  6582. var localRecvOnlyCName;
  6583. /**
  6584. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  6585. * from given Jingle IQ.
  6586. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  6587. * @param actionName display name of the action which will be printed in log
  6588. * messages.
  6589. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  6590. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  6591. * other SSRCs left to be signaled after removing it.
  6592. */
  6593. var filterOutSource = function (modifyIq, actionName) {
  6594. var modifyIqTree = $(modifyIq.tree());
  6595. if (!localVideoSSRC)
  6596. return modifyIqTree[0];
  6597. var videoSSRC = modifyIqTree.find(
  6598. '>jingle>content[name="video"]' +
  6599. '>description>source[ssrc="' + localVideoSSRC + '"]');
  6600. if (!videoSSRC.length) {
  6601. return modifyIqTree[0];
  6602. }
  6603. logger.info(
  6604. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  6605. videoSSRC.remove();
  6606. // Check if any sources still left to be added/removed
  6607. if (modifyIqTree.find('>jingle>content>description>source').length) {
  6608. return modifyIqTree[0];
  6609. } else {
  6610. return null;
  6611. }
  6612. };
  6613. /**
  6614. * Scans given Jingle IQ for video SSRC and stores it.
  6615. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  6616. */
  6617. var storeLocalVideoSSRC = function (jingleIq) {
  6618. var videoSSRCs =
  6619. $(jingleIq.tree())
  6620. .find('>jingle>content[name="video"]>description>source');
  6621. videoSSRCs.each(function (idx, ssrcElem) {
  6622. if (localVideoSSRC)
  6623. return;
  6624. // We consider SSRC real only if it has msid attribute
  6625. // recvonly streams in FF do not have it as well as local SSRCs
  6626. // we generate for recvonly streams in Chrome
  6627. var ssrSel = $(ssrcElem);
  6628. var msid = ssrSel.find('>parameter[name="msid"]');
  6629. if (msid.length) {
  6630. var ssrcVal = ssrSel.attr('ssrc');
  6631. if (ssrcVal) {
  6632. localVideoSSRC = ssrcVal;
  6633. logger.info('Stored local video SSRC' +
  6634. ' for future re-use: ' + localVideoSSRC);
  6635. }
  6636. }
  6637. });
  6638. };
  6639. /**
  6640. * Generates new label/mslabel attribute
  6641. * @returns {string} label/mslabel attribute
  6642. */
  6643. function generateLabel() {
  6644. return RandomUtil.random8digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" +
  6645. RandomUtil.random4digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" + RandomUtil.random12digitsHex();
  6646. }
  6647. /**
  6648. * Generates new SSRC, CNAME, mslabel, label and msid for local video recvonly stream.
  6649. * FIXME what about eventual SSRC collision ?
  6650. */
  6651. function generateRecvonlySSRC() {
  6652. localRecvOnlySSRC =
  6653. Math.random().toString(10).substring(2, 11);
  6654. localRecvOnlyCName =
  6655. Math.random().toString(36).substring(2);
  6656. localRecvOnlyMSLabel = generateLabel();
  6657. localRecvOnlyLabel = generateLabel();
  6658. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  6659. logger.info(
  6660. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  6661. ", cname: " + localRecvOnlyCName);
  6662. }
  6663. var LocalSSRCReplacement = {
  6664. /**
  6665. * Method must be called before 'session-initiate' or 'session-invite' is
  6666. * sent. Scans the IQ for local video SSRC and stores it if detected.
  6667. *
  6668. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  6669. * which will be scanned for local video SSRC.
  6670. */
  6671. processSessionInit: function (sessionInit) {
  6672. if (!isEnabled)
  6673. return;
  6674. if (localVideoSSRC) {
  6675. logger.error("Local SSRC stored already: " + localVideoSSRC);
  6676. return;
  6677. }
  6678. storeLocalVideoSSRC(sessionInit);
  6679. },
  6680. /**
  6681. * If we have local video SSRC stored searched given
  6682. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  6683. * with the stored one.
  6684. * @param localDescription local description object that will have local
  6685. * video SSRC replaced with the stored one
  6686. * @returns modified <tt>localDescription</tt> object.
  6687. */
  6688. mungeLocalVideoSSRC: function (localDescription) {
  6689. if (!isEnabled)
  6690. return localDescription;
  6691. if (!localDescription) {
  6692. logger.warn("localDescription is null or undefined");
  6693. return localDescription;
  6694. }
  6695. // IF we have local video SSRC stored make sure it is replaced
  6696. // with old SSRC
  6697. if (localVideoSSRC) {
  6698. var newSdp = new SDP(localDescription.sdp);
  6699. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  6700. !newSdp.containsSSRC(localVideoSSRC)) {
  6701. // Get new video SSRC
  6702. var map = newSdp.getMediaSsrcMap();
  6703. var videoPart = map[1];
  6704. var videoSSRCs = videoPart.ssrcs;
  6705. var newSSRC = Object.keys(videoSSRCs)[0];
  6706. logger.info(
  6707. "Replacing new video SSRC: " + newSSRC +
  6708. " with " + localVideoSSRC);
  6709. localDescription.sdp =
  6710. newSdp.raw.replace(
  6711. new RegExp('a=ssrc:' + newSSRC, 'g'),
  6712. 'a=ssrc:' + localVideoSSRC);
  6713. }
  6714. } else {
  6715. // Make sure we have any SSRC for recvonly video stream
  6716. var sdp = new SDP(localDescription.sdp);
  6717. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  6718. sdp.media[1].indexOf('a=recvonly') !== -1) {
  6719. if (!localRecvOnlySSRC) {
  6720. generateRecvonlySSRC();
  6721. }
  6722. localVideoSSRC = localRecvOnlySSRC;
  6723. logger.info('No SSRC in video recvonly stream' +
  6724. ' - adding SSRC: ' + localRecvOnlySSRC);
  6725. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  6726. ' cname:' + localRecvOnlyCName + '\r\n' +
  6727. 'a=ssrc:' + localRecvOnlySSRC +
  6728. ' msid:' + localRecvOnlyMSID + '\r\n' +
  6729. 'a=ssrc:' + localRecvOnlySSRC +
  6730. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  6731. 'a=ssrc:' + localRecvOnlySSRC +
  6732. ' label:' + localRecvOnlyLabel + '\r\n';
  6733. localDescription.sdp = sdp.session + sdp.media.join('');
  6734. }
  6735. }
  6736. return localDescription;
  6737. },
  6738. /**
  6739. * Method must be called before 'source-add' notification is sent. In case
  6740. * we have local video SSRC advertised already it will be removed from the
  6741. * notification. If no other SSRCs are described by given IQ null will be
  6742. * returned which means that there is no point in sending the notification.
  6743. * @param sourceAdd 'source-add' Jingle IQ to be processed
  6744. * @returns modified 'source-add' IQ which can be sent to the focus or
  6745. * <tt>null</tt> if no notification shall be sent. It is no longer
  6746. * a Strophe IQ Builder instance, but DOM element tree.
  6747. */
  6748. processSourceAdd: function (sourceAdd) {
  6749. if (!isEnabled)
  6750. return sourceAdd;
  6751. if (!localVideoSSRC) {
  6752. // Store local SSRC if available
  6753. storeLocalVideoSSRC(sourceAdd);
  6754. return sourceAdd;
  6755. } else {
  6756. return filterOutSource(sourceAdd, 'source-add');
  6757. }
  6758. },
  6759. /**
  6760. * Method must be called before 'source-remove' notification is sent.
  6761. * Removes local video SSRC from the notification. If there are no other
  6762. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  6763. * means that there is no point in sending the notification.
  6764. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  6765. * @returns modified 'source-remove' IQ which can be sent to the focus or
  6766. * <tt>null</tt> if no notification shall be sent. It is no longer
  6767. * a Strophe IQ Builder instance, but DOM element tree.
  6768. */
  6769. processSourceRemove: function (sourceRemove) {
  6770. if (!isEnabled)
  6771. return sourceRemove;
  6772. return filterOutSource(sourceRemove, 'source-remove');
  6773. },
  6774. /**
  6775. * Turns the hack on or off
  6776. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  6777. * to disable it
  6778. */
  6779. setEnabled: function (enabled) {
  6780. isEnabled = enabled;
  6781. }
  6782. };
  6783. module.exports = LocalSSRCReplacement;
  6784. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  6785. },{"../RTC/RTCBrowserType":14,"../util/RandomUtil":22,"./SDP":27,"jitsi-meet-logger":44}],27:[function(require,module,exports){
  6786. (function (__filename){
  6787. /* jshint -W117 */
  6788. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6789. var SDPUtil = require("./SDPUtil");
  6790. // SDP STUFF
  6791. function SDP(sdp) {
  6792. this.media = sdp.split('\r\nm=');
  6793. for (var i = 1; i < this.media.length; i++) {
  6794. this.media[i] = 'm=' + this.media[i];
  6795. if (i != this.media.length - 1) {
  6796. this.media[i] += '\r\n';
  6797. }
  6798. }
  6799. this.session = this.media.shift() + '\r\n';
  6800. this.raw = this.session + this.media.join('');
  6801. }
  6802. /**
  6803. * Returns map of MediaChannel mapped per channel idx.
  6804. */
  6805. SDP.prototype.getMediaSsrcMap = function() {
  6806. var self = this;
  6807. var media_ssrcs = {};
  6808. var tmp;
  6809. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  6810. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  6811. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  6812. var media = {
  6813. mediaindex: mediaindex,
  6814. mid: mid,
  6815. ssrcs: {},
  6816. ssrcGroups: []
  6817. };
  6818. media_ssrcs[mediaindex] = media;
  6819. tmp.forEach(function (line) {
  6820. var linessrc = line.substring(7).split(' ')[0];
  6821. // allocate new ChannelSsrc
  6822. if(!media.ssrcs[linessrc]) {
  6823. media.ssrcs[linessrc] = {
  6824. ssrc: linessrc,
  6825. lines: []
  6826. };
  6827. }
  6828. media.ssrcs[linessrc].lines.push(line);
  6829. });
  6830. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  6831. tmp.forEach(function(line){
  6832. var semantics = line.substr(0, idx).substr(13);
  6833. var ssrcs = line.substr(14 + semantics.length).split(' ');
  6834. if (ssrcs.length != 0) {
  6835. media.ssrcGroups.push({
  6836. semantics: semantics,
  6837. ssrcs: ssrcs
  6838. });
  6839. }
  6840. });
  6841. }
  6842. return media_ssrcs;
  6843. };
  6844. /**
  6845. * Returns <tt>true</tt> if this SDP contains given SSRC.
  6846. * @param ssrc the ssrc to check.
  6847. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  6848. */
  6849. SDP.prototype.containsSSRC = function(ssrc) {
  6850. var medias = this.getMediaSsrcMap();
  6851. var contains = false;
  6852. Object.keys(medias).forEach(function(mediaindex){
  6853. var media = medias[mediaindex];
  6854. //logger.log("Check", channel, ssrc);
  6855. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  6856. contains = true;
  6857. }
  6858. });
  6859. return contains;
  6860. };
  6861. // remove iSAC and CN from SDP
  6862. SDP.prototype.mangle = function () {
  6863. var i, j, mline, lines, rtpmap, newdesc;
  6864. for (i = 0; i < this.media.length; i++) {
  6865. lines = this.media[i].split('\r\n');
  6866. lines.pop(); // remove empty last element
  6867. mline = SDPUtil.parse_mline(lines.shift());
  6868. if (mline.media != 'audio')
  6869. continue;
  6870. newdesc = '';
  6871. mline.fmt.length = 0;
  6872. for (j = 0; j < lines.length; j++) {
  6873. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  6874. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  6875. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  6876. continue;
  6877. mline.fmt.push(rtpmap.id);
  6878. newdesc += lines[j] + '\r\n';
  6879. } else {
  6880. newdesc += lines[j] + '\r\n';
  6881. }
  6882. }
  6883. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  6884. this.media[i] += newdesc;
  6885. }
  6886. this.raw = this.session + this.media.join('');
  6887. };
  6888. // remove lines matching prefix from session section
  6889. SDP.prototype.removeSessionLines = function(prefix) {
  6890. var self = this;
  6891. var lines = SDPUtil.find_lines(this.session, prefix);
  6892. lines.forEach(function(line) {
  6893. self.session = self.session.replace(line + '\r\n', '');
  6894. });
  6895. this.raw = this.session + this.media.join('');
  6896. return lines;
  6897. }
  6898. // remove lines matching prefix from a media section specified by mediaindex
  6899. // TODO: non-numeric mediaindex could match mid
  6900. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  6901. var self = this;
  6902. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  6903. lines.forEach(function(line) {
  6904. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  6905. });
  6906. this.raw = this.session + this.media.join('');
  6907. return lines;
  6908. }
  6909. // add content's to a jingle element
  6910. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  6911. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  6912. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  6913. var self = this;
  6914. // new bundle plan
  6915. if (SDPUtil.find_line(this.session, 'a=group:')) {
  6916. lines = SDPUtil.find_lines(this.session, 'a=group:');
  6917. for (i = 0; i < lines.length; i++) {
  6918. tmp = lines[i].split(' ');
  6919. var semantics = tmp.shift().substr(8);
  6920. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  6921. for (j = 0; j < tmp.length; j++) {
  6922. elem.c('content', {name: tmp[j]}).up();
  6923. }
  6924. elem.up();
  6925. }
  6926. }
  6927. for (i = 0; i < this.media.length; i++) {
  6928. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  6929. if (!(mline.media === 'audio' ||
  6930. mline.media === 'video' ||
  6931. mline.media === 'application'))
  6932. {
  6933. continue;
  6934. }
  6935. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  6936. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  6937. } else {
  6938. if(ssrcs && ssrcs[mline.media])
  6939. {
  6940. ssrc = ssrcs[mline.media];
  6941. }
  6942. else
  6943. ssrc = false;
  6944. }
  6945. elem.c('content', {creator: thecreator, name: mline.media});
  6946. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  6947. // prefer identifier from a=mid if present
  6948. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  6949. elem.attrs({ name: mid });
  6950. }
  6951. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  6952. {
  6953. elem.c('description',
  6954. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  6955. media: mline.media });
  6956. if (ssrc) {
  6957. elem.attrs({ssrc: ssrc});
  6958. }
  6959. for (j = 0; j < mline.fmt.length; j++) {
  6960. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  6961. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  6962. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  6963. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  6964. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  6965. for (k = 0; k < tmp.length; k++) {
  6966. elem.c('parameter', tmp[k]).up();
  6967. }
  6968. }
  6969. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  6970. elem.up();
  6971. }
  6972. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  6973. elem.c('encryption', {required: 1});
  6974. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  6975. crypto.forEach(function(line) {
  6976. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  6977. });
  6978. elem.up(); // end of encryption
  6979. }
  6980. if (ssrc) {
  6981. // new style mapping
  6982. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6983. // FIXME: group by ssrc and support multiple different ssrcs
  6984. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  6985. if(ssrclines.length > 0) {
  6986. ssrclines.forEach(function (line) {
  6987. idx = line.indexOf(' ');
  6988. var linessrc = line.substr(0, idx).substr(7);
  6989. if (linessrc != ssrc) {
  6990. elem.up();
  6991. ssrc = linessrc;
  6992. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6993. }
  6994. var kv = line.substr(idx + 1);
  6995. elem.c('parameter');
  6996. if (kv.indexOf(':') == -1) {
  6997. elem.attrs({ name: kv });
  6998. } else {
  6999. var k = kv.split(':', 2)[0];
  7000. elem.attrs({ name: k });
  7001. var v = kv.split(':', 2)[1];
  7002. v = SDPUtil.filter_special_chars(v);
  7003. elem.attrs({ value: v });
  7004. }
  7005. elem.up();
  7006. });
  7007. }
  7008. else
  7009. {
  7010. elem.up();
  7011. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7012. elem.c('parameter');
  7013. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7014. elem.up();
  7015. var msid = null;
  7016. if(mline.media == "audio")
  7017. {
  7018. msid = APP.RTC.localAudio.getId();
  7019. }
  7020. else
  7021. {
  7022. msid = APP.RTC.localVideo.getId();
  7023. }
  7024. if(msid != null)
  7025. {
  7026. msid = SDPUtil.filter_special_chars(msid);
  7027. elem.c('parameter');
  7028. elem.attrs({name: "msid", value:msid});
  7029. elem.up();
  7030. elem.c('parameter');
  7031. elem.attrs({name: "mslabel", value:msid});
  7032. elem.up();
  7033. elem.c('parameter');
  7034. elem.attrs({name: "label", value:msid});
  7035. elem.up();
  7036. }
  7037. }
  7038. elem.up();
  7039. // XEP-0339 handle ssrc-group attributes
  7040. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7041. ssrc_group_lines.forEach(function(line) {
  7042. idx = line.indexOf(' ');
  7043. var semantics = line.substr(0, idx).substr(13);
  7044. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7045. if (ssrcs.length != 0) {
  7046. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7047. ssrcs.forEach(function(ssrc) {
  7048. elem.c('source', { ssrc: ssrc })
  7049. .up();
  7050. });
  7051. elem.up();
  7052. }
  7053. });
  7054. }
  7055. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7056. elem.c('rtcp-mux').up();
  7057. }
  7058. // XEP-0293 -- map a=rtcp-fb:*
  7059. this.RtcpFbToJingle(i, elem, '*');
  7060. // XEP-0294
  7061. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7062. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7063. for (j = 0; j < lines.length; j++) {
  7064. tmp = SDPUtil.parse_extmap(lines[j]);
  7065. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7066. uri: tmp.uri,
  7067. id: tmp.value });
  7068. if (tmp.hasOwnProperty('direction')) {
  7069. switch (tmp.direction) {
  7070. case 'sendonly':
  7071. elem.attrs({senders: 'responder'});
  7072. break;
  7073. case 'recvonly':
  7074. elem.attrs({senders: 'initiator'});
  7075. break;
  7076. case 'sendrecv':
  7077. elem.attrs({senders: 'both'});
  7078. break;
  7079. case 'inactive':
  7080. elem.attrs({senders: 'none'});
  7081. break;
  7082. }
  7083. }
  7084. // TODO: handle params
  7085. elem.up();
  7086. }
  7087. }
  7088. elem.up(); // end of description
  7089. }
  7090. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7091. this.TransportToJingle(i, elem);
  7092. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7093. elem.attrs({senders: 'both'});
  7094. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7095. elem.attrs({senders: 'initiator'});
  7096. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7097. elem.attrs({senders: 'responder'});
  7098. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7099. elem.attrs({senders: 'none'});
  7100. }
  7101. if (mline.port == '0') {
  7102. // estos hack to reject an m-line
  7103. elem.attrs({senders: 'rejected'});
  7104. }
  7105. elem.up(); // end of content
  7106. }
  7107. elem.up();
  7108. return elem;
  7109. };
  7110. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  7111. var i = mediaindex;
  7112. var tmp;
  7113. var self = this;
  7114. elem.c('transport');
  7115. // XEP-0343 DTLS/SCTP
  7116. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7117. {
  7118. var sctpmap = SDPUtil.find_line(
  7119. this.media[i], 'a=sctpmap:', self.session);
  7120. if (sctpmap)
  7121. {
  7122. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7123. elem.c('sctpmap',
  7124. {
  7125. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7126. number: sctpAttrs[0], /* SCTP port */
  7127. protocol: sctpAttrs[1], /* protocol */
  7128. });
  7129. // Optional stream count attribute
  7130. if (sctpAttrs.length > 2)
  7131. elem.attrs({ streams: sctpAttrs[2]});
  7132. elem.up();
  7133. }
  7134. }
  7135. // XEP-0320
  7136. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7137. fingerprints.forEach(function(line) {
  7138. tmp = SDPUtil.parse_fingerprint(line);
  7139. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7140. elem.c('fingerprint').t(tmp.fingerprint);
  7141. delete tmp.fingerprint;
  7142. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7143. if (line) {
  7144. tmp.setup = line.substr(8);
  7145. }
  7146. elem.attrs(tmp);
  7147. elem.up(); // end of fingerprint
  7148. });
  7149. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7150. if (tmp) {
  7151. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7152. elem.attrs(tmp);
  7153. // XEP-0176
  7154. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7155. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7156. lines.forEach(function (line) {
  7157. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  7158. });
  7159. }
  7160. }
  7161. elem.up(); // end of transport
  7162. }
  7163. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7164. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7165. lines.forEach(function (line) {
  7166. var tmp = SDPUtil.parse_rtcpfb(line);
  7167. if (tmp.type == 'trr-int') {
  7168. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7169. elem.up();
  7170. } else {
  7171. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7172. if (tmp.params.length > 0) {
  7173. elem.attrs({'subtype': tmp.params[0]});
  7174. }
  7175. elem.up();
  7176. }
  7177. });
  7178. };
  7179. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  7180. var media = '';
  7181. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7182. if (tmp.length) {
  7183. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  7184. if (tmp.attr('value')) {
  7185. media += tmp.attr('value');
  7186. } else {
  7187. media += '0';
  7188. }
  7189. media += '\r\n';
  7190. }
  7191. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7192. tmp.each(function () {
  7193. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  7194. if ($(this).attr('subtype')) {
  7195. media += ' ' + $(this).attr('subtype');
  7196. }
  7197. media += '\r\n';
  7198. });
  7199. return media;
  7200. };
  7201. // construct an SDP from a jingle stanza
  7202. SDP.prototype.fromJingle = function (jingle) {
  7203. var self = this;
  7204. this.raw = 'v=0\r\n' +
  7205. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7206. 's=-\r\n' +
  7207. 't=0 0\r\n';
  7208. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  7209. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  7210. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  7211. var contents = $(group).find('>content').map(function (idx, content) {
  7212. return content.getAttribute('name');
  7213. }).get();
  7214. if (contents.length > 0) {
  7215. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  7216. }
  7217. });
  7218. }
  7219. this.session = this.raw;
  7220. jingle.find('>content').each(function () {
  7221. var m = self.jingle2media($(this));
  7222. self.media.push(m);
  7223. });
  7224. // reconstruct msid-semantic -- apparently not necessary
  7225. /*
  7226. var msid = SDPUtil.parse_ssrc(this.raw);
  7227. if (msid.hasOwnProperty('mslabel')) {
  7228. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  7229. }
  7230. */
  7231. this.raw = this.session + this.media.join('');
  7232. };
  7233. // translate a jingle content element into an an SDP media part
  7234. SDP.prototype.jingle2media = function (content) {
  7235. var media = '',
  7236. desc = content.find('description'),
  7237. ssrc = desc.attr('ssrc'),
  7238. self = this,
  7239. tmp;
  7240. var sctp = content.find(
  7241. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  7242. tmp = { media: desc.attr('media') };
  7243. tmp.port = '1';
  7244. if (content.attr('senders') == 'rejected') {
  7245. // estos hack to reject an m-line.
  7246. tmp.port = '0';
  7247. }
  7248. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  7249. if (sctp.length)
  7250. tmp.proto = 'DTLS/SCTP';
  7251. else
  7252. tmp.proto = 'RTP/SAVPF';
  7253. } else {
  7254. tmp.proto = 'RTP/AVPF';
  7255. }
  7256. if (!sctp.length)
  7257. {
  7258. tmp.fmt = desc.find('payload-type').map(
  7259. function () { return this.getAttribute('id'); }).get();
  7260. media += SDPUtil.build_mline(tmp) + '\r\n';
  7261. }
  7262. else
  7263. {
  7264. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  7265. media += 'a=sctpmap:' + sctp.attr('number') +
  7266. ' ' + sctp.attr('protocol');
  7267. var streamCount = sctp.attr('streams');
  7268. if (streamCount)
  7269. media += ' ' + streamCount + '\r\n';
  7270. else
  7271. media += '\r\n';
  7272. }
  7273. media += 'c=IN IP4 0.0.0.0\r\n';
  7274. if (!sctp.length)
  7275. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  7276. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  7277. if (tmp.length) {
  7278. if (tmp.attr('ufrag')) {
  7279. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  7280. }
  7281. if (tmp.attr('pwd')) {
  7282. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  7283. }
  7284. tmp.find('>fingerprint').each(function () {
  7285. // FIXME: check namespace at some point
  7286. media += 'a=fingerprint:' + this.getAttribute('hash');
  7287. media += ' ' + $(this).text();
  7288. media += '\r\n';
  7289. if (this.getAttribute('setup')) {
  7290. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  7291. }
  7292. });
  7293. }
  7294. switch (content.attr('senders')) {
  7295. case 'initiator':
  7296. media += 'a=sendonly\r\n';
  7297. break;
  7298. case 'responder':
  7299. media += 'a=recvonly\r\n';
  7300. break;
  7301. case 'none':
  7302. media += 'a=inactive\r\n';
  7303. break;
  7304. case 'both':
  7305. media += 'a=sendrecv\r\n';
  7306. break;
  7307. }
  7308. media += 'a=mid:' + content.attr('name') + '\r\n';
  7309. // <description><rtcp-mux/></description>
  7310. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  7311. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  7312. if (desc.find('rtcp-mux').length) {
  7313. media += 'a=rtcp-mux\r\n';
  7314. }
  7315. if (desc.find('encryption').length) {
  7316. desc.find('encryption>crypto').each(function () {
  7317. media += 'a=crypto:' + this.getAttribute('tag');
  7318. media += ' ' + this.getAttribute('crypto-suite');
  7319. media += ' ' + this.getAttribute('key-params');
  7320. if (this.getAttribute('session-params')) {
  7321. media += ' ' + this.getAttribute('session-params');
  7322. }
  7323. media += '\r\n';
  7324. });
  7325. }
  7326. desc.find('payload-type').each(function () {
  7327. media += SDPUtil.build_rtpmap(this) + '\r\n';
  7328. if ($(this).find('>parameter').length) {
  7329. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  7330. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  7331. media += '\r\n';
  7332. }
  7333. // xep-0293
  7334. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  7335. });
  7336. // xep-0293
  7337. media += self.RtcpFbFromJingle(desc, '*');
  7338. // xep-0294
  7339. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  7340. tmp.each(function () {
  7341. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  7342. });
  7343. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  7344. media += SDPUtil.candidateFromJingle(this);
  7345. });
  7346. // XEP-0339 handle ssrc-group attributes
  7347. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7348. var semantics = this.getAttribute('semantics');
  7349. var ssrcs = $(this).find('>source').map(function() {
  7350. return this.getAttribute('ssrc');
  7351. }).get();
  7352. if (ssrcs.length != 0) {
  7353. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7354. }
  7355. });
  7356. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7357. tmp.each(function () {
  7358. var ssrc = this.getAttribute('ssrc');
  7359. $(this).find('>parameter').each(function () {
  7360. var name = this.getAttribute('name');
  7361. var value = this.getAttribute('value');
  7362. value = SDPUtil.filter_special_chars(value);
  7363. media += 'a=ssrc:' + ssrc + ' ' + name;
  7364. if (value && value.length)
  7365. media += ':' + value;
  7366. media += '\r\n';
  7367. });
  7368. });
  7369. return media;
  7370. };
  7371. module.exports = SDP;
  7372. }).call(this,"/modules/xmpp/SDP.js")
  7373. },{"./SDPUtil":29,"jitsi-meet-logger":44}],28:[function(require,module,exports){
  7374. var SDPUtil = require("./SDPUtil");
  7375. function SDPDiffer(mySDP, otherSDP) {
  7376. this.mySDP = mySDP;
  7377. this.otherSDP = otherSDP;
  7378. }
  7379. /**
  7380. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  7381. * @param otherSdp the other SDP to check ssrc with.
  7382. */
  7383. SDPDiffer.prototype.getNewMedia = function() {
  7384. // this could be useful in Array.prototype.
  7385. function arrayEquals(array) {
  7386. // if the other array is a falsy value, return
  7387. if (!array)
  7388. return false;
  7389. // compare lengths - can save a lot of time
  7390. if (this.length != array.length)
  7391. return false;
  7392. for (var i = 0, l=this.length; i < l; i++) {
  7393. // Check if we have nested arrays
  7394. if (this[i] instanceof Array && array[i] instanceof Array) {
  7395. // recurse into the nested arrays
  7396. if (!this[i].equals(array[i]))
  7397. return false;
  7398. }
  7399. else if (this[i] != array[i]) {
  7400. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  7401. return false;
  7402. }
  7403. }
  7404. return true;
  7405. }
  7406. var myMedias = this.mySDP.getMediaSsrcMap();
  7407. var othersMedias = this.otherSDP.getMediaSsrcMap();
  7408. var newMedia = {};
  7409. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  7410. var myMedia = myMedias[othersMediaIdx];
  7411. var othersMedia = othersMedias[othersMediaIdx];
  7412. if(!myMedia && othersMedia) {
  7413. // Add whole channel
  7414. newMedia[othersMediaIdx] = othersMedia;
  7415. return;
  7416. }
  7417. // Look for new ssrcs accross the channel
  7418. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  7419. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  7420. // Allocate channel if we've found ssrc that doesn't exist in our channel
  7421. if(!newMedia[othersMediaIdx]){
  7422. newMedia[othersMediaIdx] = {
  7423. mediaindex: othersMedia.mediaindex,
  7424. mid: othersMedia.mid,
  7425. ssrcs: {},
  7426. ssrcGroups: []
  7427. };
  7428. }
  7429. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  7430. }
  7431. });
  7432. // Look for new ssrc groups across the channels
  7433. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  7434. // try to match the other ssrc-group with an ssrc-group of ours
  7435. var matched = false;
  7436. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  7437. var mySsrcGroup = myMedia.ssrcGroups[i];
  7438. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  7439. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  7440. matched = true;
  7441. break;
  7442. }
  7443. }
  7444. if (!matched) {
  7445. // Allocate channel if we've found an ssrc-group that doesn't
  7446. // exist in our channel
  7447. if(!newMedia[othersMediaIdx]){
  7448. newMedia[othersMediaIdx] = {
  7449. mediaindex: othersMedia.mediaindex,
  7450. mid: othersMedia.mid,
  7451. ssrcs: {},
  7452. ssrcGroups: []
  7453. };
  7454. }
  7455. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  7456. }
  7457. });
  7458. });
  7459. return newMedia;
  7460. };
  7461. /**
  7462. * Sends SSRC update IQ.
  7463. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  7464. * @param sid session identifier that will be put into the IQ.
  7465. * @param initiator initiator identifier.
  7466. * @param toJid destination Jid
  7467. * @param isAdd indicates if this is remove or add operation.
  7468. */
  7469. SDPDiffer.prototype.toJingle = function(modify) {
  7470. var sdpMediaSsrcs = this.getNewMedia();
  7471. var self = this;
  7472. // FIXME: only announce video ssrcs since we mix audio and dont need
  7473. // the audio ssrcs therefore
  7474. var modified = false;
  7475. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  7476. modified = true;
  7477. var media = sdpMediaSsrcs[mediaindex];
  7478. modify.c('content', {name: media.mid});
  7479. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  7480. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  7481. // generate sources from lines
  7482. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  7483. var mediaSsrc = media.ssrcs[ssrcNum];
  7484. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7485. modify.attrs({ssrc: mediaSsrc.ssrc});
  7486. // iterate over ssrc lines
  7487. mediaSsrc.lines.forEach(function (line) {
  7488. var idx = line.indexOf(' ');
  7489. var kv = line.substr(idx + 1);
  7490. modify.c('parameter');
  7491. if (kv.indexOf(':') == -1) {
  7492. modify.attrs({ name: kv });
  7493. } else {
  7494. var nv = kv.split(':', 2);
  7495. var name = nv[0];
  7496. var value = SDPUtil.filter_special_chars(nv[1]);
  7497. modify.attrs({ name: name });
  7498. modify.attrs({ value: value });
  7499. }
  7500. modify.up(); // end of parameter
  7501. });
  7502. modify.up(); // end of source
  7503. });
  7504. // generate source groups from lines
  7505. media.ssrcGroups.forEach(function(ssrcGroup) {
  7506. if (ssrcGroup.ssrcs.length != 0) {
  7507. modify.c('ssrc-group', {
  7508. semantics: ssrcGroup.semantics,
  7509. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  7510. });
  7511. ssrcGroup.ssrcs.forEach(function (ssrc) {
  7512. modify.c('source', { ssrc: ssrc })
  7513. .up(); // end of source
  7514. });
  7515. modify.up(); // end of ssrc-group
  7516. }
  7517. });
  7518. modify.up(); // end of description
  7519. modify.up(); // end of content
  7520. });
  7521. return modified;
  7522. };
  7523. module.exports = SDPDiffer;
  7524. },{"./SDPUtil":29}],29:[function(require,module,exports){
  7525. (function (__filename){
  7526. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7527. SDPUtil = {
  7528. filter_special_chars: function (text) {
  7529. return text.replace(/[\\\/\{,\}\+]/g, "");
  7530. },
  7531. iceparams: function (mediadesc, sessiondesc) {
  7532. var data = null;
  7533. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  7534. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  7535. data = {
  7536. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  7537. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  7538. };
  7539. }
  7540. return data;
  7541. },
  7542. parse_iceufrag: function (line) {
  7543. return line.substring(12);
  7544. },
  7545. build_iceufrag: function (frag) {
  7546. return 'a=ice-ufrag:' + frag;
  7547. },
  7548. parse_icepwd: function (line) {
  7549. return line.substring(10);
  7550. },
  7551. build_icepwd: function (pwd) {
  7552. return 'a=ice-pwd:' + pwd;
  7553. },
  7554. parse_mid: function (line) {
  7555. return line.substring(6);
  7556. },
  7557. parse_mline: function (line) {
  7558. var parts = line.substring(2).split(' '),
  7559. data = {};
  7560. data.media = parts.shift();
  7561. data.port = parts.shift();
  7562. data.proto = parts.shift();
  7563. if (parts[parts.length - 1] === '') { // trailing whitespace
  7564. parts.pop();
  7565. }
  7566. data.fmt = parts;
  7567. return data;
  7568. },
  7569. build_mline: function (mline) {
  7570. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  7571. },
  7572. parse_rtpmap: function (line) {
  7573. var parts = line.substring(9).split(' '),
  7574. data = {};
  7575. data.id = parts.shift();
  7576. parts = parts[0].split('/');
  7577. data.name = parts.shift();
  7578. data.clockrate = parts.shift();
  7579. data.channels = parts.length ? parts.shift() : '1';
  7580. return data;
  7581. },
  7582. /**
  7583. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  7584. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  7585. * @returns [SCTP port number, protocol, streams]
  7586. */
  7587. parse_sctpmap: function (line)
  7588. {
  7589. var parts = line.substring(10).split(' ');
  7590. var sctpPort = parts[0];
  7591. var protocol = parts[1];
  7592. // Stream count is optional
  7593. var streamCount = parts.length > 2 ? parts[2] : null;
  7594. return [sctpPort, protocol, streamCount];// SCTP port
  7595. },
  7596. build_rtpmap: function (el) {
  7597. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  7598. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  7599. line += '/' + el.getAttribute('channels');
  7600. }
  7601. return line;
  7602. },
  7603. parse_crypto: function (line) {
  7604. var parts = line.substring(9).split(' '),
  7605. data = {};
  7606. data.tag = parts.shift();
  7607. data['crypto-suite'] = parts.shift();
  7608. data['key-params'] = parts.shift();
  7609. if (parts.length) {
  7610. data['session-params'] = parts.join(' ');
  7611. }
  7612. return data;
  7613. },
  7614. parse_fingerprint: function (line) { // RFC 4572
  7615. var parts = line.substring(14).split(' '),
  7616. data = {};
  7617. data.hash = parts.shift();
  7618. data.fingerprint = parts.shift();
  7619. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  7620. return data;
  7621. },
  7622. parse_fmtp: function (line) {
  7623. var parts = line.split(' '),
  7624. i, key, value,
  7625. data = [];
  7626. parts.shift();
  7627. parts = parts.join(' ').split(';');
  7628. for (i = 0; i < parts.length; i++) {
  7629. key = parts[i].split('=')[0];
  7630. while (key.length && key[0] == ' ') {
  7631. key = key.substring(1);
  7632. }
  7633. value = parts[i].split('=')[1];
  7634. if (key && value) {
  7635. data.push({name: key, value: value});
  7636. } else if (key) {
  7637. // rfc 4733 (DTMF) style stuff
  7638. data.push({name: '', value: key});
  7639. }
  7640. }
  7641. return data;
  7642. },
  7643. parse_icecandidate: function (line) {
  7644. var candidate = {},
  7645. elems = line.split(' ');
  7646. candidate.foundation = elems[0].substring(12);
  7647. candidate.component = elems[1];
  7648. candidate.protocol = elems[2].toLowerCase();
  7649. candidate.priority = elems[3];
  7650. candidate.ip = elems[4];
  7651. candidate.port = elems[5];
  7652. // elems[6] => "typ"
  7653. candidate.type = elems[7];
  7654. candidate.generation = 0; // default value, may be overwritten below
  7655. for (var i = 8; i < elems.length; i += 2) {
  7656. switch (elems[i]) {
  7657. case 'raddr':
  7658. candidate['rel-addr'] = elems[i + 1];
  7659. break;
  7660. case 'rport':
  7661. candidate['rel-port'] = elems[i + 1];
  7662. break;
  7663. case 'generation':
  7664. candidate.generation = elems[i + 1];
  7665. break;
  7666. case 'tcptype':
  7667. candidate.tcptype = elems[i + 1];
  7668. break;
  7669. default: // TODO
  7670. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  7671. }
  7672. }
  7673. candidate.network = '1';
  7674. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  7675. return candidate;
  7676. },
  7677. build_icecandidate: function (cand) {
  7678. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  7679. line += ' ';
  7680. switch (cand.type) {
  7681. case 'srflx':
  7682. case 'prflx':
  7683. case 'relay':
  7684. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  7685. line += 'raddr';
  7686. line += ' ';
  7687. line += cand['rel-addr'];
  7688. line += ' ';
  7689. line += 'rport';
  7690. line += ' ';
  7691. line += cand['rel-port'];
  7692. line += ' ';
  7693. }
  7694. break;
  7695. }
  7696. if (cand.hasOwnAttribute('tcptype')) {
  7697. line += 'tcptype';
  7698. line += ' ';
  7699. line += cand.tcptype;
  7700. line += ' ';
  7701. }
  7702. line += 'generation';
  7703. line += ' ';
  7704. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  7705. return line;
  7706. },
  7707. parse_ssrc: function (desc) {
  7708. // proprietary mapping of a=ssrc lines
  7709. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  7710. // and parse according to that
  7711. var lines = desc.split('\r\n'),
  7712. data = {};
  7713. for (var i = 0; i < lines.length; i++) {
  7714. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  7715. var idx = lines[i].indexOf(' ');
  7716. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  7717. }
  7718. }
  7719. return data;
  7720. },
  7721. parse_rtcpfb: function (line) {
  7722. var parts = line.substr(10).split(' ');
  7723. var data = {};
  7724. data.pt = parts.shift();
  7725. data.type = parts.shift();
  7726. data.params = parts;
  7727. return data;
  7728. },
  7729. parse_extmap: function (line) {
  7730. var parts = line.substr(9).split(' ');
  7731. var data = {};
  7732. data.value = parts.shift();
  7733. if (data.value.indexOf('/') != -1) {
  7734. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  7735. data.value = data.value.substr(0, data.value.indexOf('/'));
  7736. } else {
  7737. data.direction = 'both';
  7738. }
  7739. data.uri = parts.shift();
  7740. data.params = parts;
  7741. return data;
  7742. },
  7743. find_line: function (haystack, needle, sessionpart) {
  7744. var lines = haystack.split('\r\n');
  7745. for (var i = 0; i < lines.length; i++) {
  7746. if (lines[i].substring(0, needle.length) == needle) {
  7747. return lines[i];
  7748. }
  7749. }
  7750. if (!sessionpart) {
  7751. return false;
  7752. }
  7753. // search session part
  7754. lines = sessionpart.split('\r\n');
  7755. for (var j = 0; j < lines.length; j++) {
  7756. if (lines[j].substring(0, needle.length) == needle) {
  7757. return lines[j];
  7758. }
  7759. }
  7760. return false;
  7761. },
  7762. find_lines: function (haystack, needle, sessionpart) {
  7763. var lines = haystack.split('\r\n'),
  7764. needles = [];
  7765. for (var i = 0; i < lines.length; i++) {
  7766. if (lines[i].substring(0, needle.length) == needle)
  7767. needles.push(lines[i]);
  7768. }
  7769. if (needles.length || !sessionpart) {
  7770. return needles;
  7771. }
  7772. // search session part
  7773. lines = sessionpart.split('\r\n');
  7774. for (var j = 0; j < lines.length; j++) {
  7775. if (lines[j].substring(0, needle.length) == needle) {
  7776. needles.push(lines[j]);
  7777. }
  7778. }
  7779. return needles;
  7780. },
  7781. candidateToJingle: function (line) {
  7782. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  7783. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  7784. if (line.indexOf('candidate:') === 0) {
  7785. line = 'a=' + line;
  7786. } else if (line.substring(0, 12) != 'a=candidate:') {
  7787. logger.log('parseCandidate called with a line that is not a candidate line');
  7788. logger.log(line);
  7789. return null;
  7790. }
  7791. if (line.substring(line.length - 2) == '\r\n') // chomp it
  7792. line = line.substring(0, line.length - 2);
  7793. var candidate = {},
  7794. elems = line.split(' '),
  7795. i;
  7796. if (elems[6] != 'typ') {
  7797. logger.log('did not find typ in the right place');
  7798. logger.log(line);
  7799. return null;
  7800. }
  7801. candidate.foundation = elems[0].substring(12);
  7802. candidate.component = elems[1];
  7803. candidate.protocol = elems[2].toLowerCase();
  7804. candidate.priority = elems[3];
  7805. candidate.ip = elems[4];
  7806. candidate.port = elems[5];
  7807. // elems[6] => "typ"
  7808. candidate.type = elems[7];
  7809. candidate.generation = '0'; // default, may be overwritten below
  7810. for (i = 8; i < elems.length; i += 2) {
  7811. switch (elems[i]) {
  7812. case 'raddr':
  7813. candidate['rel-addr'] = elems[i + 1];
  7814. break;
  7815. case 'rport':
  7816. candidate['rel-port'] = elems[i + 1];
  7817. break;
  7818. case 'generation':
  7819. candidate.generation = elems[i + 1];
  7820. break;
  7821. case 'tcptype':
  7822. candidate.tcptype = elems[i + 1];
  7823. break;
  7824. default: // TODO
  7825. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  7826. }
  7827. }
  7828. candidate.network = '1';
  7829. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  7830. return candidate;
  7831. },
  7832. candidateFromJingle: function (cand) {
  7833. var line = 'a=candidate:';
  7834. line += cand.getAttribute('foundation');
  7835. line += ' ';
  7836. line += cand.getAttribute('component');
  7837. line += ' ';
  7838. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  7839. line += ' ';
  7840. line += cand.getAttribute('priority');
  7841. line += ' ';
  7842. line += cand.getAttribute('ip');
  7843. line += ' ';
  7844. line += cand.getAttribute('port');
  7845. line += ' ';
  7846. line += 'typ';
  7847. line += ' ' + cand.getAttribute('type');
  7848. line += ' ';
  7849. switch (cand.getAttribute('type')) {
  7850. case 'srflx':
  7851. case 'prflx':
  7852. case 'relay':
  7853. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  7854. line += 'raddr';
  7855. line += ' ';
  7856. line += cand.getAttribute('rel-addr');
  7857. line += ' ';
  7858. line += 'rport';
  7859. line += ' ';
  7860. line += cand.getAttribute('rel-port');
  7861. line += ' ';
  7862. }
  7863. break;
  7864. }
  7865. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  7866. line += 'tcptype';
  7867. line += ' ';
  7868. line += cand.getAttribute('tcptype');
  7869. line += ' ';
  7870. }
  7871. line += 'generation';
  7872. line += ' ';
  7873. line += cand.getAttribute('generation') || '0';
  7874. return line + '\r\n';
  7875. }
  7876. };
  7877. module.exports = SDPUtil;
  7878. }).call(this,"/modules/xmpp/SDPUtil.js")
  7879. },{"jitsi-meet-logger":44}],30:[function(require,module,exports){
  7880. (function (__filename){
  7881. var RTC = require('../RTC/RTC');
  7882. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7883. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  7884. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7885. var SSRCReplacement = require("./LocalSSRCReplacement");
  7886. function TraceablePeerConnection(ice_config, constraints, session) {
  7887. var self = this;
  7888. this.session = session;
  7889. var RTCPeerConnectionType = null;
  7890. if (RTCBrowserType.isFirefox()) {
  7891. RTCPeerConnectionType = mozRTCPeerConnection;
  7892. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  7893. RTCPeerConnectionType = RTCPeerConnection;
  7894. } else {
  7895. RTCPeerConnectionType = webkitRTCPeerConnection;
  7896. }
  7897. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  7898. this.updateLog = [];
  7899. this.stats = {};
  7900. this.statsinterval = null;
  7901. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  7902. var Interop = require('sdp-interop').Interop;
  7903. this.interop = new Interop();
  7904. var Simulcast = require('sdp-simulcast');
  7905. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  7906. // override as desired
  7907. this.trace = function (what, info) {
  7908. /*logger.warn('WTRACE', what, info);
  7909. if (info && RTCBrowserType.isIExplorer()) {
  7910. if (info.length > 1024) {
  7911. logger.warn('WTRACE', what, info.substr(1024));
  7912. }
  7913. if (info.length > 2048) {
  7914. logger.warn('WTRACE', what, info.substr(2048));
  7915. }
  7916. }*/
  7917. self.updateLog.push({
  7918. time: new Date(),
  7919. type: what,
  7920. value: info || ""
  7921. });
  7922. };
  7923. this.onicecandidate = null;
  7924. this.peerconnection.onicecandidate = function (event) {
  7925. // FIXME: this causes stack overflow with Temasys Plugin
  7926. if (!RTCBrowserType.isTemasysPluginUsed())
  7927. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  7928. if (self.onicecandidate !== null) {
  7929. self.onicecandidate(event);
  7930. }
  7931. };
  7932. this.onaddstream = null;
  7933. this.peerconnection.onaddstream = function (event) {
  7934. self.trace('onaddstream', event.stream.id);
  7935. if (self.onaddstream !== null) {
  7936. self.onaddstream(event);
  7937. }
  7938. };
  7939. this.onremovestream = null;
  7940. this.peerconnection.onremovestream = function (event) {
  7941. self.trace('onremovestream', event.stream.id);
  7942. if (self.onremovestream !== null) {
  7943. self.onremovestream(event);
  7944. }
  7945. };
  7946. this.onsignalingstatechange = null;
  7947. this.peerconnection.onsignalingstatechange = function (event) {
  7948. self.trace('onsignalingstatechange', self.signalingState);
  7949. if (self.onsignalingstatechange !== null) {
  7950. self.onsignalingstatechange(event);
  7951. }
  7952. };
  7953. this.oniceconnectionstatechange = null;
  7954. this.peerconnection.oniceconnectionstatechange = function (event) {
  7955. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  7956. if (self.oniceconnectionstatechange !== null) {
  7957. self.oniceconnectionstatechange(event);
  7958. }
  7959. };
  7960. this.onnegotiationneeded = null;
  7961. this.peerconnection.onnegotiationneeded = function (event) {
  7962. self.trace('onnegotiationneeded');
  7963. if (self.onnegotiationneeded !== null) {
  7964. self.onnegotiationneeded(event);
  7965. }
  7966. };
  7967. self.ondatachannel = null;
  7968. this.peerconnection.ondatachannel = function (event) {
  7969. self.trace('ondatachannel', event);
  7970. if (self.ondatachannel !== null) {
  7971. self.ondatachannel(event);
  7972. }
  7973. };
  7974. // XXX: do all non-firefox browsers which we support also support this?
  7975. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  7976. this.statsinterval = window.setInterval(function() {
  7977. self.peerconnection.getStats(function(stats) {
  7978. var results = stats.result();
  7979. var now = new Date();
  7980. for (var i = 0; i < results.length; ++i) {
  7981. results[i].names().forEach(function (name) {
  7982. var id = results[i].id + '-' + name;
  7983. if (!self.stats[id]) {
  7984. self.stats[id] = {
  7985. startTime: now,
  7986. endTime: now,
  7987. values: [],
  7988. times: []
  7989. };
  7990. }
  7991. self.stats[id].values.push(results[i].stat(name));
  7992. self.stats[id].times.push(now.getTime());
  7993. if (self.stats[id].values.length > self.maxstats) {
  7994. self.stats[id].values.shift();
  7995. self.stats[id].times.shift();
  7996. }
  7997. self.stats[id].endTime = now;
  7998. });
  7999. }
  8000. });
  8001. }, 1000);
  8002. }
  8003. }
  8004. /**
  8005. * Returns a string representation of a SessionDescription object.
  8006. */
  8007. var dumpSDP = function(description) {
  8008. if (typeof description === 'undefined' || description == null) {
  8009. return '';
  8010. }
  8011. return 'type: ' + description.type + '\r\n' + description.sdp;
  8012. };
  8013. /**
  8014. * Takes a SessionDescription object and returns a "normalized" version.
  8015. * Currently it only takes care of ordering the a=ssrc lines.
  8016. */
  8017. var normalizePlanB = function(desc) {
  8018. if (typeof desc !== 'object' || desc === null ||
  8019. typeof desc.sdp !== 'string') {
  8020. logger.warn('An empty description was passed as an argument.');
  8021. return desc;
  8022. }
  8023. var transform = require('sdp-transform');
  8024. var session = transform.parse(desc.sdp);
  8025. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8026. Array.isArray(session.media)) {
  8027. session.media.forEach(function (mLine) {
  8028. // Chrome appears to be picky about the order in which a=ssrc lines
  8029. // are listed in an m-line when rtx is enabled (and thus there are
  8030. // a=ssrc-group lines with FID semantics). Specifically if we have
  8031. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8032. // the "a=ssrc:S1" lines, SRD fails.
  8033. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8034. // first.
  8035. var firstSsrcs = [];
  8036. var newSsrcLines = [];
  8037. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8038. mLine.ssrcGroups.forEach(function (group) {
  8039. if (typeof group.semantics !== 'undefined' &&
  8040. group.semantics === 'FID') {
  8041. if (typeof group.ssrcs !== 'undefined') {
  8042. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8043. }
  8044. }
  8045. });
  8046. }
  8047. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8048. for (var i = 0; i<mLine.ssrcs.length; i++){
  8049. if (typeof mLine.ssrcs[i] === 'object'
  8050. && typeof mLine.ssrcs[i].id !== 'undefined'
  8051. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  8052. newSsrcLines.push(mLine.ssrcs[i]);
  8053. delete mLine.ssrcs[i];
  8054. }
  8055. }
  8056. for (var i = 0; i<mLine.ssrcs.length; i++){
  8057. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8058. newSsrcLines.push(mLine.ssrcs[i]);
  8059. }
  8060. }
  8061. mLine.ssrcs = newSsrcLines;
  8062. }
  8063. });
  8064. }
  8065. var resStr = transform.write(session);
  8066. return new RTCSessionDescription({
  8067. type: desc.type,
  8068. sdp: resStr
  8069. });
  8070. };
  8071. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  8072. TraceablePeerConnection.prototype.__defineGetter__(
  8073. 'signalingState',
  8074. function() { return this.peerconnection.signalingState; });
  8075. TraceablePeerConnection.prototype.__defineGetter__(
  8076. 'iceConnectionState',
  8077. function() { return this.peerconnection.iceConnectionState; });
  8078. TraceablePeerConnection.prototype.__defineGetter__(
  8079. 'localDescription',
  8080. function() {
  8081. var desc = this.peerconnection.localDescription;
  8082. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8083. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8084. // if we're running on FF, transform to Plan B first.
  8085. if (RTCBrowserType.usesUnifiedPlan()) {
  8086. desc = this.interop.toPlanB(desc);
  8087. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8088. }
  8089. return desc;
  8090. });
  8091. TraceablePeerConnection.prototype.__defineGetter__(
  8092. 'remoteDescription',
  8093. function() {
  8094. var desc = this.peerconnection.remoteDescription;
  8095. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8096. // if we're running on FF, transform to Plan B first.
  8097. if (RTCBrowserType.usesUnifiedPlan()) {
  8098. desc = this.interop.toPlanB(desc);
  8099. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8100. }
  8101. return desc;
  8102. });
  8103. }
  8104. TraceablePeerConnection.prototype.addStream = function (stream) {
  8105. this.trace('addStream', stream.id);
  8106. try
  8107. {
  8108. this.peerconnection.addStream(stream);
  8109. }
  8110. catch (e)
  8111. {
  8112. logger.error(e);
  8113. }
  8114. };
  8115. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8116. this.trace('removeStream', stream.id);
  8117. if(stopStreams) {
  8118. stream.getAudioTracks().forEach(function (track) {
  8119. // stop() not supported with IE
  8120. if (track.stop) {
  8121. track.stop();
  8122. }
  8123. });
  8124. stream.getVideoTracks().forEach(function (track) {
  8125. // stop() not supported with IE
  8126. if (track.stop) {
  8127. track.stop();
  8128. }
  8129. });
  8130. if (stream.stop) {
  8131. stream.stop();
  8132. }
  8133. }
  8134. try {
  8135. // FF doesn't support this yet.
  8136. if (this.peerconnection.removeStream)
  8137. this.peerconnection.removeStream(stream);
  8138. } catch (e) {
  8139. logger.error(e);
  8140. }
  8141. };
  8142. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8143. this.trace('createDataChannel', label, opts);
  8144. return this.peerconnection.createDataChannel(label, opts);
  8145. };
  8146. TraceablePeerConnection.prototype.setLocalDescription
  8147. = function (description, successCallback, failureCallback) {
  8148. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8149. // if we're running on FF, transform to Plan A first.
  8150. if (RTCBrowserType.usesUnifiedPlan()) {
  8151. description = this.interop.toUnifiedPlan(description);
  8152. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8153. }
  8154. var self = this;
  8155. this.peerconnection.setLocalDescription(description,
  8156. function () {
  8157. self.trace('setLocalDescriptionOnSuccess');
  8158. successCallback();
  8159. },
  8160. function (err) {
  8161. self.trace('setLocalDescriptionOnFailure', err);
  8162. failureCallback(err);
  8163. }
  8164. );
  8165. /*
  8166. if (this.statsinterval === null && this.maxstats > 0) {
  8167. // start gathering stats
  8168. }
  8169. */
  8170. };
  8171. TraceablePeerConnection.prototype.setRemoteDescription
  8172. = function (description, successCallback, failureCallback) {
  8173. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  8174. // TODO the focus should squeze or explode the remote simulcast
  8175. description = this.simulcast.mungeRemoteDescription(description);
  8176. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  8177. // if we're running on FF, transform to Plan A first.
  8178. if (RTCBrowserType.usesUnifiedPlan()) {
  8179. description = this.interop.toUnifiedPlan(description);
  8180. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  8181. }
  8182. if (RTCBrowserType.usesPlanB()) {
  8183. description = normalizePlanB(description);
  8184. }
  8185. var self = this;
  8186. this.peerconnection.setRemoteDescription(description,
  8187. function () {
  8188. self.trace('setRemoteDescriptionOnSuccess');
  8189. successCallback();
  8190. },
  8191. function (err) {
  8192. self.trace('setRemoteDescriptionOnFailure', err);
  8193. failureCallback(err);
  8194. }
  8195. );
  8196. /*
  8197. if (this.statsinterval === null && this.maxstats > 0) {
  8198. // start gathering stats
  8199. }
  8200. */
  8201. };
  8202. TraceablePeerConnection.prototype.close = function () {
  8203. this.trace('stop');
  8204. if (this.statsinterval !== null) {
  8205. window.clearInterval(this.statsinterval);
  8206. this.statsinterval = null;
  8207. }
  8208. this.peerconnection.close();
  8209. };
  8210. TraceablePeerConnection.prototype.createOffer
  8211. = function (successCallback, failureCallback, constraints) {
  8212. var self = this;
  8213. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  8214. this.peerconnection.createOffer(
  8215. function (offer) {
  8216. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  8217. // NOTE this is not tested because in meet the focus generates the
  8218. // offer.
  8219. // if we're running on FF, transform to Plan B first.
  8220. if (RTCBrowserType.usesUnifiedPlan()) {
  8221. offer = self.interop.toPlanB(offer);
  8222. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  8223. }
  8224. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  8225. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8226. offer = self.simulcast.mungeLocalDescription(offer);
  8227. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  8228. }
  8229. successCallback(offer);
  8230. },
  8231. function(err) {
  8232. self.trace('createOfferOnFailure', err);
  8233. failureCallback(err);
  8234. },
  8235. constraints
  8236. );
  8237. };
  8238. TraceablePeerConnection.prototype.createAnswer
  8239. = function (successCallback, failureCallback, constraints) {
  8240. var self = this;
  8241. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  8242. this.peerconnection.createAnswer(
  8243. function (answer) {
  8244. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  8245. // if we're running on FF, transform to Plan A first.
  8246. if (RTCBrowserType.usesUnifiedPlan()) {
  8247. answer = self.interop.toPlanB(answer);
  8248. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  8249. }
  8250. // munge local video SSRC
  8251. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  8252. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8253. answer = self.simulcast.mungeLocalDescription(answer);
  8254. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  8255. }
  8256. successCallback(answer);
  8257. },
  8258. function(err) {
  8259. self.trace('createAnswerOnFailure', err);
  8260. failureCallback(err);
  8261. },
  8262. constraints
  8263. );
  8264. };
  8265. TraceablePeerConnection.prototype.addIceCandidate
  8266. = function (candidate, successCallback, failureCallback) {
  8267. //var self = this;
  8268. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  8269. this.peerconnection.addIceCandidate(candidate);
  8270. /* maybe later
  8271. this.peerconnection.addIceCandidate(candidate,
  8272. function () {
  8273. self.trace('addIceCandidateOnSuccess');
  8274. successCallback();
  8275. },
  8276. function (err) {
  8277. self.trace('addIceCandidateOnFailure', err);
  8278. failureCallback(err);
  8279. }
  8280. );
  8281. */
  8282. };
  8283. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  8284. // TODO: Is this the correct way to handle Opera, Temasys?
  8285. if (RTCBrowserType.isFirefox()) {
  8286. // ignore for now...
  8287. if(!errback)
  8288. errback = function () {};
  8289. this.peerconnection.getStats(null, callback, errback);
  8290. } else {
  8291. this.peerconnection.getStats(callback);
  8292. }
  8293. };
  8294. module.exports = TraceablePeerConnection;
  8295. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  8296. },{"../../service/xmpp/XMPPEvents":82,"../RTC/RTC":13,"../RTC/RTCBrowserType.js":14,"./LocalSSRCReplacement":26,"jitsi-meet-logger":44,"sdp-interop":62,"sdp-simulcast":65,"sdp-transform":72}],31:[function(require,module,exports){
  8297. (function (__filename){
  8298. /* global $, $iq, APP, config, messageHandler,
  8299. roomName, sessionTerminated, Strophe, Util */
  8300. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8301. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8302. var Settings = require("../settings/Settings");
  8303. var AuthenticationEvents
  8304. = require("../../service/authentication/AuthenticationEvents");
  8305. function createExpBackoffTimer(step) {
  8306. var count = 1;
  8307. return function (reset) {
  8308. // Reset call
  8309. if (reset) {
  8310. count = 1;
  8311. return;
  8312. }
  8313. // Calculate next timeout
  8314. var timeout = Math.pow(2, count - 1);
  8315. count += 1;
  8316. return timeout * step;
  8317. };
  8318. }
  8319. function Moderator(roomName, xmpp, emitter) {
  8320. this.roomName = roomName;
  8321. this.xmppService = xmpp;
  8322. this.getNextTimeout = createExpBackoffTimer(1000);
  8323. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  8324. // External authentication stuff
  8325. this.externalAuthEnabled = false;
  8326. this.settings = new Settings(roomName);
  8327. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  8328. // it will be enabled automatically if focus detects the component through
  8329. // service discovery.
  8330. this.sipGatewayEnabled =
  8331. this.xmppService.options.hosts.call_control !== undefined;
  8332. this.eventEmitter = emitter;
  8333. this.connection = this.xmppService.connection;
  8334. this.focusUserJid;
  8335. //FIXME:
  8336. // Message listener that talks to POPUP window
  8337. function listener(event) {
  8338. if (event.data && event.data.sessionId) {
  8339. if (event.origin !== window.location.origin) {
  8340. logger.warn("Ignoring sessionId from different origin: " +
  8341. event.origin);
  8342. return;
  8343. }
  8344. localStorage.setItem('sessionId', event.data.sessionId);
  8345. // After popup is closed we will authenticate
  8346. }
  8347. }
  8348. // Register
  8349. if (window.addEventListener) {
  8350. window.addEventListener("message", listener, false);
  8351. } else {
  8352. window.attachEvent("onmessage", listener);
  8353. }
  8354. }
  8355. Moderator.prototype.isExternalAuthEnabled = function () {
  8356. return this.externalAuthEnabled;
  8357. };
  8358. Moderator.prototype.isSipGatewayEnabled = function () {
  8359. return this.sipGatewayEnabled;
  8360. };
  8361. Moderator.prototype.onMucMemberLeft = function (jid) {
  8362. logger.info("Someone left is it focus ? " + jid);
  8363. var resource = Strophe.getResourceFromJid(jid);
  8364. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  8365. logger.info(
  8366. "Focus has left the room - leaving conference");
  8367. //hangUp();
  8368. // We'd rather reload to have everything re-initialized
  8369. //FIXME: show some message before reload
  8370. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  8371. }
  8372. };
  8373. Moderator.prototype.setFocusUserJid = function (focusJid) {
  8374. if (!this.focusUserJid) {
  8375. this.focusUserJid = focusJid;
  8376. logger.info("Focus jid set to: " + this.focusUserJid);
  8377. }
  8378. };
  8379. Moderator.prototype.getFocusUserJid = function () {
  8380. return this.focusUserJid;
  8381. };
  8382. Moderator.prototype.getFocusComponent = function () {
  8383. // Get focus component address
  8384. var focusComponent = this.xmppService.options.hosts.focus;
  8385. // If not specified use default: 'focus.domain'
  8386. if (!focusComponent) {
  8387. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  8388. }
  8389. return focusComponent;
  8390. };
  8391. Moderator.prototype.createConferenceIq = function () {
  8392. // Generate create conference IQ
  8393. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  8394. // Session Id used for authentication
  8395. var sessionId = localStorage.getItem('sessionId');
  8396. var machineUID = this.settings.getSettings().uid;
  8397. logger.info(
  8398. "Session ID: " + sessionId + " machine UID: " + machineUID);
  8399. elem.c('conference', {
  8400. xmlns: 'http://jitsi.org/protocol/focus',
  8401. room: this.roomName,
  8402. 'machine-uid': machineUID
  8403. });
  8404. if (sessionId) {
  8405. elem.attrs({ 'session-id': sessionId});
  8406. }
  8407. if (this.xmppService.options.hosts.bridge !== undefined) {
  8408. elem.c(
  8409. 'property', {
  8410. name: 'bridge',
  8411. value: this.xmppService.options.hosts.bridge
  8412. }).up();
  8413. }
  8414. // Tell the focus we have Jigasi configured
  8415. if (this.xmppService.options.hosts.call_control !== undefined) {
  8416. elem.c(
  8417. 'property', {
  8418. name: 'call_control',
  8419. value: this.xmppService.options.hosts.call_control
  8420. }).up();
  8421. }
  8422. if (this.xmppService.options.channelLastN !== undefined) {
  8423. elem.c(
  8424. 'property', {
  8425. name: 'channelLastN',
  8426. value: this.xmppService.options.channelLastN
  8427. }).up();
  8428. }
  8429. if (this.xmppService.options.adaptiveLastN !== undefined) {
  8430. elem.c(
  8431. 'property', {
  8432. name: 'adaptiveLastN',
  8433. value: this.xmppService.options.adaptiveLastN
  8434. }).up();
  8435. }
  8436. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  8437. elem.c(
  8438. 'property', {
  8439. name: 'adaptiveSimulcast',
  8440. value: this.xmppService.options.adaptiveSimulcast
  8441. }).up();
  8442. }
  8443. if (this.xmppService.options.openSctp !== undefined) {
  8444. elem.c(
  8445. 'property', {
  8446. name: 'openSctp',
  8447. value: this.xmppService.options.openSctp
  8448. }).up();
  8449. }
  8450. if (this.xmppService.options.startAudioMuted !== undefined)
  8451. {
  8452. elem.c(
  8453. 'property', {
  8454. name: 'startAudioMuted',
  8455. value: this.xmppService.options.startAudioMuted
  8456. }).up();
  8457. }
  8458. if (this.xmppService.options.startVideoMuted !== undefined)
  8459. {
  8460. elem.c(
  8461. 'property', {
  8462. name: 'startVideoMuted',
  8463. value: this.xmppService.options.startVideoMuted
  8464. }).up();
  8465. }
  8466. elem.c(
  8467. 'property', {
  8468. name: 'simulcastMode',
  8469. value: 'rewriting'
  8470. }).up();
  8471. elem.up();
  8472. return elem;
  8473. };
  8474. Moderator.prototype.parseSessionId = function (resultIq) {
  8475. var sessionId = $(resultIq).find('conference').attr('session-id');
  8476. if (sessionId) {
  8477. logger.info('Received sessionId: ' + sessionId);
  8478. localStorage.setItem('sessionId', sessionId);
  8479. }
  8480. };
  8481. Moderator.prototype.parseConfigOptions = function (resultIq) {
  8482. this.setFocusUserJid(
  8483. $(resultIq).find('conference').attr('focusjid'));
  8484. var authenticationEnabled
  8485. = $(resultIq).find(
  8486. '>conference>property' +
  8487. '[name=\'authentication\'][value=\'true\']').length > 0;
  8488. logger.info("Authentication enabled: " + authenticationEnabled);
  8489. this.externalAuthEnabled = $(resultIq).find(
  8490. '>conference>property' +
  8491. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  8492. console.info(
  8493. 'External authentication enabled: ' + this.externalAuthEnabled);
  8494. if (!this.externalAuthEnabled) {
  8495. // We expect to receive sessionId in 'internal' authentication mode
  8496. this.parseSessionId(resultIq);
  8497. }
  8498. var authIdentity = $(resultIq).find('>conference').attr('identity');
  8499. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  8500. authenticationEnabled, authIdentity);
  8501. // Check if focus has auto-detected Jigasi component(this will be also
  8502. // included if we have passed our host from the config)
  8503. if ($(resultIq).find(
  8504. '>conference>property' +
  8505. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  8506. this.sipGatewayEnabled = true;
  8507. }
  8508. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  8509. };
  8510. // FIXME = we need to show the fact that we're waiting for the focus
  8511. // to the user(or that focus is not available)
  8512. Moderator.prototype.allocateConferenceFocus = function (callback) {
  8513. // Try to use focus user JID from the config
  8514. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  8515. // Send create conference IQ
  8516. var iq = this.createConferenceIq();
  8517. var self = this;
  8518. this.connection.sendIQ(
  8519. iq,
  8520. function (result) {
  8521. // Setup config options
  8522. self.parseConfigOptions(result);
  8523. if ('true' === $(result).find('conference').attr('ready')) {
  8524. // Reset both timers
  8525. self.getNextTimeout(true);
  8526. self.getNextErrorTimeout(true);
  8527. // Exec callback
  8528. callback();
  8529. } else {
  8530. var waitMs = self.getNextTimeout();
  8531. logger.info("Waiting for the focus... " + waitMs);
  8532. // Reset error timeout
  8533. self.getNextErrorTimeout(true);
  8534. window.setTimeout(
  8535. function () {
  8536. self.allocateConferenceFocus(callback);
  8537. }, waitMs);
  8538. }
  8539. },
  8540. function (error) {
  8541. // Invalid session ? remove and try again
  8542. // without session ID to get a new one
  8543. var invalidSession
  8544. = $(error).find('>error>session-invalid').length;
  8545. if (invalidSession) {
  8546. logger.info("Session expired! - removing");
  8547. localStorage.removeItem("sessionId");
  8548. }
  8549. if ($(error).find('>error>graceful-shutdown').length) {
  8550. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  8551. return;
  8552. }
  8553. // Check for error returned by the reservation system
  8554. var reservationErr = $(error).find('>error>reservation-error');
  8555. if (reservationErr.length) {
  8556. // Trigger error event
  8557. var errorCode = reservationErr.attr('error-code');
  8558. var errorMsg;
  8559. if ($(error).find('>error>text')) {
  8560. errorMsg = $(error).find('>error>text').text();
  8561. }
  8562. self.eventEmitter.emit(
  8563. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  8564. return;
  8565. }
  8566. // Not authorized to create new room
  8567. if ($(error).find('>error>not-authorized').length) {
  8568. logger.warn("Unauthorized to start the conference", error);
  8569. var toDomain
  8570. = Strophe.getDomainFromJid(error.getAttribute('to'));
  8571. if (toDomain !==
  8572. this.xmppService.options.hosts.anonymousdomain) {
  8573. //FIXME: "is external" should come either from
  8574. // the focus or config.js
  8575. self.externalAuthEnabled = true;
  8576. }
  8577. self.eventEmitter.emit(
  8578. XMPPEvents.AUTHENTICATION_REQUIRED,
  8579. function () {
  8580. self.allocateConferenceFocus(
  8581. callback);
  8582. });
  8583. return;
  8584. }
  8585. var waitMs = self.getNextErrorTimeout();
  8586. logger.error("Focus error, retry after " + waitMs, error);
  8587. // Show message
  8588. var focusComponent = self.getFocusComponent();
  8589. var retrySec = waitMs / 1000;
  8590. //FIXME: message is duplicated ?
  8591. // Do not show in case of session invalid
  8592. // which means just a retry
  8593. if (!invalidSession) {
  8594. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  8595. focusComponent, retrySec);
  8596. }
  8597. // Reset response timeout
  8598. self.getNextTimeout(true);
  8599. window.setTimeout(
  8600. function () {
  8601. self.allocateConferenceFocus(callback);
  8602. }, waitMs);
  8603. }
  8604. );
  8605. };
  8606. Moderator.prototype.getLoginUrl = function (urlCallback) {
  8607. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  8608. iq.c('login-url', {
  8609. xmlns: 'http://jitsi.org/protocol/focus',
  8610. room: this.roomName,
  8611. 'machine-uid': this.settings.getSettings().uid
  8612. });
  8613. this.connection.sendIQ(
  8614. iq,
  8615. function (result) {
  8616. var url = $(result).find('login-url').attr('url');
  8617. url = url = decodeURIComponent(url);
  8618. if (url) {
  8619. logger.info("Got auth url: " + url);
  8620. urlCallback(url);
  8621. } else {
  8622. logger.error(
  8623. "Failed to get auth url from the focus", result);
  8624. }
  8625. },
  8626. function (error) {
  8627. logger.error("Get auth url error", error);
  8628. }
  8629. );
  8630. };
  8631. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  8632. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  8633. iq.c('login-url', {
  8634. xmlns: 'http://jitsi.org/protocol/focus',
  8635. room: this.roomName,
  8636. 'machine-uid': this.settings.getSettings().uid,
  8637. popup: true
  8638. });
  8639. this.connection.sendIQ(
  8640. iq,
  8641. function (result) {
  8642. var url = $(result).find('login-url').attr('url');
  8643. url = url = decodeURIComponent(url);
  8644. if (url) {
  8645. logger.info("Got POPUP auth url: " + url);
  8646. urlCallback(url);
  8647. } else {
  8648. logger.error(
  8649. "Failed to get POPUP auth url from the focus", result);
  8650. }
  8651. },
  8652. function (error) {
  8653. logger.error('Get POPUP auth url error', error);
  8654. }
  8655. );
  8656. };
  8657. Moderator.prototype.logout = function (callback) {
  8658. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  8659. var sessionId = localStorage.getItem('sessionId');
  8660. if (!sessionId) {
  8661. callback();
  8662. return;
  8663. }
  8664. iq.c('logout', {
  8665. xmlns: 'http://jitsi.org/protocol/focus',
  8666. 'session-id': sessionId
  8667. });
  8668. this.connection.sendIQ(
  8669. iq,
  8670. function (result) {
  8671. var logoutUrl = $(result).find('logout').attr('logout-url');
  8672. if (logoutUrl) {
  8673. logoutUrl = decodeURIComponent(logoutUrl);
  8674. }
  8675. logger.info("Log out OK, url: " + logoutUrl, result);
  8676. localStorage.removeItem('sessionId');
  8677. callback(logoutUrl);
  8678. },
  8679. function (error) {
  8680. logger.error("Logout error", error);
  8681. }
  8682. );
  8683. };
  8684. module.exports = Moderator;
  8685. }).call(this,"/modules/xmpp/moderator.js")
  8686. },{"../../service/authentication/AuthenticationEvents":79,"../../service/xmpp/XMPPEvents":82,"../settings/Settings":18,"jitsi-meet-logger":44}],32:[function(require,module,exports){
  8687. (function (__filename){
  8688. /* jshint -W117 */
  8689. /* a simple MUC connection plugin
  8690. * can only handle a single MUC room
  8691. */
  8692. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8693. var ChatRoom = require("./ChatRoom");
  8694. module.exports = function(XMPP) {
  8695. Strophe.addConnectionPlugin('emuc', {
  8696. connection: null,
  8697. rooms: {},//map with the rooms
  8698. init: function (conn) {
  8699. this.connection = conn;
  8700. // add handlers (just once)
  8701. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  8702. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  8703. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  8704. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  8705. },
  8706. createRoom: function (jid, password, options) {
  8707. var roomJid = Strophe.getBareJidFromJid(jid);
  8708. if (this.rooms[roomJid]) {
  8709. logger.error("You are already in the room!");
  8710. return;
  8711. }
  8712. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  8713. return this.rooms[roomJid];
  8714. },
  8715. doLeave: function (jid) {
  8716. this.rooms[jid].doLeave();
  8717. delete this.rooms[jid];
  8718. },
  8719. onPresence: function (pres) {
  8720. var from = pres.getAttribute('from');
  8721. // What is this for? A workaround for something?
  8722. if (pres.getAttribute('type')) {
  8723. return true;
  8724. }
  8725. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8726. if(!room)
  8727. return;
  8728. // Parse status.
  8729. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  8730. room.createNonAnonymousRoom();
  8731. }
  8732. room.onPresence(pres);
  8733. return true;
  8734. },
  8735. onPresenceUnavailable: function (pres) {
  8736. var from = pres.getAttribute('from');
  8737. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8738. if(!room)
  8739. return;
  8740. room.onPresenceUnavailable(pres, from);
  8741. return true;
  8742. },
  8743. onPresenceError: function (pres) {
  8744. var from = pres.getAttribute('from');
  8745. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8746. if(!room)
  8747. return;
  8748. room.onPresenceError(pres, from);
  8749. return true;
  8750. },
  8751. onMessage: function (msg) {
  8752. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  8753. var from = msg.getAttribute('from');
  8754. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8755. if(!room)
  8756. return;
  8757. room.onMessage(msg, from);
  8758. return true;
  8759. },
  8760. setJingleSession: function (from, session) {
  8761. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8762. if(!room)
  8763. return;
  8764. room.setJingleSession(session);
  8765. }
  8766. });
  8767. };
  8768. }).call(this,"/modules/xmpp/strophe.emuc.js")
  8769. },{"./ChatRoom":23,"jitsi-meet-logger":44}],33:[function(require,module,exports){
  8770. (function (__filename){
  8771. /* jshint -W117 */
  8772. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8773. var JingleSession = require("./JingleSessionPC");
  8774. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8775. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8776. module.exports = function(XMPP, eventEmitter) {
  8777. Strophe.addConnectionPlugin('jingle', {
  8778. connection: null,
  8779. sessions: {},
  8780. jid2session: {},
  8781. ice_config: {iceServers: []},
  8782. media_constraints: {
  8783. mandatory: {
  8784. 'OfferToReceiveAudio': true,
  8785. 'OfferToReceiveVideo': true
  8786. }
  8787. // MozDontOfferDataChannel: true when this is firefox
  8788. },
  8789. init: function (conn) {
  8790. this.connection = conn;
  8791. if (this.connection.disco) {
  8792. // http://xmpp.org/extensions/xep-0167.html#support
  8793. // http://xmpp.org/extensions/xep-0176.html#support
  8794. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  8795. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  8796. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  8797. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  8798. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  8799. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  8800. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  8801. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  8802. || RTCBrowserType.isTemasysPluginUsed()) {
  8803. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  8804. }
  8805. // this is dealt with by SDP O/A so we don't need to announce this
  8806. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  8807. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  8808. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  8809. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  8810. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  8811. }
  8812. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  8813. },
  8814. onJingle: function (iq) {
  8815. var sid = $(iq).find('jingle').attr('sid');
  8816. var action = $(iq).find('jingle').attr('action');
  8817. var fromJid = iq.getAttribute('from');
  8818. // send ack first
  8819. var ack = $iq({type: 'result',
  8820. to: fromJid,
  8821. id: iq.getAttribute('id')
  8822. });
  8823. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  8824. var sess = this.sessions[sid];
  8825. if ('session-initiate' != action) {
  8826. if (sess === null) {
  8827. ack.type = 'error';
  8828. ack.c('error', {type: 'cancel'})
  8829. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  8830. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  8831. this.connection.send(ack);
  8832. return true;
  8833. }
  8834. // local jid is not checked
  8835. if (fromJid != sess.peerjid) {
  8836. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  8837. ack.type = 'error';
  8838. ack.c('error', {type: 'cancel'})
  8839. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  8840. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  8841. this.connection.send(ack);
  8842. return true;
  8843. }
  8844. } else if (sess !== undefined) {
  8845. // existing session with same session id
  8846. // this might be out-of-order if the sess.peerjid is the same as from
  8847. ack.type = 'error';
  8848. ack.c('error', {type: 'cancel'})
  8849. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  8850. logger.warn('duplicate session id', sid);
  8851. this.connection.send(ack);
  8852. return true;
  8853. }
  8854. // FIXME: check for a defined action
  8855. this.connection.send(ack);
  8856. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  8857. switch (action) {
  8858. case 'session-initiate':
  8859. var startMuted = $(iq).find('jingle>startmuted');
  8860. if (startMuted && startMuted.length > 0) {
  8861. var audioMuted = startMuted.attr("audio");
  8862. var videoMuted = startMuted.attr("video");
  8863. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  8864. audioMuted === "true", videoMuted === "true");
  8865. }
  8866. sess = new JingleSession(
  8867. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  8868. this.connection, XMPP);
  8869. // configure session
  8870. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  8871. this.connection.emuc.setJingleSession(fromBareJid, sess);
  8872. sess.media_constraints = this.media_constraints;
  8873. sess.ice_config = this.ice_config;
  8874. sess.initialize(fromJid, false);
  8875. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  8876. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  8877. sess.setOffer($(iq).find('>jingle'));
  8878. this.sessions[sess.sid] = sess;
  8879. this.jid2session[sess.peerjid] = sess;
  8880. // the callback should either
  8881. // .sendAnswer and .accept
  8882. // or .sendTerminate -- not necessarily synchronous
  8883. sess.sendAnswer();
  8884. sess.accept();
  8885. break;
  8886. case 'session-accept':
  8887. sess.setAnswer($(iq).find('>jingle'));
  8888. sess.accept();
  8889. break;
  8890. case 'session-terminate':
  8891. // If this is not the focus sending the terminate, we have
  8892. // nothing more to do here.
  8893. if (Object.keys(this.sessions).length < 1
  8894. || !(this.sessions[Object.keys(this.sessions)[0]]
  8895. instanceof JingleSession))
  8896. {
  8897. break;
  8898. }
  8899. logger.log('terminating...', sess.sid);
  8900. sess.terminate();
  8901. this.terminate(sess.sid);
  8902. if ($(iq).find('>jingle>reason').length) {
  8903. $(document).trigger('callterminated.jingle', [
  8904. sess.sid,
  8905. sess.peerjid,
  8906. $(iq).find('>jingle>reason>:first')[0].tagName,
  8907. $(iq).find('>jingle>reason>text').text()
  8908. ]);
  8909. } else {
  8910. $(document).trigger('callterminated.jingle',
  8911. [sess.sid, sess.peerjid]);
  8912. }
  8913. break;
  8914. case 'transport-info':
  8915. sess.addIceCandidate($(iq).find('>jingle>content'));
  8916. break;
  8917. case 'session-info':
  8918. var affected;
  8919. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  8920. $(document).trigger('ringing.jingle', [sess.sid]);
  8921. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  8922. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  8923. $(document).trigger('mute.jingle', [sess.sid, affected]);
  8924. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  8925. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  8926. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  8927. }
  8928. break;
  8929. case 'addsource': // FIXME: proprietary, un-jingleish
  8930. case 'source-add': // FIXME: proprietary
  8931. sess.addSource($(iq).find('>jingle>content'), fromJid);
  8932. break;
  8933. case 'removesource': // FIXME: proprietary, un-jingleish
  8934. case 'source-remove': // FIXME: proprietary
  8935. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  8936. break;
  8937. default:
  8938. logger.warn('jingle action not implemented', action);
  8939. break;
  8940. }
  8941. return true;
  8942. },
  8943. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  8944. if (sid === null || sid === undefined) {
  8945. for (sid in this.sessions) {
  8946. if (this.sessions[sid].state != 'ended') {
  8947. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  8948. this.sessions[sid].terminate();
  8949. }
  8950. delete this.jid2session[this.sessions[sid].peerjid];
  8951. delete this.sessions[sid];
  8952. }
  8953. } else if (this.sessions.hasOwnProperty(sid)) {
  8954. if (this.sessions[sid].state != 'ended') {
  8955. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  8956. this.sessions[sid].terminate();
  8957. }
  8958. delete this.jid2session[this.sessions[sid].peerjid];
  8959. delete this.sessions[sid];
  8960. }
  8961. },
  8962. getStunAndTurnCredentials: function () {
  8963. // get stun and turn configuration from server via xep-0215
  8964. // uses time-limited credentials as described in
  8965. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  8966. //
  8967. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  8968. // for a prosody module which implements this
  8969. //
  8970. // currently, this doesn't work with updateIce and therefore credentials with a long
  8971. // validity have to be fetched before creating the peerconnection
  8972. // TODO: implement refresh via updateIce as described in
  8973. // https://code.google.com/p/webrtc/issues/detail?id=1650
  8974. var self = this;
  8975. this.connection.sendIQ(
  8976. $iq({type: 'get', to: this.connection.domain})
  8977. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  8978. function (res) {
  8979. var iceservers = [];
  8980. $(res).find('>services>service').each(function (idx, el) {
  8981. el = $(el);
  8982. var dict = {};
  8983. var type = el.attr('type');
  8984. switch (type) {
  8985. case 'stun':
  8986. dict.url = 'stun:' + el.attr('host');
  8987. if (el.attr('port')) {
  8988. dict.url += ':' + el.attr('port');
  8989. }
  8990. iceservers.push(dict);
  8991. break;
  8992. case 'turn':
  8993. case 'turns':
  8994. dict.url = type + ':';
  8995. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  8996. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  8997. dict.url += el.attr('username') + '@';
  8998. } else {
  8999. dict.username = el.attr('username'); // only works in M28
  9000. }
  9001. }
  9002. dict.url += el.attr('host');
  9003. if (el.attr('port') && el.attr('port') != '3478') {
  9004. dict.url += ':' + el.attr('port');
  9005. }
  9006. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9007. dict.url += '?transport=' + el.attr('transport');
  9008. }
  9009. if (el.attr('password')) {
  9010. dict.credential = el.attr('password');
  9011. }
  9012. iceservers.push(dict);
  9013. break;
  9014. }
  9015. });
  9016. self.ice_config.iceServers = iceservers;
  9017. },
  9018. function (err) {
  9019. logger.warn('getting turn credentials failed', err);
  9020. logger.warn('is mod_turncredentials or similar installed?');
  9021. }
  9022. );
  9023. // implement push?
  9024. },
  9025. /**
  9026. * Returns the data saved in 'updateLog' in a format to be logged.
  9027. */
  9028. getLog: function () {
  9029. var data = {};
  9030. var self = this;
  9031. Object.keys(this.sessions).forEach(function (sid) {
  9032. var session = self.sessions[sid];
  9033. if (session.peerconnection && session.peerconnection.updateLog) {
  9034. // FIXME: should probably be a .dump call
  9035. data["jingle_" + session.sid] = {
  9036. updateLog: session.peerconnection.updateLog,
  9037. stats: session.peerconnection.stats,
  9038. url: window.location.href
  9039. };
  9040. }
  9041. });
  9042. return data;
  9043. }
  9044. });
  9045. };
  9046. }).call(this,"/modules/xmpp/strophe.jingle.js")
  9047. },{"../../service/xmpp/XMPPEvents":82,"../RTC/RTCBrowserType":14,"./JingleSessionPC":25,"jitsi-meet-logger":44}],34:[function(require,module,exports){
  9048. /* global Strophe */
  9049. module.exports = function () {
  9050. Strophe.addConnectionPlugin('logger', {
  9051. // logs raw stanzas and makes them available for download as JSON
  9052. connection: null,
  9053. log: [],
  9054. init: function (conn) {
  9055. this.connection = conn;
  9056. this.connection.rawInput = this.log_incoming.bind(this);
  9057. this.connection.rawOutput = this.log_outgoing.bind(this);
  9058. },
  9059. log_incoming: function (stanza) {
  9060. this.log.push([new Date().getTime(), 'incoming', stanza]);
  9061. },
  9062. log_outgoing: function (stanza) {
  9063. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  9064. }
  9065. });
  9066. };
  9067. },{}],35:[function(require,module,exports){
  9068. /* global $, $iq, Strophe */
  9069. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9070. /**
  9071. * Ping every 20 sec
  9072. */
  9073. var PING_INTERVAL = 20000;
  9074. /**
  9075. * Ping timeout error after 15 sec of waiting.
  9076. */
  9077. var PING_TIMEOUT = 15000;
  9078. /**
  9079. * Will close the connection after 3 consecutive ping errors.
  9080. */
  9081. var PING_THRESHOLD = 3;
  9082. /**
  9083. * XEP-0199 ping plugin.
  9084. *
  9085. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  9086. */
  9087. module.exports = function (XMPP, eventEmitter) {
  9088. Strophe.addConnectionPlugin('ping', {
  9089. connection: null,
  9090. failedPings: 0,
  9091. /**
  9092. * Initializes the plugin. Method called by Strophe.
  9093. * @param connection Strophe connection instance.
  9094. */
  9095. init: function (connection) {
  9096. this.connection = connection;
  9097. Strophe.addNamespace('PING', "urn:xmpp:ping");
  9098. },
  9099. /**
  9100. * Sends "ping" to given <tt>jid</tt>
  9101. * @param jid the JID to which ping request will be sent.
  9102. * @param success callback called on success.
  9103. * @param error callback called on error.
  9104. * @param timeout ms how long are we going to wait for the response. On
  9105. * timeout <tt>error<//t> callback is called with undefined error
  9106. * argument.
  9107. */
  9108. ping: function (jid, success, error, timeout) {
  9109. var iq = $iq({type: 'get', to: jid});
  9110. iq.c('ping', {xmlns: Strophe.NS.PING});
  9111. this.connection.sendIQ(iq, success, error, timeout);
  9112. },
  9113. /**
  9114. * Starts to send ping in given interval to specified remote JID.
  9115. * This plugin supports only one such task and <tt>stopInterval</tt>
  9116. * must be called before starting a new one.
  9117. * @param remoteJid remote JID to which ping requests will be sent to.
  9118. * @param interval task interval in ms.
  9119. */
  9120. startInterval: function (remoteJid, interval) {
  9121. if (this.intervalId) {
  9122. console.error("Ping task scheduled already");
  9123. return;
  9124. }
  9125. if (!interval)
  9126. interval = PING_INTERVAL;
  9127. var self = this;
  9128. this.intervalId = window.setInterval(function () {
  9129. self.ping(remoteJid,
  9130. function (result) {
  9131. // Ping OK
  9132. self.failedPings = 0;
  9133. },
  9134. function (error) {
  9135. self.failedPings += 1;
  9136. console.error(
  9137. "Ping " + (error ? "error" : "timeout"), error);
  9138. if (self.failedPings >= PING_THRESHOLD) {
  9139. self.connection.disconnect();
  9140. }
  9141. }, PING_TIMEOUT);
  9142. }, interval);
  9143. console.info("XMPP pings will be sent every " + interval + " ms");
  9144. },
  9145. /**
  9146. * Stops current "ping" interval task.
  9147. */
  9148. stopInterval: function () {
  9149. if (this.intervalId) {
  9150. window.clearInterval(this.intervalId);
  9151. this.intervalId = null;
  9152. this.failedPings = 0;
  9153. console.info("Ping interval cleared");
  9154. }
  9155. }
  9156. });
  9157. };
  9158. },{"../../service/xmpp/XMPPEvents":82}],36:[function(require,module,exports){
  9159. (function (__filename){
  9160. /* jshint -W117 */
  9161. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9162. module.exports = function() {
  9163. Strophe.addConnectionPlugin('rayo',
  9164. {
  9165. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  9166. connection: null,
  9167. init: function (conn) {
  9168. this.connection = conn;
  9169. if (this.connection.disco) {
  9170. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  9171. }
  9172. this.connection.addHandler(
  9173. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  9174. },
  9175. onRayo: function (iq) {
  9176. logger.info("Rayo IQ", iq);
  9177. },
  9178. dial: function (to, from, roomName, roomPass) {
  9179. var self = this;
  9180. var req = $iq(
  9181. {
  9182. type: 'set',
  9183. to: this.connection.emuc.focusMucJid
  9184. }
  9185. );
  9186. req.c('dial',
  9187. {
  9188. xmlns: this.RAYO_XMLNS,
  9189. to: to,
  9190. from: from
  9191. });
  9192. req.c('header',
  9193. {
  9194. name: 'JvbRoomName',
  9195. value: roomName
  9196. }).up();
  9197. if (roomPass !== null && roomPass.length) {
  9198. req.c('header',
  9199. {
  9200. name: 'JvbRoomPassword',
  9201. value: roomPass
  9202. }).up();
  9203. }
  9204. this.connection.sendIQ(
  9205. req,
  9206. function (result) {
  9207. logger.info('Dial result ', result);
  9208. var resource = $(result).find('ref').attr('uri');
  9209. this.call_resource = resource.substr('xmpp:'.length);
  9210. logger.info(
  9211. "Received call resource: " + this.call_resource);
  9212. },
  9213. function (error) {
  9214. logger.info('Dial error ', error);
  9215. }
  9216. );
  9217. },
  9218. hang_up: function () {
  9219. if (!this.call_resource) {
  9220. logger.warn("No call in progress");
  9221. return;
  9222. }
  9223. var self = this;
  9224. var req = $iq(
  9225. {
  9226. type: 'set',
  9227. to: this.call_resource
  9228. }
  9229. );
  9230. req.c('hangup',
  9231. {
  9232. xmlns: this.RAYO_XMLNS
  9233. });
  9234. this.connection.sendIQ(
  9235. req,
  9236. function (result) {
  9237. logger.info('Hangup result ', result);
  9238. self.call_resource = null;
  9239. },
  9240. function (error) {
  9241. logger.info('Hangup error ', error);
  9242. self.call_resource = null;
  9243. }
  9244. );
  9245. }
  9246. }
  9247. );
  9248. };
  9249. }).call(this,"/modules/xmpp/strophe.rayo.js")
  9250. },{"jitsi-meet-logger":44}],37:[function(require,module,exports){
  9251. (function (__filename){
  9252. /**
  9253. * Strophe logger implementation. Logs from level WARN and above.
  9254. */
  9255. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9256. module.exports = function () {
  9257. Strophe.log = function (level, msg) {
  9258. switch (level) {
  9259. case Strophe.LogLevel.WARN:
  9260. logger.warn("Strophe: " + msg);
  9261. break;
  9262. case Strophe.LogLevel.ERROR:
  9263. case Strophe.LogLevel.FATAL:
  9264. logger.error("Strophe: " + msg);
  9265. break;
  9266. }
  9267. };
  9268. Strophe.getStatusString = function (status) {
  9269. switch (status) {
  9270. case Strophe.Status.ERROR:
  9271. return "ERROR";
  9272. case Strophe.Status.CONNECTING:
  9273. return "CONNECTING";
  9274. case Strophe.Status.CONNFAIL:
  9275. return "CONNFAIL";
  9276. case Strophe.Status.AUTHENTICATING:
  9277. return "AUTHENTICATING";
  9278. case Strophe.Status.AUTHFAIL:
  9279. return "AUTHFAIL";
  9280. case Strophe.Status.CONNECTED:
  9281. return "CONNECTED";
  9282. case Strophe.Status.DISCONNECTED:
  9283. return "DISCONNECTED";
  9284. case Strophe.Status.DISCONNECTING:
  9285. return "DISCONNECTING";
  9286. case Strophe.Status.ATTACHED:
  9287. return "ATTACHED";
  9288. default:
  9289. return "unknown";
  9290. }
  9291. };
  9292. };
  9293. }).call(this,"/modules/xmpp/strophe.util.js")
  9294. },{"jitsi-meet-logger":44}],38:[function(require,module,exports){
  9295. (function (__filename){
  9296. /* global $, APP, config, Strophe*/
  9297. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9298. var EventEmitter = require("events");
  9299. var Pako = require("pako");
  9300. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9301. var RTCEvents = require("../../service/RTC/RTCEvents");
  9302. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9303. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  9304. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9305. var RTC = require("../RTC/RTC");
  9306. var authenticatedUser = false;
  9307. function createConnection(bosh) {
  9308. bosh = bosh || '/http-bind';
  9309. return new Strophe.Connection(bosh);
  9310. };
  9311. //!!!!!!!!!! FIXME: ...
  9312. function initStrophePlugins(XMPP)
  9313. {
  9314. require("./strophe.emuc")(XMPP);
  9315. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  9316. // require("./strophe.moderate")(XMPP, eventEmitter);
  9317. require("./strophe.util")();
  9318. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  9319. require("./strophe.rayo")();
  9320. require("./strophe.logger")();
  9321. }
  9322. //!!!!!!!!!! FIXME: ...
  9323. ///**
  9324. // * If given <tt>localStream</tt> is video one this method will advertise it's
  9325. // * video type in MUC presence.
  9326. // * @param localStream new or modified <tt>LocalStream</tt>.
  9327. // */
  9328. //function broadcastLocalVideoType(localStream) {
  9329. // if (localStream.videoType)
  9330. // XMPP.addToPresence('videoType', localStream.videoType);
  9331. //}
  9332. //
  9333. //function registerListeners() {
  9334. // RTC.addStreamListener(
  9335. // broadcastLocalVideoType,
  9336. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  9337. // );
  9338. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  9339. // XMPP.addToPresence("devices", devices);
  9340. // });
  9341. //}
  9342. function XMPP(options) {
  9343. this.eventEmitter = new EventEmitter();
  9344. this.connection = null;
  9345. this.disconnectInProgress = false;
  9346. this.forceMuted = false;
  9347. this.options = options;
  9348. initStrophePlugins(this);
  9349. // registerListeners();
  9350. this.connection = createConnection(options.bosh);
  9351. }
  9352. XMPP.prototype.getConnection = function(){ return connection; };
  9353. XMPP.prototype._connect = function (jid, password) {
  9354. var self = this;
  9355. // connection.connect() starts the connection process.
  9356. //
  9357. // As the connection process proceeds, the user supplied callback will
  9358. // be triggered multiple times with status updates. The callback should
  9359. // take two arguments - the status code and the error condition.
  9360. //
  9361. // The status code will be one of the values in the Strophe.Status
  9362. // constants. The error condition will be one of the conditions defined
  9363. // in RFC 3920 or the condition ‘strophe-parsererror’.
  9364. //
  9365. // The Parameters wait, hold and route are optional and only relevant
  9366. // for BOSH connections. Please see XEP 124 for a more detailed
  9367. // explanation of the optional parameters.
  9368. //
  9369. // Connection status constants for use by the connection handler
  9370. // callback.
  9371. //
  9372. // Status.ERROR - An error has occurred (websockets specific)
  9373. // Status.CONNECTING - The connection is currently being made
  9374. // Status.CONNFAIL - The connection attempt failed
  9375. // Status.AUTHENTICATING - The connection is authenticating
  9376. // Status.AUTHFAIL - The authentication attempt failed
  9377. // Status.CONNECTED - The connection has succeeded
  9378. // Status.DISCONNECTED - The connection has been terminated
  9379. // Status.DISCONNECTING - The connection is currently being terminated
  9380. // Status.ATTACHED - The connection has been attached
  9381. var anonymousConnectionFailed = false;
  9382. var connectionFailed = false;
  9383. var lastErrorMsg;
  9384. this.connection.connect(jid, password, function (status, msg) {
  9385. logger.log('Strophe status changed to',
  9386. Strophe.getStatusString(status), msg);
  9387. if (status === Strophe.Status.CONNECTED) {
  9388. if (self.options.useStunTurn) {
  9389. self.connection.jingle.getStunAndTurnCredentials();
  9390. }
  9391. logger.info("My Jabber ID: " + self.connection.jid);
  9392. self.connection.ping.startInterval(
  9393. Strophe.getDomainFromJid(self.connection.jid));
  9394. if (password)
  9395. authenticatedUser = true;
  9396. if (self.connection && self.connection.connected &&
  9397. Strophe.getResourceFromJid(self.connection.jid)) {
  9398. // .connected is true while connecting?
  9399. // self.connection.send($pres());
  9400. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  9401. Strophe.getResourceFromJid(self.connection.jid));
  9402. }
  9403. } else if (status === Strophe.Status.CONNFAIL) {
  9404. if (msg === 'x-strophe-bad-non-anon-jid') {
  9405. anonymousConnectionFailed = true;
  9406. }
  9407. else
  9408. {
  9409. connectionFailed = true;
  9410. }
  9411. lastErrorMsg = msg;
  9412. } else if (status === Strophe.Status.DISCONNECTED) {
  9413. // Stop ping interval
  9414. self.connection.ping.stopInterval();
  9415. self.disconnectInProgress = false;
  9416. if (anonymousConnectionFailed) {
  9417. // prompt user for username and password
  9418. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9419. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9420. } else if(connectionFailed) {
  9421. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9422. JitsiConnectionErrors.OTHER_ERROR,
  9423. msg ? msg : lastErrorMsg);
  9424. } else {
  9425. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  9426. msg ? msg : lastErrorMsg);
  9427. }
  9428. } else if (status === Strophe.Status.AUTHFAIL) {
  9429. // wrong password or username, prompt user
  9430. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9431. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9432. }
  9433. });
  9434. }
  9435. XMPP.prototype.connect = function (jid, password) {
  9436. if(!jid) {
  9437. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  9438. // Force authenticated domain if room is appended with '?login=true'
  9439. if (this.options.hosts.anonymousdomain &&
  9440. window.location.search.indexOf("login=true") !== -1) {
  9441. configDomain = this.options.hosts.domain;
  9442. }
  9443. jid = configDomain || window.location.hostname;
  9444. }
  9445. return this._connect(jid, password);
  9446. };
  9447. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  9448. var roomjid = roomName + '@' + this.options.hosts.muc;
  9449. if (useNicks) {
  9450. if (nick) {
  9451. roomjid += '/' + nick;
  9452. } else {
  9453. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  9454. }
  9455. } else {
  9456. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  9457. if(!authenticatedUser)
  9458. tmpJid = tmpJid.substr(0, 8);
  9459. roomjid += '/' + tmpJid;
  9460. }
  9461. return this.connection.emuc.createRoom(roomjid, null, options);
  9462. }
  9463. XMPP.prototype.addListener = function(type, listener) {
  9464. this.eventEmitter.on(type, listener);
  9465. };
  9466. XMPP.prototype.removeListener = function (type, listener) {
  9467. this.eventEmitter.removeListener(type, listener);
  9468. };
  9469. //FIXME: this should work with the room
  9470. XMPP.prototype.leaveRoom = function (jid) {
  9471. var handler = this.connection.jingle.jid2session[jid];
  9472. if (handler && handler.peerconnection) {
  9473. // FIXME: probably removing streams is not required and close() should
  9474. // be enough
  9475. if (RTC.localAudio) {
  9476. handler.peerconnection.removeStream(
  9477. RTC.localAudio.getOriginalStream(), true);
  9478. }
  9479. if (RTC.localVideo) {
  9480. handler.peerconnection.removeStream(
  9481. RTC.localVideo.getOriginalStream(), true);
  9482. }
  9483. handler.peerconnection.close();
  9484. }
  9485. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  9486. this.connection.emuc.doLeave(jid);
  9487. };
  9488. /**
  9489. * Sends 'data' as a log message to the focus. Returns true iff a message
  9490. * was sent.
  9491. * @param data
  9492. * @returns {boolean} true iff a message was sent.
  9493. */
  9494. XMPP.prototype.sendLogs = function (data) {
  9495. if(!this.connection.emuc.focusMucJid)
  9496. return false;
  9497. var deflate = true;
  9498. var content = JSON.stringify(data);
  9499. if (deflate) {
  9500. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  9501. }
  9502. content = Base64.encode(content);
  9503. // XEP-0337-ish
  9504. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  9505. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  9506. id: 'PeerConnectionStats'});
  9507. message.c('message').t(content).up();
  9508. if (deflate) {
  9509. message.c('tag', {name: "deflated", value: "true"}).up();
  9510. }
  9511. message.up();
  9512. this.connection.send(message);
  9513. return true;
  9514. };
  9515. // Gets the logs from strophe.jingle.
  9516. XMPP.prototype.getJingleLog = function () {
  9517. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  9518. };
  9519. // Gets the logs from strophe.
  9520. XMPP.prototype.getXmppLog = function () {
  9521. return this.connection.logger ? this.connection.logger.log : null;
  9522. };
  9523. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  9524. this.connection.rayo.dial(to, from, roomName,roomPass);
  9525. };
  9526. XMPP.prototype.setMute = function (jid, mute) {
  9527. this.connection.moderate.setMute(jid, mute);
  9528. };
  9529. XMPP.prototype.eject = function (jid) {
  9530. this.connection.moderate.eject(jid);
  9531. };
  9532. XMPP.prototype.getSessions = function () {
  9533. return this.connection.jingle.sessions;
  9534. };
  9535. XMPP.prototype.disconnect = function () {
  9536. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  9537. {
  9538. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  9539. return;
  9540. }
  9541. this.disconnectInProgress = true;
  9542. this.connection.disconnect();
  9543. };
  9544. module.exports = XMPP;
  9545. }).call(this,"/modules/xmpp/xmpp.js")
  9546. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":76,"../../service/RTC/StreamEventTypes":78,"../../service/xmpp/XMPPEvents":82,"../RTC/RTC":13,"./strophe.emuc":32,"./strophe.jingle":33,"./strophe.logger":34,"./strophe.ping":35,"./strophe.rayo":36,"./strophe.util":37,"events":40,"jitsi-meet-logger":44,"pako":45}],39:[function(require,module,exports){
  9547. (function (process){
  9548. /*!
  9549. * async
  9550. * https://github.com/caolan/async
  9551. *
  9552. * Copyright 2010-2014 Caolan McMahon
  9553. * Released under the MIT license
  9554. */
  9555. /*jshint onevar: false, indent:4 */
  9556. /*global setImmediate: false, setTimeout: false, console: false */
  9557. (function () {
  9558. var async = {};
  9559. // global on the server, window in the browser
  9560. var root, previous_async;
  9561. root = this;
  9562. if (root != null) {
  9563. previous_async = root.async;
  9564. }
  9565. async.noConflict = function () {
  9566. root.async = previous_async;
  9567. return async;
  9568. };
  9569. function only_once(fn) {
  9570. var called = false;
  9571. return function() {
  9572. if (called) throw new Error("Callback was already called.");
  9573. called = true;
  9574. fn.apply(root, arguments);
  9575. }
  9576. }
  9577. //// cross-browser compatiblity functions ////
  9578. var _toString = Object.prototype.toString;
  9579. var _isArray = Array.isArray || function (obj) {
  9580. return _toString.call(obj) === '[object Array]';
  9581. };
  9582. var _each = function (arr, iterator) {
  9583. if (arr.forEach) {
  9584. return arr.forEach(iterator);
  9585. }
  9586. for (var i = 0; i < arr.length; i += 1) {
  9587. iterator(arr[i], i, arr);
  9588. }
  9589. };
  9590. var _map = function (arr, iterator) {
  9591. if (arr.map) {
  9592. return arr.map(iterator);
  9593. }
  9594. var results = [];
  9595. _each(arr, function (x, i, a) {
  9596. results.push(iterator(x, i, a));
  9597. });
  9598. return results;
  9599. };
  9600. var _reduce = function (arr, iterator, memo) {
  9601. if (arr.reduce) {
  9602. return arr.reduce(iterator, memo);
  9603. }
  9604. _each(arr, function (x, i, a) {
  9605. memo = iterator(memo, x, i, a);
  9606. });
  9607. return memo;
  9608. };
  9609. var _keys = function (obj) {
  9610. if (Object.keys) {
  9611. return Object.keys(obj);
  9612. }
  9613. var keys = [];
  9614. for (var k in obj) {
  9615. if (obj.hasOwnProperty(k)) {
  9616. keys.push(k);
  9617. }
  9618. }
  9619. return keys;
  9620. };
  9621. //// exported async module functions ////
  9622. //// nextTick implementation with browser-compatible fallback ////
  9623. if (typeof process === 'undefined' || !(process.nextTick)) {
  9624. if (typeof setImmediate === 'function') {
  9625. async.nextTick = function (fn) {
  9626. // not a direct alias for IE10 compatibility
  9627. setImmediate(fn);
  9628. };
  9629. async.setImmediate = async.nextTick;
  9630. }
  9631. else {
  9632. async.nextTick = function (fn) {
  9633. setTimeout(fn, 0);
  9634. };
  9635. async.setImmediate = async.nextTick;
  9636. }
  9637. }
  9638. else {
  9639. async.nextTick = process.nextTick;
  9640. if (typeof setImmediate !== 'undefined') {
  9641. async.setImmediate = function (fn) {
  9642. // not a direct alias for IE10 compatibility
  9643. setImmediate(fn);
  9644. };
  9645. }
  9646. else {
  9647. async.setImmediate = async.nextTick;
  9648. }
  9649. }
  9650. async.each = function (arr, iterator, callback) {
  9651. callback = callback || function () {};
  9652. if (!arr.length) {
  9653. return callback();
  9654. }
  9655. var completed = 0;
  9656. _each(arr, function (x) {
  9657. iterator(x, only_once(done) );
  9658. });
  9659. function done(err) {
  9660. if (err) {
  9661. callback(err);
  9662. callback = function () {};
  9663. }
  9664. else {
  9665. completed += 1;
  9666. if (completed >= arr.length) {
  9667. callback();
  9668. }
  9669. }
  9670. }
  9671. };
  9672. async.forEach = async.each;
  9673. async.eachSeries = function (arr, iterator, callback) {
  9674. callback = callback || function () {};
  9675. if (!arr.length) {
  9676. return callback();
  9677. }
  9678. var completed = 0;
  9679. var iterate = function () {
  9680. iterator(arr[completed], function (err) {
  9681. if (err) {
  9682. callback(err);
  9683. callback = function () {};
  9684. }
  9685. else {
  9686. completed += 1;
  9687. if (completed >= arr.length) {
  9688. callback();
  9689. }
  9690. else {
  9691. iterate();
  9692. }
  9693. }
  9694. });
  9695. };
  9696. iterate();
  9697. };
  9698. async.forEachSeries = async.eachSeries;
  9699. async.eachLimit = function (arr, limit, iterator, callback) {
  9700. var fn = _eachLimit(limit);
  9701. fn.apply(null, [arr, iterator, callback]);
  9702. };
  9703. async.forEachLimit = async.eachLimit;
  9704. var _eachLimit = function (limit) {
  9705. return function (arr, iterator, callback) {
  9706. callback = callback || function () {};
  9707. if (!arr.length || limit <= 0) {
  9708. return callback();
  9709. }
  9710. var completed = 0;
  9711. var started = 0;
  9712. var running = 0;
  9713. (function replenish () {
  9714. if (completed >= arr.length) {
  9715. return callback();
  9716. }
  9717. while (running < limit && started < arr.length) {
  9718. started += 1;
  9719. running += 1;
  9720. iterator(arr[started - 1], function (err) {
  9721. if (err) {
  9722. callback(err);
  9723. callback = function () {};
  9724. }
  9725. else {
  9726. completed += 1;
  9727. running -= 1;
  9728. if (completed >= arr.length) {
  9729. callback();
  9730. }
  9731. else {
  9732. replenish();
  9733. }
  9734. }
  9735. });
  9736. }
  9737. })();
  9738. };
  9739. };
  9740. var doParallel = function (fn) {
  9741. return function () {
  9742. var args = Array.prototype.slice.call(arguments);
  9743. return fn.apply(null, [async.each].concat(args));
  9744. };
  9745. };
  9746. var doParallelLimit = function(limit, fn) {
  9747. return function () {
  9748. var args = Array.prototype.slice.call(arguments);
  9749. return fn.apply(null, [_eachLimit(limit)].concat(args));
  9750. };
  9751. };
  9752. var doSeries = function (fn) {
  9753. return function () {
  9754. var args = Array.prototype.slice.call(arguments);
  9755. return fn.apply(null, [async.eachSeries].concat(args));
  9756. };
  9757. };
  9758. var _asyncMap = function (eachfn, arr, iterator, callback) {
  9759. arr = _map(arr, function (x, i) {
  9760. return {index: i, value: x};
  9761. });
  9762. if (!callback) {
  9763. eachfn(arr, function (x, callback) {
  9764. iterator(x.value, function (err) {
  9765. callback(err);
  9766. });
  9767. });
  9768. } else {
  9769. var results = [];
  9770. eachfn(arr, function (x, callback) {
  9771. iterator(x.value, function (err, v) {
  9772. results[x.index] = v;
  9773. callback(err);
  9774. });
  9775. }, function (err) {
  9776. callback(err, results);
  9777. });
  9778. }
  9779. };
  9780. async.map = doParallel(_asyncMap);
  9781. async.mapSeries = doSeries(_asyncMap);
  9782. async.mapLimit = function (arr, limit, iterator, callback) {
  9783. return _mapLimit(limit)(arr, iterator, callback);
  9784. };
  9785. var _mapLimit = function(limit) {
  9786. return doParallelLimit(limit, _asyncMap);
  9787. };
  9788. // reduce only has a series version, as doing reduce in parallel won't
  9789. // work in many situations.
  9790. async.reduce = function (arr, memo, iterator, callback) {
  9791. async.eachSeries(arr, function (x, callback) {
  9792. iterator(memo, x, function (err, v) {
  9793. memo = v;
  9794. callback(err);
  9795. });
  9796. }, function (err) {
  9797. callback(err, memo);
  9798. });
  9799. };
  9800. // inject alias
  9801. async.inject = async.reduce;
  9802. // foldl alias
  9803. async.foldl = async.reduce;
  9804. async.reduceRight = function (arr, memo, iterator, callback) {
  9805. var reversed = _map(arr, function (x) {
  9806. return x;
  9807. }).reverse();
  9808. async.reduce(reversed, memo, iterator, callback);
  9809. };
  9810. // foldr alias
  9811. async.foldr = async.reduceRight;
  9812. var _filter = function (eachfn, arr, iterator, callback) {
  9813. var results = [];
  9814. arr = _map(arr, function (x, i) {
  9815. return {index: i, value: x};
  9816. });
  9817. eachfn(arr, function (x, callback) {
  9818. iterator(x.value, function (v) {
  9819. if (v) {
  9820. results.push(x);
  9821. }
  9822. callback();
  9823. });
  9824. }, function (err) {
  9825. callback(_map(results.sort(function (a, b) {
  9826. return a.index - b.index;
  9827. }), function (x) {
  9828. return x.value;
  9829. }));
  9830. });
  9831. };
  9832. async.filter = doParallel(_filter);
  9833. async.filterSeries = doSeries(_filter);
  9834. // select alias
  9835. async.select = async.filter;
  9836. async.selectSeries = async.filterSeries;
  9837. var _reject = function (eachfn, arr, iterator, callback) {
  9838. var results = [];
  9839. arr = _map(arr, function (x, i) {
  9840. return {index: i, value: x};
  9841. });
  9842. eachfn(arr, function (x, callback) {
  9843. iterator(x.value, function (v) {
  9844. if (!v) {
  9845. results.push(x);
  9846. }
  9847. callback();
  9848. });
  9849. }, function (err) {
  9850. callback(_map(results.sort(function (a, b) {
  9851. return a.index - b.index;
  9852. }), function (x) {
  9853. return x.value;
  9854. }));
  9855. });
  9856. };
  9857. async.reject = doParallel(_reject);
  9858. async.rejectSeries = doSeries(_reject);
  9859. var _detect = function (eachfn, arr, iterator, main_callback) {
  9860. eachfn(arr, function (x, callback) {
  9861. iterator(x, function (result) {
  9862. if (result) {
  9863. main_callback(x);
  9864. main_callback = function () {};
  9865. }
  9866. else {
  9867. callback();
  9868. }
  9869. });
  9870. }, function (err) {
  9871. main_callback();
  9872. });
  9873. };
  9874. async.detect = doParallel(_detect);
  9875. async.detectSeries = doSeries(_detect);
  9876. async.some = function (arr, iterator, main_callback) {
  9877. async.each(arr, function (x, callback) {
  9878. iterator(x, function (v) {
  9879. if (v) {
  9880. main_callback(true);
  9881. main_callback = function () {};
  9882. }
  9883. callback();
  9884. });
  9885. }, function (err) {
  9886. main_callback(false);
  9887. });
  9888. };
  9889. // any alias
  9890. async.any = async.some;
  9891. async.every = function (arr, iterator, main_callback) {
  9892. async.each(arr, function (x, callback) {
  9893. iterator(x, function (v) {
  9894. if (!v) {
  9895. main_callback(false);
  9896. main_callback = function () {};
  9897. }
  9898. callback();
  9899. });
  9900. }, function (err) {
  9901. main_callback(true);
  9902. });
  9903. };
  9904. // all alias
  9905. async.all = async.every;
  9906. async.sortBy = function (arr, iterator, callback) {
  9907. async.map(arr, function (x, callback) {
  9908. iterator(x, function (err, criteria) {
  9909. if (err) {
  9910. callback(err);
  9911. }
  9912. else {
  9913. callback(null, {value: x, criteria: criteria});
  9914. }
  9915. });
  9916. }, function (err, results) {
  9917. if (err) {
  9918. return callback(err);
  9919. }
  9920. else {
  9921. var fn = function (left, right) {
  9922. var a = left.criteria, b = right.criteria;
  9923. return a < b ? -1 : a > b ? 1 : 0;
  9924. };
  9925. callback(null, _map(results.sort(fn), function (x) {
  9926. return x.value;
  9927. }));
  9928. }
  9929. });
  9930. };
  9931. async.auto = function (tasks, callback) {
  9932. callback = callback || function () {};
  9933. var keys = _keys(tasks);
  9934. var remainingTasks = keys.length
  9935. if (!remainingTasks) {
  9936. return callback();
  9937. }
  9938. var results = {};
  9939. var listeners = [];
  9940. var addListener = function (fn) {
  9941. listeners.unshift(fn);
  9942. };
  9943. var removeListener = function (fn) {
  9944. for (var i = 0; i < listeners.length; i += 1) {
  9945. if (listeners[i] === fn) {
  9946. listeners.splice(i, 1);
  9947. return;
  9948. }
  9949. }
  9950. };
  9951. var taskComplete = function () {
  9952. remainingTasks--
  9953. _each(listeners.slice(0), function (fn) {
  9954. fn();
  9955. });
  9956. };
  9957. addListener(function () {
  9958. if (!remainingTasks) {
  9959. var theCallback = callback;
  9960. // prevent final callback from calling itself if it errors
  9961. callback = function () {};
  9962. theCallback(null, results);
  9963. }
  9964. });
  9965. _each(keys, function (k) {
  9966. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  9967. var taskCallback = function (err) {
  9968. var args = Array.prototype.slice.call(arguments, 1);
  9969. if (args.length <= 1) {
  9970. args = args[0];
  9971. }
  9972. if (err) {
  9973. var safeResults = {};
  9974. _each(_keys(results), function(rkey) {
  9975. safeResults[rkey] = results[rkey];
  9976. });
  9977. safeResults[k] = args;
  9978. callback(err, safeResults);
  9979. // stop subsequent errors hitting callback multiple times
  9980. callback = function () {};
  9981. }
  9982. else {
  9983. results[k] = args;
  9984. async.setImmediate(taskComplete);
  9985. }
  9986. };
  9987. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  9988. var ready = function () {
  9989. return _reduce(requires, function (a, x) {
  9990. return (a && results.hasOwnProperty(x));
  9991. }, true) && !results.hasOwnProperty(k);
  9992. };
  9993. if (ready()) {
  9994. task[task.length - 1](taskCallback, results);
  9995. }
  9996. else {
  9997. var listener = function () {
  9998. if (ready()) {
  9999. removeListener(listener);
  10000. task[task.length - 1](taskCallback, results);
  10001. }
  10002. };
  10003. addListener(listener);
  10004. }
  10005. });
  10006. };
  10007. async.retry = function(times, task, callback) {
  10008. var DEFAULT_TIMES = 5;
  10009. var attempts = [];
  10010. // Use defaults if times not passed
  10011. if (typeof times === 'function') {
  10012. callback = task;
  10013. task = times;
  10014. times = DEFAULT_TIMES;
  10015. }
  10016. // Make sure times is a number
  10017. times = parseInt(times, 10) || DEFAULT_TIMES;
  10018. var wrappedTask = function(wrappedCallback, wrappedResults) {
  10019. var retryAttempt = function(task, finalAttempt) {
  10020. return function(seriesCallback) {
  10021. task(function(err, result){
  10022. seriesCallback(!err || finalAttempt, {err: err, result: result});
  10023. }, wrappedResults);
  10024. };
  10025. };
  10026. while (times) {
  10027. attempts.push(retryAttempt(task, !(times-=1)));
  10028. }
  10029. async.series(attempts, function(done, data){
  10030. data = data[data.length - 1];
  10031. (wrappedCallback || callback)(data.err, data.result);
  10032. });
  10033. }
  10034. // If a callback is passed, run this as a controll flow
  10035. return callback ? wrappedTask() : wrappedTask
  10036. };
  10037. async.waterfall = function (tasks, callback) {
  10038. callback = callback || function () {};
  10039. if (!_isArray(tasks)) {
  10040. var err = new Error('First argument to waterfall must be an array of functions');
  10041. return callback(err);
  10042. }
  10043. if (!tasks.length) {
  10044. return callback();
  10045. }
  10046. var wrapIterator = function (iterator) {
  10047. return function (err) {
  10048. if (err) {
  10049. callback.apply(null, arguments);
  10050. callback = function () {};
  10051. }
  10052. else {
  10053. var args = Array.prototype.slice.call(arguments, 1);
  10054. var next = iterator.next();
  10055. if (next) {
  10056. args.push(wrapIterator(next));
  10057. }
  10058. else {
  10059. args.push(callback);
  10060. }
  10061. async.setImmediate(function () {
  10062. iterator.apply(null, args);
  10063. });
  10064. }
  10065. };
  10066. };
  10067. wrapIterator(async.iterator(tasks))();
  10068. };
  10069. var _parallel = function(eachfn, tasks, callback) {
  10070. callback = callback || function () {};
  10071. if (_isArray(tasks)) {
  10072. eachfn.map(tasks, function (fn, callback) {
  10073. if (fn) {
  10074. fn(function (err) {
  10075. var args = Array.prototype.slice.call(arguments, 1);
  10076. if (args.length <= 1) {
  10077. args = args[0];
  10078. }
  10079. callback.call(null, err, args);
  10080. });
  10081. }
  10082. }, callback);
  10083. }
  10084. else {
  10085. var results = {};
  10086. eachfn.each(_keys(tasks), function (k, callback) {
  10087. tasks[k](function (err) {
  10088. var args = Array.prototype.slice.call(arguments, 1);
  10089. if (args.length <= 1) {
  10090. args = args[0];
  10091. }
  10092. results[k] = args;
  10093. callback(err);
  10094. });
  10095. }, function (err) {
  10096. callback(err, results);
  10097. });
  10098. }
  10099. };
  10100. async.parallel = function (tasks, callback) {
  10101. _parallel({ map: async.map, each: async.each }, tasks, callback);
  10102. };
  10103. async.parallelLimit = function(tasks, limit, callback) {
  10104. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  10105. };
  10106. async.series = function (tasks, callback) {
  10107. callback = callback || function () {};
  10108. if (_isArray(tasks)) {
  10109. async.mapSeries(tasks, function (fn, callback) {
  10110. if (fn) {
  10111. fn(function (err) {
  10112. var args = Array.prototype.slice.call(arguments, 1);
  10113. if (args.length <= 1) {
  10114. args = args[0];
  10115. }
  10116. callback.call(null, err, args);
  10117. });
  10118. }
  10119. }, callback);
  10120. }
  10121. else {
  10122. var results = {};
  10123. async.eachSeries(_keys(tasks), function (k, callback) {
  10124. tasks[k](function (err) {
  10125. var args = Array.prototype.slice.call(arguments, 1);
  10126. if (args.length <= 1) {
  10127. args = args[0];
  10128. }
  10129. results[k] = args;
  10130. callback(err);
  10131. });
  10132. }, function (err) {
  10133. callback(err, results);
  10134. });
  10135. }
  10136. };
  10137. async.iterator = function (tasks) {
  10138. var makeCallback = function (index) {
  10139. var fn = function () {
  10140. if (tasks.length) {
  10141. tasks[index].apply(null, arguments);
  10142. }
  10143. return fn.next();
  10144. };
  10145. fn.next = function () {
  10146. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  10147. };
  10148. return fn;
  10149. };
  10150. return makeCallback(0);
  10151. };
  10152. async.apply = function (fn) {
  10153. var args = Array.prototype.slice.call(arguments, 1);
  10154. return function () {
  10155. return fn.apply(
  10156. null, args.concat(Array.prototype.slice.call(arguments))
  10157. );
  10158. };
  10159. };
  10160. var _concat = function (eachfn, arr, fn, callback) {
  10161. var r = [];
  10162. eachfn(arr, function (x, cb) {
  10163. fn(x, function (err, y) {
  10164. r = r.concat(y || []);
  10165. cb(err);
  10166. });
  10167. }, function (err) {
  10168. callback(err, r);
  10169. });
  10170. };
  10171. async.concat = doParallel(_concat);
  10172. async.concatSeries = doSeries(_concat);
  10173. async.whilst = function (test, iterator, callback) {
  10174. if (test()) {
  10175. iterator(function (err) {
  10176. if (err) {
  10177. return callback(err);
  10178. }
  10179. async.whilst(test, iterator, callback);
  10180. });
  10181. }
  10182. else {
  10183. callback();
  10184. }
  10185. };
  10186. async.doWhilst = function (iterator, test, callback) {
  10187. iterator(function (err) {
  10188. if (err) {
  10189. return callback(err);
  10190. }
  10191. var args = Array.prototype.slice.call(arguments, 1);
  10192. if (test.apply(null, args)) {
  10193. async.doWhilst(iterator, test, callback);
  10194. }
  10195. else {
  10196. callback();
  10197. }
  10198. });
  10199. };
  10200. async.until = function (test, iterator, callback) {
  10201. if (!test()) {
  10202. iterator(function (err) {
  10203. if (err) {
  10204. return callback(err);
  10205. }
  10206. async.until(test, iterator, callback);
  10207. });
  10208. }
  10209. else {
  10210. callback();
  10211. }
  10212. };
  10213. async.doUntil = function (iterator, test, callback) {
  10214. iterator(function (err) {
  10215. if (err) {
  10216. return callback(err);
  10217. }
  10218. var args = Array.prototype.slice.call(arguments, 1);
  10219. if (!test.apply(null, args)) {
  10220. async.doUntil(iterator, test, callback);
  10221. }
  10222. else {
  10223. callback();
  10224. }
  10225. });
  10226. };
  10227. async.queue = function (worker, concurrency) {
  10228. if (concurrency === undefined) {
  10229. concurrency = 1;
  10230. }
  10231. function _insert(q, data, pos, callback) {
  10232. if (!q.started){
  10233. q.started = true;
  10234. }
  10235. if (!_isArray(data)) {
  10236. data = [data];
  10237. }
  10238. if(data.length == 0) {
  10239. // call drain immediately if there are no tasks
  10240. return async.setImmediate(function() {
  10241. if (q.drain) {
  10242. q.drain();
  10243. }
  10244. });
  10245. }
  10246. _each(data, function(task) {
  10247. var item = {
  10248. data: task,
  10249. callback: typeof callback === 'function' ? callback : null
  10250. };
  10251. if (pos) {
  10252. q.tasks.unshift(item);
  10253. } else {
  10254. q.tasks.push(item);
  10255. }
  10256. if (q.saturated && q.tasks.length === q.concurrency) {
  10257. q.saturated();
  10258. }
  10259. async.setImmediate(q.process);
  10260. });
  10261. }
  10262. var workers = 0;
  10263. var q = {
  10264. tasks: [],
  10265. concurrency: concurrency,
  10266. saturated: null,
  10267. empty: null,
  10268. drain: null,
  10269. started: false,
  10270. paused: false,
  10271. push: function (data, callback) {
  10272. _insert(q, data, false, callback);
  10273. },
  10274. kill: function () {
  10275. q.drain = null;
  10276. q.tasks = [];
  10277. },
  10278. unshift: function (data, callback) {
  10279. _insert(q, data, true, callback);
  10280. },
  10281. process: function () {
  10282. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  10283. var task = q.tasks.shift();
  10284. if (q.empty && q.tasks.length === 0) {
  10285. q.empty();
  10286. }
  10287. workers += 1;
  10288. var next = function () {
  10289. workers -= 1;
  10290. if (task.callback) {
  10291. task.callback.apply(task, arguments);
  10292. }
  10293. if (q.drain && q.tasks.length + workers === 0) {
  10294. q.drain();
  10295. }
  10296. q.process();
  10297. };
  10298. var cb = only_once(next);
  10299. worker(task.data, cb);
  10300. }
  10301. },
  10302. length: function () {
  10303. return q.tasks.length;
  10304. },
  10305. running: function () {
  10306. return workers;
  10307. },
  10308. idle: function() {
  10309. return q.tasks.length + workers === 0;
  10310. },
  10311. pause: function () {
  10312. if (q.paused === true) { return; }
  10313. q.paused = true;
  10314. q.process();
  10315. },
  10316. resume: function () {
  10317. if (q.paused === false) { return; }
  10318. q.paused = false;
  10319. q.process();
  10320. }
  10321. };
  10322. return q;
  10323. };
  10324. async.priorityQueue = function (worker, concurrency) {
  10325. function _compareTasks(a, b){
  10326. return a.priority - b.priority;
  10327. };
  10328. function _binarySearch(sequence, item, compare) {
  10329. var beg = -1,
  10330. end = sequence.length - 1;
  10331. while (beg < end) {
  10332. var mid = beg + ((end - beg + 1) >>> 1);
  10333. if (compare(item, sequence[mid]) >= 0) {
  10334. beg = mid;
  10335. } else {
  10336. end = mid - 1;
  10337. }
  10338. }
  10339. return beg;
  10340. }
  10341. function _insert(q, data, priority, callback) {
  10342. if (!q.started){
  10343. q.started = true;
  10344. }
  10345. if (!_isArray(data)) {
  10346. data = [data];
  10347. }
  10348. if(data.length == 0) {
  10349. // call drain immediately if there are no tasks
  10350. return async.setImmediate(function() {
  10351. if (q.drain) {
  10352. q.drain();
  10353. }
  10354. });
  10355. }
  10356. _each(data, function(task) {
  10357. var item = {
  10358. data: task,
  10359. priority: priority,
  10360. callback: typeof callback === 'function' ? callback : null
  10361. };
  10362. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  10363. if (q.saturated && q.tasks.length === q.concurrency) {
  10364. q.saturated();
  10365. }
  10366. async.setImmediate(q.process);
  10367. });
  10368. }
  10369. // Start with a normal queue
  10370. var q = async.queue(worker, concurrency);
  10371. // Override push to accept second parameter representing priority
  10372. q.push = function (data, priority, callback) {
  10373. _insert(q, data, priority, callback);
  10374. };
  10375. // Remove unshift function
  10376. delete q.unshift;
  10377. return q;
  10378. };
  10379. async.cargo = function (worker, payload) {
  10380. var working = false,
  10381. tasks = [];
  10382. var cargo = {
  10383. tasks: tasks,
  10384. payload: payload,
  10385. saturated: null,
  10386. empty: null,
  10387. drain: null,
  10388. drained: true,
  10389. push: function (data, callback) {
  10390. if (!_isArray(data)) {
  10391. data = [data];
  10392. }
  10393. _each(data, function(task) {
  10394. tasks.push({
  10395. data: task,
  10396. callback: typeof callback === 'function' ? callback : null
  10397. });
  10398. cargo.drained = false;
  10399. if (cargo.saturated && tasks.length === payload) {
  10400. cargo.saturated();
  10401. }
  10402. });
  10403. async.setImmediate(cargo.process);
  10404. },
  10405. process: function process() {
  10406. if (working) return;
  10407. if (tasks.length === 0) {
  10408. if(cargo.drain && !cargo.drained) cargo.drain();
  10409. cargo.drained = true;
  10410. return;
  10411. }
  10412. var ts = typeof payload === 'number'
  10413. ? tasks.splice(0, payload)
  10414. : tasks.splice(0, tasks.length);
  10415. var ds = _map(ts, function (task) {
  10416. return task.data;
  10417. });
  10418. if(cargo.empty) cargo.empty();
  10419. working = true;
  10420. worker(ds, function () {
  10421. working = false;
  10422. var args = arguments;
  10423. _each(ts, function (data) {
  10424. if (data.callback) {
  10425. data.callback.apply(null, args);
  10426. }
  10427. });
  10428. process();
  10429. });
  10430. },
  10431. length: function () {
  10432. return tasks.length;
  10433. },
  10434. running: function () {
  10435. return working;
  10436. }
  10437. };
  10438. return cargo;
  10439. };
  10440. var _console_fn = function (name) {
  10441. return function (fn) {
  10442. var args = Array.prototype.slice.call(arguments, 1);
  10443. fn.apply(null, args.concat([function (err) {
  10444. var args = Array.prototype.slice.call(arguments, 1);
  10445. if (typeof console !== 'undefined') {
  10446. if (err) {
  10447. if (console.error) {
  10448. console.error(err);
  10449. }
  10450. }
  10451. else if (console[name]) {
  10452. _each(args, function (x) {
  10453. console[name](x);
  10454. });
  10455. }
  10456. }
  10457. }]));
  10458. };
  10459. };
  10460. async.log = _console_fn('log');
  10461. async.dir = _console_fn('dir');
  10462. /*async.info = _console_fn('info');
  10463. async.warn = _console_fn('warn');
  10464. async.error = _console_fn('error');*/
  10465. async.memoize = function (fn, hasher) {
  10466. var memo = {};
  10467. var queues = {};
  10468. hasher = hasher || function (x) {
  10469. return x;
  10470. };
  10471. var memoized = function () {
  10472. var args = Array.prototype.slice.call(arguments);
  10473. var callback = args.pop();
  10474. var key = hasher.apply(null, args);
  10475. if (key in memo) {
  10476. async.nextTick(function () {
  10477. callback.apply(null, memo[key]);
  10478. });
  10479. }
  10480. else if (key in queues) {
  10481. queues[key].push(callback);
  10482. }
  10483. else {
  10484. queues[key] = [callback];
  10485. fn.apply(null, args.concat([function () {
  10486. memo[key] = arguments;
  10487. var q = queues[key];
  10488. delete queues[key];
  10489. for (var i = 0, l = q.length; i < l; i++) {
  10490. q[i].apply(null, arguments);
  10491. }
  10492. }]));
  10493. }
  10494. };
  10495. memoized.memo = memo;
  10496. memoized.unmemoized = fn;
  10497. return memoized;
  10498. };
  10499. async.unmemoize = function (fn) {
  10500. return function () {
  10501. return (fn.unmemoized || fn).apply(null, arguments);
  10502. };
  10503. };
  10504. async.times = function (count, iterator, callback) {
  10505. var counter = [];
  10506. for (var i = 0; i < count; i++) {
  10507. counter.push(i);
  10508. }
  10509. return async.map(counter, iterator, callback);
  10510. };
  10511. async.timesSeries = function (count, iterator, callback) {
  10512. var counter = [];
  10513. for (var i = 0; i < count; i++) {
  10514. counter.push(i);
  10515. }
  10516. return async.mapSeries(counter, iterator, callback);
  10517. };
  10518. async.seq = function (/* functions... */) {
  10519. var fns = arguments;
  10520. return function () {
  10521. var that = this;
  10522. var args = Array.prototype.slice.call(arguments);
  10523. var callback = args.pop();
  10524. async.reduce(fns, args, function (newargs, fn, cb) {
  10525. fn.apply(that, newargs.concat([function () {
  10526. var err = arguments[0];
  10527. var nextargs = Array.prototype.slice.call(arguments, 1);
  10528. cb(err, nextargs);
  10529. }]))
  10530. },
  10531. function (err, results) {
  10532. callback.apply(that, [err].concat(results));
  10533. });
  10534. };
  10535. };
  10536. async.compose = function (/* functions... */) {
  10537. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  10538. };
  10539. var _applyEach = function (eachfn, fns /*args...*/) {
  10540. var go = function () {
  10541. var that = this;
  10542. var args = Array.prototype.slice.call(arguments);
  10543. var callback = args.pop();
  10544. return eachfn(fns, function (fn, cb) {
  10545. fn.apply(that, args.concat([cb]));
  10546. },
  10547. callback);
  10548. };
  10549. if (arguments.length > 2) {
  10550. var args = Array.prototype.slice.call(arguments, 2);
  10551. return go.apply(this, args);
  10552. }
  10553. else {
  10554. return go;
  10555. }
  10556. };
  10557. async.applyEach = doParallel(_applyEach);
  10558. async.applyEachSeries = doSeries(_applyEach);
  10559. async.forever = function (fn, callback) {
  10560. function next(err) {
  10561. if (err) {
  10562. if (callback) {
  10563. return callback(err);
  10564. }
  10565. throw err;
  10566. }
  10567. fn(next);
  10568. }
  10569. next();
  10570. };
  10571. // Node.js
  10572. if (typeof module !== 'undefined' && module.exports) {
  10573. module.exports = async;
  10574. }
  10575. // AMD / RequireJS
  10576. else if (typeof define !== 'undefined' && define.amd) {
  10577. define([], function () {
  10578. return async;
  10579. });
  10580. }
  10581. // included directly via <script> tag
  10582. else {
  10583. root.async = async;
  10584. }
  10585. }());
  10586. }).call(this,require('_process'))
  10587. },{"_process":41}],40:[function(require,module,exports){
  10588. // Copyright Joyent, Inc. and other Node contributors.
  10589. //
  10590. // Permission is hereby granted, free of charge, to any person obtaining a
  10591. // copy of this software and associated documentation files (the
  10592. // "Software"), to deal in the Software without restriction, including
  10593. // without limitation the rights to use, copy, modify, merge, publish,
  10594. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10595. // persons to whom the Software is furnished to do so, subject to the
  10596. // following conditions:
  10597. //
  10598. // The above copyright notice and this permission notice shall be included
  10599. // in all copies or substantial portions of the Software.
  10600. //
  10601. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10602. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10603. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10604. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10605. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10606. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10607. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10608. function EventEmitter() {
  10609. this._events = this._events || {};
  10610. this._maxListeners = this._maxListeners || undefined;
  10611. }
  10612. module.exports = EventEmitter;
  10613. // Backwards-compat with node 0.10.x
  10614. EventEmitter.EventEmitter = EventEmitter;
  10615. EventEmitter.prototype._events = undefined;
  10616. EventEmitter.prototype._maxListeners = undefined;
  10617. // By default EventEmitters will print a warning if more than 10 listeners are
  10618. // added to it. This is a useful default which helps finding memory leaks.
  10619. EventEmitter.defaultMaxListeners = 10;
  10620. // Obviously not all Emitters should be limited to 10. This function allows
  10621. // that to be increased. Set to zero for unlimited.
  10622. EventEmitter.prototype.setMaxListeners = function(n) {
  10623. if (!isNumber(n) || n < 0 || isNaN(n))
  10624. throw TypeError('n must be a positive number');
  10625. this._maxListeners = n;
  10626. return this;
  10627. };
  10628. EventEmitter.prototype.emit = function(type) {
  10629. var er, handler, len, args, i, listeners;
  10630. if (!this._events)
  10631. this._events = {};
  10632. // If there is no 'error' event listener then throw.
  10633. if (type === 'error') {
  10634. if (!this._events.error ||
  10635. (isObject(this._events.error) && !this._events.error.length)) {
  10636. er = arguments[1];
  10637. if (er instanceof Error) {
  10638. throw er; // Unhandled 'error' event
  10639. }
  10640. throw TypeError('Uncaught, unspecified "error" event.');
  10641. }
  10642. }
  10643. handler = this._events[type];
  10644. if (isUndefined(handler))
  10645. return false;
  10646. if (isFunction(handler)) {
  10647. switch (arguments.length) {
  10648. // fast cases
  10649. case 1:
  10650. handler.call(this);
  10651. break;
  10652. case 2:
  10653. handler.call(this, arguments[1]);
  10654. break;
  10655. case 3:
  10656. handler.call(this, arguments[1], arguments[2]);
  10657. break;
  10658. // slower
  10659. default:
  10660. len = arguments.length;
  10661. args = new Array(len - 1);
  10662. for (i = 1; i < len; i++)
  10663. args[i - 1] = arguments[i];
  10664. handler.apply(this, args);
  10665. }
  10666. } else if (isObject(handler)) {
  10667. len = arguments.length;
  10668. args = new Array(len - 1);
  10669. for (i = 1; i < len; i++)
  10670. args[i - 1] = arguments[i];
  10671. listeners = handler.slice();
  10672. len = listeners.length;
  10673. for (i = 0; i < len; i++)
  10674. listeners[i].apply(this, args);
  10675. }
  10676. return true;
  10677. };
  10678. EventEmitter.prototype.addListener = function(type, listener) {
  10679. var m;
  10680. if (!isFunction(listener))
  10681. throw TypeError('listener must be a function');
  10682. if (!this._events)
  10683. this._events = {};
  10684. // To avoid recursion in the case that type === "newListener"! Before
  10685. // adding it to the listeners, first emit "newListener".
  10686. if (this._events.newListener)
  10687. this.emit('newListener', type,
  10688. isFunction(listener.listener) ?
  10689. listener.listener : listener);
  10690. if (!this._events[type])
  10691. // Optimize the case of one listener. Don't need the extra array object.
  10692. this._events[type] = listener;
  10693. else if (isObject(this._events[type]))
  10694. // If we've already got an array, just append.
  10695. this._events[type].push(listener);
  10696. else
  10697. // Adding the second element, need to change to array.
  10698. this._events[type] = [this._events[type], listener];
  10699. // Check for listener leak
  10700. if (isObject(this._events[type]) && !this._events[type].warned) {
  10701. var m;
  10702. if (!isUndefined(this._maxListeners)) {
  10703. m = this._maxListeners;
  10704. } else {
  10705. m = EventEmitter.defaultMaxListeners;
  10706. }
  10707. if (m && m > 0 && this._events[type].length > m) {
  10708. this._events[type].warned = true;
  10709. console.error('(node) warning: possible EventEmitter memory ' +
  10710. 'leak detected. %d listeners added. ' +
  10711. 'Use emitter.setMaxListeners() to increase limit.',
  10712. this._events[type].length);
  10713. if (typeof console.trace === 'function') {
  10714. // not supported in IE 10
  10715. console.trace();
  10716. }
  10717. }
  10718. }
  10719. return this;
  10720. };
  10721. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  10722. EventEmitter.prototype.once = function(type, listener) {
  10723. if (!isFunction(listener))
  10724. throw TypeError('listener must be a function');
  10725. var fired = false;
  10726. function g() {
  10727. this.removeListener(type, g);
  10728. if (!fired) {
  10729. fired = true;
  10730. listener.apply(this, arguments);
  10731. }
  10732. }
  10733. g.listener = listener;
  10734. this.on(type, g);
  10735. return this;
  10736. };
  10737. // emits a 'removeListener' event iff the listener was removed
  10738. EventEmitter.prototype.removeListener = function(type, listener) {
  10739. var list, position, length, i;
  10740. if (!isFunction(listener))
  10741. throw TypeError('listener must be a function');
  10742. if (!this._events || !this._events[type])
  10743. return this;
  10744. list = this._events[type];
  10745. length = list.length;
  10746. position = -1;
  10747. if (list === listener ||
  10748. (isFunction(list.listener) && list.listener === listener)) {
  10749. delete this._events[type];
  10750. if (this._events.removeListener)
  10751. this.emit('removeListener', type, listener);
  10752. } else if (isObject(list)) {
  10753. for (i = length; i-- > 0;) {
  10754. if (list[i] === listener ||
  10755. (list[i].listener && list[i].listener === listener)) {
  10756. position = i;
  10757. break;
  10758. }
  10759. }
  10760. if (position < 0)
  10761. return this;
  10762. if (list.length === 1) {
  10763. list.length = 0;
  10764. delete this._events[type];
  10765. } else {
  10766. list.splice(position, 1);
  10767. }
  10768. if (this._events.removeListener)
  10769. this.emit('removeListener', type, listener);
  10770. }
  10771. return this;
  10772. };
  10773. EventEmitter.prototype.removeAllListeners = function(type) {
  10774. var key, listeners;
  10775. if (!this._events)
  10776. return this;
  10777. // not listening for removeListener, no need to emit
  10778. if (!this._events.removeListener) {
  10779. if (arguments.length === 0)
  10780. this._events = {};
  10781. else if (this._events[type])
  10782. delete this._events[type];
  10783. return this;
  10784. }
  10785. // emit removeListener for all listeners on all events
  10786. if (arguments.length === 0) {
  10787. for (key in this._events) {
  10788. if (key === 'removeListener') continue;
  10789. this.removeAllListeners(key);
  10790. }
  10791. this.removeAllListeners('removeListener');
  10792. this._events = {};
  10793. return this;
  10794. }
  10795. listeners = this._events[type];
  10796. if (isFunction(listeners)) {
  10797. this.removeListener(type, listeners);
  10798. } else {
  10799. // LIFO order
  10800. while (listeners.length)
  10801. this.removeListener(type, listeners[listeners.length - 1]);
  10802. }
  10803. delete this._events[type];
  10804. return this;
  10805. };
  10806. EventEmitter.prototype.listeners = function(type) {
  10807. var ret;
  10808. if (!this._events || !this._events[type])
  10809. ret = [];
  10810. else if (isFunction(this._events[type]))
  10811. ret = [this._events[type]];
  10812. else
  10813. ret = this._events[type].slice();
  10814. return ret;
  10815. };
  10816. EventEmitter.listenerCount = function(emitter, type) {
  10817. var ret;
  10818. if (!emitter._events || !emitter._events[type])
  10819. ret = 0;
  10820. else if (isFunction(emitter._events[type]))
  10821. ret = 1;
  10822. else
  10823. ret = emitter._events[type].length;
  10824. return ret;
  10825. };
  10826. function isFunction(arg) {
  10827. return typeof arg === 'function';
  10828. }
  10829. function isNumber(arg) {
  10830. return typeof arg === 'number';
  10831. }
  10832. function isObject(arg) {
  10833. return typeof arg === 'object' && arg !== null;
  10834. }
  10835. function isUndefined(arg) {
  10836. return arg === void 0;
  10837. }
  10838. },{}],41:[function(require,module,exports){
  10839. // shim for using process in browser
  10840. var process = module.exports = {};
  10841. var queue = [];
  10842. var draining = false;
  10843. var currentQueue;
  10844. var queueIndex = -1;
  10845. function cleanUpNextTick() {
  10846. draining = false;
  10847. if (currentQueue.length) {
  10848. queue = currentQueue.concat(queue);
  10849. } else {
  10850. queueIndex = -1;
  10851. }
  10852. if (queue.length) {
  10853. drainQueue();
  10854. }
  10855. }
  10856. function drainQueue() {
  10857. if (draining) {
  10858. return;
  10859. }
  10860. var timeout = setTimeout(cleanUpNextTick);
  10861. draining = true;
  10862. var len = queue.length;
  10863. while(len) {
  10864. currentQueue = queue;
  10865. queue = [];
  10866. while (++queueIndex < len) {
  10867. if (currentQueue) {
  10868. currentQueue[queueIndex].run();
  10869. }
  10870. }
  10871. queueIndex = -1;
  10872. len = queue.length;
  10873. }
  10874. currentQueue = null;
  10875. draining = false;
  10876. clearTimeout(timeout);
  10877. }
  10878. process.nextTick = function (fun) {
  10879. var args = new Array(arguments.length - 1);
  10880. if (arguments.length > 1) {
  10881. for (var i = 1; i < arguments.length; i++) {
  10882. args[i - 1] = arguments[i];
  10883. }
  10884. }
  10885. queue.push(new Item(fun, args));
  10886. if (queue.length === 1 && !draining) {
  10887. setTimeout(drainQueue, 0);
  10888. }
  10889. };
  10890. // v8 likes predictible objects
  10891. function Item(fun, array) {
  10892. this.fun = fun;
  10893. this.array = array;
  10894. }
  10895. Item.prototype.run = function () {
  10896. this.fun.apply(null, this.array);
  10897. };
  10898. process.title = 'browser';
  10899. process.browser = true;
  10900. process.env = {};
  10901. process.argv = [];
  10902. process.version = ''; // empty string to avoid regexp issues
  10903. process.versions = {};
  10904. function noop() {}
  10905. process.on = noop;
  10906. process.addListener = noop;
  10907. process.once = noop;
  10908. process.off = noop;
  10909. process.removeListener = noop;
  10910. process.removeAllListeners = noop;
  10911. process.emit = noop;
  10912. process.binding = function (name) {
  10913. throw new Error('process.binding is not supported');
  10914. };
  10915. process.cwd = function () { return '/' };
  10916. process.chdir = function (dir) {
  10917. throw new Error('process.chdir is not supported');
  10918. };
  10919. process.umask = function() { return 0; };
  10920. },{}],42:[function(require,module,exports){
  10921. (function (process,global){
  10922. /*!
  10923. * @overview es6-promise - a tiny implementation of Promises/A+.
  10924. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  10925. * @license Licensed under MIT license
  10926. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  10927. * @version 3.0.2
  10928. */
  10929. (function() {
  10930. "use strict";
  10931. function lib$es6$promise$utils$$objectOrFunction(x) {
  10932. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  10933. }
  10934. function lib$es6$promise$utils$$isFunction(x) {
  10935. return typeof x === 'function';
  10936. }
  10937. function lib$es6$promise$utils$$isMaybeThenable(x) {
  10938. return typeof x === 'object' && x !== null;
  10939. }
  10940. var lib$es6$promise$utils$$_isArray;
  10941. if (!Array.isArray) {
  10942. lib$es6$promise$utils$$_isArray = function (x) {
  10943. return Object.prototype.toString.call(x) === '[object Array]';
  10944. };
  10945. } else {
  10946. lib$es6$promise$utils$$_isArray = Array.isArray;
  10947. }
  10948. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  10949. var lib$es6$promise$asap$$len = 0;
  10950. var lib$es6$promise$asap$$toString = {}.toString;
  10951. var lib$es6$promise$asap$$vertxNext;
  10952. var lib$es6$promise$asap$$customSchedulerFn;
  10953. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  10954. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  10955. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  10956. lib$es6$promise$asap$$len += 2;
  10957. if (lib$es6$promise$asap$$len === 2) {
  10958. // If len is 2, that means that we need to schedule an async flush.
  10959. // If additional callbacks are queued before the queue is flushed, they
  10960. // will be processed by this flush that we are scheduling.
  10961. if (lib$es6$promise$asap$$customSchedulerFn) {
  10962. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  10963. } else {
  10964. lib$es6$promise$asap$$scheduleFlush();
  10965. }
  10966. }
  10967. }
  10968. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  10969. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  10970. }
  10971. function lib$es6$promise$asap$$setAsap(asapFn) {
  10972. lib$es6$promise$asap$$asap = asapFn;
  10973. }
  10974. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  10975. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  10976. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  10977. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  10978. // test for web worker but not in IE10
  10979. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  10980. typeof importScripts !== 'undefined' &&
  10981. typeof MessageChannel !== 'undefined';
  10982. // node
  10983. function lib$es6$promise$asap$$useNextTick() {
  10984. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  10985. // see https://github.com/cujojs/when/issues/410 for details
  10986. return function() {
  10987. process.nextTick(lib$es6$promise$asap$$flush);
  10988. };
  10989. }
  10990. // vertx
  10991. function lib$es6$promise$asap$$useVertxTimer() {
  10992. return function() {
  10993. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  10994. };
  10995. }
  10996. function lib$es6$promise$asap$$useMutationObserver() {
  10997. var iterations = 0;
  10998. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  10999. var node = document.createTextNode('');
  11000. observer.observe(node, { characterData: true });
  11001. return function() {
  11002. node.data = (iterations = ++iterations % 2);
  11003. };
  11004. }
  11005. // web worker
  11006. function lib$es6$promise$asap$$useMessageChannel() {
  11007. var channel = new MessageChannel();
  11008. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  11009. return function () {
  11010. channel.port2.postMessage(0);
  11011. };
  11012. }
  11013. function lib$es6$promise$asap$$useSetTimeout() {
  11014. return function() {
  11015. setTimeout(lib$es6$promise$asap$$flush, 1);
  11016. };
  11017. }
  11018. var lib$es6$promise$asap$$queue = new Array(1000);
  11019. function lib$es6$promise$asap$$flush() {
  11020. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  11021. var callback = lib$es6$promise$asap$$queue[i];
  11022. var arg = lib$es6$promise$asap$$queue[i+1];
  11023. callback(arg);
  11024. lib$es6$promise$asap$$queue[i] = undefined;
  11025. lib$es6$promise$asap$$queue[i+1] = undefined;
  11026. }
  11027. lib$es6$promise$asap$$len = 0;
  11028. }
  11029. function lib$es6$promise$asap$$attemptVertx() {
  11030. try {
  11031. var r = require;
  11032. var vertx = r('vertx');
  11033. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  11034. return lib$es6$promise$asap$$useVertxTimer();
  11035. } catch(e) {
  11036. return lib$es6$promise$asap$$useSetTimeout();
  11037. }
  11038. }
  11039. var lib$es6$promise$asap$$scheduleFlush;
  11040. // Decide what async method to use to triggering processing of queued callbacks:
  11041. if (lib$es6$promise$asap$$isNode) {
  11042. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  11043. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  11044. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  11045. } else if (lib$es6$promise$asap$$isWorker) {
  11046. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  11047. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  11048. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  11049. } else {
  11050. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  11051. }
  11052. function lib$es6$promise$$internal$$noop() {}
  11053. var lib$es6$promise$$internal$$PENDING = void 0;
  11054. var lib$es6$promise$$internal$$FULFILLED = 1;
  11055. var lib$es6$promise$$internal$$REJECTED = 2;
  11056. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11057. function lib$es6$promise$$internal$$selfFulfillment() {
  11058. return new TypeError("You cannot resolve a promise with itself");
  11059. }
  11060. function lib$es6$promise$$internal$$cannotReturnOwn() {
  11061. return new TypeError('A promises callback cannot return that same promise.');
  11062. }
  11063. function lib$es6$promise$$internal$$getThen(promise) {
  11064. try {
  11065. return promise.then;
  11066. } catch(error) {
  11067. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  11068. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  11069. }
  11070. }
  11071. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  11072. try {
  11073. then.call(value, fulfillmentHandler, rejectionHandler);
  11074. } catch(e) {
  11075. return e;
  11076. }
  11077. }
  11078. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  11079. lib$es6$promise$asap$$asap(function(promise) {
  11080. var sealed = false;
  11081. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  11082. if (sealed) { return; }
  11083. sealed = true;
  11084. if (thenable !== value) {
  11085. lib$es6$promise$$internal$$resolve(promise, value);
  11086. } else {
  11087. lib$es6$promise$$internal$$fulfill(promise, value);
  11088. }
  11089. }, function(reason) {
  11090. if (sealed) { return; }
  11091. sealed = true;
  11092. lib$es6$promise$$internal$$reject(promise, reason);
  11093. }, 'Settle: ' + (promise._label || ' unknown promise'));
  11094. if (!sealed && error) {
  11095. sealed = true;
  11096. lib$es6$promise$$internal$$reject(promise, error);
  11097. }
  11098. }, promise);
  11099. }
  11100. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  11101. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  11102. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  11103. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  11104. lib$es6$promise$$internal$$reject(promise, thenable._result);
  11105. } else {
  11106. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  11107. lib$es6$promise$$internal$$resolve(promise, value);
  11108. }, function(reason) {
  11109. lib$es6$promise$$internal$$reject(promise, reason);
  11110. });
  11111. }
  11112. }
  11113. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  11114. if (maybeThenable.constructor === promise.constructor) {
  11115. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  11116. } else {
  11117. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  11118. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  11119. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  11120. } else if (then === undefined) {
  11121. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11122. } else if (lib$es6$promise$utils$$isFunction(then)) {
  11123. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  11124. } else {
  11125. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11126. }
  11127. }
  11128. }
  11129. function lib$es6$promise$$internal$$resolve(promise, value) {
  11130. if (promise === value) {
  11131. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  11132. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  11133. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  11134. } else {
  11135. lib$es6$promise$$internal$$fulfill(promise, value);
  11136. }
  11137. }
  11138. function lib$es6$promise$$internal$$publishRejection(promise) {
  11139. if (promise._onerror) {
  11140. promise._onerror(promise._result);
  11141. }
  11142. lib$es6$promise$$internal$$publish(promise);
  11143. }
  11144. function lib$es6$promise$$internal$$fulfill(promise, value) {
  11145. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11146. promise._result = value;
  11147. promise._state = lib$es6$promise$$internal$$FULFILLED;
  11148. if (promise._subscribers.length !== 0) {
  11149. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  11150. }
  11151. }
  11152. function lib$es6$promise$$internal$$reject(promise, reason) {
  11153. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11154. promise._state = lib$es6$promise$$internal$$REJECTED;
  11155. promise._result = reason;
  11156. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  11157. }
  11158. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  11159. var subscribers = parent._subscribers;
  11160. var length = subscribers.length;
  11161. parent._onerror = null;
  11162. subscribers[length] = child;
  11163. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  11164. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  11165. if (length === 0 && parent._state) {
  11166. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  11167. }
  11168. }
  11169. function lib$es6$promise$$internal$$publish(promise) {
  11170. var subscribers = promise._subscribers;
  11171. var settled = promise._state;
  11172. if (subscribers.length === 0) { return; }
  11173. var child, callback, detail = promise._result;
  11174. for (var i = 0; i < subscribers.length; i += 3) {
  11175. child = subscribers[i];
  11176. callback = subscribers[i + settled];
  11177. if (child) {
  11178. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  11179. } else {
  11180. callback(detail);
  11181. }
  11182. }
  11183. promise._subscribers.length = 0;
  11184. }
  11185. function lib$es6$promise$$internal$$ErrorObject() {
  11186. this.error = null;
  11187. }
  11188. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11189. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  11190. try {
  11191. return callback(detail);
  11192. } catch(e) {
  11193. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  11194. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  11195. }
  11196. }
  11197. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  11198. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  11199. value, error, succeeded, failed;
  11200. if (hasCallback) {
  11201. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  11202. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  11203. failed = true;
  11204. error = value.error;
  11205. value = null;
  11206. } else {
  11207. succeeded = true;
  11208. }
  11209. if (promise === value) {
  11210. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  11211. return;
  11212. }
  11213. } else {
  11214. value = detail;
  11215. succeeded = true;
  11216. }
  11217. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  11218. // noop
  11219. } else if (hasCallback && succeeded) {
  11220. lib$es6$promise$$internal$$resolve(promise, value);
  11221. } else if (failed) {
  11222. lib$es6$promise$$internal$$reject(promise, error);
  11223. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  11224. lib$es6$promise$$internal$$fulfill(promise, value);
  11225. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  11226. lib$es6$promise$$internal$$reject(promise, value);
  11227. }
  11228. }
  11229. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  11230. try {
  11231. resolver(function resolvePromise(value){
  11232. lib$es6$promise$$internal$$resolve(promise, value);
  11233. }, function rejectPromise(reason) {
  11234. lib$es6$promise$$internal$$reject(promise, reason);
  11235. });
  11236. } catch(e) {
  11237. lib$es6$promise$$internal$$reject(promise, e);
  11238. }
  11239. }
  11240. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  11241. var enumerator = this;
  11242. enumerator._instanceConstructor = Constructor;
  11243. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  11244. if (enumerator._validateInput(input)) {
  11245. enumerator._input = input;
  11246. enumerator.length = input.length;
  11247. enumerator._remaining = input.length;
  11248. enumerator._init();
  11249. if (enumerator.length === 0) {
  11250. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11251. } else {
  11252. enumerator.length = enumerator.length || 0;
  11253. enumerator._enumerate();
  11254. if (enumerator._remaining === 0) {
  11255. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11256. }
  11257. }
  11258. } else {
  11259. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  11260. }
  11261. }
  11262. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  11263. return lib$es6$promise$utils$$isArray(input);
  11264. };
  11265. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  11266. return new Error('Array Methods must be provided an Array');
  11267. };
  11268. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  11269. this._result = new Array(this.length);
  11270. };
  11271. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  11272. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  11273. var enumerator = this;
  11274. var length = enumerator.length;
  11275. var promise = enumerator.promise;
  11276. var input = enumerator._input;
  11277. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11278. enumerator._eachEntry(input[i], i);
  11279. }
  11280. };
  11281. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  11282. var enumerator = this;
  11283. var c = enumerator._instanceConstructor;
  11284. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  11285. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  11286. entry._onerror = null;
  11287. enumerator._settledAt(entry._state, i, entry._result);
  11288. } else {
  11289. enumerator._willSettleAt(c.resolve(entry), i);
  11290. }
  11291. } else {
  11292. enumerator._remaining--;
  11293. enumerator._result[i] = entry;
  11294. }
  11295. };
  11296. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  11297. var enumerator = this;
  11298. var promise = enumerator.promise;
  11299. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  11300. enumerator._remaining--;
  11301. if (state === lib$es6$promise$$internal$$REJECTED) {
  11302. lib$es6$promise$$internal$$reject(promise, value);
  11303. } else {
  11304. enumerator._result[i] = value;
  11305. }
  11306. }
  11307. if (enumerator._remaining === 0) {
  11308. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  11309. }
  11310. };
  11311. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  11312. var enumerator = this;
  11313. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  11314. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  11315. }, function(reason) {
  11316. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  11317. });
  11318. };
  11319. function lib$es6$promise$promise$all$$all(entries) {
  11320. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  11321. }
  11322. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  11323. function lib$es6$promise$promise$race$$race(entries) {
  11324. /*jshint validthis:true */
  11325. var Constructor = this;
  11326. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11327. if (!lib$es6$promise$utils$$isArray(entries)) {
  11328. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  11329. return promise;
  11330. }
  11331. var length = entries.length;
  11332. function onFulfillment(value) {
  11333. lib$es6$promise$$internal$$resolve(promise, value);
  11334. }
  11335. function onRejection(reason) {
  11336. lib$es6$promise$$internal$$reject(promise, reason);
  11337. }
  11338. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11339. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  11340. }
  11341. return promise;
  11342. }
  11343. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  11344. function lib$es6$promise$promise$resolve$$resolve(object) {
  11345. /*jshint validthis:true */
  11346. var Constructor = this;
  11347. if (object && typeof object === 'object' && object.constructor === Constructor) {
  11348. return object;
  11349. }
  11350. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11351. lib$es6$promise$$internal$$resolve(promise, object);
  11352. return promise;
  11353. }
  11354. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  11355. function lib$es6$promise$promise$reject$$reject(reason) {
  11356. /*jshint validthis:true */
  11357. var Constructor = this;
  11358. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11359. lib$es6$promise$$internal$$reject(promise, reason);
  11360. return promise;
  11361. }
  11362. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  11363. var lib$es6$promise$promise$$counter = 0;
  11364. function lib$es6$promise$promise$$needsResolver() {
  11365. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  11366. }
  11367. function lib$es6$promise$promise$$needsNew() {
  11368. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  11369. }
  11370. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  11371. /**
  11372. Promise objects represent the eventual result of an asynchronous operation. The
  11373. primary way of interacting with a promise is through its `then` method, which
  11374. registers callbacks to receive either a promise's eventual value or the reason
  11375. why the promise cannot be fulfilled.
  11376. Terminology
  11377. -----------
  11378. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  11379. - `thenable` is an object or function that defines a `then` method.
  11380. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  11381. - `exception` is a value that is thrown using the throw statement.
  11382. - `reason` is a value that indicates why a promise was rejected.
  11383. - `settled` the final resting state of a promise, fulfilled or rejected.
  11384. A promise can be in one of three states: pending, fulfilled, or rejected.
  11385. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  11386. state. Promises that are rejected have a rejection reason and are in the
  11387. rejected state. A fulfillment value is never a thenable.
  11388. Promises can also be said to *resolve* a value. If this value is also a
  11389. promise, then the original promise's settled state will match the value's
  11390. settled state. So a promise that *resolves* a promise that rejects will
  11391. itself reject, and a promise that *resolves* a promise that fulfills will
  11392. itself fulfill.
  11393. Basic Usage:
  11394. ------------
  11395. ```js
  11396. var promise = new Promise(function(resolve, reject) {
  11397. // on success
  11398. resolve(value);
  11399. // on failure
  11400. reject(reason);
  11401. });
  11402. promise.then(function(value) {
  11403. // on fulfillment
  11404. }, function(reason) {
  11405. // on rejection
  11406. });
  11407. ```
  11408. Advanced Usage:
  11409. ---------------
  11410. Promises shine when abstracting away asynchronous interactions such as
  11411. `XMLHttpRequest`s.
  11412. ```js
  11413. function getJSON(url) {
  11414. return new Promise(function(resolve, reject){
  11415. var xhr = new XMLHttpRequest();
  11416. xhr.open('GET', url);
  11417. xhr.onreadystatechange = handler;
  11418. xhr.responseType = 'json';
  11419. xhr.setRequestHeader('Accept', 'application/json');
  11420. xhr.send();
  11421. function handler() {
  11422. if (this.readyState === this.DONE) {
  11423. if (this.status === 200) {
  11424. resolve(this.response);
  11425. } else {
  11426. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  11427. }
  11428. }
  11429. };
  11430. });
  11431. }
  11432. getJSON('/posts.json').then(function(json) {
  11433. // on fulfillment
  11434. }, function(reason) {
  11435. // on rejection
  11436. });
  11437. ```
  11438. Unlike callbacks, promises are great composable primitives.
  11439. ```js
  11440. Promise.all([
  11441. getJSON('/posts'),
  11442. getJSON('/comments')
  11443. ]).then(function(values){
  11444. values[0] // => postsJSON
  11445. values[1] // => commentsJSON
  11446. return values;
  11447. });
  11448. ```
  11449. @class Promise
  11450. @param {function} resolver
  11451. Useful for tooling.
  11452. @constructor
  11453. */
  11454. function lib$es6$promise$promise$$Promise(resolver) {
  11455. this._id = lib$es6$promise$promise$$counter++;
  11456. this._state = undefined;
  11457. this._result = undefined;
  11458. this._subscribers = [];
  11459. if (lib$es6$promise$$internal$$noop !== resolver) {
  11460. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  11461. lib$es6$promise$promise$$needsResolver();
  11462. }
  11463. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  11464. lib$es6$promise$promise$$needsNew();
  11465. }
  11466. lib$es6$promise$$internal$$initializePromise(this, resolver);
  11467. }
  11468. }
  11469. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  11470. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  11471. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  11472. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  11473. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  11474. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  11475. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  11476. lib$es6$promise$promise$$Promise.prototype = {
  11477. constructor: lib$es6$promise$promise$$Promise,
  11478. /**
  11479. The primary way of interacting with a promise is through its `then` method,
  11480. which registers callbacks to receive either a promise's eventual value or the
  11481. reason why the promise cannot be fulfilled.
  11482. ```js
  11483. findUser().then(function(user){
  11484. // user is available
  11485. }, function(reason){
  11486. // user is unavailable, and you are given the reason why
  11487. });
  11488. ```
  11489. Chaining
  11490. --------
  11491. The return value of `then` is itself a promise. This second, 'downstream'
  11492. promise is resolved with the return value of the first promise's fulfillment
  11493. or rejection handler, or rejected if the handler throws an exception.
  11494. ```js
  11495. findUser().then(function (user) {
  11496. return user.name;
  11497. }, function (reason) {
  11498. return 'default name';
  11499. }).then(function (userName) {
  11500. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  11501. // will be `'default name'`
  11502. });
  11503. findUser().then(function (user) {
  11504. throw new Error('Found user, but still unhappy');
  11505. }, function (reason) {
  11506. throw new Error('`findUser` rejected and we're unhappy');
  11507. }).then(function (value) {
  11508. // never reached
  11509. }, function (reason) {
  11510. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  11511. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  11512. });
  11513. ```
  11514. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  11515. ```js
  11516. findUser().then(function (user) {
  11517. throw new PedagogicalException('Upstream error');
  11518. }).then(function (value) {
  11519. // never reached
  11520. }).then(function (value) {
  11521. // never reached
  11522. }, function (reason) {
  11523. // The `PedgagocialException` is propagated all the way down to here
  11524. });
  11525. ```
  11526. Assimilation
  11527. ------------
  11528. Sometimes the value you want to propagate to a downstream promise can only be
  11529. retrieved asynchronously. This can be achieved by returning a promise in the
  11530. fulfillment or rejection handler. The downstream promise will then be pending
  11531. until the returned promise is settled. This is called *assimilation*.
  11532. ```js
  11533. findUser().then(function (user) {
  11534. return findCommentsByAuthor(user);
  11535. }).then(function (comments) {
  11536. // The user's comments are now available
  11537. });
  11538. ```
  11539. If the assimliated promise rejects, then the downstream promise will also reject.
  11540. ```js
  11541. findUser().then(function (user) {
  11542. return findCommentsByAuthor(user);
  11543. }).then(function (comments) {
  11544. // If `findCommentsByAuthor` fulfills, we'll have the value here
  11545. }, function (reason) {
  11546. // If `findCommentsByAuthor` rejects, we'll have the reason here
  11547. });
  11548. ```
  11549. Simple Example
  11550. --------------
  11551. Synchronous Example
  11552. ```javascript
  11553. var result;
  11554. try {
  11555. result = findResult();
  11556. // success
  11557. } catch(reason) {
  11558. // failure
  11559. }
  11560. ```
  11561. Errback Example
  11562. ```js
  11563. findResult(function(result, err){
  11564. if (err) {
  11565. // failure
  11566. } else {
  11567. // success
  11568. }
  11569. });
  11570. ```
  11571. Promise Example;
  11572. ```javascript
  11573. findResult().then(function(result){
  11574. // success
  11575. }, function(reason){
  11576. // failure
  11577. });
  11578. ```
  11579. Advanced Example
  11580. --------------
  11581. Synchronous Example
  11582. ```javascript
  11583. var author, books;
  11584. try {
  11585. author = findAuthor();
  11586. books = findBooksByAuthor(author);
  11587. // success
  11588. } catch(reason) {
  11589. // failure
  11590. }
  11591. ```
  11592. Errback Example
  11593. ```js
  11594. function foundBooks(books) {
  11595. }
  11596. function failure(reason) {
  11597. }
  11598. findAuthor(function(author, err){
  11599. if (err) {
  11600. failure(err);
  11601. // failure
  11602. } else {
  11603. try {
  11604. findBoooksByAuthor(author, function(books, err) {
  11605. if (err) {
  11606. failure(err);
  11607. } else {
  11608. try {
  11609. foundBooks(books);
  11610. } catch(reason) {
  11611. failure(reason);
  11612. }
  11613. }
  11614. });
  11615. } catch(error) {
  11616. failure(err);
  11617. }
  11618. // success
  11619. }
  11620. });
  11621. ```
  11622. Promise Example;
  11623. ```javascript
  11624. findAuthor().
  11625. then(findBooksByAuthor).
  11626. then(function(books){
  11627. // found books
  11628. }).catch(function(reason){
  11629. // something went wrong
  11630. });
  11631. ```
  11632. @method then
  11633. @param {Function} onFulfilled
  11634. @param {Function} onRejected
  11635. Useful for tooling.
  11636. @return {Promise}
  11637. */
  11638. then: function(onFulfillment, onRejection) {
  11639. var parent = this;
  11640. var state = parent._state;
  11641. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  11642. return this;
  11643. }
  11644. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  11645. var result = parent._result;
  11646. if (state) {
  11647. var callback = arguments[state - 1];
  11648. lib$es6$promise$asap$$asap(function(){
  11649. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  11650. });
  11651. } else {
  11652. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  11653. }
  11654. return child;
  11655. },
  11656. /**
  11657. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  11658. as the catch block of a try/catch statement.
  11659. ```js
  11660. function findAuthor(){
  11661. throw new Error('couldn't find that author');
  11662. }
  11663. // synchronous
  11664. try {
  11665. findAuthor();
  11666. } catch(reason) {
  11667. // something went wrong
  11668. }
  11669. // async with promises
  11670. findAuthor().catch(function(reason){
  11671. // something went wrong
  11672. });
  11673. ```
  11674. @method catch
  11675. @param {Function} onRejection
  11676. Useful for tooling.
  11677. @return {Promise}
  11678. */
  11679. 'catch': function(onRejection) {
  11680. return this.then(null, onRejection);
  11681. }
  11682. };
  11683. function lib$es6$promise$polyfill$$polyfill() {
  11684. var local;
  11685. if (typeof global !== 'undefined') {
  11686. local = global;
  11687. } else if (typeof self !== 'undefined') {
  11688. local = self;
  11689. } else {
  11690. try {
  11691. local = Function('return this')();
  11692. } catch (e) {
  11693. throw new Error('polyfill failed because global object is unavailable in this environment');
  11694. }
  11695. }
  11696. var P = local.Promise;
  11697. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  11698. return;
  11699. }
  11700. local.Promise = lib$es6$promise$promise$$default;
  11701. }
  11702. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  11703. var lib$es6$promise$umd$$ES6Promise = {
  11704. 'Promise': lib$es6$promise$promise$$default,
  11705. 'polyfill': lib$es6$promise$polyfill$$default
  11706. };
  11707. /* global define:true module:true window: true */
  11708. if (typeof define === 'function' && define['amd']) {
  11709. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  11710. } else if (typeof module !== 'undefined' && module['exports']) {
  11711. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  11712. } else if (typeof this !== 'undefined') {
  11713. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  11714. }
  11715. lib$es6$promise$polyfill$$default();
  11716. }).call(this);
  11717. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11718. },{"_process":41}],43:[function(require,module,exports){
  11719. /* Copyright @ 2015 Atlassian Pty Ltd
  11720. *
  11721. * Licensed under the Apache License, Version 2.0 (the "License");
  11722. * you may not use this file except in compliance with the License.
  11723. * You may obtain a copy of the License at
  11724. *
  11725. * http://www.apache.org/licenses/LICENSE-2.0
  11726. *
  11727. * Unless required by applicable law or agreed to in writing, software
  11728. * distributed under the License is distributed on an "AS IS" BASIS,
  11729. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11730. * See the License for the specific language governing permissions and
  11731. * limitations under the License.
  11732. */
  11733. /**
  11734. * Ordered log levels.
  11735. */
  11736. var levels = {
  11737. "trace": 0,
  11738. "debug": 1,
  11739. "info": 2,
  11740. "log": 3,
  11741. "warn": 4,
  11742. "error": 5
  11743. };
  11744. /**
  11745. * Parses Error's object stack trace and extracts information about the last
  11746. * caller before the log method was called.
  11747. * @returns JS object with info about the caller - method name, file location,
  11748. * line and column.
  11749. */
  11750. function getCallerInfo() {
  11751. var callerInfo = {
  11752. methodName: "",
  11753. fileLocation: "",
  11754. line: null,
  11755. column: null
  11756. };
  11757. //gets the part of the stack without the logger wrappers
  11758. var error = new Error();
  11759. var stack = error.stack.split("\n");
  11760. if(!stack || stack.length < 1) {
  11761. return callerInfo;
  11762. }
  11763. var m = null;
  11764. if(stack[3]) {
  11765. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  11766. }
  11767. if(!m || m.length <= 4) {
  11768. //Firefox && Safari
  11769. if(stack[2].indexOf("log@") === 0){
  11770. //Safari
  11771. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  11772. } else {
  11773. //Firefox
  11774. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  11775. }
  11776. return callerInfo;
  11777. }
  11778. callerInfo.methodName = m[1];
  11779. callerInfo.fileLocation = m[2];
  11780. callerInfo.line = m[3];
  11781. callerInfo.column = m[4];
  11782. return callerInfo;
  11783. }
  11784. /**
  11785. * Logs messages using the transports and level from the logger.
  11786. * @param logger a logger instance.
  11787. * @param level the log level of the message. See the levels variable.
  11788. * @param arguments array with arguments that will be logged.
  11789. */
  11790. function log() {
  11791. var logger = arguments[0], level = arguments[1],
  11792. args = Array.prototype.slice.call(arguments, 2);
  11793. if(levels[level] <= logger.level) {
  11794. return;
  11795. }
  11796. var callerInfo = getCallerInfo();
  11797. for(var i = 0; i < logger.transports.length; i++) {
  11798. var t = logger.transports[i];
  11799. var l = t[level];
  11800. if(l && typeof(l) === "function") {
  11801. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  11802. .apply(t, args);
  11803. }
  11804. }
  11805. }
  11806. /**
  11807. *
  11808. * Constructs new logger object.
  11809. * @param level the logging level for the new logger
  11810. * @param id optional identifier for the logger instance.
  11811. * @param transports optional list of handlers(objects) for the logs.
  11812. * The handlers must support - log, warn, error, debug, info, trace.
  11813. * @param format optional (NOT implemented) string.
  11814. */
  11815. function Logger(level, id, transports, format) {
  11816. this.id = id;
  11817. this.format = format;
  11818. if(!this.transports) {
  11819. this.transports = [];
  11820. this.transports.push(Logger.consoleTransport);
  11821. }
  11822. this.level = levels[level];
  11823. var methods = Object.keys(levels);
  11824. for(var i = 0; i < methods.length; i++){
  11825. this[methods[i]] =
  11826. log.bind(null, this, methods[i]);
  11827. }
  11828. }
  11829. /**
  11830. * Sets the log level for the logger.
  11831. * @param level the new log level.
  11832. */
  11833. Logger.prototype.setLevel = function (level) {
  11834. this.level = levels[level];
  11835. };
  11836. module.exports = Logger;
  11837. /**
  11838. * The default transport - console
  11839. */
  11840. Logger.consoleTransport = console;
  11841. /**
  11842. * Enum for the supported log levels.
  11843. */
  11844. Logger.levels = {
  11845. TRACE: "trace",
  11846. DEBUG: "debug",
  11847. INFO: "info",
  11848. LOG: "log",
  11849. WARN: "warn",
  11850. ERROR: "error"
  11851. };
  11852. },{}],44:[function(require,module,exports){
  11853. /* Copyright @ 2015 Atlassian Pty Ltd
  11854. *
  11855. * Licensed under the Apache License, Version 2.0 (the "License");
  11856. * you may not use this file except in compliance with the License.
  11857. * You may obtain a copy of the License at
  11858. *
  11859. * http://www.apache.org/licenses/LICENSE-2.0
  11860. *
  11861. * Unless required by applicable law or agreed to in writing, software
  11862. * distributed under the License is distributed on an "AS IS" BASIS,
  11863. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11864. * See the License for the specific language governing permissions and
  11865. * limitations under the License.
  11866. */
  11867. var Logger = require("./Logger");
  11868. /**
  11869. * Map with the created loggers with ID.
  11870. */
  11871. var idLoggers = {};
  11872. /**
  11873. * Array with the loggers without id.
  11874. */
  11875. var loggers = [];
  11876. /**
  11877. * Log level for the lbrary.
  11878. */
  11879. var curLevel = Logger.levels.TRACE;
  11880. module.exports = {
  11881. /**
  11882. * Creates new logger.
  11883. * @arguments the same as Logger constructor
  11884. */
  11885. getLogger: function(id, transports, format) {
  11886. var logger = new Logger(curLevel, id, transports, format);
  11887. if(id) {
  11888. idLoggers[id] = idLoggers[id] || [];
  11889. idLoggers[id].push(logger);
  11890. } else {
  11891. loggers.push(logger);
  11892. }
  11893. return logger;
  11894. },
  11895. /**
  11896. * Changes the log level for the existing loggers by id.
  11897. * @param level the new log level.
  11898. * @param id if specified the level will be changed only for loggers with the
  11899. * same id. Otherwise the operation will affect all loggers that don't
  11900. * have id.
  11901. */
  11902. setLogLevelById: function(level, id) {
  11903. var l = id? (idLoggers[id] || []) : loggers;
  11904. for(var i = 0; i < l.length; i++) {
  11905. l[i].setLevel(level);
  11906. }
  11907. },
  11908. /**
  11909. * Changes the log level for all existing loggers.
  11910. * @param level the new log level.
  11911. */
  11912. setLogLevel: function (level) {
  11913. curLevel = level;
  11914. var i = 0;
  11915. for(; i < loggers.length; i++) {
  11916. loggers[i].setLevel(level);
  11917. }
  11918. for(var id in idLoggers) {
  11919. var l = idLoggers[id] || [];
  11920. for(i = 0; i < l.length; i++) {
  11921. l[i].setLevel(level);
  11922. }
  11923. }
  11924. },
  11925. /**
  11926. * The supported log levels.
  11927. */
  11928. levels: Logger.levels
  11929. };
  11930. },{"./Logger":43}],45:[function(require,module,exports){
  11931. // Top level file is just a mixin of submodules & constants
  11932. 'use strict';
  11933. var assign = require('./lib/utils/common').assign;
  11934. var deflate = require('./lib/deflate');
  11935. var inflate = require('./lib/inflate');
  11936. var constants = require('./lib/zlib/constants');
  11937. var pako = {};
  11938. assign(pako, deflate, inflate, constants);
  11939. module.exports = pako;
  11940. },{"./lib/deflate":46,"./lib/inflate":47,"./lib/utils/common":48,"./lib/zlib/constants":51}],46:[function(require,module,exports){
  11941. 'use strict';
  11942. var zlib_deflate = require('./zlib/deflate.js');
  11943. var utils = require('./utils/common');
  11944. var strings = require('./utils/strings');
  11945. var msg = require('./zlib/messages');
  11946. var zstream = require('./zlib/zstream');
  11947. var toString = Object.prototype.toString;
  11948. /* Public constants ==========================================================*/
  11949. /* ===========================================================================*/
  11950. var Z_NO_FLUSH = 0;
  11951. var Z_FINISH = 4;
  11952. var Z_OK = 0;
  11953. var Z_STREAM_END = 1;
  11954. var Z_SYNC_FLUSH = 2;
  11955. var Z_DEFAULT_COMPRESSION = -1;
  11956. var Z_DEFAULT_STRATEGY = 0;
  11957. var Z_DEFLATED = 8;
  11958. /* ===========================================================================*/
  11959. /**
  11960. * class Deflate
  11961. *
  11962. * Generic JS-style wrapper for zlib calls. If you don't need
  11963. * streaming behaviour - use more simple functions: [[deflate]],
  11964. * [[deflateRaw]] and [[gzip]].
  11965. **/
  11966. /* internal
  11967. * Deflate.chunks -> Array
  11968. *
  11969. * Chunks of output data, if [[Deflate#onData]] not overriden.
  11970. **/
  11971. /**
  11972. * Deflate.result -> Uint8Array|Array
  11973. *
  11974. * Compressed result, generated by default [[Deflate#onData]]
  11975. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  11976. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  11977. * push a chunk with explicit flush (call [[Deflate#push]] with
  11978. * `Z_SYNC_FLUSH` param).
  11979. **/
  11980. /**
  11981. * Deflate.err -> Number
  11982. *
  11983. * Error code after deflate finished. 0 (Z_OK) on success.
  11984. * You will not need it in real life, because deflate errors
  11985. * are possible only on wrong options or bad `onData` / `onEnd`
  11986. * custom handlers.
  11987. **/
  11988. /**
  11989. * Deflate.msg -> String
  11990. *
  11991. * Error message, if [[Deflate.err]] != 0
  11992. **/
  11993. /**
  11994. * new Deflate(options)
  11995. * - options (Object): zlib deflate options.
  11996. *
  11997. * Creates new deflator instance with specified params. Throws exception
  11998. * on bad params. Supported options:
  11999. *
  12000. * - `level`
  12001. * - `windowBits`
  12002. * - `memLevel`
  12003. * - `strategy`
  12004. *
  12005. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12006. * for more information on these.
  12007. *
  12008. * Additional options, for internal needs:
  12009. *
  12010. * - `chunkSize` - size of generated data chunks (16K by default)
  12011. * - `raw` (Boolean) - do raw deflate
  12012. * - `gzip` (Boolean) - create gzip wrapper
  12013. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12014. * (each char code [0..255])
  12015. * - `header` (Object) - custom header for gzip
  12016. * - `text` (Boolean) - true if compressed data believed to be text
  12017. * - `time` (Number) - modification time, unix timestamp
  12018. * - `os` (Number) - operation system code
  12019. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12020. * - `name` (String) - file name (binary string)
  12021. * - `comment` (String) - comment (binary string)
  12022. * - `hcrc` (Boolean) - true if header crc should be added
  12023. *
  12024. * ##### Example:
  12025. *
  12026. * ```javascript
  12027. * var pako = require('pako')
  12028. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12029. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12030. *
  12031. * var deflate = new pako.Deflate({ level: 3});
  12032. *
  12033. * deflate.push(chunk1, false);
  12034. * deflate.push(chunk2, true); // true -> last chunk
  12035. *
  12036. * if (deflate.err) { throw new Error(deflate.err); }
  12037. *
  12038. * console.log(deflate.result);
  12039. * ```
  12040. **/
  12041. var Deflate = function(options) {
  12042. this.options = utils.assign({
  12043. level: Z_DEFAULT_COMPRESSION,
  12044. method: Z_DEFLATED,
  12045. chunkSize: 16384,
  12046. windowBits: 15,
  12047. memLevel: 8,
  12048. strategy: Z_DEFAULT_STRATEGY,
  12049. to: ''
  12050. }, options || {});
  12051. var opt = this.options;
  12052. if (opt.raw && (opt.windowBits > 0)) {
  12053. opt.windowBits = -opt.windowBits;
  12054. }
  12055. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12056. opt.windowBits += 16;
  12057. }
  12058. this.err = 0; // error code, if happens (0 = Z_OK)
  12059. this.msg = ''; // error message
  12060. this.ended = false; // used to avoid multiple onEnd() calls
  12061. this.chunks = []; // chunks of compressed data
  12062. this.strm = new zstream();
  12063. this.strm.avail_out = 0;
  12064. var status = zlib_deflate.deflateInit2(
  12065. this.strm,
  12066. opt.level,
  12067. opt.method,
  12068. opt.windowBits,
  12069. opt.memLevel,
  12070. opt.strategy
  12071. );
  12072. if (status !== Z_OK) {
  12073. throw new Error(msg[status]);
  12074. }
  12075. if (opt.header) {
  12076. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12077. }
  12078. };
  12079. /**
  12080. * Deflate#push(data[, mode]) -> Boolean
  12081. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12082. * converted to utf8 byte sequence.
  12083. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12084. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12085. *
  12086. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12087. * new compressed chunks. Returns `true` on success. The last data block must have
  12088. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12089. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12090. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12091. *
  12092. * On fail call [[Deflate#onEnd]] with error code and return false.
  12093. *
  12094. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12095. * array format is detected automatically). Also, don't skip last param and always
  12096. * use the same type in your code (boolean or number). That will improve JS speed.
  12097. *
  12098. * For regular `Array`-s make sure all elements are [0..255].
  12099. *
  12100. * ##### Example
  12101. *
  12102. * ```javascript
  12103. * push(chunk, false); // push one of data chunks
  12104. * ...
  12105. * push(chunk, true); // push last chunk
  12106. * ```
  12107. **/
  12108. Deflate.prototype.push = function(data, mode) {
  12109. var strm = this.strm;
  12110. var chunkSize = this.options.chunkSize;
  12111. var status, _mode;
  12112. if (this.ended) { return false; }
  12113. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  12114. // Convert data if needed
  12115. if (typeof data === 'string') {
  12116. // If we need to compress text, change encoding to utf8.
  12117. strm.input = strings.string2buf(data);
  12118. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12119. strm.input = new Uint8Array(data);
  12120. } else {
  12121. strm.input = data;
  12122. }
  12123. strm.next_in = 0;
  12124. strm.avail_in = strm.input.length;
  12125. do {
  12126. if (strm.avail_out === 0) {
  12127. strm.output = new utils.Buf8(chunkSize);
  12128. strm.next_out = 0;
  12129. strm.avail_out = chunkSize;
  12130. }
  12131. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  12132. if (status !== Z_STREAM_END && status !== Z_OK) {
  12133. this.onEnd(status);
  12134. this.ended = true;
  12135. return false;
  12136. }
  12137. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  12138. if (this.options.to === 'string') {
  12139. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  12140. } else {
  12141. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12142. }
  12143. }
  12144. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  12145. // Finalize on the last chunk.
  12146. if (_mode === Z_FINISH) {
  12147. status = zlib_deflate.deflateEnd(this.strm);
  12148. this.onEnd(status);
  12149. this.ended = true;
  12150. return status === Z_OK;
  12151. }
  12152. // callback interim results if Z_SYNC_FLUSH.
  12153. if (_mode === Z_SYNC_FLUSH) {
  12154. this.onEnd(Z_OK);
  12155. strm.avail_out = 0;
  12156. return true;
  12157. }
  12158. return true;
  12159. };
  12160. /**
  12161. * Deflate#onData(chunk) -> Void
  12162. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12163. * on js engine support. When string output requested, each chunk
  12164. * will be string.
  12165. *
  12166. * By default, stores data blocks in `chunks[]` property and glue
  12167. * those in `onEnd`. Override this handler, if you need another behaviour.
  12168. **/
  12169. Deflate.prototype.onData = function(chunk) {
  12170. this.chunks.push(chunk);
  12171. };
  12172. /**
  12173. * Deflate#onEnd(status) -> Void
  12174. * - status (Number): deflate status. 0 (Z_OK) on success,
  12175. * other if not.
  12176. *
  12177. * Called once after you tell deflate that the input stream is
  12178. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12179. * or if an error happened. By default - join collected chunks,
  12180. * free memory and fill `results` / `err` properties.
  12181. **/
  12182. Deflate.prototype.onEnd = function(status) {
  12183. // On success - join
  12184. if (status === Z_OK) {
  12185. if (this.options.to === 'string') {
  12186. this.result = this.chunks.join('');
  12187. } else {
  12188. this.result = utils.flattenChunks(this.chunks);
  12189. }
  12190. }
  12191. this.chunks = [];
  12192. this.err = status;
  12193. this.msg = this.strm.msg;
  12194. };
  12195. /**
  12196. * deflate(data[, options]) -> Uint8Array|Array|String
  12197. * - data (Uint8Array|Array|String): input data to compress.
  12198. * - options (Object): zlib deflate options.
  12199. *
  12200. * Compress `data` with deflate alrorythm and `options`.
  12201. *
  12202. * Supported options are:
  12203. *
  12204. * - level
  12205. * - windowBits
  12206. * - memLevel
  12207. * - strategy
  12208. *
  12209. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12210. * for more information on these.
  12211. *
  12212. * Sugar (options):
  12213. *
  12214. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12215. * negative windowBits implicitly.
  12216. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12217. * (each char code [0..255])
  12218. *
  12219. * ##### Example:
  12220. *
  12221. * ```javascript
  12222. * var pako = require('pako')
  12223. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  12224. *
  12225. * console.log(pako.deflate(data));
  12226. * ```
  12227. **/
  12228. function deflate(input, options) {
  12229. var deflator = new Deflate(options);
  12230. deflator.push(input, true);
  12231. // That will never happens, if you don't cheat with options :)
  12232. if (deflator.err) { throw deflator.msg; }
  12233. return deflator.result;
  12234. }
  12235. /**
  12236. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  12237. * - data (Uint8Array|Array|String): input data to compress.
  12238. * - options (Object): zlib deflate options.
  12239. *
  12240. * The same as [[deflate]], but creates raw data, without wrapper
  12241. * (header and adler32 crc).
  12242. **/
  12243. function deflateRaw(input, options) {
  12244. options = options || {};
  12245. options.raw = true;
  12246. return deflate(input, options);
  12247. }
  12248. /**
  12249. * gzip(data[, options]) -> Uint8Array|Array|String
  12250. * - data (Uint8Array|Array|String): input data to compress.
  12251. * - options (Object): zlib deflate options.
  12252. *
  12253. * The same as [[deflate]], but create gzip wrapper instead of
  12254. * deflate one.
  12255. **/
  12256. function gzip(input, options) {
  12257. options = options || {};
  12258. options.gzip = true;
  12259. return deflate(input, options);
  12260. }
  12261. exports.Deflate = Deflate;
  12262. exports.deflate = deflate;
  12263. exports.deflateRaw = deflateRaw;
  12264. exports.gzip = gzip;
  12265. },{"./utils/common":48,"./utils/strings":49,"./zlib/deflate.js":53,"./zlib/messages":58,"./zlib/zstream":60}],47:[function(require,module,exports){
  12266. 'use strict';
  12267. var zlib_inflate = require('./zlib/inflate.js');
  12268. var utils = require('./utils/common');
  12269. var strings = require('./utils/strings');
  12270. var c = require('./zlib/constants');
  12271. var msg = require('./zlib/messages');
  12272. var zstream = require('./zlib/zstream');
  12273. var gzheader = require('./zlib/gzheader');
  12274. var toString = Object.prototype.toString;
  12275. /**
  12276. * class Inflate
  12277. *
  12278. * Generic JS-style wrapper for zlib calls. If you don't need
  12279. * streaming behaviour - use more simple functions: [[inflate]]
  12280. * and [[inflateRaw]].
  12281. **/
  12282. /* internal
  12283. * inflate.chunks -> Array
  12284. *
  12285. * Chunks of output data, if [[Inflate#onData]] not overriden.
  12286. **/
  12287. /**
  12288. * Inflate.result -> Uint8Array|Array|String
  12289. *
  12290. * Uncompressed result, generated by default [[Inflate#onData]]
  12291. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  12292. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  12293. * push a chunk with explicit flush (call [[Inflate#push]] with
  12294. * `Z_SYNC_FLUSH` param).
  12295. **/
  12296. /**
  12297. * Inflate.err -> Number
  12298. *
  12299. * Error code after inflate finished. 0 (Z_OK) on success.
  12300. * Should be checked if broken data possible.
  12301. **/
  12302. /**
  12303. * Inflate.msg -> String
  12304. *
  12305. * Error message, if [[Inflate.err]] != 0
  12306. **/
  12307. /**
  12308. * new Inflate(options)
  12309. * - options (Object): zlib inflate options.
  12310. *
  12311. * Creates new inflator instance with specified params. Throws exception
  12312. * on bad params. Supported options:
  12313. *
  12314. * - `windowBits`
  12315. *
  12316. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12317. * for more information on these.
  12318. *
  12319. * Additional options, for internal needs:
  12320. *
  12321. * - `chunkSize` - size of generated data chunks (16K by default)
  12322. * - `raw` (Boolean) - do raw inflate
  12323. * - `to` (String) - if equal to 'string', then result will be converted
  12324. * from utf8 to utf16 (javascript) string. When string output requested,
  12325. * chunk length can differ from `chunkSize`, depending on content.
  12326. *
  12327. * By default, when no options set, autodetect deflate/gzip data format via
  12328. * wrapper header.
  12329. *
  12330. * ##### Example:
  12331. *
  12332. * ```javascript
  12333. * var pako = require('pako')
  12334. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12335. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12336. *
  12337. * var inflate = new pako.Inflate({ level: 3});
  12338. *
  12339. * inflate.push(chunk1, false);
  12340. * inflate.push(chunk2, true); // true -> last chunk
  12341. *
  12342. * if (inflate.err) { throw new Error(inflate.err); }
  12343. *
  12344. * console.log(inflate.result);
  12345. * ```
  12346. **/
  12347. var Inflate = function(options) {
  12348. this.options = utils.assign({
  12349. chunkSize: 16384,
  12350. windowBits: 0,
  12351. to: ''
  12352. }, options || {});
  12353. var opt = this.options;
  12354. // Force window size for `raw` data, if not set directly,
  12355. // because we have no header for autodetect.
  12356. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  12357. opt.windowBits = -opt.windowBits;
  12358. if (opt.windowBits === 0) { opt.windowBits = -15; }
  12359. }
  12360. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  12361. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  12362. !(options && options.windowBits)) {
  12363. opt.windowBits += 32;
  12364. }
  12365. // Gzip header has no info about windows size, we can do autodetect only
  12366. // for deflate. So, if window size not set, force it to max when gzip possible
  12367. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  12368. // bit 3 (16) -> gzipped data
  12369. // bit 4 (32) -> autodetect gzip/deflate
  12370. if ((opt.windowBits & 15) === 0) {
  12371. opt.windowBits |= 15;
  12372. }
  12373. }
  12374. this.err = 0; // error code, if happens (0 = Z_OK)
  12375. this.msg = ''; // error message
  12376. this.ended = false; // used to avoid multiple onEnd() calls
  12377. this.chunks = []; // chunks of compressed data
  12378. this.strm = new zstream();
  12379. this.strm.avail_out = 0;
  12380. var status = zlib_inflate.inflateInit2(
  12381. this.strm,
  12382. opt.windowBits
  12383. );
  12384. if (status !== c.Z_OK) {
  12385. throw new Error(msg[status]);
  12386. }
  12387. this.header = new gzheader();
  12388. zlib_inflate.inflateGetHeader(this.strm, this.header);
  12389. };
  12390. /**
  12391. * Inflate#push(data[, mode]) -> Boolean
  12392. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  12393. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12394. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12395. *
  12396. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  12397. * new output chunks. Returns `true` on success. The last data block must have
  12398. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12399. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12400. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  12401. *
  12402. * On fail call [[Inflate#onEnd]] with error code and return false.
  12403. *
  12404. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12405. * format is detected automatically). Also, don't skip last param and always
  12406. * use the same type in your code (boolean or number). That will improve JS speed.
  12407. *
  12408. * For regular `Array`-s make sure all elements are [0..255].
  12409. *
  12410. * ##### Example
  12411. *
  12412. * ```javascript
  12413. * push(chunk, false); // push one of data chunks
  12414. * ...
  12415. * push(chunk, true); // push last chunk
  12416. * ```
  12417. **/
  12418. Inflate.prototype.push = function(data, mode) {
  12419. var strm = this.strm;
  12420. var chunkSize = this.options.chunkSize;
  12421. var status, _mode;
  12422. var next_out_utf8, tail, utf8str;
  12423. // Flag to properly process Z_BUF_ERROR on testing inflate call
  12424. // when we check that all output data was flushed.
  12425. var allowBufError = false;
  12426. if (this.ended) { return false; }
  12427. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  12428. // Convert data if needed
  12429. if (typeof data === 'string') {
  12430. // Only binary strings can be decompressed on practice
  12431. strm.input = strings.binstring2buf(data);
  12432. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12433. strm.input = new Uint8Array(data);
  12434. } else {
  12435. strm.input = data;
  12436. }
  12437. strm.next_in = 0;
  12438. strm.avail_in = strm.input.length;
  12439. do {
  12440. if (strm.avail_out === 0) {
  12441. strm.output = new utils.Buf8(chunkSize);
  12442. strm.next_out = 0;
  12443. strm.avail_out = chunkSize;
  12444. }
  12445. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  12446. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  12447. status = c.Z_OK;
  12448. allowBufError = false;
  12449. }
  12450. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  12451. this.onEnd(status);
  12452. this.ended = true;
  12453. return false;
  12454. }
  12455. if (strm.next_out) {
  12456. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  12457. if (this.options.to === 'string') {
  12458. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  12459. tail = strm.next_out - next_out_utf8;
  12460. utf8str = strings.buf2string(strm.output, next_out_utf8);
  12461. // move tail
  12462. strm.next_out = tail;
  12463. strm.avail_out = chunkSize - tail;
  12464. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  12465. this.onData(utf8str);
  12466. } else {
  12467. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12468. }
  12469. }
  12470. }
  12471. // When no more input data, we should check that internal inflate buffers
  12472. // are flushed. The only way to do it when avail_out = 0 - run one more
  12473. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  12474. // Here we set flag to process this error properly.
  12475. //
  12476. // NOTE. Deflate does not return error in this case and does not needs such
  12477. // logic.
  12478. if (strm.avail_in === 0 && strm.avail_out === 0) {
  12479. allowBufError = true;
  12480. }
  12481. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  12482. if (status === c.Z_STREAM_END) {
  12483. _mode = c.Z_FINISH;
  12484. }
  12485. // Finalize on the last chunk.
  12486. if (_mode === c.Z_FINISH) {
  12487. status = zlib_inflate.inflateEnd(this.strm);
  12488. this.onEnd(status);
  12489. this.ended = true;
  12490. return status === c.Z_OK;
  12491. }
  12492. // callback interim results if Z_SYNC_FLUSH.
  12493. if (_mode === c.Z_SYNC_FLUSH) {
  12494. this.onEnd(c.Z_OK);
  12495. strm.avail_out = 0;
  12496. return true;
  12497. }
  12498. return true;
  12499. };
  12500. /**
  12501. * Inflate#onData(chunk) -> Void
  12502. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12503. * on js engine support. When string output requested, each chunk
  12504. * will be string.
  12505. *
  12506. * By default, stores data blocks in `chunks[]` property and glue
  12507. * those in `onEnd`. Override this handler, if you need another behaviour.
  12508. **/
  12509. Inflate.prototype.onData = function(chunk) {
  12510. this.chunks.push(chunk);
  12511. };
  12512. /**
  12513. * Inflate#onEnd(status) -> Void
  12514. * - status (Number): inflate status. 0 (Z_OK) on success,
  12515. * other if not.
  12516. *
  12517. * Called either after you tell inflate that the input stream is
  12518. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12519. * or if an error happened. By default - join collected chunks,
  12520. * free memory and fill `results` / `err` properties.
  12521. **/
  12522. Inflate.prototype.onEnd = function(status) {
  12523. // On success - join
  12524. if (status === c.Z_OK) {
  12525. if (this.options.to === 'string') {
  12526. // Glue & convert here, until we teach pako to send
  12527. // utf8 alligned strings to onData
  12528. this.result = this.chunks.join('');
  12529. } else {
  12530. this.result = utils.flattenChunks(this.chunks);
  12531. }
  12532. }
  12533. this.chunks = [];
  12534. this.err = status;
  12535. this.msg = this.strm.msg;
  12536. };
  12537. /**
  12538. * inflate(data[, options]) -> Uint8Array|Array|String
  12539. * - data (Uint8Array|Array|String): input data to decompress.
  12540. * - options (Object): zlib inflate options.
  12541. *
  12542. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  12543. * format via wrapper header by default. That's why we don't provide
  12544. * separate `ungzip` method.
  12545. *
  12546. * Supported options are:
  12547. *
  12548. * - windowBits
  12549. *
  12550. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12551. * for more information.
  12552. *
  12553. * Sugar (options):
  12554. *
  12555. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12556. * negative windowBits implicitly.
  12557. * - `to` (String) - if equal to 'string', then result will be converted
  12558. * from utf8 to utf16 (javascript) string. When string output requested,
  12559. * chunk length can differ from `chunkSize`, depending on content.
  12560. *
  12561. *
  12562. * ##### Example:
  12563. *
  12564. * ```javascript
  12565. * var pako = require('pako')
  12566. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  12567. * , output;
  12568. *
  12569. * try {
  12570. * output = pako.inflate(input);
  12571. * } catch (err)
  12572. * console.log(err);
  12573. * }
  12574. * ```
  12575. **/
  12576. function inflate(input, options) {
  12577. var inflator = new Inflate(options);
  12578. inflator.push(input, true);
  12579. // That will never happens, if you don't cheat with options :)
  12580. if (inflator.err) { throw inflator.msg; }
  12581. return inflator.result;
  12582. }
  12583. /**
  12584. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  12585. * - data (Uint8Array|Array|String): input data to decompress.
  12586. * - options (Object): zlib inflate options.
  12587. *
  12588. * The same as [[inflate]], but creates raw data, without wrapper
  12589. * (header and adler32 crc).
  12590. **/
  12591. function inflateRaw(input, options) {
  12592. options = options || {};
  12593. options.raw = true;
  12594. return inflate(input, options);
  12595. }
  12596. /**
  12597. * ungzip(data[, options]) -> Uint8Array|Array|String
  12598. * - data (Uint8Array|Array|String): input data to decompress.
  12599. * - options (Object): zlib inflate options.
  12600. *
  12601. * Just shortcut to [[inflate]], because it autodetects format
  12602. * by header.content. Done for convenience.
  12603. **/
  12604. exports.Inflate = Inflate;
  12605. exports.inflate = inflate;
  12606. exports.inflateRaw = inflateRaw;
  12607. exports.ungzip = inflate;
  12608. },{"./utils/common":48,"./utils/strings":49,"./zlib/constants":51,"./zlib/gzheader":54,"./zlib/inflate.js":56,"./zlib/messages":58,"./zlib/zstream":60}],48:[function(require,module,exports){
  12609. 'use strict';
  12610. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  12611. (typeof Uint16Array !== 'undefined') &&
  12612. (typeof Int32Array !== 'undefined');
  12613. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  12614. var sources = Array.prototype.slice.call(arguments, 1);
  12615. while (sources.length) {
  12616. var source = sources.shift();
  12617. if (!source) { continue; }
  12618. if (typeof source !== 'object') {
  12619. throw new TypeError(source + 'must be non-object');
  12620. }
  12621. for (var p in source) {
  12622. if (source.hasOwnProperty(p)) {
  12623. obj[p] = source[p];
  12624. }
  12625. }
  12626. }
  12627. return obj;
  12628. };
  12629. // reduce buffer size, avoiding mem copy
  12630. exports.shrinkBuf = function (buf, size) {
  12631. if (buf.length === size) { return buf; }
  12632. if (buf.subarray) { return buf.subarray(0, size); }
  12633. buf.length = size;
  12634. return buf;
  12635. };
  12636. var fnTyped = {
  12637. arraySet: function (dest, src, src_offs, len, dest_offs) {
  12638. if (src.subarray && dest.subarray) {
  12639. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  12640. return;
  12641. }
  12642. // Fallback to ordinary array
  12643. for (var i=0; i<len; i++) {
  12644. dest[dest_offs + i] = src[src_offs + i];
  12645. }
  12646. },
  12647. // Join array of chunks to single array.
  12648. flattenChunks: function(chunks) {
  12649. var i, l, len, pos, chunk, result;
  12650. // calculate data length
  12651. len = 0;
  12652. for (i=0, l=chunks.length; i<l; i++) {
  12653. len += chunks[i].length;
  12654. }
  12655. // join chunks
  12656. result = new Uint8Array(len);
  12657. pos = 0;
  12658. for (i=0, l=chunks.length; i<l; i++) {
  12659. chunk = chunks[i];
  12660. result.set(chunk, pos);
  12661. pos += chunk.length;
  12662. }
  12663. return result;
  12664. }
  12665. };
  12666. var fnUntyped = {
  12667. arraySet: function (dest, src, src_offs, len, dest_offs) {
  12668. for (var i=0; i<len; i++) {
  12669. dest[dest_offs + i] = src[src_offs + i];
  12670. }
  12671. },
  12672. // Join array of chunks to single array.
  12673. flattenChunks: function(chunks) {
  12674. return [].concat.apply([], chunks);
  12675. }
  12676. };
  12677. // Enable/Disable typed arrays use, for testing
  12678. //
  12679. exports.setTyped = function (on) {
  12680. if (on) {
  12681. exports.Buf8 = Uint8Array;
  12682. exports.Buf16 = Uint16Array;
  12683. exports.Buf32 = Int32Array;
  12684. exports.assign(exports, fnTyped);
  12685. } else {
  12686. exports.Buf8 = Array;
  12687. exports.Buf16 = Array;
  12688. exports.Buf32 = Array;
  12689. exports.assign(exports, fnUntyped);
  12690. }
  12691. };
  12692. exports.setTyped(TYPED_OK);
  12693. },{}],49:[function(require,module,exports){
  12694. // String encode/decode helpers
  12695. 'use strict';
  12696. var utils = require('./common');
  12697. // Quick check if we can use fast array to bin string conversion
  12698. //
  12699. // - apply(Array) can fail on Android 2.2
  12700. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  12701. //
  12702. var STR_APPLY_OK = true;
  12703. var STR_APPLY_UIA_OK = true;
  12704. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  12705. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  12706. // Table with utf8 lengths (calculated by first byte of sequence)
  12707. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  12708. // because max possible codepoint is 0x10ffff
  12709. var _utf8len = new utils.Buf8(256);
  12710. for (var q=0; q<256; q++) {
  12711. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  12712. }
  12713. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  12714. // convert string to array (typed, when possible)
  12715. exports.string2buf = function (str) {
  12716. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  12717. // count binary size
  12718. for (m_pos = 0; m_pos < str_len; m_pos++) {
  12719. c = str.charCodeAt(m_pos);
  12720. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  12721. c2 = str.charCodeAt(m_pos+1);
  12722. if ((c2 & 0xfc00) === 0xdc00) {
  12723. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  12724. m_pos++;
  12725. }
  12726. }
  12727. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  12728. }
  12729. // allocate buffer
  12730. buf = new utils.Buf8(buf_len);
  12731. // convert
  12732. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  12733. c = str.charCodeAt(m_pos);
  12734. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  12735. c2 = str.charCodeAt(m_pos+1);
  12736. if ((c2 & 0xfc00) === 0xdc00) {
  12737. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  12738. m_pos++;
  12739. }
  12740. }
  12741. if (c < 0x80) {
  12742. /* one byte */
  12743. buf[i++] = c;
  12744. } else if (c < 0x800) {
  12745. /* two bytes */
  12746. buf[i++] = 0xC0 | (c >>> 6);
  12747. buf[i++] = 0x80 | (c & 0x3f);
  12748. } else if (c < 0x10000) {
  12749. /* three bytes */
  12750. buf[i++] = 0xE0 | (c >>> 12);
  12751. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  12752. buf[i++] = 0x80 | (c & 0x3f);
  12753. } else {
  12754. /* four bytes */
  12755. buf[i++] = 0xf0 | (c >>> 18);
  12756. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  12757. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  12758. buf[i++] = 0x80 | (c & 0x3f);
  12759. }
  12760. }
  12761. return buf;
  12762. };
  12763. // Helper (used in 2 places)
  12764. function buf2binstring(buf, len) {
  12765. // use fallback for big arrays to avoid stack overflow
  12766. if (len < 65537) {
  12767. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  12768. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  12769. }
  12770. }
  12771. var result = '';
  12772. for (var i=0; i < len; i++) {
  12773. result += String.fromCharCode(buf[i]);
  12774. }
  12775. return result;
  12776. }
  12777. // Convert byte array to binary string
  12778. exports.buf2binstring = function(buf) {
  12779. return buf2binstring(buf, buf.length);
  12780. };
  12781. // Convert binary string (typed, when possible)
  12782. exports.binstring2buf = function(str) {
  12783. var buf = new utils.Buf8(str.length);
  12784. for (var i=0, len=buf.length; i < len; i++) {
  12785. buf[i] = str.charCodeAt(i);
  12786. }
  12787. return buf;
  12788. };
  12789. // convert array to string
  12790. exports.buf2string = function (buf, max) {
  12791. var i, out, c, c_len;
  12792. var len = max || buf.length;
  12793. // Reserve max possible length (2 words per char)
  12794. // NB: by unknown reasons, Array is significantly faster for
  12795. // String.fromCharCode.apply than Uint16Array.
  12796. var utf16buf = new Array(len*2);
  12797. for (out=0, i=0; i<len;) {
  12798. c = buf[i++];
  12799. // quick process ascii
  12800. if (c < 0x80) { utf16buf[out++] = c; continue; }
  12801. c_len = _utf8len[c];
  12802. // skip 5 & 6 byte codes
  12803. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  12804. // apply mask on first byte
  12805. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  12806. // join the rest
  12807. while (c_len > 1 && i < len) {
  12808. c = (c << 6) | (buf[i++] & 0x3f);
  12809. c_len--;
  12810. }
  12811. // terminated by end of string?
  12812. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  12813. if (c < 0x10000) {
  12814. utf16buf[out++] = c;
  12815. } else {
  12816. c -= 0x10000;
  12817. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  12818. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  12819. }
  12820. }
  12821. return buf2binstring(utf16buf, out);
  12822. };
  12823. // Calculate max possible position in utf8 buffer,
  12824. // that will not break sequence. If that's not possible
  12825. // - (very small limits) return max size as is.
  12826. //
  12827. // buf[] - utf8 bytes array
  12828. // max - length limit (mandatory);
  12829. exports.utf8border = function(buf, max) {
  12830. var pos;
  12831. max = max || buf.length;
  12832. if (max > buf.length) { max = buf.length; }
  12833. // go back from last position, until start of sequence found
  12834. pos = max-1;
  12835. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  12836. // Fuckup - very small and broken sequence,
  12837. // return max, because we should return something anyway.
  12838. if (pos < 0) { return max; }
  12839. // If we came to start of buffer - that means vuffer is too small,
  12840. // return max too.
  12841. if (pos === 0) { return max; }
  12842. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  12843. };
  12844. },{"./common":48}],50:[function(require,module,exports){
  12845. 'use strict';
  12846. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  12847. // It doesn't worth to make additional optimizationa as in original.
  12848. // Small size is preferable.
  12849. function adler32(adler, buf, len, pos) {
  12850. var s1 = (adler & 0xffff) |0,
  12851. s2 = ((adler >>> 16) & 0xffff) |0,
  12852. n = 0;
  12853. while (len !== 0) {
  12854. // Set limit ~ twice less than 5552, to keep
  12855. // s2 in 31-bits, because we force signed ints.
  12856. // in other case %= will fail.
  12857. n = len > 2000 ? 2000 : len;
  12858. len -= n;
  12859. do {
  12860. s1 = (s1 + buf[pos++]) |0;
  12861. s2 = (s2 + s1) |0;
  12862. } while (--n);
  12863. s1 %= 65521;
  12864. s2 %= 65521;
  12865. }
  12866. return (s1 | (s2 << 16)) |0;
  12867. }
  12868. module.exports = adler32;
  12869. },{}],51:[function(require,module,exports){
  12870. module.exports = {
  12871. /* Allowed flush values; see deflate() and inflate() below for details */
  12872. Z_NO_FLUSH: 0,
  12873. Z_PARTIAL_FLUSH: 1,
  12874. Z_SYNC_FLUSH: 2,
  12875. Z_FULL_FLUSH: 3,
  12876. Z_FINISH: 4,
  12877. Z_BLOCK: 5,
  12878. Z_TREES: 6,
  12879. /* Return codes for the compression/decompression functions. Negative values
  12880. * are errors, positive values are used for special but normal events.
  12881. */
  12882. Z_OK: 0,
  12883. Z_STREAM_END: 1,
  12884. Z_NEED_DICT: 2,
  12885. Z_ERRNO: -1,
  12886. Z_STREAM_ERROR: -2,
  12887. Z_DATA_ERROR: -3,
  12888. //Z_MEM_ERROR: -4,
  12889. Z_BUF_ERROR: -5,
  12890. //Z_VERSION_ERROR: -6,
  12891. /* compression levels */
  12892. Z_NO_COMPRESSION: 0,
  12893. Z_BEST_SPEED: 1,
  12894. Z_BEST_COMPRESSION: 9,
  12895. Z_DEFAULT_COMPRESSION: -1,
  12896. Z_FILTERED: 1,
  12897. Z_HUFFMAN_ONLY: 2,
  12898. Z_RLE: 3,
  12899. Z_FIXED: 4,
  12900. Z_DEFAULT_STRATEGY: 0,
  12901. /* Possible values of the data_type field (though see inflate()) */
  12902. Z_BINARY: 0,
  12903. Z_TEXT: 1,
  12904. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  12905. Z_UNKNOWN: 2,
  12906. /* The deflate compression method */
  12907. Z_DEFLATED: 8
  12908. //Z_NULL: null // Use -1 or null inline, depending on var type
  12909. };
  12910. },{}],52:[function(require,module,exports){
  12911. 'use strict';
  12912. // Note: we can't get significant speed boost here.
  12913. // So write code to minimize size - no pregenerated tables
  12914. // and array tools dependencies.
  12915. // Use ordinary array, since untyped makes no boost here
  12916. function makeTable() {
  12917. var c, table = [];
  12918. for (var n =0; n < 256; n++) {
  12919. c = n;
  12920. for (var k =0; k < 8; k++) {
  12921. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  12922. }
  12923. table[n] = c;
  12924. }
  12925. return table;
  12926. }
  12927. // Create table on load. Just 255 signed longs. Not a problem.
  12928. var crcTable = makeTable();
  12929. function crc32(crc, buf, len, pos) {
  12930. var t = crcTable,
  12931. end = pos + len;
  12932. crc = crc ^ (-1);
  12933. for (var i = pos; i < end; i++) {
  12934. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  12935. }
  12936. return (crc ^ (-1)); // >>> 0;
  12937. }
  12938. module.exports = crc32;
  12939. },{}],53:[function(require,module,exports){
  12940. 'use strict';
  12941. var utils = require('../utils/common');
  12942. var trees = require('./trees');
  12943. var adler32 = require('./adler32');
  12944. var crc32 = require('./crc32');
  12945. var msg = require('./messages');
  12946. /* Public constants ==========================================================*/
  12947. /* ===========================================================================*/
  12948. /* Allowed flush values; see deflate() and inflate() below for details */
  12949. var Z_NO_FLUSH = 0;
  12950. var Z_PARTIAL_FLUSH = 1;
  12951. //var Z_SYNC_FLUSH = 2;
  12952. var Z_FULL_FLUSH = 3;
  12953. var Z_FINISH = 4;
  12954. var Z_BLOCK = 5;
  12955. //var Z_TREES = 6;
  12956. /* Return codes for the compression/decompression functions. Negative values
  12957. * are errors, positive values are used for special but normal events.
  12958. */
  12959. var Z_OK = 0;
  12960. var Z_STREAM_END = 1;
  12961. //var Z_NEED_DICT = 2;
  12962. //var Z_ERRNO = -1;
  12963. var Z_STREAM_ERROR = -2;
  12964. var Z_DATA_ERROR = -3;
  12965. //var Z_MEM_ERROR = -4;
  12966. var Z_BUF_ERROR = -5;
  12967. //var Z_VERSION_ERROR = -6;
  12968. /* compression levels */
  12969. //var Z_NO_COMPRESSION = 0;
  12970. //var Z_BEST_SPEED = 1;
  12971. //var Z_BEST_COMPRESSION = 9;
  12972. var Z_DEFAULT_COMPRESSION = -1;
  12973. var Z_FILTERED = 1;
  12974. var Z_HUFFMAN_ONLY = 2;
  12975. var Z_RLE = 3;
  12976. var Z_FIXED = 4;
  12977. var Z_DEFAULT_STRATEGY = 0;
  12978. /* Possible values of the data_type field (though see inflate()) */
  12979. //var Z_BINARY = 0;
  12980. //var Z_TEXT = 1;
  12981. //var Z_ASCII = 1; // = Z_TEXT
  12982. var Z_UNKNOWN = 2;
  12983. /* The deflate compression method */
  12984. var Z_DEFLATED = 8;
  12985. /*============================================================================*/
  12986. var MAX_MEM_LEVEL = 9;
  12987. /* Maximum value for memLevel in deflateInit2 */
  12988. var MAX_WBITS = 15;
  12989. /* 32K LZ77 window */
  12990. var DEF_MEM_LEVEL = 8;
  12991. var LENGTH_CODES = 29;
  12992. /* number of length codes, not counting the special END_BLOCK code */
  12993. var LITERALS = 256;
  12994. /* number of literal bytes 0..255 */
  12995. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  12996. /* number of Literal or Length codes, including the END_BLOCK code */
  12997. var D_CODES = 30;
  12998. /* number of distance codes */
  12999. var BL_CODES = 19;
  13000. /* number of codes used to transfer the bit lengths */
  13001. var HEAP_SIZE = 2*L_CODES + 1;
  13002. /* maximum heap size */
  13003. var MAX_BITS = 15;
  13004. /* All codes must not exceed MAX_BITS bits */
  13005. var MIN_MATCH = 3;
  13006. var MAX_MATCH = 258;
  13007. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13008. var PRESET_DICT = 0x20;
  13009. var INIT_STATE = 42;
  13010. var EXTRA_STATE = 69;
  13011. var NAME_STATE = 73;
  13012. var COMMENT_STATE = 91;
  13013. var HCRC_STATE = 103;
  13014. var BUSY_STATE = 113;
  13015. var FINISH_STATE = 666;
  13016. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13017. var BS_BLOCK_DONE = 2; /* block flush performed */
  13018. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13019. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13020. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13021. function err(strm, errorCode) {
  13022. strm.msg = msg[errorCode];
  13023. return errorCode;
  13024. }
  13025. function rank(f) {
  13026. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13027. }
  13028. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13029. /* =========================================================================
  13030. * Flush as much pending output as possible. All deflate() output goes
  13031. * through this function so some applications may wish to modify it
  13032. * to avoid allocating a large strm->output buffer and copying into it.
  13033. * (See also read_buf()).
  13034. */
  13035. function flush_pending(strm) {
  13036. var s = strm.state;
  13037. //_tr_flush_bits(s);
  13038. var len = s.pending;
  13039. if (len > strm.avail_out) {
  13040. len = strm.avail_out;
  13041. }
  13042. if (len === 0) { return; }
  13043. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13044. strm.next_out += len;
  13045. s.pending_out += len;
  13046. strm.total_out += len;
  13047. strm.avail_out -= len;
  13048. s.pending -= len;
  13049. if (s.pending === 0) {
  13050. s.pending_out = 0;
  13051. }
  13052. }
  13053. function flush_block_only (s, last) {
  13054. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13055. s.block_start = s.strstart;
  13056. flush_pending(s.strm);
  13057. }
  13058. function put_byte(s, b) {
  13059. s.pending_buf[s.pending++] = b;
  13060. }
  13061. /* =========================================================================
  13062. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13063. * IN assertion: the stream state is correct and there is enough room in
  13064. * pending_buf.
  13065. */
  13066. function putShortMSB(s, b) {
  13067. // put_byte(s, (Byte)(b >> 8));
  13068. // put_byte(s, (Byte)(b & 0xff));
  13069. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13070. s.pending_buf[s.pending++] = b & 0xff;
  13071. }
  13072. /* ===========================================================================
  13073. * Read a new buffer from the current input stream, update the adler32
  13074. * and total number of bytes read. All deflate() input goes through
  13075. * this function so some applications may wish to modify it to avoid
  13076. * allocating a large strm->input buffer and copying from it.
  13077. * (See also flush_pending()).
  13078. */
  13079. function read_buf(strm, buf, start, size) {
  13080. var len = strm.avail_in;
  13081. if (len > size) { len = size; }
  13082. if (len === 0) { return 0; }
  13083. strm.avail_in -= len;
  13084. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13085. if (strm.state.wrap === 1) {
  13086. strm.adler = adler32(strm.adler, buf, len, start);
  13087. }
  13088. else if (strm.state.wrap === 2) {
  13089. strm.adler = crc32(strm.adler, buf, len, start);
  13090. }
  13091. strm.next_in += len;
  13092. strm.total_in += len;
  13093. return len;
  13094. }
  13095. /* ===========================================================================
  13096. * Set match_start to the longest match starting at the given string and
  13097. * return its length. Matches shorter or equal to prev_length are discarded,
  13098. * in which case the result is equal to prev_length and match_start is
  13099. * garbage.
  13100. * IN assertions: cur_match is the head of the hash chain for the current
  13101. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13102. * OUT assertion: the match length is not greater than s->lookahead.
  13103. */
  13104. function longest_match(s, cur_match) {
  13105. var chain_length = s.max_chain_length; /* max hash chain length */
  13106. var scan = s.strstart; /* current string */
  13107. var match; /* matched string */
  13108. var len; /* length of current match */
  13109. var best_len = s.prev_length; /* best match length so far */
  13110. var nice_match = s.nice_match; /* stop if match long enough */
  13111. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  13112. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  13113. var _win = s.window; // shortcut
  13114. var wmask = s.w_mask;
  13115. var prev = s.prev;
  13116. /* Stop when cur_match becomes <= limit. To simplify the code,
  13117. * we prevent matches with the string of window index 0.
  13118. */
  13119. var strend = s.strstart + MAX_MATCH;
  13120. var scan_end1 = _win[scan + best_len - 1];
  13121. var scan_end = _win[scan + best_len];
  13122. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  13123. * It is easy to get rid of this optimization if necessary.
  13124. */
  13125. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  13126. /* Do not waste too much time if we already have a good match: */
  13127. if (s.prev_length >= s.good_match) {
  13128. chain_length >>= 2;
  13129. }
  13130. /* Do not look for matches beyond the end of the input. This is necessary
  13131. * to make deflate deterministic.
  13132. */
  13133. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  13134. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  13135. do {
  13136. // Assert(cur_match < s->strstart, "no future");
  13137. match = cur_match;
  13138. /* Skip to next match if the match length cannot increase
  13139. * or if the match length is less than 2. Note that the checks below
  13140. * for insufficient lookahead only occur occasionally for performance
  13141. * reasons. Therefore uninitialized memory will be accessed, and
  13142. * conditional jumps will be made that depend on those values.
  13143. * However the length of the match is limited to the lookahead, so
  13144. * the output of deflate is not affected by the uninitialized values.
  13145. */
  13146. if (_win[match + best_len] !== scan_end ||
  13147. _win[match + best_len - 1] !== scan_end1 ||
  13148. _win[match] !== _win[scan] ||
  13149. _win[++match] !== _win[scan + 1]) {
  13150. continue;
  13151. }
  13152. /* The check at best_len-1 can be removed because it will be made
  13153. * again later. (This heuristic is not always a win.)
  13154. * It is not necessary to compare scan[2] and match[2] since they
  13155. * are always equal when the other bytes match, given that
  13156. * the hash keys are equal and that HASH_BITS >= 8.
  13157. */
  13158. scan += 2;
  13159. match++;
  13160. // Assert(*scan == *match, "match[2]?");
  13161. /* We check for insufficient lookahead only every 8th comparison;
  13162. * the 256th check will be made at strstart+258.
  13163. */
  13164. do {
  13165. /*jshint noempty:false*/
  13166. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13167. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13168. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13169. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13170. scan < strend);
  13171. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  13172. len = MAX_MATCH - (strend - scan);
  13173. scan = strend - MAX_MATCH;
  13174. if (len > best_len) {
  13175. s.match_start = cur_match;
  13176. best_len = len;
  13177. if (len >= nice_match) {
  13178. break;
  13179. }
  13180. scan_end1 = _win[scan + best_len - 1];
  13181. scan_end = _win[scan + best_len];
  13182. }
  13183. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  13184. if (best_len <= s.lookahead) {
  13185. return best_len;
  13186. }
  13187. return s.lookahead;
  13188. }
  13189. /* ===========================================================================
  13190. * Fill the window when the lookahead becomes insufficient.
  13191. * Updates strstart and lookahead.
  13192. *
  13193. * IN assertion: lookahead < MIN_LOOKAHEAD
  13194. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  13195. * At least one byte has been read, or avail_in == 0; reads are
  13196. * performed for at least two bytes (required for the zip translate_eol
  13197. * option -- not supported here).
  13198. */
  13199. function fill_window(s) {
  13200. var _w_size = s.w_size;
  13201. var p, n, m, more, str;
  13202. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  13203. do {
  13204. more = s.window_size - s.lookahead - s.strstart;
  13205. // JS ints have 32 bit, block below not needed
  13206. /* Deal with !@#$% 64K limit: */
  13207. //if (sizeof(int) <= 2) {
  13208. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  13209. // more = wsize;
  13210. //
  13211. // } else if (more == (unsigned)(-1)) {
  13212. // /* Very unlikely, but possible on 16 bit machine if
  13213. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  13214. // */
  13215. // more--;
  13216. // }
  13217. //}
  13218. /* If the window is almost full and there is insufficient lookahead,
  13219. * move the upper half to the lower one to make room in the upper half.
  13220. */
  13221. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  13222. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  13223. s.match_start -= _w_size;
  13224. s.strstart -= _w_size;
  13225. /* we now have strstart >= MAX_DIST */
  13226. s.block_start -= _w_size;
  13227. /* Slide the hash table (could be avoided with 32 bit values
  13228. at the expense of memory usage). We slide even when level == 0
  13229. to keep the hash table consistent if we switch back to level > 0
  13230. later. (Using level 0 permanently is not an optimal usage of
  13231. zlib, so we don't care about this pathological case.)
  13232. */
  13233. n = s.hash_size;
  13234. p = n;
  13235. do {
  13236. m = s.head[--p];
  13237. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  13238. } while (--n);
  13239. n = _w_size;
  13240. p = n;
  13241. do {
  13242. m = s.prev[--p];
  13243. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  13244. /* If n is not on any hash chain, prev[n] is garbage but
  13245. * its value will never be used.
  13246. */
  13247. } while (--n);
  13248. more += _w_size;
  13249. }
  13250. if (s.strm.avail_in === 0) {
  13251. break;
  13252. }
  13253. /* If there was no sliding:
  13254. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  13255. * more == window_size - lookahead - strstart
  13256. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  13257. * => more >= window_size - 2*WSIZE + 2
  13258. * In the BIG_MEM or MMAP case (not yet supported),
  13259. * window_size == input_size + MIN_LOOKAHEAD &&
  13260. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  13261. * Otherwise, window_size == 2*WSIZE so more >= 2.
  13262. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  13263. */
  13264. //Assert(more >= 2, "more < 2");
  13265. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  13266. s.lookahead += n;
  13267. /* Initialize the hash value now that we have some input: */
  13268. if (s.lookahead + s.insert >= MIN_MATCH) {
  13269. str = s.strstart - s.insert;
  13270. s.ins_h = s.window[str];
  13271. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  13272. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  13273. //#if MIN_MATCH != 3
  13274. // Call update_hash() MIN_MATCH-3 more times
  13275. //#endif
  13276. while (s.insert) {
  13277. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  13278. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  13279. s.prev[str & s.w_mask] = s.head[s.ins_h];
  13280. s.head[s.ins_h] = str;
  13281. str++;
  13282. s.insert--;
  13283. if (s.lookahead + s.insert < MIN_MATCH) {
  13284. break;
  13285. }
  13286. }
  13287. }
  13288. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  13289. * but this is not important since only literal bytes will be emitted.
  13290. */
  13291. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  13292. /* If the WIN_INIT bytes after the end of the current data have never been
  13293. * written, then zero those bytes in order to avoid memory check reports of
  13294. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  13295. * the longest match routines. Update the high water mark for the next
  13296. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  13297. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  13298. */
  13299. // if (s.high_water < s.window_size) {
  13300. // var curr = s.strstart + s.lookahead;
  13301. // var init = 0;
  13302. //
  13303. // if (s.high_water < curr) {
  13304. // /* Previous high water mark below current data -- zero WIN_INIT
  13305. // * bytes or up to end of window, whichever is less.
  13306. // */
  13307. // init = s.window_size - curr;
  13308. // if (init > WIN_INIT)
  13309. // init = WIN_INIT;
  13310. // zmemzero(s->window + curr, (unsigned)init);
  13311. // s->high_water = curr + init;
  13312. // }
  13313. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  13314. // /* High water mark at or above current data, but below current data
  13315. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  13316. // * to end of window, whichever is less.
  13317. // */
  13318. // init = (ulg)curr + WIN_INIT - s->high_water;
  13319. // if (init > s->window_size - s->high_water)
  13320. // init = s->window_size - s->high_water;
  13321. // zmemzero(s->window + s->high_water, (unsigned)init);
  13322. // s->high_water += init;
  13323. // }
  13324. // }
  13325. //
  13326. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  13327. // "not enough room for search");
  13328. }
  13329. /* ===========================================================================
  13330. * Copy without compression as much as possible from the input stream, return
  13331. * the current block state.
  13332. * This function does not insert new strings in the dictionary since
  13333. * uncompressible data is probably not useful. This function is used
  13334. * only for the level=0 compression option.
  13335. * NOTE: this function should be optimized to avoid extra copying from
  13336. * window to pending_buf.
  13337. */
  13338. function deflate_stored(s, flush) {
  13339. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  13340. * to pending_buf_size, and each stored block has a 5 byte header:
  13341. */
  13342. var max_block_size = 0xffff;
  13343. if (max_block_size > s.pending_buf_size - 5) {
  13344. max_block_size = s.pending_buf_size - 5;
  13345. }
  13346. /* Copy as much as possible from input to output: */
  13347. for (;;) {
  13348. /* Fill the window as much as possible: */
  13349. if (s.lookahead <= 1) {
  13350. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  13351. // s->block_start >= (long)s->w_size, "slide too late");
  13352. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  13353. // s.block_start >= s.w_size)) {
  13354. // throw new Error("slide too late");
  13355. // }
  13356. fill_window(s);
  13357. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  13358. return BS_NEED_MORE;
  13359. }
  13360. if (s.lookahead === 0) {
  13361. break;
  13362. }
  13363. /* flush the current block */
  13364. }
  13365. //Assert(s->block_start >= 0L, "block gone");
  13366. // if (s.block_start < 0) throw new Error("block gone");
  13367. s.strstart += s.lookahead;
  13368. s.lookahead = 0;
  13369. /* Emit a stored block if pending_buf will be full: */
  13370. var max_start = s.block_start + max_block_size;
  13371. if (s.strstart === 0 || s.strstart >= max_start) {
  13372. /* strstart == 0 is possible when wraparound on 16-bit machine */
  13373. s.lookahead = s.strstart - max_start;
  13374. s.strstart = max_start;
  13375. /*** FLUSH_BLOCK(s, 0); ***/
  13376. flush_block_only(s, false);
  13377. if (s.strm.avail_out === 0) {
  13378. return BS_NEED_MORE;
  13379. }
  13380. /***/
  13381. }
  13382. /* Flush if we may have to slide, otherwise block_start may become
  13383. * negative and the data will be gone:
  13384. */
  13385. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  13386. /*** FLUSH_BLOCK(s, 0); ***/
  13387. flush_block_only(s, false);
  13388. if (s.strm.avail_out === 0) {
  13389. return BS_NEED_MORE;
  13390. }
  13391. /***/
  13392. }
  13393. }
  13394. s.insert = 0;
  13395. if (flush === Z_FINISH) {
  13396. /*** FLUSH_BLOCK(s, 1); ***/
  13397. flush_block_only(s, true);
  13398. if (s.strm.avail_out === 0) {
  13399. return BS_FINISH_STARTED;
  13400. }
  13401. /***/
  13402. return BS_FINISH_DONE;
  13403. }
  13404. if (s.strstart > s.block_start) {
  13405. /*** FLUSH_BLOCK(s, 0); ***/
  13406. flush_block_only(s, false);
  13407. if (s.strm.avail_out === 0) {
  13408. return BS_NEED_MORE;
  13409. }
  13410. /***/
  13411. }
  13412. return BS_NEED_MORE;
  13413. }
  13414. /* ===========================================================================
  13415. * Compress as much as possible from the input stream, return the current
  13416. * block state.
  13417. * This function does not perform lazy evaluation of matches and inserts
  13418. * new strings in the dictionary only for unmatched strings or for short
  13419. * matches. It is used only for the fast compression options.
  13420. */
  13421. function deflate_fast(s, flush) {
  13422. var hash_head; /* head of the hash chain */
  13423. var bflush; /* set if current block must be flushed */
  13424. for (;;) {
  13425. /* Make sure that we always have enough lookahead, except
  13426. * at the end of the input file. We need MAX_MATCH bytes
  13427. * for the next match, plus MIN_MATCH bytes to insert the
  13428. * string following the next match.
  13429. */
  13430. if (s.lookahead < MIN_LOOKAHEAD) {
  13431. fill_window(s);
  13432. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  13433. return BS_NEED_MORE;
  13434. }
  13435. if (s.lookahead === 0) {
  13436. break; /* flush the current block */
  13437. }
  13438. }
  13439. /* Insert the string window[strstart .. strstart+2] in the
  13440. * dictionary, and set hash_head to the head of the hash chain:
  13441. */
  13442. hash_head = 0/*NIL*/;
  13443. if (s.lookahead >= MIN_MATCH) {
  13444. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13445. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13446. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13447. s.head[s.ins_h] = s.strstart;
  13448. /***/
  13449. }
  13450. /* Find the longest match, discarding those <= prev_length.
  13451. * At this point we have always match_length < MIN_MATCH
  13452. */
  13453. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  13454. /* To simplify the code, we prevent matches with the string
  13455. * of window index 0 (in particular we have to avoid a match
  13456. * of the string with itself at the start of the input file).
  13457. */
  13458. s.match_length = longest_match(s, hash_head);
  13459. /* longest_match() sets match_start */
  13460. }
  13461. if (s.match_length >= MIN_MATCH) {
  13462. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  13463. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  13464. s.match_length - MIN_MATCH, bflush); ***/
  13465. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  13466. s.lookahead -= s.match_length;
  13467. /* Insert new strings in the hash table only if the match length
  13468. * is not too large. This saves time but degrades compression.
  13469. */
  13470. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  13471. s.match_length--; /* string at strstart already in table */
  13472. do {
  13473. s.strstart++;
  13474. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13475. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13476. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13477. s.head[s.ins_h] = s.strstart;
  13478. /***/
  13479. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  13480. * always MIN_MATCH bytes ahead.
  13481. */
  13482. } while (--s.match_length !== 0);
  13483. s.strstart++;
  13484. } else
  13485. {
  13486. s.strstart += s.match_length;
  13487. s.match_length = 0;
  13488. s.ins_h = s.window[s.strstart];
  13489. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  13490. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  13491. //#if MIN_MATCH != 3
  13492. // Call UPDATE_HASH() MIN_MATCH-3 more times
  13493. //#endif
  13494. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  13495. * matter since it will be recomputed at next deflate call.
  13496. */
  13497. }
  13498. } else {
  13499. /* No match, output a literal byte */
  13500. //Tracevv((stderr,"%c", s.window[s.strstart]));
  13501. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  13502. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  13503. s.lookahead--;
  13504. s.strstart++;
  13505. }
  13506. if (bflush) {
  13507. /*** FLUSH_BLOCK(s, 0); ***/
  13508. flush_block_only(s, false);
  13509. if (s.strm.avail_out === 0) {
  13510. return BS_NEED_MORE;
  13511. }
  13512. /***/
  13513. }
  13514. }
  13515. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  13516. if (flush === Z_FINISH) {
  13517. /*** FLUSH_BLOCK(s, 1); ***/
  13518. flush_block_only(s, true);
  13519. if (s.strm.avail_out === 0) {
  13520. return BS_FINISH_STARTED;
  13521. }
  13522. /***/
  13523. return BS_FINISH_DONE;
  13524. }
  13525. if (s.last_lit) {
  13526. /*** FLUSH_BLOCK(s, 0); ***/
  13527. flush_block_only(s, false);
  13528. if (s.strm.avail_out === 0) {
  13529. return BS_NEED_MORE;
  13530. }
  13531. /***/
  13532. }
  13533. return BS_BLOCK_DONE;
  13534. }
  13535. /* ===========================================================================
  13536. * Same as above, but achieves better compression. We use a lazy
  13537. * evaluation for matches: a match is finally adopted only if there is
  13538. * no better match at the next window position.
  13539. */
  13540. function deflate_slow(s, flush) {
  13541. var hash_head; /* head of hash chain */
  13542. var bflush; /* set if current block must be flushed */
  13543. var max_insert;
  13544. /* Process the input block. */
  13545. for (;;) {
  13546. /* Make sure that we always have enough lookahead, except
  13547. * at the end of the input file. We need MAX_MATCH bytes
  13548. * for the next match, plus MIN_MATCH bytes to insert the
  13549. * string following the next match.
  13550. */
  13551. if (s.lookahead < MIN_LOOKAHEAD) {
  13552. fill_window(s);
  13553. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  13554. return BS_NEED_MORE;
  13555. }
  13556. if (s.lookahead === 0) { break; } /* flush the current block */
  13557. }
  13558. /* Insert the string window[strstart .. strstart+2] in the
  13559. * dictionary, and set hash_head to the head of the hash chain:
  13560. */
  13561. hash_head = 0/*NIL*/;
  13562. if (s.lookahead >= MIN_MATCH) {
  13563. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13564. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13565. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13566. s.head[s.ins_h] = s.strstart;
  13567. /***/
  13568. }
  13569. /* Find the longest match, discarding those <= prev_length.
  13570. */
  13571. s.prev_length = s.match_length;
  13572. s.prev_match = s.match_start;
  13573. s.match_length = MIN_MATCH-1;
  13574. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  13575. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  13576. /* To simplify the code, we prevent matches with the string
  13577. * of window index 0 (in particular we have to avoid a match
  13578. * of the string with itself at the start of the input file).
  13579. */
  13580. s.match_length = longest_match(s, hash_head);
  13581. /* longest_match() sets match_start */
  13582. if (s.match_length <= 5 &&
  13583. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  13584. /* If prev_match is also MIN_MATCH, match_start is garbage
  13585. * but we will ignore the current match anyway.
  13586. */
  13587. s.match_length = MIN_MATCH-1;
  13588. }
  13589. }
  13590. /* If there was a match at the previous step and the current
  13591. * match is not better, output the previous match:
  13592. */
  13593. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  13594. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  13595. /* Do not insert strings in hash table beyond this. */
  13596. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  13597. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  13598. s.prev_length - MIN_MATCH, bflush);***/
  13599. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  13600. /* Insert in hash table all strings up to the end of the match.
  13601. * strstart-1 and strstart are already inserted. If there is not
  13602. * enough lookahead, the last two strings are not inserted in
  13603. * the hash table.
  13604. */
  13605. s.lookahead -= s.prev_length-1;
  13606. s.prev_length -= 2;
  13607. do {
  13608. if (++s.strstart <= max_insert) {
  13609. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13610. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13611. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13612. s.head[s.ins_h] = s.strstart;
  13613. /***/
  13614. }
  13615. } while (--s.prev_length !== 0);
  13616. s.match_available = 0;
  13617. s.match_length = MIN_MATCH-1;
  13618. s.strstart++;
  13619. if (bflush) {
  13620. /*** FLUSH_BLOCK(s, 0); ***/
  13621. flush_block_only(s, false);
  13622. if (s.strm.avail_out === 0) {
  13623. return BS_NEED_MORE;
  13624. }
  13625. /***/
  13626. }
  13627. } else if (s.match_available) {
  13628. /* If there was no match at the previous position, output a
  13629. * single literal. If there was a match but the current match
  13630. * is longer, truncate the previous match to a single literal.
  13631. */
  13632. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  13633. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  13634. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  13635. if (bflush) {
  13636. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  13637. flush_block_only(s, false);
  13638. /***/
  13639. }
  13640. s.strstart++;
  13641. s.lookahead--;
  13642. if (s.strm.avail_out === 0) {
  13643. return BS_NEED_MORE;
  13644. }
  13645. } else {
  13646. /* There is no previous match to compare with, wait for
  13647. * the next step to decide.
  13648. */
  13649. s.match_available = 1;
  13650. s.strstart++;
  13651. s.lookahead--;
  13652. }
  13653. }
  13654. //Assert (flush != Z_NO_FLUSH, "no flush?");
  13655. if (s.match_available) {
  13656. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  13657. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  13658. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  13659. s.match_available = 0;
  13660. }
  13661. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  13662. if (flush === Z_FINISH) {
  13663. /*** FLUSH_BLOCK(s, 1); ***/
  13664. flush_block_only(s, true);
  13665. if (s.strm.avail_out === 0) {
  13666. return BS_FINISH_STARTED;
  13667. }
  13668. /***/
  13669. return BS_FINISH_DONE;
  13670. }
  13671. if (s.last_lit) {
  13672. /*** FLUSH_BLOCK(s, 0); ***/
  13673. flush_block_only(s, false);
  13674. if (s.strm.avail_out === 0) {
  13675. return BS_NEED_MORE;
  13676. }
  13677. /***/
  13678. }
  13679. return BS_BLOCK_DONE;
  13680. }
  13681. /* ===========================================================================
  13682. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  13683. * one. Do not maintain a hash table. (It will be regenerated if this run of
  13684. * deflate switches away from Z_RLE.)
  13685. */
  13686. function deflate_rle(s, flush) {
  13687. var bflush; /* set if current block must be flushed */
  13688. var prev; /* byte at distance one to match */
  13689. var scan, strend; /* scan goes up to strend for length of run */
  13690. var _win = s.window;
  13691. for (;;) {
  13692. /* Make sure that we always have enough lookahead, except
  13693. * at the end of the input file. We need MAX_MATCH bytes
  13694. * for the longest run, plus one for the unrolled loop.
  13695. */
  13696. if (s.lookahead <= MAX_MATCH) {
  13697. fill_window(s);
  13698. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  13699. return BS_NEED_MORE;
  13700. }
  13701. if (s.lookahead === 0) { break; } /* flush the current block */
  13702. }
  13703. /* See how many times the previous byte repeats */
  13704. s.match_length = 0;
  13705. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  13706. scan = s.strstart - 1;
  13707. prev = _win[scan];
  13708. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  13709. strend = s.strstart + MAX_MATCH;
  13710. do {
  13711. /*jshint noempty:false*/
  13712. } while (prev === _win[++scan] && prev === _win[++scan] &&
  13713. prev === _win[++scan] && prev === _win[++scan] &&
  13714. prev === _win[++scan] && prev === _win[++scan] &&
  13715. prev === _win[++scan] && prev === _win[++scan] &&
  13716. scan < strend);
  13717. s.match_length = MAX_MATCH - (strend - scan);
  13718. if (s.match_length > s.lookahead) {
  13719. s.match_length = s.lookahead;
  13720. }
  13721. }
  13722. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  13723. }
  13724. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  13725. if (s.match_length >= MIN_MATCH) {
  13726. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  13727. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  13728. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  13729. s.lookahead -= s.match_length;
  13730. s.strstart += s.match_length;
  13731. s.match_length = 0;
  13732. } else {
  13733. /* No match, output a literal byte */
  13734. //Tracevv((stderr,"%c", s->window[s->strstart]));
  13735. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  13736. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  13737. s.lookahead--;
  13738. s.strstart++;
  13739. }
  13740. if (bflush) {
  13741. /*** FLUSH_BLOCK(s, 0); ***/
  13742. flush_block_only(s, false);
  13743. if (s.strm.avail_out === 0) {
  13744. return BS_NEED_MORE;
  13745. }
  13746. /***/
  13747. }
  13748. }
  13749. s.insert = 0;
  13750. if (flush === Z_FINISH) {
  13751. /*** FLUSH_BLOCK(s, 1); ***/
  13752. flush_block_only(s, true);
  13753. if (s.strm.avail_out === 0) {
  13754. return BS_FINISH_STARTED;
  13755. }
  13756. /***/
  13757. return BS_FINISH_DONE;
  13758. }
  13759. if (s.last_lit) {
  13760. /*** FLUSH_BLOCK(s, 0); ***/
  13761. flush_block_only(s, false);
  13762. if (s.strm.avail_out === 0) {
  13763. return BS_NEED_MORE;
  13764. }
  13765. /***/
  13766. }
  13767. return BS_BLOCK_DONE;
  13768. }
  13769. /* ===========================================================================
  13770. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  13771. * (It will be regenerated if this run of deflate switches away from Huffman.)
  13772. */
  13773. function deflate_huff(s, flush) {
  13774. var bflush; /* set if current block must be flushed */
  13775. for (;;) {
  13776. /* Make sure that we have a literal to write. */
  13777. if (s.lookahead === 0) {
  13778. fill_window(s);
  13779. if (s.lookahead === 0) {
  13780. if (flush === Z_NO_FLUSH) {
  13781. return BS_NEED_MORE;
  13782. }
  13783. break; /* flush the current block */
  13784. }
  13785. }
  13786. /* Output a literal byte */
  13787. s.match_length = 0;
  13788. //Tracevv((stderr,"%c", s->window[s->strstart]));
  13789. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  13790. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  13791. s.lookahead--;
  13792. s.strstart++;
  13793. if (bflush) {
  13794. /*** FLUSH_BLOCK(s, 0); ***/
  13795. flush_block_only(s, false);
  13796. if (s.strm.avail_out === 0) {
  13797. return BS_NEED_MORE;
  13798. }
  13799. /***/
  13800. }
  13801. }
  13802. s.insert = 0;
  13803. if (flush === Z_FINISH) {
  13804. /*** FLUSH_BLOCK(s, 1); ***/
  13805. flush_block_only(s, true);
  13806. if (s.strm.avail_out === 0) {
  13807. return BS_FINISH_STARTED;
  13808. }
  13809. /***/
  13810. return BS_FINISH_DONE;
  13811. }
  13812. if (s.last_lit) {
  13813. /*** FLUSH_BLOCK(s, 0); ***/
  13814. flush_block_only(s, false);
  13815. if (s.strm.avail_out === 0) {
  13816. return BS_NEED_MORE;
  13817. }
  13818. /***/
  13819. }
  13820. return BS_BLOCK_DONE;
  13821. }
  13822. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  13823. * the desired pack level (0..9). The values given below have been tuned to
  13824. * exclude worst case performance for pathological files. Better values may be
  13825. * found for specific files.
  13826. */
  13827. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  13828. this.good_length = good_length;
  13829. this.max_lazy = max_lazy;
  13830. this.nice_length = nice_length;
  13831. this.max_chain = max_chain;
  13832. this.func = func;
  13833. };
  13834. var configuration_table;
  13835. configuration_table = [
  13836. /* good lazy nice chain */
  13837. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  13838. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  13839. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  13840. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  13841. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  13842. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  13843. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  13844. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  13845. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  13846. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  13847. ];
  13848. /* ===========================================================================
  13849. * Initialize the "longest match" routines for a new zlib stream
  13850. */
  13851. function lm_init(s) {
  13852. s.window_size = 2 * s.w_size;
  13853. /*** CLEAR_HASH(s); ***/
  13854. zero(s.head); // Fill with NIL (= 0);
  13855. /* Set the default configuration parameters:
  13856. */
  13857. s.max_lazy_match = configuration_table[s.level].max_lazy;
  13858. s.good_match = configuration_table[s.level].good_length;
  13859. s.nice_match = configuration_table[s.level].nice_length;
  13860. s.max_chain_length = configuration_table[s.level].max_chain;
  13861. s.strstart = 0;
  13862. s.block_start = 0;
  13863. s.lookahead = 0;
  13864. s.insert = 0;
  13865. s.match_length = s.prev_length = MIN_MATCH - 1;
  13866. s.match_available = 0;
  13867. s.ins_h = 0;
  13868. }
  13869. function DeflateState() {
  13870. this.strm = null; /* pointer back to this zlib stream */
  13871. this.status = 0; /* as the name implies */
  13872. this.pending_buf = null; /* output still pending */
  13873. this.pending_buf_size = 0; /* size of pending_buf */
  13874. this.pending_out = 0; /* next pending byte to output to the stream */
  13875. this.pending = 0; /* nb of bytes in the pending buffer */
  13876. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  13877. this.gzhead = null; /* gzip header information to write */
  13878. this.gzindex = 0; /* where in extra, name, or comment */
  13879. this.method = Z_DEFLATED; /* can only be DEFLATED */
  13880. this.last_flush = -1; /* value of flush param for previous deflate call */
  13881. this.w_size = 0; /* LZ77 window size (32K by default) */
  13882. this.w_bits = 0; /* log2(w_size) (8..16) */
  13883. this.w_mask = 0; /* w_size - 1 */
  13884. this.window = null;
  13885. /* Sliding window. Input bytes are read into the second half of the window,
  13886. * and move to the first half later to keep a dictionary of at least wSize
  13887. * bytes. With this organization, matches are limited to a distance of
  13888. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  13889. * performed with a length multiple of the block size.
  13890. */
  13891. this.window_size = 0;
  13892. /* Actual size of window: 2*wSize, except when the user input buffer
  13893. * is directly used as sliding window.
  13894. */
  13895. this.prev = null;
  13896. /* Link to older string with same hash index. To limit the size of this
  13897. * array to 64K, this link is maintained only for the last 32K strings.
  13898. * An index in this array is thus a window index modulo 32K.
  13899. */
  13900. this.head = null; /* Heads of the hash chains or NIL. */
  13901. this.ins_h = 0; /* hash index of string to be inserted */
  13902. this.hash_size = 0; /* number of elements in hash table */
  13903. this.hash_bits = 0; /* log2(hash_size) */
  13904. this.hash_mask = 0; /* hash_size-1 */
  13905. this.hash_shift = 0;
  13906. /* Number of bits by which ins_h must be shifted at each input
  13907. * step. It must be such that after MIN_MATCH steps, the oldest
  13908. * byte no longer takes part in the hash key, that is:
  13909. * hash_shift * MIN_MATCH >= hash_bits
  13910. */
  13911. this.block_start = 0;
  13912. /* Window position at the beginning of the current output block. Gets
  13913. * negative when the window is moved backwards.
  13914. */
  13915. this.match_length = 0; /* length of best match */
  13916. this.prev_match = 0; /* previous match */
  13917. this.match_available = 0; /* set if previous match exists */
  13918. this.strstart = 0; /* start of string to insert */
  13919. this.match_start = 0; /* start of matching string */
  13920. this.lookahead = 0; /* number of valid bytes ahead in window */
  13921. this.prev_length = 0;
  13922. /* Length of the best match at previous step. Matches not greater than this
  13923. * are discarded. This is used in the lazy match evaluation.
  13924. */
  13925. this.max_chain_length = 0;
  13926. /* To speed up deflation, hash chains are never searched beyond this
  13927. * length. A higher limit improves compression ratio but degrades the
  13928. * speed.
  13929. */
  13930. this.max_lazy_match = 0;
  13931. /* Attempt to find a better match only when the current match is strictly
  13932. * smaller than this value. This mechanism is used only for compression
  13933. * levels >= 4.
  13934. */
  13935. // That's alias to max_lazy_match, don't use directly
  13936. //this.max_insert_length = 0;
  13937. /* Insert new strings in the hash table only if the match length is not
  13938. * greater than this length. This saves time but degrades compression.
  13939. * max_insert_length is used only for compression levels <= 3.
  13940. */
  13941. this.level = 0; /* compression level (1..9) */
  13942. this.strategy = 0; /* favor or force Huffman coding*/
  13943. this.good_match = 0;
  13944. /* Use a faster search when the previous match is longer than this */
  13945. this.nice_match = 0; /* Stop searching when current match exceeds this */
  13946. /* used by trees.c: */
  13947. /* Didn't use ct_data typedef below to suppress compiler warning */
  13948. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  13949. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  13950. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  13951. // Use flat array of DOUBLE size, with interleaved fata,
  13952. // because JS does not support effective
  13953. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  13954. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  13955. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  13956. zero(this.dyn_ltree);
  13957. zero(this.dyn_dtree);
  13958. zero(this.bl_tree);
  13959. this.l_desc = null; /* desc. for literal tree */
  13960. this.d_desc = null; /* desc. for distance tree */
  13961. this.bl_desc = null; /* desc. for bit length tree */
  13962. //ush bl_count[MAX_BITS+1];
  13963. this.bl_count = new utils.Buf16(MAX_BITS+1);
  13964. /* number of codes at each bit length for an optimal tree */
  13965. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  13966. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  13967. zero(this.heap);
  13968. this.heap_len = 0; /* number of elements in the heap */
  13969. this.heap_max = 0; /* element of largest frequency */
  13970. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  13971. * The same heap array is used to build all trees.
  13972. */
  13973. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  13974. zero(this.depth);
  13975. /* Depth of each subtree used as tie breaker for trees of equal frequency
  13976. */
  13977. this.l_buf = 0; /* buffer index for literals or lengths */
  13978. this.lit_bufsize = 0;
  13979. /* Size of match buffer for literals/lengths. There are 4 reasons for
  13980. * limiting lit_bufsize to 64K:
  13981. * - frequencies can be kept in 16 bit counters
  13982. * - if compression is not successful for the first block, all input
  13983. * data is still in the window so we can still emit a stored block even
  13984. * when input comes from standard input. (This can also be done for
  13985. * all blocks if lit_bufsize is not greater than 32K.)
  13986. * - if compression is not successful for a file smaller than 64K, we can
  13987. * even emit a stored file instead of a stored block (saving 5 bytes).
  13988. * This is applicable only for zip (not gzip or zlib).
  13989. * - creating new Huffman trees less frequently may not provide fast
  13990. * adaptation to changes in the input data statistics. (Take for
  13991. * example a binary file with poorly compressible code followed by
  13992. * a highly compressible string table.) Smaller buffer sizes give
  13993. * fast adaptation but have of course the overhead of transmitting
  13994. * trees more frequently.
  13995. * - I can't count above 4
  13996. */
  13997. this.last_lit = 0; /* running index in l_buf */
  13998. this.d_buf = 0;
  13999. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14000. * the same number of elements. To use different lengths, an extra flag
  14001. * array would be necessary.
  14002. */
  14003. this.opt_len = 0; /* bit length of current block with optimal trees */
  14004. this.static_len = 0; /* bit length of current block with static trees */
  14005. this.matches = 0; /* number of string matches in current block */
  14006. this.insert = 0; /* bytes at end of window left to insert */
  14007. this.bi_buf = 0;
  14008. /* Output buffer. bits are inserted starting at the bottom (least
  14009. * significant bits).
  14010. */
  14011. this.bi_valid = 0;
  14012. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14013. * are always zero.
  14014. */
  14015. // Used for window memory init. We safely ignore it for JS. That makes
  14016. // sense only for pointers and memory check tools.
  14017. //this.high_water = 0;
  14018. /* High water mark offset in window for initialized bytes -- bytes above
  14019. * this are set to zero in order to avoid memory check warnings when
  14020. * longest match routines access bytes past the input. This is then
  14021. * updated to the new high water mark.
  14022. */
  14023. }
  14024. function deflateResetKeep(strm) {
  14025. var s;
  14026. if (!strm || !strm.state) {
  14027. return err(strm, Z_STREAM_ERROR);
  14028. }
  14029. strm.total_in = strm.total_out = 0;
  14030. strm.data_type = Z_UNKNOWN;
  14031. s = strm.state;
  14032. s.pending = 0;
  14033. s.pending_out = 0;
  14034. if (s.wrap < 0) {
  14035. s.wrap = -s.wrap;
  14036. /* was made negative by deflate(..., Z_FINISH); */
  14037. }
  14038. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14039. strm.adler = (s.wrap === 2) ?
  14040. 0 // crc32(0, Z_NULL, 0)
  14041. :
  14042. 1; // adler32(0, Z_NULL, 0)
  14043. s.last_flush = Z_NO_FLUSH;
  14044. trees._tr_init(s);
  14045. return Z_OK;
  14046. }
  14047. function deflateReset(strm) {
  14048. var ret = deflateResetKeep(strm);
  14049. if (ret === Z_OK) {
  14050. lm_init(strm.state);
  14051. }
  14052. return ret;
  14053. }
  14054. function deflateSetHeader(strm, head) {
  14055. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14056. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14057. strm.state.gzhead = head;
  14058. return Z_OK;
  14059. }
  14060. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14061. if (!strm) { // === Z_NULL
  14062. return Z_STREAM_ERROR;
  14063. }
  14064. var wrap = 1;
  14065. if (level === Z_DEFAULT_COMPRESSION) {
  14066. level = 6;
  14067. }
  14068. if (windowBits < 0) { /* suppress zlib wrapper */
  14069. wrap = 0;
  14070. windowBits = -windowBits;
  14071. }
  14072. else if (windowBits > 15) {
  14073. wrap = 2; /* write gzip wrapper instead */
  14074. windowBits -= 16;
  14075. }
  14076. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14077. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14078. strategy < 0 || strategy > Z_FIXED) {
  14079. return err(strm, Z_STREAM_ERROR);
  14080. }
  14081. if (windowBits === 8) {
  14082. windowBits = 9;
  14083. }
  14084. /* until 256-byte window bug fixed */
  14085. var s = new DeflateState();
  14086. strm.state = s;
  14087. s.strm = strm;
  14088. s.wrap = wrap;
  14089. s.gzhead = null;
  14090. s.w_bits = windowBits;
  14091. s.w_size = 1 << s.w_bits;
  14092. s.w_mask = s.w_size - 1;
  14093. s.hash_bits = memLevel + 7;
  14094. s.hash_size = 1 << s.hash_bits;
  14095. s.hash_mask = s.hash_size - 1;
  14096. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14097. s.window = new utils.Buf8(s.w_size * 2);
  14098. s.head = new utils.Buf16(s.hash_size);
  14099. s.prev = new utils.Buf16(s.w_size);
  14100. // Don't need mem init magic for JS.
  14101. //s.high_water = 0; /* nothing written to s->window yet */
  14102. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14103. s.pending_buf_size = s.lit_bufsize * 4;
  14104. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14105. s.d_buf = s.lit_bufsize >> 1;
  14106. s.l_buf = (1 + 2) * s.lit_bufsize;
  14107. s.level = level;
  14108. s.strategy = strategy;
  14109. s.method = method;
  14110. return deflateReset(strm);
  14111. }
  14112. function deflateInit(strm, level) {
  14113. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  14114. }
  14115. function deflate(strm, flush) {
  14116. var old_flush, s;
  14117. var beg, val; // for gzip header write only
  14118. if (!strm || !strm.state ||
  14119. flush > Z_BLOCK || flush < 0) {
  14120. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  14121. }
  14122. s = strm.state;
  14123. if (!strm.output ||
  14124. (!strm.input && strm.avail_in !== 0) ||
  14125. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  14126. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  14127. }
  14128. s.strm = strm; /* just in case */
  14129. old_flush = s.last_flush;
  14130. s.last_flush = flush;
  14131. /* Write the header */
  14132. if (s.status === INIT_STATE) {
  14133. if (s.wrap === 2) { // GZIP header
  14134. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14135. put_byte(s, 31);
  14136. put_byte(s, 139);
  14137. put_byte(s, 8);
  14138. if (!s.gzhead) { // s->gzhead == Z_NULL
  14139. put_byte(s, 0);
  14140. put_byte(s, 0);
  14141. put_byte(s, 0);
  14142. put_byte(s, 0);
  14143. put_byte(s, 0);
  14144. put_byte(s, s.level === 9 ? 2 :
  14145. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14146. 4 : 0));
  14147. put_byte(s, OS_CODE);
  14148. s.status = BUSY_STATE;
  14149. }
  14150. else {
  14151. put_byte(s, (s.gzhead.text ? 1 : 0) +
  14152. (s.gzhead.hcrc ? 2 : 0) +
  14153. (!s.gzhead.extra ? 0 : 4) +
  14154. (!s.gzhead.name ? 0 : 8) +
  14155. (!s.gzhead.comment ? 0 : 16)
  14156. );
  14157. put_byte(s, s.gzhead.time & 0xff);
  14158. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  14159. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  14160. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  14161. put_byte(s, s.level === 9 ? 2 :
  14162. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14163. 4 : 0));
  14164. put_byte(s, s.gzhead.os & 0xff);
  14165. if (s.gzhead.extra && s.gzhead.extra.length) {
  14166. put_byte(s, s.gzhead.extra.length & 0xff);
  14167. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  14168. }
  14169. if (s.gzhead.hcrc) {
  14170. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  14171. }
  14172. s.gzindex = 0;
  14173. s.status = EXTRA_STATE;
  14174. }
  14175. }
  14176. else // DEFLATE header
  14177. {
  14178. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  14179. var level_flags = -1;
  14180. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  14181. level_flags = 0;
  14182. } else if (s.level < 6) {
  14183. level_flags = 1;
  14184. } else if (s.level === 6) {
  14185. level_flags = 2;
  14186. } else {
  14187. level_flags = 3;
  14188. }
  14189. header |= (level_flags << 6);
  14190. if (s.strstart !== 0) { header |= PRESET_DICT; }
  14191. header += 31 - (header % 31);
  14192. s.status = BUSY_STATE;
  14193. putShortMSB(s, header);
  14194. /* Save the adler32 of the preset dictionary: */
  14195. if (s.strstart !== 0) {
  14196. putShortMSB(s, strm.adler >>> 16);
  14197. putShortMSB(s, strm.adler & 0xffff);
  14198. }
  14199. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  14200. }
  14201. }
  14202. //#ifdef GZIP
  14203. if (s.status === EXTRA_STATE) {
  14204. if (s.gzhead.extra/* != Z_NULL*/) {
  14205. beg = s.pending; /* start of bytes to update crc */
  14206. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  14207. if (s.pending === s.pending_buf_size) {
  14208. if (s.gzhead.hcrc && s.pending > beg) {
  14209. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14210. }
  14211. flush_pending(strm);
  14212. beg = s.pending;
  14213. if (s.pending === s.pending_buf_size) {
  14214. break;
  14215. }
  14216. }
  14217. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  14218. s.gzindex++;
  14219. }
  14220. if (s.gzhead.hcrc && s.pending > beg) {
  14221. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14222. }
  14223. if (s.gzindex === s.gzhead.extra.length) {
  14224. s.gzindex = 0;
  14225. s.status = NAME_STATE;
  14226. }
  14227. }
  14228. else {
  14229. s.status = NAME_STATE;
  14230. }
  14231. }
  14232. if (s.status === NAME_STATE) {
  14233. if (s.gzhead.name/* != Z_NULL*/) {
  14234. beg = s.pending; /* start of bytes to update crc */
  14235. //int val;
  14236. do {
  14237. if (s.pending === s.pending_buf_size) {
  14238. if (s.gzhead.hcrc && s.pending > beg) {
  14239. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14240. }
  14241. flush_pending(strm);
  14242. beg = s.pending;
  14243. if (s.pending === s.pending_buf_size) {
  14244. val = 1;
  14245. break;
  14246. }
  14247. }
  14248. // JS specific: little magic to add zero terminator to end of string
  14249. if (s.gzindex < s.gzhead.name.length) {
  14250. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  14251. } else {
  14252. val = 0;
  14253. }
  14254. put_byte(s, val);
  14255. } while (val !== 0);
  14256. if (s.gzhead.hcrc && s.pending > beg) {
  14257. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14258. }
  14259. if (val === 0) {
  14260. s.gzindex = 0;
  14261. s.status = COMMENT_STATE;
  14262. }
  14263. }
  14264. else {
  14265. s.status = COMMENT_STATE;
  14266. }
  14267. }
  14268. if (s.status === COMMENT_STATE) {
  14269. if (s.gzhead.comment/* != Z_NULL*/) {
  14270. beg = s.pending; /* start of bytes to update crc */
  14271. //int val;
  14272. do {
  14273. if (s.pending === s.pending_buf_size) {
  14274. if (s.gzhead.hcrc && s.pending > beg) {
  14275. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14276. }
  14277. flush_pending(strm);
  14278. beg = s.pending;
  14279. if (s.pending === s.pending_buf_size) {
  14280. val = 1;
  14281. break;
  14282. }
  14283. }
  14284. // JS specific: little magic to add zero terminator to end of string
  14285. if (s.gzindex < s.gzhead.comment.length) {
  14286. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  14287. } else {
  14288. val = 0;
  14289. }
  14290. put_byte(s, val);
  14291. } while (val !== 0);
  14292. if (s.gzhead.hcrc && s.pending > beg) {
  14293. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14294. }
  14295. if (val === 0) {
  14296. s.status = HCRC_STATE;
  14297. }
  14298. }
  14299. else {
  14300. s.status = HCRC_STATE;
  14301. }
  14302. }
  14303. if (s.status === HCRC_STATE) {
  14304. if (s.gzhead.hcrc) {
  14305. if (s.pending + 2 > s.pending_buf_size) {
  14306. flush_pending(strm);
  14307. }
  14308. if (s.pending + 2 <= s.pending_buf_size) {
  14309. put_byte(s, strm.adler & 0xff);
  14310. put_byte(s, (strm.adler >> 8) & 0xff);
  14311. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14312. s.status = BUSY_STATE;
  14313. }
  14314. }
  14315. else {
  14316. s.status = BUSY_STATE;
  14317. }
  14318. }
  14319. //#endif
  14320. /* Flush as much pending output as possible */
  14321. if (s.pending !== 0) {
  14322. flush_pending(strm);
  14323. if (strm.avail_out === 0) {
  14324. /* Since avail_out is 0, deflate will be called again with
  14325. * more output space, but possibly with both pending and
  14326. * avail_in equal to zero. There won't be anything to do,
  14327. * but this is not an error situation so make sure we
  14328. * return OK instead of BUF_ERROR at next call of deflate:
  14329. */
  14330. s.last_flush = -1;
  14331. return Z_OK;
  14332. }
  14333. /* Make sure there is something to do and avoid duplicate consecutive
  14334. * flushes. For repeated and useless calls with Z_FINISH, we keep
  14335. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  14336. */
  14337. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  14338. flush !== Z_FINISH) {
  14339. return err(strm, Z_BUF_ERROR);
  14340. }
  14341. /* User must not provide more input after the first FINISH: */
  14342. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  14343. return err(strm, Z_BUF_ERROR);
  14344. }
  14345. /* Start a new block or continue the current one.
  14346. */
  14347. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  14348. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  14349. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  14350. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  14351. configuration_table[s.level].func(s, flush));
  14352. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  14353. s.status = FINISH_STATE;
  14354. }
  14355. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  14356. if (strm.avail_out === 0) {
  14357. s.last_flush = -1;
  14358. /* avoid BUF_ERROR next call, see above */
  14359. }
  14360. return Z_OK;
  14361. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  14362. * of deflate should use the same flush parameter to make sure
  14363. * that the flush is complete. So we don't have to output an
  14364. * empty block here, this will be done at next call. This also
  14365. * ensures that for a very small output buffer, we emit at most
  14366. * one empty block.
  14367. */
  14368. }
  14369. if (bstate === BS_BLOCK_DONE) {
  14370. if (flush === Z_PARTIAL_FLUSH) {
  14371. trees._tr_align(s);
  14372. }
  14373. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  14374. trees._tr_stored_block(s, 0, 0, false);
  14375. /* For a full flush, this empty block will be recognized
  14376. * as a special marker by inflate_sync().
  14377. */
  14378. if (flush === Z_FULL_FLUSH) {
  14379. /*** CLEAR_HASH(s); ***/ /* forget history */
  14380. zero(s.head); // Fill with NIL (= 0);
  14381. if (s.lookahead === 0) {
  14382. s.strstart = 0;
  14383. s.block_start = 0;
  14384. s.insert = 0;
  14385. }
  14386. }
  14387. }
  14388. flush_pending(strm);
  14389. if (strm.avail_out === 0) {
  14390. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  14391. return Z_OK;
  14392. }
  14393. }
  14394. }
  14395. //Assert(strm->avail_out > 0, "bug2");
  14396. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  14397. if (flush !== Z_FINISH) { return Z_OK; }
  14398. if (s.wrap <= 0) { return Z_STREAM_END; }
  14399. /* Write the trailer */
  14400. if (s.wrap === 2) {
  14401. put_byte(s, strm.adler & 0xff);
  14402. put_byte(s, (strm.adler >> 8) & 0xff);
  14403. put_byte(s, (strm.adler >> 16) & 0xff);
  14404. put_byte(s, (strm.adler >> 24) & 0xff);
  14405. put_byte(s, strm.total_in & 0xff);
  14406. put_byte(s, (strm.total_in >> 8) & 0xff);
  14407. put_byte(s, (strm.total_in >> 16) & 0xff);
  14408. put_byte(s, (strm.total_in >> 24) & 0xff);
  14409. }
  14410. else
  14411. {
  14412. putShortMSB(s, strm.adler >>> 16);
  14413. putShortMSB(s, strm.adler & 0xffff);
  14414. }
  14415. flush_pending(strm);
  14416. /* If avail_out is zero, the application will call deflate again
  14417. * to flush the rest.
  14418. */
  14419. if (s.wrap > 0) { s.wrap = -s.wrap; }
  14420. /* write the trailer only once! */
  14421. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  14422. }
  14423. function deflateEnd(strm) {
  14424. var status;
  14425. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  14426. return Z_STREAM_ERROR;
  14427. }
  14428. status = strm.state.status;
  14429. if (status !== INIT_STATE &&
  14430. status !== EXTRA_STATE &&
  14431. status !== NAME_STATE &&
  14432. status !== COMMENT_STATE &&
  14433. status !== HCRC_STATE &&
  14434. status !== BUSY_STATE &&
  14435. status !== FINISH_STATE
  14436. ) {
  14437. return err(strm, Z_STREAM_ERROR);
  14438. }
  14439. strm.state = null;
  14440. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  14441. }
  14442. /* =========================================================================
  14443. * Copy the source state to the destination state
  14444. */
  14445. //function deflateCopy(dest, source) {
  14446. //
  14447. //}
  14448. exports.deflateInit = deflateInit;
  14449. exports.deflateInit2 = deflateInit2;
  14450. exports.deflateReset = deflateReset;
  14451. exports.deflateResetKeep = deflateResetKeep;
  14452. exports.deflateSetHeader = deflateSetHeader;
  14453. exports.deflate = deflate;
  14454. exports.deflateEnd = deflateEnd;
  14455. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  14456. /* Not implemented
  14457. exports.deflateBound = deflateBound;
  14458. exports.deflateCopy = deflateCopy;
  14459. exports.deflateSetDictionary = deflateSetDictionary;
  14460. exports.deflateParams = deflateParams;
  14461. exports.deflatePending = deflatePending;
  14462. exports.deflatePrime = deflatePrime;
  14463. exports.deflateTune = deflateTune;
  14464. */
  14465. },{"../utils/common":48,"./adler32":50,"./crc32":52,"./messages":58,"./trees":59}],54:[function(require,module,exports){
  14466. 'use strict';
  14467. function GZheader() {
  14468. /* true if compressed data believed to be text */
  14469. this.text = 0;
  14470. /* modification time */
  14471. this.time = 0;
  14472. /* extra flags (not used when writing a gzip file) */
  14473. this.xflags = 0;
  14474. /* operating system */
  14475. this.os = 0;
  14476. /* pointer to extra field or Z_NULL if none */
  14477. this.extra = null;
  14478. /* extra field length (valid if extra != Z_NULL) */
  14479. this.extra_len = 0; // Actually, we don't need it in JS,
  14480. // but leave for few code modifications
  14481. //
  14482. // Setup limits is not necessary because in js we should not preallocate memory
  14483. // for inflate use constant limit in 65536 bytes
  14484. //
  14485. /* space at extra (only when reading header) */
  14486. // this.extra_max = 0;
  14487. /* pointer to zero-terminated file name or Z_NULL */
  14488. this.name = '';
  14489. /* space at name (only when reading header) */
  14490. // this.name_max = 0;
  14491. /* pointer to zero-terminated comment or Z_NULL */
  14492. this.comment = '';
  14493. /* space at comment (only when reading header) */
  14494. // this.comm_max = 0;
  14495. /* true if there was or will be a header crc */
  14496. this.hcrc = 0;
  14497. /* true when done reading gzip header (not used when writing a gzip file) */
  14498. this.done = false;
  14499. }
  14500. module.exports = GZheader;
  14501. },{}],55:[function(require,module,exports){
  14502. 'use strict';
  14503. // See state defs from inflate.js
  14504. var BAD = 30; /* got a data error -- remain here until reset */
  14505. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  14506. /*
  14507. Decode literal, length, and distance codes and write out the resulting
  14508. literal and match bytes until either not enough input or output is
  14509. available, an end-of-block is encountered, or a data error is encountered.
  14510. When large enough input and output buffers are supplied to inflate(), for
  14511. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  14512. inflate execution time is spent in this routine.
  14513. Entry assumptions:
  14514. state.mode === LEN
  14515. strm.avail_in >= 6
  14516. strm.avail_out >= 258
  14517. start >= strm.avail_out
  14518. state.bits < 8
  14519. On return, state.mode is one of:
  14520. LEN -- ran out of enough output space or enough available input
  14521. TYPE -- reached end of block code, inflate() to interpret next block
  14522. BAD -- error in block data
  14523. Notes:
  14524. - The maximum input bits used by a length/distance pair is 15 bits for the
  14525. length code, 5 bits for the length extra, 15 bits for the distance code,
  14526. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  14527. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  14528. checking for available input while decoding.
  14529. - The maximum bytes that a single length/distance pair can output is 258
  14530. bytes, which is the maximum length that can be coded. inflate_fast()
  14531. requires strm.avail_out >= 258 for each loop to avoid checking for
  14532. output space.
  14533. */
  14534. module.exports = function inflate_fast(strm, start) {
  14535. var state;
  14536. var _in; /* local strm.input */
  14537. var last; /* have enough input while in < last */
  14538. var _out; /* local strm.output */
  14539. var beg; /* inflate()'s initial strm.output */
  14540. var end; /* while out < end, enough space available */
  14541. //#ifdef INFLATE_STRICT
  14542. var dmax; /* maximum distance from zlib header */
  14543. //#endif
  14544. var wsize; /* window size or zero if not using window */
  14545. var whave; /* valid bytes in the window */
  14546. var wnext; /* window write index */
  14547. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  14548. var s_window; /* allocated sliding window, if wsize != 0 */
  14549. var hold; /* local strm.hold */
  14550. var bits; /* local strm.bits */
  14551. var lcode; /* local strm.lencode */
  14552. var dcode; /* local strm.distcode */
  14553. var lmask; /* mask for first level of length codes */
  14554. var dmask; /* mask for first level of distance codes */
  14555. var here; /* retrieved table entry */
  14556. var op; /* code bits, operation, extra bits, or */
  14557. /* window position, window bytes to copy */
  14558. var len; /* match length, unused bytes */
  14559. var dist; /* match distance */
  14560. var from; /* where to copy match from */
  14561. var from_source;
  14562. var input, output; // JS specific, because we have no pointers
  14563. /* copy state to local variables */
  14564. state = strm.state;
  14565. //here = state.here;
  14566. _in = strm.next_in;
  14567. input = strm.input;
  14568. last = _in + (strm.avail_in - 5);
  14569. _out = strm.next_out;
  14570. output = strm.output;
  14571. beg = _out - (start - strm.avail_out);
  14572. end = _out + (strm.avail_out - 257);
  14573. //#ifdef INFLATE_STRICT
  14574. dmax = state.dmax;
  14575. //#endif
  14576. wsize = state.wsize;
  14577. whave = state.whave;
  14578. wnext = state.wnext;
  14579. s_window = state.window;
  14580. hold = state.hold;
  14581. bits = state.bits;
  14582. lcode = state.lencode;
  14583. dcode = state.distcode;
  14584. lmask = (1 << state.lenbits) - 1;
  14585. dmask = (1 << state.distbits) - 1;
  14586. /* decode literals and length/distances until end-of-block or not enough
  14587. input data or output space */
  14588. top:
  14589. do {
  14590. if (bits < 15) {
  14591. hold += input[_in++] << bits;
  14592. bits += 8;
  14593. hold += input[_in++] << bits;
  14594. bits += 8;
  14595. }
  14596. here = lcode[hold & lmask];
  14597. dolen:
  14598. for (;;) { // Goto emulation
  14599. op = here >>> 24/*here.bits*/;
  14600. hold >>>= op;
  14601. bits -= op;
  14602. op = (here >>> 16) & 0xff/*here.op*/;
  14603. if (op === 0) { /* literal */
  14604. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  14605. // "inflate: literal '%c'\n" :
  14606. // "inflate: literal 0x%02x\n", here.val));
  14607. output[_out++] = here & 0xffff/*here.val*/;
  14608. }
  14609. else if (op & 16) { /* length base */
  14610. len = here & 0xffff/*here.val*/;
  14611. op &= 15; /* number of extra bits */
  14612. if (op) {
  14613. if (bits < op) {
  14614. hold += input[_in++] << bits;
  14615. bits += 8;
  14616. }
  14617. len += hold & ((1 << op) - 1);
  14618. hold >>>= op;
  14619. bits -= op;
  14620. }
  14621. //Tracevv((stderr, "inflate: length %u\n", len));
  14622. if (bits < 15) {
  14623. hold += input[_in++] << bits;
  14624. bits += 8;
  14625. hold += input[_in++] << bits;
  14626. bits += 8;
  14627. }
  14628. here = dcode[hold & dmask];
  14629. dodist:
  14630. for (;;) { // goto emulation
  14631. op = here >>> 24/*here.bits*/;
  14632. hold >>>= op;
  14633. bits -= op;
  14634. op = (here >>> 16) & 0xff/*here.op*/;
  14635. if (op & 16) { /* distance base */
  14636. dist = here & 0xffff/*here.val*/;
  14637. op &= 15; /* number of extra bits */
  14638. if (bits < op) {
  14639. hold += input[_in++] << bits;
  14640. bits += 8;
  14641. if (bits < op) {
  14642. hold += input[_in++] << bits;
  14643. bits += 8;
  14644. }
  14645. }
  14646. dist += hold & ((1 << op) - 1);
  14647. //#ifdef INFLATE_STRICT
  14648. if (dist > dmax) {
  14649. strm.msg = 'invalid distance too far back';
  14650. state.mode = BAD;
  14651. break top;
  14652. }
  14653. //#endif
  14654. hold >>>= op;
  14655. bits -= op;
  14656. //Tracevv((stderr, "inflate: distance %u\n", dist));
  14657. op = _out - beg; /* max distance in output */
  14658. if (dist > op) { /* see if copy from window */
  14659. op = dist - op; /* distance back in window */
  14660. if (op > whave) {
  14661. if (state.sane) {
  14662. strm.msg = 'invalid distance too far back';
  14663. state.mode = BAD;
  14664. break top;
  14665. }
  14666. // (!) This block is disabled in zlib defailts,
  14667. // don't enable it for binary compatibility
  14668. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  14669. // if (len <= op - whave) {
  14670. // do {
  14671. // output[_out++] = 0;
  14672. // } while (--len);
  14673. // continue top;
  14674. // }
  14675. // len -= op - whave;
  14676. // do {
  14677. // output[_out++] = 0;
  14678. // } while (--op > whave);
  14679. // if (op === 0) {
  14680. // from = _out - dist;
  14681. // do {
  14682. // output[_out++] = output[from++];
  14683. // } while (--len);
  14684. // continue top;
  14685. // }
  14686. //#endif
  14687. }
  14688. from = 0; // window index
  14689. from_source = s_window;
  14690. if (wnext === 0) { /* very common case */
  14691. from += wsize - op;
  14692. if (op < len) { /* some from window */
  14693. len -= op;
  14694. do {
  14695. output[_out++] = s_window[from++];
  14696. } while (--op);
  14697. from = _out - dist; /* rest from output */
  14698. from_source = output;
  14699. }
  14700. }
  14701. else if (wnext < op) { /* wrap around window */
  14702. from += wsize + wnext - op;
  14703. op -= wnext;
  14704. if (op < len) { /* some from end of window */
  14705. len -= op;
  14706. do {
  14707. output[_out++] = s_window[from++];
  14708. } while (--op);
  14709. from = 0;
  14710. if (wnext < len) { /* some from start of window */
  14711. op = wnext;
  14712. len -= op;
  14713. do {
  14714. output[_out++] = s_window[from++];
  14715. } while (--op);
  14716. from = _out - dist; /* rest from output */
  14717. from_source = output;
  14718. }
  14719. }
  14720. }
  14721. else { /* contiguous in window */
  14722. from += wnext - op;
  14723. if (op < len) { /* some from window */
  14724. len -= op;
  14725. do {
  14726. output[_out++] = s_window[from++];
  14727. } while (--op);
  14728. from = _out - dist; /* rest from output */
  14729. from_source = output;
  14730. }
  14731. }
  14732. while (len > 2) {
  14733. output[_out++] = from_source[from++];
  14734. output[_out++] = from_source[from++];
  14735. output[_out++] = from_source[from++];
  14736. len -= 3;
  14737. }
  14738. if (len) {
  14739. output[_out++] = from_source[from++];
  14740. if (len > 1) {
  14741. output[_out++] = from_source[from++];
  14742. }
  14743. }
  14744. }
  14745. else {
  14746. from = _out - dist; /* copy direct from output */
  14747. do { /* minimum length is three */
  14748. output[_out++] = output[from++];
  14749. output[_out++] = output[from++];
  14750. output[_out++] = output[from++];
  14751. len -= 3;
  14752. } while (len > 2);
  14753. if (len) {
  14754. output[_out++] = output[from++];
  14755. if (len > 1) {
  14756. output[_out++] = output[from++];
  14757. }
  14758. }
  14759. }
  14760. }
  14761. else if ((op & 64) === 0) { /* 2nd level distance code */
  14762. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  14763. continue dodist;
  14764. }
  14765. else {
  14766. strm.msg = 'invalid distance code';
  14767. state.mode = BAD;
  14768. break top;
  14769. }
  14770. break; // need to emulate goto via "continue"
  14771. }
  14772. }
  14773. else if ((op & 64) === 0) { /* 2nd level length code */
  14774. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  14775. continue dolen;
  14776. }
  14777. else if (op & 32) { /* end-of-block */
  14778. //Tracevv((stderr, "inflate: end of block\n"));
  14779. state.mode = TYPE;
  14780. break top;
  14781. }
  14782. else {
  14783. strm.msg = 'invalid literal/length code';
  14784. state.mode = BAD;
  14785. break top;
  14786. }
  14787. break; // need to emulate goto via "continue"
  14788. }
  14789. } while (_in < last && _out < end);
  14790. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  14791. len = bits >> 3;
  14792. _in -= len;
  14793. bits -= len << 3;
  14794. hold &= (1 << bits) - 1;
  14795. /* update state and return */
  14796. strm.next_in = _in;
  14797. strm.next_out = _out;
  14798. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  14799. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  14800. state.hold = hold;
  14801. state.bits = bits;
  14802. return;
  14803. };
  14804. },{}],56:[function(require,module,exports){
  14805. 'use strict';
  14806. var utils = require('../utils/common');
  14807. var adler32 = require('./adler32');
  14808. var crc32 = require('./crc32');
  14809. var inflate_fast = require('./inffast');
  14810. var inflate_table = require('./inftrees');
  14811. var CODES = 0;
  14812. var LENS = 1;
  14813. var DISTS = 2;
  14814. /* Public constants ==========================================================*/
  14815. /* ===========================================================================*/
  14816. /* Allowed flush values; see deflate() and inflate() below for details */
  14817. //var Z_NO_FLUSH = 0;
  14818. //var Z_PARTIAL_FLUSH = 1;
  14819. //var Z_SYNC_FLUSH = 2;
  14820. //var Z_FULL_FLUSH = 3;
  14821. var Z_FINISH = 4;
  14822. var Z_BLOCK = 5;
  14823. var Z_TREES = 6;
  14824. /* Return codes for the compression/decompression functions. Negative values
  14825. * are errors, positive values are used for special but normal events.
  14826. */
  14827. var Z_OK = 0;
  14828. var Z_STREAM_END = 1;
  14829. var Z_NEED_DICT = 2;
  14830. //var Z_ERRNO = -1;
  14831. var Z_STREAM_ERROR = -2;
  14832. var Z_DATA_ERROR = -3;
  14833. var Z_MEM_ERROR = -4;
  14834. var Z_BUF_ERROR = -5;
  14835. //var Z_VERSION_ERROR = -6;
  14836. /* The deflate compression method */
  14837. var Z_DEFLATED = 8;
  14838. /* STATES ====================================================================*/
  14839. /* ===========================================================================*/
  14840. var HEAD = 1; /* i: waiting for magic header */
  14841. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  14842. var TIME = 3; /* i: waiting for modification time (gzip) */
  14843. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  14844. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  14845. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  14846. var NAME = 7; /* i: waiting for end of file name (gzip) */
  14847. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  14848. var HCRC = 9; /* i: waiting for header crc (gzip) */
  14849. var DICTID = 10; /* i: waiting for dictionary check value */
  14850. var DICT = 11; /* waiting for inflateSetDictionary() call */
  14851. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  14852. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  14853. var STORED = 14; /* i: waiting for stored size (length and complement) */
  14854. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  14855. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  14856. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  14857. var LENLENS = 18; /* i: waiting for code length code lengths */
  14858. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  14859. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  14860. var LEN = 21; /* i: waiting for length/lit/eob code */
  14861. var LENEXT = 22; /* i: waiting for length extra bits */
  14862. var DIST = 23; /* i: waiting for distance code */
  14863. var DISTEXT = 24; /* i: waiting for distance extra bits */
  14864. var MATCH = 25; /* o: waiting for output space to copy string */
  14865. var LIT = 26; /* o: waiting for output space to write literal */
  14866. var CHECK = 27; /* i: waiting for 32-bit check value */
  14867. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  14868. var DONE = 29; /* finished check, done -- remain here until reset */
  14869. var BAD = 30; /* got a data error -- remain here until reset */
  14870. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  14871. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  14872. /* ===========================================================================*/
  14873. var ENOUGH_LENS = 852;
  14874. var ENOUGH_DISTS = 592;
  14875. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  14876. var MAX_WBITS = 15;
  14877. /* 32K LZ77 window */
  14878. var DEF_WBITS = MAX_WBITS;
  14879. function ZSWAP32(q) {
  14880. return (((q >>> 24) & 0xff) +
  14881. ((q >>> 8) & 0xff00) +
  14882. ((q & 0xff00) << 8) +
  14883. ((q & 0xff) << 24));
  14884. }
  14885. function InflateState() {
  14886. this.mode = 0; /* current inflate mode */
  14887. this.last = false; /* true if processing last block */
  14888. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14889. this.havedict = false; /* true if dictionary provided */
  14890. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  14891. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  14892. this.check = 0; /* protected copy of check value */
  14893. this.total = 0; /* protected copy of output count */
  14894. // TODO: may be {}
  14895. this.head = null; /* where to save gzip header information */
  14896. /* sliding window */
  14897. this.wbits = 0; /* log base 2 of requested window size */
  14898. this.wsize = 0; /* window size or zero if not using window */
  14899. this.whave = 0; /* valid bytes in the window */
  14900. this.wnext = 0; /* window write index */
  14901. this.window = null; /* allocated sliding window, if needed */
  14902. /* bit accumulator */
  14903. this.hold = 0; /* input bit accumulator */
  14904. this.bits = 0; /* number of bits in "in" */
  14905. /* for string and stored block copying */
  14906. this.length = 0; /* literal or length of data to copy */
  14907. this.offset = 0; /* distance back to copy string from */
  14908. /* for table and code decoding */
  14909. this.extra = 0; /* extra bits needed */
  14910. /* fixed and dynamic code tables */
  14911. this.lencode = null; /* starting table for length/literal codes */
  14912. this.distcode = null; /* starting table for distance codes */
  14913. this.lenbits = 0; /* index bits for lencode */
  14914. this.distbits = 0; /* index bits for distcode */
  14915. /* dynamic table building */
  14916. this.ncode = 0; /* number of code length code lengths */
  14917. this.nlen = 0; /* number of length code lengths */
  14918. this.ndist = 0; /* number of distance code lengths */
  14919. this.have = 0; /* number of code lengths in lens[] */
  14920. this.next = null; /* next available space in codes[] */
  14921. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  14922. this.work = new utils.Buf16(288); /* work area for code table building */
  14923. /*
  14924. because we don't have pointers in js, we use lencode and distcode directly
  14925. as buffers so we don't need codes
  14926. */
  14927. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  14928. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  14929. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  14930. this.sane = 0; /* if false, allow invalid distance too far */
  14931. this.back = 0; /* bits back of last unprocessed length/lit */
  14932. this.was = 0; /* initial length of match */
  14933. }
  14934. function inflateResetKeep(strm) {
  14935. var state;
  14936. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14937. state = strm.state;
  14938. strm.total_in = strm.total_out = state.total = 0;
  14939. strm.msg = ''; /*Z_NULL*/
  14940. if (state.wrap) { /* to support ill-conceived Java test suite */
  14941. strm.adler = state.wrap & 1;
  14942. }
  14943. state.mode = HEAD;
  14944. state.last = 0;
  14945. state.havedict = 0;
  14946. state.dmax = 32768;
  14947. state.head = null/*Z_NULL*/;
  14948. state.hold = 0;
  14949. state.bits = 0;
  14950. //state.lencode = state.distcode = state.next = state.codes;
  14951. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  14952. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  14953. state.sane = 1;
  14954. state.back = -1;
  14955. //Tracev((stderr, "inflate: reset\n"));
  14956. return Z_OK;
  14957. }
  14958. function inflateReset(strm) {
  14959. var state;
  14960. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14961. state = strm.state;
  14962. state.wsize = 0;
  14963. state.whave = 0;
  14964. state.wnext = 0;
  14965. return inflateResetKeep(strm);
  14966. }
  14967. function inflateReset2(strm, windowBits) {
  14968. var wrap;
  14969. var state;
  14970. /* get the state */
  14971. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14972. state = strm.state;
  14973. /* extract wrap request from windowBits parameter */
  14974. if (windowBits < 0) {
  14975. wrap = 0;
  14976. windowBits = -windowBits;
  14977. }
  14978. else {
  14979. wrap = (windowBits >> 4) + 1;
  14980. if (windowBits < 48) {
  14981. windowBits &= 15;
  14982. }
  14983. }
  14984. /* set number of window bits, free window if different */
  14985. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  14986. return Z_STREAM_ERROR;
  14987. }
  14988. if (state.window !== null && state.wbits !== windowBits) {
  14989. state.window = null;
  14990. }
  14991. /* update state and reset the rest of it */
  14992. state.wrap = wrap;
  14993. state.wbits = windowBits;
  14994. return inflateReset(strm);
  14995. }
  14996. function inflateInit2(strm, windowBits) {
  14997. var ret;
  14998. var state;
  14999. if (!strm) { return Z_STREAM_ERROR; }
  15000. //strm.msg = Z_NULL; /* in case we return an error */
  15001. state = new InflateState();
  15002. //if (state === Z_NULL) return Z_MEM_ERROR;
  15003. //Tracev((stderr, "inflate: allocated\n"));
  15004. strm.state = state;
  15005. state.window = null/*Z_NULL*/;
  15006. ret = inflateReset2(strm, windowBits);
  15007. if (ret !== Z_OK) {
  15008. strm.state = null/*Z_NULL*/;
  15009. }
  15010. return ret;
  15011. }
  15012. function inflateInit(strm) {
  15013. return inflateInit2(strm, DEF_WBITS);
  15014. }
  15015. /*
  15016. Return state with length and distance decoding tables and index sizes set to
  15017. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15018. If BUILDFIXED is defined, then instead this routine builds the tables the
  15019. first time it's called, and returns those tables the first time and
  15020. thereafter. This reduces the size of the code by about 2K bytes, in
  15021. exchange for a little execution time. However, BUILDFIXED should not be
  15022. used for threaded applications, since the rewriting of the tables and virgin
  15023. may not be thread-safe.
  15024. */
  15025. var virgin = true;
  15026. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15027. function fixedtables(state) {
  15028. /* build fixed huffman tables if first call (may not be thread safe) */
  15029. if (virgin) {
  15030. var sym;
  15031. lenfix = new utils.Buf32(512);
  15032. distfix = new utils.Buf32(32);
  15033. /* literal/length table */
  15034. sym = 0;
  15035. while (sym < 144) { state.lens[sym++] = 8; }
  15036. while (sym < 256) { state.lens[sym++] = 9; }
  15037. while (sym < 280) { state.lens[sym++] = 7; }
  15038. while (sym < 288) { state.lens[sym++] = 8; }
  15039. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  15040. /* distance table */
  15041. sym = 0;
  15042. while (sym < 32) { state.lens[sym++] = 5; }
  15043. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  15044. /* do this just once */
  15045. virgin = false;
  15046. }
  15047. state.lencode = lenfix;
  15048. state.lenbits = 9;
  15049. state.distcode = distfix;
  15050. state.distbits = 5;
  15051. }
  15052. /*
  15053. Update the window with the last wsize (normally 32K) bytes written before
  15054. returning. If window does not exist yet, create it. This is only called
  15055. when a window is already in use, or when output has been written during this
  15056. inflate call, but the end of the deflate stream has not been reached yet.
  15057. It is also called to create a window for dictionary data when a dictionary
  15058. is loaded.
  15059. Providing output buffers larger than 32K to inflate() should provide a speed
  15060. advantage, since only the last 32K of output is copied to the sliding window
  15061. upon return from inflate(), and since all distances after the first 32K of
  15062. output will fall in the output data, making match copies simpler and faster.
  15063. The advantage may be dependent on the size of the processor's data caches.
  15064. */
  15065. function updatewindow(strm, src, end, copy) {
  15066. var dist;
  15067. var state = strm.state;
  15068. /* if it hasn't been done already, allocate space for the window */
  15069. if (state.window === null) {
  15070. state.wsize = 1 << state.wbits;
  15071. state.wnext = 0;
  15072. state.whave = 0;
  15073. state.window = new utils.Buf8(state.wsize);
  15074. }
  15075. /* copy state->wsize or less output bytes into the circular window */
  15076. if (copy >= state.wsize) {
  15077. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  15078. state.wnext = 0;
  15079. state.whave = state.wsize;
  15080. }
  15081. else {
  15082. dist = state.wsize - state.wnext;
  15083. if (dist > copy) {
  15084. dist = copy;
  15085. }
  15086. //zmemcpy(state->window + state->wnext, end - copy, dist);
  15087. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  15088. copy -= dist;
  15089. if (copy) {
  15090. //zmemcpy(state->window, end - copy, copy);
  15091. utils.arraySet(state.window,src, end - copy, copy, 0);
  15092. state.wnext = copy;
  15093. state.whave = state.wsize;
  15094. }
  15095. else {
  15096. state.wnext += dist;
  15097. if (state.wnext === state.wsize) { state.wnext = 0; }
  15098. if (state.whave < state.wsize) { state.whave += dist; }
  15099. }
  15100. }
  15101. return 0;
  15102. }
  15103. function inflate(strm, flush) {
  15104. var state;
  15105. var input, output; // input/output buffers
  15106. var next; /* next input INDEX */
  15107. var put; /* next output INDEX */
  15108. var have, left; /* available input and output */
  15109. var hold; /* bit buffer */
  15110. var bits; /* bits in bit buffer */
  15111. var _in, _out; /* save starting available input and output */
  15112. var copy; /* number of stored or match bytes to copy */
  15113. var from; /* where to copy match bytes from */
  15114. var from_source;
  15115. var here = 0; /* current decoding table entry */
  15116. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  15117. //var last; /* parent table entry */
  15118. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  15119. var len; /* length to copy for repeats, bits to drop */
  15120. var ret; /* return code */
  15121. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  15122. var opts;
  15123. var n; // temporary var for NEED_BITS
  15124. var order = /* permutation of code lengths */
  15125. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  15126. if (!strm || !strm.state || !strm.output ||
  15127. (!strm.input && strm.avail_in !== 0)) {
  15128. return Z_STREAM_ERROR;
  15129. }
  15130. state = strm.state;
  15131. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  15132. //--- LOAD() ---
  15133. put = strm.next_out;
  15134. output = strm.output;
  15135. left = strm.avail_out;
  15136. next = strm.next_in;
  15137. input = strm.input;
  15138. have = strm.avail_in;
  15139. hold = state.hold;
  15140. bits = state.bits;
  15141. //---
  15142. _in = have;
  15143. _out = left;
  15144. ret = Z_OK;
  15145. inf_leave: // goto emulation
  15146. for (;;) {
  15147. switch (state.mode) {
  15148. case HEAD:
  15149. if (state.wrap === 0) {
  15150. state.mode = TYPEDO;
  15151. break;
  15152. }
  15153. //=== NEEDBITS(16);
  15154. while (bits < 16) {
  15155. if (have === 0) { break inf_leave; }
  15156. have--;
  15157. hold += input[next++] << bits;
  15158. bits += 8;
  15159. }
  15160. //===//
  15161. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  15162. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  15163. //=== CRC2(state.check, hold);
  15164. hbuf[0] = hold & 0xff;
  15165. hbuf[1] = (hold >>> 8) & 0xff;
  15166. state.check = crc32(state.check, hbuf, 2, 0);
  15167. //===//
  15168. //=== INITBITS();
  15169. hold = 0;
  15170. bits = 0;
  15171. //===//
  15172. state.mode = FLAGS;
  15173. break;
  15174. }
  15175. state.flags = 0; /* expect zlib header */
  15176. if (state.head) {
  15177. state.head.done = false;
  15178. }
  15179. if (!(state.wrap & 1) || /* check if zlib header allowed */
  15180. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  15181. strm.msg = 'incorrect header check';
  15182. state.mode = BAD;
  15183. break;
  15184. }
  15185. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  15186. strm.msg = 'unknown compression method';
  15187. state.mode = BAD;
  15188. break;
  15189. }
  15190. //--- DROPBITS(4) ---//
  15191. hold >>>= 4;
  15192. bits -= 4;
  15193. //---//
  15194. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  15195. if (state.wbits === 0) {
  15196. state.wbits = len;
  15197. }
  15198. else if (len > state.wbits) {
  15199. strm.msg = 'invalid window size';
  15200. state.mode = BAD;
  15201. break;
  15202. }
  15203. state.dmax = 1 << len;
  15204. //Tracev((stderr, "inflate: zlib header ok\n"));
  15205. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15206. state.mode = hold & 0x200 ? DICTID : TYPE;
  15207. //=== INITBITS();
  15208. hold = 0;
  15209. bits = 0;
  15210. //===//
  15211. break;
  15212. case FLAGS:
  15213. //=== NEEDBITS(16); */
  15214. while (bits < 16) {
  15215. if (have === 0) { break inf_leave; }
  15216. have--;
  15217. hold += input[next++] << bits;
  15218. bits += 8;
  15219. }
  15220. //===//
  15221. state.flags = hold;
  15222. if ((state.flags & 0xff) !== Z_DEFLATED) {
  15223. strm.msg = 'unknown compression method';
  15224. state.mode = BAD;
  15225. break;
  15226. }
  15227. if (state.flags & 0xe000) {
  15228. strm.msg = 'unknown header flags set';
  15229. state.mode = BAD;
  15230. break;
  15231. }
  15232. if (state.head) {
  15233. state.head.text = ((hold >> 8) & 1);
  15234. }
  15235. if (state.flags & 0x0200) {
  15236. //=== CRC2(state.check, hold);
  15237. hbuf[0] = hold & 0xff;
  15238. hbuf[1] = (hold >>> 8) & 0xff;
  15239. state.check = crc32(state.check, hbuf, 2, 0);
  15240. //===//
  15241. }
  15242. //=== INITBITS();
  15243. hold = 0;
  15244. bits = 0;
  15245. //===//
  15246. state.mode = TIME;
  15247. /* falls through */
  15248. case TIME:
  15249. //=== NEEDBITS(32); */
  15250. while (bits < 32) {
  15251. if (have === 0) { break inf_leave; }
  15252. have--;
  15253. hold += input[next++] << bits;
  15254. bits += 8;
  15255. }
  15256. //===//
  15257. if (state.head) {
  15258. state.head.time = hold;
  15259. }
  15260. if (state.flags & 0x0200) {
  15261. //=== CRC4(state.check, hold)
  15262. hbuf[0] = hold & 0xff;
  15263. hbuf[1] = (hold >>> 8) & 0xff;
  15264. hbuf[2] = (hold >>> 16) & 0xff;
  15265. hbuf[3] = (hold >>> 24) & 0xff;
  15266. state.check = crc32(state.check, hbuf, 4, 0);
  15267. //===
  15268. }
  15269. //=== INITBITS();
  15270. hold = 0;
  15271. bits = 0;
  15272. //===//
  15273. state.mode = OS;
  15274. /* falls through */
  15275. case OS:
  15276. //=== NEEDBITS(16); */
  15277. while (bits < 16) {
  15278. if (have === 0) { break inf_leave; }
  15279. have--;
  15280. hold += input[next++] << bits;
  15281. bits += 8;
  15282. }
  15283. //===//
  15284. if (state.head) {
  15285. state.head.xflags = (hold & 0xff);
  15286. state.head.os = (hold >> 8);
  15287. }
  15288. if (state.flags & 0x0200) {
  15289. //=== CRC2(state.check, hold);
  15290. hbuf[0] = hold & 0xff;
  15291. hbuf[1] = (hold >>> 8) & 0xff;
  15292. state.check = crc32(state.check, hbuf, 2, 0);
  15293. //===//
  15294. }
  15295. //=== INITBITS();
  15296. hold = 0;
  15297. bits = 0;
  15298. //===//
  15299. state.mode = EXLEN;
  15300. /* falls through */
  15301. case EXLEN:
  15302. if (state.flags & 0x0400) {
  15303. //=== NEEDBITS(16); */
  15304. while (bits < 16) {
  15305. if (have === 0) { break inf_leave; }
  15306. have--;
  15307. hold += input[next++] << bits;
  15308. bits += 8;
  15309. }
  15310. //===//
  15311. state.length = hold;
  15312. if (state.head) {
  15313. state.head.extra_len = hold;
  15314. }
  15315. if (state.flags & 0x0200) {
  15316. //=== CRC2(state.check, hold);
  15317. hbuf[0] = hold & 0xff;
  15318. hbuf[1] = (hold >>> 8) & 0xff;
  15319. state.check = crc32(state.check, hbuf, 2, 0);
  15320. //===//
  15321. }
  15322. //=== INITBITS();
  15323. hold = 0;
  15324. bits = 0;
  15325. //===//
  15326. }
  15327. else if (state.head) {
  15328. state.head.extra = null/*Z_NULL*/;
  15329. }
  15330. state.mode = EXTRA;
  15331. /* falls through */
  15332. case EXTRA:
  15333. if (state.flags & 0x0400) {
  15334. copy = state.length;
  15335. if (copy > have) { copy = have; }
  15336. if (copy) {
  15337. if (state.head) {
  15338. len = state.head.extra_len - state.length;
  15339. if (!state.head.extra) {
  15340. // Use untyped array for more conveniend processing later
  15341. state.head.extra = new Array(state.head.extra_len);
  15342. }
  15343. utils.arraySet(
  15344. state.head.extra,
  15345. input,
  15346. next,
  15347. // extra field is limited to 65536 bytes
  15348. // - no need for additional size check
  15349. copy,
  15350. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  15351. len
  15352. );
  15353. //zmemcpy(state.head.extra + len, next,
  15354. // len + copy > state.head.extra_max ?
  15355. // state.head.extra_max - len : copy);
  15356. }
  15357. if (state.flags & 0x0200) {
  15358. state.check = crc32(state.check, input, copy, next);
  15359. }
  15360. have -= copy;
  15361. next += copy;
  15362. state.length -= copy;
  15363. }
  15364. if (state.length) { break inf_leave; }
  15365. }
  15366. state.length = 0;
  15367. state.mode = NAME;
  15368. /* falls through */
  15369. case NAME:
  15370. if (state.flags & 0x0800) {
  15371. if (have === 0) { break inf_leave; }
  15372. copy = 0;
  15373. do {
  15374. // TODO: 2 or 1 bytes?
  15375. len = input[next + copy++];
  15376. /* use constant limit because in js we should not preallocate memory */
  15377. if (state.head && len &&
  15378. (state.length < 65536 /*state.head.name_max*/)) {
  15379. state.head.name += String.fromCharCode(len);
  15380. }
  15381. } while (len && copy < have);
  15382. if (state.flags & 0x0200) {
  15383. state.check = crc32(state.check, input, copy, next);
  15384. }
  15385. have -= copy;
  15386. next += copy;
  15387. if (len) { break inf_leave; }
  15388. }
  15389. else if (state.head) {
  15390. state.head.name = null;
  15391. }
  15392. state.length = 0;
  15393. state.mode = COMMENT;
  15394. /* falls through */
  15395. case COMMENT:
  15396. if (state.flags & 0x1000) {
  15397. if (have === 0) { break inf_leave; }
  15398. copy = 0;
  15399. do {
  15400. len = input[next + copy++];
  15401. /* use constant limit because in js we should not preallocate memory */
  15402. if (state.head && len &&
  15403. (state.length < 65536 /*state.head.comm_max*/)) {
  15404. state.head.comment += String.fromCharCode(len);
  15405. }
  15406. } while (len && copy < have);
  15407. if (state.flags & 0x0200) {
  15408. state.check = crc32(state.check, input, copy, next);
  15409. }
  15410. have -= copy;
  15411. next += copy;
  15412. if (len) { break inf_leave; }
  15413. }
  15414. else if (state.head) {
  15415. state.head.comment = null;
  15416. }
  15417. state.mode = HCRC;
  15418. /* falls through */
  15419. case HCRC:
  15420. if (state.flags & 0x0200) {
  15421. //=== NEEDBITS(16); */
  15422. while (bits < 16) {
  15423. if (have === 0) { break inf_leave; }
  15424. have--;
  15425. hold += input[next++] << bits;
  15426. bits += 8;
  15427. }
  15428. //===//
  15429. if (hold !== (state.check & 0xffff)) {
  15430. strm.msg = 'header crc mismatch';
  15431. state.mode = BAD;
  15432. break;
  15433. }
  15434. //=== INITBITS();
  15435. hold = 0;
  15436. bits = 0;
  15437. //===//
  15438. }
  15439. if (state.head) {
  15440. state.head.hcrc = ((state.flags >> 9) & 1);
  15441. state.head.done = true;
  15442. }
  15443. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  15444. state.mode = TYPE;
  15445. break;
  15446. case DICTID:
  15447. //=== NEEDBITS(32); */
  15448. while (bits < 32) {
  15449. if (have === 0) { break inf_leave; }
  15450. have--;
  15451. hold += input[next++] << bits;
  15452. bits += 8;
  15453. }
  15454. //===//
  15455. strm.adler = state.check = ZSWAP32(hold);
  15456. //=== INITBITS();
  15457. hold = 0;
  15458. bits = 0;
  15459. //===//
  15460. state.mode = DICT;
  15461. /* falls through */
  15462. case DICT:
  15463. if (state.havedict === 0) {
  15464. //--- RESTORE() ---
  15465. strm.next_out = put;
  15466. strm.avail_out = left;
  15467. strm.next_in = next;
  15468. strm.avail_in = have;
  15469. state.hold = hold;
  15470. state.bits = bits;
  15471. //---
  15472. return Z_NEED_DICT;
  15473. }
  15474. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15475. state.mode = TYPE;
  15476. /* falls through */
  15477. case TYPE:
  15478. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  15479. /* falls through */
  15480. case TYPEDO:
  15481. if (state.last) {
  15482. //--- BYTEBITS() ---//
  15483. hold >>>= bits & 7;
  15484. bits -= bits & 7;
  15485. //---//
  15486. state.mode = CHECK;
  15487. break;
  15488. }
  15489. //=== NEEDBITS(3); */
  15490. while (bits < 3) {
  15491. if (have === 0) { break inf_leave; }
  15492. have--;
  15493. hold += input[next++] << bits;
  15494. bits += 8;
  15495. }
  15496. //===//
  15497. state.last = (hold & 0x01)/*BITS(1)*/;
  15498. //--- DROPBITS(1) ---//
  15499. hold >>>= 1;
  15500. bits -= 1;
  15501. //---//
  15502. switch ((hold & 0x03)/*BITS(2)*/) {
  15503. case 0: /* stored block */
  15504. //Tracev((stderr, "inflate: stored block%s\n",
  15505. // state.last ? " (last)" : ""));
  15506. state.mode = STORED;
  15507. break;
  15508. case 1: /* fixed block */
  15509. fixedtables(state);
  15510. //Tracev((stderr, "inflate: fixed codes block%s\n",
  15511. // state.last ? " (last)" : ""));
  15512. state.mode = LEN_; /* decode codes */
  15513. if (flush === Z_TREES) {
  15514. //--- DROPBITS(2) ---//
  15515. hold >>>= 2;
  15516. bits -= 2;
  15517. //---//
  15518. break inf_leave;
  15519. }
  15520. break;
  15521. case 2: /* dynamic block */
  15522. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  15523. // state.last ? " (last)" : ""));
  15524. state.mode = TABLE;
  15525. break;
  15526. case 3:
  15527. strm.msg = 'invalid block type';
  15528. state.mode = BAD;
  15529. }
  15530. //--- DROPBITS(2) ---//
  15531. hold >>>= 2;
  15532. bits -= 2;
  15533. //---//
  15534. break;
  15535. case STORED:
  15536. //--- BYTEBITS() ---// /* go to byte boundary */
  15537. hold >>>= bits & 7;
  15538. bits -= bits & 7;
  15539. //---//
  15540. //=== NEEDBITS(32); */
  15541. while (bits < 32) {
  15542. if (have === 0) { break inf_leave; }
  15543. have--;
  15544. hold += input[next++] << bits;
  15545. bits += 8;
  15546. }
  15547. //===//
  15548. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  15549. strm.msg = 'invalid stored block lengths';
  15550. state.mode = BAD;
  15551. break;
  15552. }
  15553. state.length = hold & 0xffff;
  15554. //Tracev((stderr, "inflate: stored length %u\n",
  15555. // state.length));
  15556. //=== INITBITS();
  15557. hold = 0;
  15558. bits = 0;
  15559. //===//
  15560. state.mode = COPY_;
  15561. if (flush === Z_TREES) { break inf_leave; }
  15562. /* falls through */
  15563. case COPY_:
  15564. state.mode = COPY;
  15565. /* falls through */
  15566. case COPY:
  15567. copy = state.length;
  15568. if (copy) {
  15569. if (copy > have) { copy = have; }
  15570. if (copy > left) { copy = left; }
  15571. if (copy === 0) { break inf_leave; }
  15572. //--- zmemcpy(put, next, copy); ---
  15573. utils.arraySet(output, input, next, copy, put);
  15574. //---//
  15575. have -= copy;
  15576. next += copy;
  15577. left -= copy;
  15578. put += copy;
  15579. state.length -= copy;
  15580. break;
  15581. }
  15582. //Tracev((stderr, "inflate: stored end\n"));
  15583. state.mode = TYPE;
  15584. break;
  15585. case TABLE:
  15586. //=== NEEDBITS(14); */
  15587. while (bits < 14) {
  15588. if (have === 0) { break inf_leave; }
  15589. have--;
  15590. hold += input[next++] << bits;
  15591. bits += 8;
  15592. }
  15593. //===//
  15594. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  15595. //--- DROPBITS(5) ---//
  15596. hold >>>= 5;
  15597. bits -= 5;
  15598. //---//
  15599. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  15600. //--- DROPBITS(5) ---//
  15601. hold >>>= 5;
  15602. bits -= 5;
  15603. //---//
  15604. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  15605. //--- DROPBITS(4) ---//
  15606. hold >>>= 4;
  15607. bits -= 4;
  15608. //---//
  15609. //#ifndef PKZIP_BUG_WORKAROUND
  15610. if (state.nlen > 286 || state.ndist > 30) {
  15611. strm.msg = 'too many length or distance symbols';
  15612. state.mode = BAD;
  15613. break;
  15614. }
  15615. //#endif
  15616. //Tracev((stderr, "inflate: table sizes ok\n"));
  15617. state.have = 0;
  15618. state.mode = LENLENS;
  15619. /* falls through */
  15620. case LENLENS:
  15621. while (state.have < state.ncode) {
  15622. //=== NEEDBITS(3);
  15623. while (bits < 3) {
  15624. if (have === 0) { break inf_leave; }
  15625. have--;
  15626. hold += input[next++] << bits;
  15627. bits += 8;
  15628. }
  15629. //===//
  15630. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  15631. //--- DROPBITS(3) ---//
  15632. hold >>>= 3;
  15633. bits -= 3;
  15634. //---//
  15635. }
  15636. while (state.have < 19) {
  15637. state.lens[order[state.have++]] = 0;
  15638. }
  15639. // We have separate tables & no pointers. 2 commented lines below not needed.
  15640. //state.next = state.codes;
  15641. //state.lencode = state.next;
  15642. // Switch to use dynamic table
  15643. state.lencode = state.lendyn;
  15644. state.lenbits = 7;
  15645. opts = {bits: state.lenbits};
  15646. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  15647. state.lenbits = opts.bits;
  15648. if (ret) {
  15649. strm.msg = 'invalid code lengths set';
  15650. state.mode = BAD;
  15651. break;
  15652. }
  15653. //Tracev((stderr, "inflate: code lengths ok\n"));
  15654. state.have = 0;
  15655. state.mode = CODELENS;
  15656. /* falls through */
  15657. case CODELENS:
  15658. while (state.have < state.nlen + state.ndist) {
  15659. for (;;) {
  15660. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  15661. here_bits = here >>> 24;
  15662. here_op = (here >>> 16) & 0xff;
  15663. here_val = here & 0xffff;
  15664. if ((here_bits) <= bits) { break; }
  15665. //--- PULLBYTE() ---//
  15666. if (have === 0) { break inf_leave; }
  15667. have--;
  15668. hold += input[next++] << bits;
  15669. bits += 8;
  15670. //---//
  15671. }
  15672. if (here_val < 16) {
  15673. //--- DROPBITS(here.bits) ---//
  15674. hold >>>= here_bits;
  15675. bits -= here_bits;
  15676. //---//
  15677. state.lens[state.have++] = here_val;
  15678. }
  15679. else {
  15680. if (here_val === 16) {
  15681. //=== NEEDBITS(here.bits + 2);
  15682. n = here_bits + 2;
  15683. while (bits < n) {
  15684. if (have === 0) { break inf_leave; }
  15685. have--;
  15686. hold += input[next++] << bits;
  15687. bits += 8;
  15688. }
  15689. //===//
  15690. //--- DROPBITS(here.bits) ---//
  15691. hold >>>= here_bits;
  15692. bits -= here_bits;
  15693. //---//
  15694. if (state.have === 0) {
  15695. strm.msg = 'invalid bit length repeat';
  15696. state.mode = BAD;
  15697. break;
  15698. }
  15699. len = state.lens[state.have - 1];
  15700. copy = 3 + (hold & 0x03);//BITS(2);
  15701. //--- DROPBITS(2) ---//
  15702. hold >>>= 2;
  15703. bits -= 2;
  15704. //---//
  15705. }
  15706. else if (here_val === 17) {
  15707. //=== NEEDBITS(here.bits + 3);
  15708. n = here_bits + 3;
  15709. while (bits < n) {
  15710. if (have === 0) { break inf_leave; }
  15711. have--;
  15712. hold += input[next++] << bits;
  15713. bits += 8;
  15714. }
  15715. //===//
  15716. //--- DROPBITS(here.bits) ---//
  15717. hold >>>= here_bits;
  15718. bits -= here_bits;
  15719. //---//
  15720. len = 0;
  15721. copy = 3 + (hold & 0x07);//BITS(3);
  15722. //--- DROPBITS(3) ---//
  15723. hold >>>= 3;
  15724. bits -= 3;
  15725. //---//
  15726. }
  15727. else {
  15728. //=== NEEDBITS(here.bits + 7);
  15729. n = here_bits + 7;
  15730. while (bits < n) {
  15731. if (have === 0) { break inf_leave; }
  15732. have--;
  15733. hold += input[next++] << bits;
  15734. bits += 8;
  15735. }
  15736. //===//
  15737. //--- DROPBITS(here.bits) ---//
  15738. hold >>>= here_bits;
  15739. bits -= here_bits;
  15740. //---//
  15741. len = 0;
  15742. copy = 11 + (hold & 0x7f);//BITS(7);
  15743. //--- DROPBITS(7) ---//
  15744. hold >>>= 7;
  15745. bits -= 7;
  15746. //---//
  15747. }
  15748. if (state.have + copy > state.nlen + state.ndist) {
  15749. strm.msg = 'invalid bit length repeat';
  15750. state.mode = BAD;
  15751. break;
  15752. }
  15753. while (copy--) {
  15754. state.lens[state.have++] = len;
  15755. }
  15756. }
  15757. }
  15758. /* handle error breaks in while */
  15759. if (state.mode === BAD) { break; }
  15760. /* check for end-of-block code (better have one) */
  15761. if (state.lens[256] === 0) {
  15762. strm.msg = 'invalid code -- missing end-of-block';
  15763. state.mode = BAD;
  15764. break;
  15765. }
  15766. /* build code tables -- note: do not change the lenbits or distbits
  15767. values here (9 and 6) without reading the comments in inftrees.h
  15768. concerning the ENOUGH constants, which depend on those values */
  15769. state.lenbits = 9;
  15770. opts = {bits: state.lenbits};
  15771. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  15772. // We have separate tables & no pointers. 2 commented lines below not needed.
  15773. // state.next_index = opts.table_index;
  15774. state.lenbits = opts.bits;
  15775. // state.lencode = state.next;
  15776. if (ret) {
  15777. strm.msg = 'invalid literal/lengths set';
  15778. state.mode = BAD;
  15779. break;
  15780. }
  15781. state.distbits = 6;
  15782. //state.distcode.copy(state.codes);
  15783. // Switch to use dynamic table
  15784. state.distcode = state.distdyn;
  15785. opts = {bits: state.distbits};
  15786. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  15787. // We have separate tables & no pointers. 2 commented lines below not needed.
  15788. // state.next_index = opts.table_index;
  15789. state.distbits = opts.bits;
  15790. // state.distcode = state.next;
  15791. if (ret) {
  15792. strm.msg = 'invalid distances set';
  15793. state.mode = BAD;
  15794. break;
  15795. }
  15796. //Tracev((stderr, 'inflate: codes ok\n'));
  15797. state.mode = LEN_;
  15798. if (flush === Z_TREES) { break inf_leave; }
  15799. /* falls through */
  15800. case LEN_:
  15801. state.mode = LEN;
  15802. /* falls through */
  15803. case LEN:
  15804. if (have >= 6 && left >= 258) {
  15805. //--- RESTORE() ---
  15806. strm.next_out = put;
  15807. strm.avail_out = left;
  15808. strm.next_in = next;
  15809. strm.avail_in = have;
  15810. state.hold = hold;
  15811. state.bits = bits;
  15812. //---
  15813. inflate_fast(strm, _out);
  15814. //--- LOAD() ---
  15815. put = strm.next_out;
  15816. output = strm.output;
  15817. left = strm.avail_out;
  15818. next = strm.next_in;
  15819. input = strm.input;
  15820. have = strm.avail_in;
  15821. hold = state.hold;
  15822. bits = state.bits;
  15823. //---
  15824. if (state.mode === TYPE) {
  15825. state.back = -1;
  15826. }
  15827. break;
  15828. }
  15829. state.back = 0;
  15830. for (;;) {
  15831. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  15832. here_bits = here >>> 24;
  15833. here_op = (here >>> 16) & 0xff;
  15834. here_val = here & 0xffff;
  15835. if (here_bits <= bits) { break; }
  15836. //--- PULLBYTE() ---//
  15837. if (have === 0) { break inf_leave; }
  15838. have--;
  15839. hold += input[next++] << bits;
  15840. bits += 8;
  15841. //---//
  15842. }
  15843. if (here_op && (here_op & 0xf0) === 0) {
  15844. last_bits = here_bits;
  15845. last_op = here_op;
  15846. last_val = here_val;
  15847. for (;;) {
  15848. here = state.lencode[last_val +
  15849. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  15850. here_bits = here >>> 24;
  15851. here_op = (here >>> 16) & 0xff;
  15852. here_val = here & 0xffff;
  15853. if ((last_bits + here_bits) <= bits) { break; }
  15854. //--- PULLBYTE() ---//
  15855. if (have === 0) { break inf_leave; }
  15856. have--;
  15857. hold += input[next++] << bits;
  15858. bits += 8;
  15859. //---//
  15860. }
  15861. //--- DROPBITS(last.bits) ---//
  15862. hold >>>= last_bits;
  15863. bits -= last_bits;
  15864. //---//
  15865. state.back += last_bits;
  15866. }
  15867. //--- DROPBITS(here.bits) ---//
  15868. hold >>>= here_bits;
  15869. bits -= here_bits;
  15870. //---//
  15871. state.back += here_bits;
  15872. state.length = here_val;
  15873. if (here_op === 0) {
  15874. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15875. // "inflate: literal '%c'\n" :
  15876. // "inflate: literal 0x%02x\n", here.val));
  15877. state.mode = LIT;
  15878. break;
  15879. }
  15880. if (here_op & 32) {
  15881. //Tracevv((stderr, "inflate: end of block\n"));
  15882. state.back = -1;
  15883. state.mode = TYPE;
  15884. break;
  15885. }
  15886. if (here_op & 64) {
  15887. strm.msg = 'invalid literal/length code';
  15888. state.mode = BAD;
  15889. break;
  15890. }
  15891. state.extra = here_op & 15;
  15892. state.mode = LENEXT;
  15893. /* falls through */
  15894. case LENEXT:
  15895. if (state.extra) {
  15896. //=== NEEDBITS(state.extra);
  15897. n = state.extra;
  15898. while (bits < n) {
  15899. if (have === 0) { break inf_leave; }
  15900. have--;
  15901. hold += input[next++] << bits;
  15902. bits += 8;
  15903. }
  15904. //===//
  15905. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  15906. //--- DROPBITS(state.extra) ---//
  15907. hold >>>= state.extra;
  15908. bits -= state.extra;
  15909. //---//
  15910. state.back += state.extra;
  15911. }
  15912. //Tracevv((stderr, "inflate: length %u\n", state.length));
  15913. state.was = state.length;
  15914. state.mode = DIST;
  15915. /* falls through */
  15916. case DIST:
  15917. for (;;) {
  15918. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  15919. here_bits = here >>> 24;
  15920. here_op = (here >>> 16) & 0xff;
  15921. here_val = here & 0xffff;
  15922. if ((here_bits) <= bits) { break; }
  15923. //--- PULLBYTE() ---//
  15924. if (have === 0) { break inf_leave; }
  15925. have--;
  15926. hold += input[next++] << bits;
  15927. bits += 8;
  15928. //---//
  15929. }
  15930. if ((here_op & 0xf0) === 0) {
  15931. last_bits = here_bits;
  15932. last_op = here_op;
  15933. last_val = here_val;
  15934. for (;;) {
  15935. here = state.distcode[last_val +
  15936. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  15937. here_bits = here >>> 24;
  15938. here_op = (here >>> 16) & 0xff;
  15939. here_val = here & 0xffff;
  15940. if ((last_bits + here_bits) <= bits) { break; }
  15941. //--- PULLBYTE() ---//
  15942. if (have === 0) { break inf_leave; }
  15943. have--;
  15944. hold += input[next++] << bits;
  15945. bits += 8;
  15946. //---//
  15947. }
  15948. //--- DROPBITS(last.bits) ---//
  15949. hold >>>= last_bits;
  15950. bits -= last_bits;
  15951. //---//
  15952. state.back += last_bits;
  15953. }
  15954. //--- DROPBITS(here.bits) ---//
  15955. hold >>>= here_bits;
  15956. bits -= here_bits;
  15957. //---//
  15958. state.back += here_bits;
  15959. if (here_op & 64) {
  15960. strm.msg = 'invalid distance code';
  15961. state.mode = BAD;
  15962. break;
  15963. }
  15964. state.offset = here_val;
  15965. state.extra = (here_op) & 15;
  15966. state.mode = DISTEXT;
  15967. /* falls through */
  15968. case DISTEXT:
  15969. if (state.extra) {
  15970. //=== NEEDBITS(state.extra);
  15971. n = state.extra;
  15972. while (bits < n) {
  15973. if (have === 0) { break inf_leave; }
  15974. have--;
  15975. hold += input[next++] << bits;
  15976. bits += 8;
  15977. }
  15978. //===//
  15979. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  15980. //--- DROPBITS(state.extra) ---//
  15981. hold >>>= state.extra;
  15982. bits -= state.extra;
  15983. //---//
  15984. state.back += state.extra;
  15985. }
  15986. //#ifdef INFLATE_STRICT
  15987. if (state.offset > state.dmax) {
  15988. strm.msg = 'invalid distance too far back';
  15989. state.mode = BAD;
  15990. break;
  15991. }
  15992. //#endif
  15993. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  15994. state.mode = MATCH;
  15995. /* falls through */
  15996. case MATCH:
  15997. if (left === 0) { break inf_leave; }
  15998. copy = _out - left;
  15999. if (state.offset > copy) { /* copy from window */
  16000. copy = state.offset - copy;
  16001. if (copy > state.whave) {
  16002. if (state.sane) {
  16003. strm.msg = 'invalid distance too far back';
  16004. state.mode = BAD;
  16005. break;
  16006. }
  16007. // (!) This block is disabled in zlib defailts,
  16008. // don't enable it for binary compatibility
  16009. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16010. // Trace((stderr, "inflate.c too far\n"));
  16011. // copy -= state.whave;
  16012. // if (copy > state.length) { copy = state.length; }
  16013. // if (copy > left) { copy = left; }
  16014. // left -= copy;
  16015. // state.length -= copy;
  16016. // do {
  16017. // output[put++] = 0;
  16018. // } while (--copy);
  16019. // if (state.length === 0) { state.mode = LEN; }
  16020. // break;
  16021. //#endif
  16022. }
  16023. if (copy > state.wnext) {
  16024. copy -= state.wnext;
  16025. from = state.wsize - copy;
  16026. }
  16027. else {
  16028. from = state.wnext - copy;
  16029. }
  16030. if (copy > state.length) { copy = state.length; }
  16031. from_source = state.window;
  16032. }
  16033. else { /* copy from output */
  16034. from_source = output;
  16035. from = put - state.offset;
  16036. copy = state.length;
  16037. }
  16038. if (copy > left) { copy = left; }
  16039. left -= copy;
  16040. state.length -= copy;
  16041. do {
  16042. output[put++] = from_source[from++];
  16043. } while (--copy);
  16044. if (state.length === 0) { state.mode = LEN; }
  16045. break;
  16046. case LIT:
  16047. if (left === 0) { break inf_leave; }
  16048. output[put++] = state.length;
  16049. left--;
  16050. state.mode = LEN;
  16051. break;
  16052. case CHECK:
  16053. if (state.wrap) {
  16054. //=== NEEDBITS(32);
  16055. while (bits < 32) {
  16056. if (have === 0) { break inf_leave; }
  16057. have--;
  16058. // Use '|' insdead of '+' to make sure that result is signed
  16059. hold |= input[next++] << bits;
  16060. bits += 8;
  16061. }
  16062. //===//
  16063. _out -= left;
  16064. strm.total_out += _out;
  16065. state.total += _out;
  16066. if (_out) {
  16067. strm.adler = state.check =
  16068. /*UPDATE(state.check, put - _out, _out);*/
  16069. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  16070. }
  16071. _out = left;
  16072. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  16073. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  16074. strm.msg = 'incorrect data check';
  16075. state.mode = BAD;
  16076. break;
  16077. }
  16078. //=== INITBITS();
  16079. hold = 0;
  16080. bits = 0;
  16081. //===//
  16082. //Tracev((stderr, "inflate: check matches trailer\n"));
  16083. }
  16084. state.mode = LENGTH;
  16085. /* falls through */
  16086. case LENGTH:
  16087. if (state.wrap && state.flags) {
  16088. //=== NEEDBITS(32);
  16089. while (bits < 32) {
  16090. if (have === 0) { break inf_leave; }
  16091. have--;
  16092. hold += input[next++] << bits;
  16093. bits += 8;
  16094. }
  16095. //===//
  16096. if (hold !== (state.total & 0xffffffff)) {
  16097. strm.msg = 'incorrect length check';
  16098. state.mode = BAD;
  16099. break;
  16100. }
  16101. //=== INITBITS();
  16102. hold = 0;
  16103. bits = 0;
  16104. //===//
  16105. //Tracev((stderr, "inflate: length matches trailer\n"));
  16106. }
  16107. state.mode = DONE;
  16108. /* falls through */
  16109. case DONE:
  16110. ret = Z_STREAM_END;
  16111. break inf_leave;
  16112. case BAD:
  16113. ret = Z_DATA_ERROR;
  16114. break inf_leave;
  16115. case MEM:
  16116. return Z_MEM_ERROR;
  16117. case SYNC:
  16118. /* falls through */
  16119. default:
  16120. return Z_STREAM_ERROR;
  16121. }
  16122. }
  16123. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  16124. /*
  16125. Return from inflate(), updating the total counts and the check value.
  16126. If there was no progress during the inflate() call, return a buffer
  16127. error. Call updatewindow() to create and/or update the window state.
  16128. Note: a memory error from inflate() is non-recoverable.
  16129. */
  16130. //--- RESTORE() ---
  16131. strm.next_out = put;
  16132. strm.avail_out = left;
  16133. strm.next_in = next;
  16134. strm.avail_in = have;
  16135. state.hold = hold;
  16136. state.bits = bits;
  16137. //---
  16138. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  16139. (state.mode < CHECK || flush !== Z_FINISH))) {
  16140. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  16141. state.mode = MEM;
  16142. return Z_MEM_ERROR;
  16143. }
  16144. }
  16145. _in -= strm.avail_in;
  16146. _out -= strm.avail_out;
  16147. strm.total_in += _in;
  16148. strm.total_out += _out;
  16149. state.total += _out;
  16150. if (state.wrap && _out) {
  16151. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  16152. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  16153. }
  16154. strm.data_type = state.bits + (state.last ? 64 : 0) +
  16155. (state.mode === TYPE ? 128 : 0) +
  16156. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  16157. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  16158. ret = Z_BUF_ERROR;
  16159. }
  16160. return ret;
  16161. }
  16162. function inflateEnd(strm) {
  16163. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  16164. return Z_STREAM_ERROR;
  16165. }
  16166. var state = strm.state;
  16167. if (state.window) {
  16168. state.window = null;
  16169. }
  16170. strm.state = null;
  16171. return Z_OK;
  16172. }
  16173. function inflateGetHeader(strm, head) {
  16174. var state;
  16175. /* check state */
  16176. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16177. state = strm.state;
  16178. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  16179. /* save header structure */
  16180. state.head = head;
  16181. head.done = false;
  16182. return Z_OK;
  16183. }
  16184. exports.inflateReset = inflateReset;
  16185. exports.inflateReset2 = inflateReset2;
  16186. exports.inflateResetKeep = inflateResetKeep;
  16187. exports.inflateInit = inflateInit;
  16188. exports.inflateInit2 = inflateInit2;
  16189. exports.inflate = inflate;
  16190. exports.inflateEnd = inflateEnd;
  16191. exports.inflateGetHeader = inflateGetHeader;
  16192. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  16193. /* Not implemented
  16194. exports.inflateCopy = inflateCopy;
  16195. exports.inflateGetDictionary = inflateGetDictionary;
  16196. exports.inflateMark = inflateMark;
  16197. exports.inflatePrime = inflatePrime;
  16198. exports.inflateSetDictionary = inflateSetDictionary;
  16199. exports.inflateSync = inflateSync;
  16200. exports.inflateSyncPoint = inflateSyncPoint;
  16201. exports.inflateUndermine = inflateUndermine;
  16202. */
  16203. },{"../utils/common":48,"./adler32":50,"./crc32":52,"./inffast":55,"./inftrees":57}],57:[function(require,module,exports){
  16204. 'use strict';
  16205. var utils = require('../utils/common');
  16206. var MAXBITS = 15;
  16207. var ENOUGH_LENS = 852;
  16208. var ENOUGH_DISTS = 592;
  16209. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16210. var CODES = 0;
  16211. var LENS = 1;
  16212. var DISTS = 2;
  16213. var lbase = [ /* Length codes 257..285 base */
  16214. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  16215. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  16216. ];
  16217. var lext = [ /* Length codes 257..285 extra */
  16218. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  16219. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  16220. ];
  16221. var dbase = [ /* Distance codes 0..29 base */
  16222. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  16223. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  16224. 8193, 12289, 16385, 24577, 0, 0
  16225. ];
  16226. var dext = [ /* Distance codes 0..29 extra */
  16227. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  16228. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  16229. 28, 28, 29, 29, 64, 64
  16230. ];
  16231. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  16232. {
  16233. var bits = opts.bits;
  16234. //here = opts.here; /* table entry for duplication */
  16235. var len = 0; /* a code's length in bits */
  16236. var sym = 0; /* index of code symbols */
  16237. var min = 0, max = 0; /* minimum and maximum code lengths */
  16238. var root = 0; /* number of index bits for root table */
  16239. var curr = 0; /* number of index bits for current table */
  16240. var drop = 0; /* code bits to drop for sub-table */
  16241. var left = 0; /* number of prefix codes available */
  16242. var used = 0; /* code entries in table used */
  16243. var huff = 0; /* Huffman code */
  16244. var incr; /* for incrementing code, index */
  16245. var fill; /* index for replicating entries */
  16246. var low; /* low bits for current root entry */
  16247. var mask; /* mask for low root bits */
  16248. var next; /* next available space in table */
  16249. var base = null; /* base value table to use */
  16250. var base_index = 0;
  16251. // var shoextra; /* extra bits table to use */
  16252. var end; /* use base and extra for symbol > end */
  16253. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  16254. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  16255. var extra = null;
  16256. var extra_index = 0;
  16257. var here_bits, here_op, here_val;
  16258. /*
  16259. Process a set of code lengths to create a canonical Huffman code. The
  16260. code lengths are lens[0..codes-1]. Each length corresponds to the
  16261. symbols 0..codes-1. The Huffman code is generated by first sorting the
  16262. symbols by length from short to long, and retaining the symbol order
  16263. for codes with equal lengths. Then the code starts with all zero bits
  16264. for the first code of the shortest length, and the codes are integer
  16265. increments for the same length, and zeros are appended as the length
  16266. increases. For the deflate format, these bits are stored backwards
  16267. from their more natural integer increment ordering, and so when the
  16268. decoding tables are built in the large loop below, the integer codes
  16269. are incremented backwards.
  16270. This routine assumes, but does not check, that all of the entries in
  16271. lens[] are in the range 0..MAXBITS. The caller must assure this.
  16272. 1..MAXBITS is interpreted as that code length. zero means that that
  16273. symbol does not occur in this code.
  16274. The codes are sorted by computing a count of codes for each length,
  16275. creating from that a table of starting indices for each length in the
  16276. sorted table, and then entering the symbols in order in the sorted
  16277. table. The sorted table is work[], with that space being provided by
  16278. the caller.
  16279. The length counts are used for other purposes as well, i.e. finding
  16280. the minimum and maximum length codes, determining if there are any
  16281. codes at all, checking for a valid set of lengths, and looking ahead
  16282. at length counts to determine sub-table sizes when building the
  16283. decoding tables.
  16284. */
  16285. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  16286. for (len = 0; len <= MAXBITS; len++) {
  16287. count[len] = 0;
  16288. }
  16289. for (sym = 0; sym < codes; sym++) {
  16290. count[lens[lens_index + sym]]++;
  16291. }
  16292. /* bound code lengths, force root to be within code lengths */
  16293. root = bits;
  16294. for (max = MAXBITS; max >= 1; max--) {
  16295. if (count[max] !== 0) { break; }
  16296. }
  16297. if (root > max) {
  16298. root = max;
  16299. }
  16300. if (max === 0) { /* no symbols to code at all */
  16301. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  16302. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  16303. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  16304. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16305. //table.op[opts.table_index] = 64;
  16306. //table.bits[opts.table_index] = 1;
  16307. //table.val[opts.table_index++] = 0;
  16308. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16309. opts.bits = 1;
  16310. return 0; /* no symbols, but wait for decoding to report error */
  16311. }
  16312. for (min = 1; min < max; min++) {
  16313. if (count[min] !== 0) { break; }
  16314. }
  16315. if (root < min) {
  16316. root = min;
  16317. }
  16318. /* check for an over-subscribed or incomplete set of lengths */
  16319. left = 1;
  16320. for (len = 1; len <= MAXBITS; len++) {
  16321. left <<= 1;
  16322. left -= count[len];
  16323. if (left < 0) {
  16324. return -1;
  16325. } /* over-subscribed */
  16326. }
  16327. if (left > 0 && (type === CODES || max !== 1)) {
  16328. return -1; /* incomplete set */
  16329. }
  16330. /* generate offsets into symbol table for each length for sorting */
  16331. offs[1] = 0;
  16332. for (len = 1; len < MAXBITS; len++) {
  16333. offs[len + 1] = offs[len] + count[len];
  16334. }
  16335. /* sort symbols by length, by symbol order within each length */
  16336. for (sym = 0; sym < codes; sym++) {
  16337. if (lens[lens_index + sym] !== 0) {
  16338. work[offs[lens[lens_index + sym]]++] = sym;
  16339. }
  16340. }
  16341. /*
  16342. Create and fill in decoding tables. In this loop, the table being
  16343. filled is at next and has curr index bits. The code being used is huff
  16344. with length len. That code is converted to an index by dropping drop
  16345. bits off of the bottom. For codes where len is less than drop + curr,
  16346. those top drop + curr - len bits are incremented through all values to
  16347. fill the table with replicated entries.
  16348. root is the number of index bits for the root table. When len exceeds
  16349. root, sub-tables are created pointed to by the root entry with an index
  16350. of the low root bits of huff. This is saved in low to check for when a
  16351. new sub-table should be started. drop is zero when the root table is
  16352. being filled, and drop is root when sub-tables are being filled.
  16353. When a new sub-table is needed, it is necessary to look ahead in the
  16354. code lengths to determine what size sub-table is needed. The length
  16355. counts are used for this, and so count[] is decremented as codes are
  16356. entered in the tables.
  16357. used keeps track of how many table entries have been allocated from the
  16358. provided *table space. It is checked for LENS and DIST tables against
  16359. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  16360. the initial root table size constants. See the comments in inftrees.h
  16361. for more information.
  16362. sym increments through all symbols, and the loop terminates when
  16363. all codes of length max, i.e. all codes, have been processed. This
  16364. routine permits incomplete codes, so another loop after this one fills
  16365. in the rest of the decoding tables with invalid code markers.
  16366. */
  16367. /* set up for code type */
  16368. // poor man optimization - use if-else instead of switch,
  16369. // to avoid deopts in old v8
  16370. if (type === CODES) {
  16371. base = extra = work; /* dummy value--not used */
  16372. end = 19;
  16373. } else if (type === LENS) {
  16374. base = lbase;
  16375. base_index -= 257;
  16376. extra = lext;
  16377. extra_index -= 257;
  16378. end = 256;
  16379. } else { /* DISTS */
  16380. base = dbase;
  16381. extra = dext;
  16382. end = -1;
  16383. }
  16384. /* initialize opts for loop */
  16385. huff = 0; /* starting code */
  16386. sym = 0; /* starting code symbol */
  16387. len = min; /* starting code length */
  16388. next = table_index; /* current table to fill in */
  16389. curr = root; /* current table index bits */
  16390. drop = 0; /* current bits to drop from code for index */
  16391. low = -1; /* trigger new sub-table when len > root */
  16392. used = 1 << root; /* use root table entries */
  16393. mask = used - 1; /* mask for comparing low */
  16394. /* check available table space */
  16395. if ((type === LENS && used > ENOUGH_LENS) ||
  16396. (type === DISTS && used > ENOUGH_DISTS)) {
  16397. return 1;
  16398. }
  16399. var i=0;
  16400. /* process all codes and make table entries */
  16401. for (;;) {
  16402. i++;
  16403. /* create table entry */
  16404. here_bits = len - drop;
  16405. if (work[sym] < end) {
  16406. here_op = 0;
  16407. here_val = work[sym];
  16408. }
  16409. else if (work[sym] > end) {
  16410. here_op = extra[extra_index + work[sym]];
  16411. here_val = base[base_index + work[sym]];
  16412. }
  16413. else {
  16414. here_op = 32 + 64; /* end of block */
  16415. here_val = 0;
  16416. }
  16417. /* replicate for those indices with low len bits equal to huff */
  16418. incr = 1 << (len - drop);
  16419. fill = 1 << curr;
  16420. min = fill; /* save offset to next table */
  16421. do {
  16422. fill -= incr;
  16423. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  16424. } while (fill !== 0);
  16425. /* backwards increment the len-bit code huff */
  16426. incr = 1 << (len - 1);
  16427. while (huff & incr) {
  16428. incr >>= 1;
  16429. }
  16430. if (incr !== 0) {
  16431. huff &= incr - 1;
  16432. huff += incr;
  16433. } else {
  16434. huff = 0;
  16435. }
  16436. /* go to next symbol, update count, len */
  16437. sym++;
  16438. if (--count[len] === 0) {
  16439. if (len === max) { break; }
  16440. len = lens[lens_index + work[sym]];
  16441. }
  16442. /* create new sub-table if needed */
  16443. if (len > root && (huff & mask) !== low) {
  16444. /* if first time, transition to sub-tables */
  16445. if (drop === 0) {
  16446. drop = root;
  16447. }
  16448. /* increment past last table */
  16449. next += min; /* here min is 1 << curr */
  16450. /* determine length of next table */
  16451. curr = len - drop;
  16452. left = 1 << curr;
  16453. while (curr + drop < max) {
  16454. left -= count[curr + drop];
  16455. if (left <= 0) { break; }
  16456. curr++;
  16457. left <<= 1;
  16458. }
  16459. /* check for enough space */
  16460. used += 1 << curr;
  16461. if ((type === LENS && used > ENOUGH_LENS) ||
  16462. (type === DISTS && used > ENOUGH_DISTS)) {
  16463. return 1;
  16464. }
  16465. /* point entry in root table to sub-table */
  16466. low = huff & mask;
  16467. /*table.op[low] = curr;
  16468. table.bits[low] = root;
  16469. table.val[low] = next - opts.table_index;*/
  16470. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  16471. }
  16472. }
  16473. /* fill in remaining table entry if code is incomplete (guaranteed to have
  16474. at most one remaining entry, since if the code is incomplete, the
  16475. maximum code length that was allowed to get this far is one bit) */
  16476. if (huff !== 0) {
  16477. //table.op[next + huff] = 64; /* invalid code marker */
  16478. //table.bits[next + huff] = len - drop;
  16479. //table.val[next + huff] = 0;
  16480. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  16481. }
  16482. /* set return parameters */
  16483. //opts.table_index += used;
  16484. opts.bits = root;
  16485. return 0;
  16486. };
  16487. },{"../utils/common":48}],58:[function(require,module,exports){
  16488. 'use strict';
  16489. module.exports = {
  16490. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  16491. '1': 'stream end', /* Z_STREAM_END 1 */
  16492. '0': '', /* Z_OK 0 */
  16493. '-1': 'file error', /* Z_ERRNO (-1) */
  16494. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  16495. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  16496. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  16497. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  16498. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  16499. };
  16500. },{}],59:[function(require,module,exports){
  16501. 'use strict';
  16502. var utils = require('../utils/common');
  16503. /* Public constants ==========================================================*/
  16504. /* ===========================================================================*/
  16505. //var Z_FILTERED = 1;
  16506. //var Z_HUFFMAN_ONLY = 2;
  16507. //var Z_RLE = 3;
  16508. var Z_FIXED = 4;
  16509. //var Z_DEFAULT_STRATEGY = 0;
  16510. /* Possible values of the data_type field (though see inflate()) */
  16511. var Z_BINARY = 0;
  16512. var Z_TEXT = 1;
  16513. //var Z_ASCII = 1; // = Z_TEXT
  16514. var Z_UNKNOWN = 2;
  16515. /*============================================================================*/
  16516. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  16517. // From zutil.h
  16518. var STORED_BLOCK = 0;
  16519. var STATIC_TREES = 1;
  16520. var DYN_TREES = 2;
  16521. /* The three kinds of block type */
  16522. var MIN_MATCH = 3;
  16523. var MAX_MATCH = 258;
  16524. /* The minimum and maximum match lengths */
  16525. // From deflate.h
  16526. /* ===========================================================================
  16527. * Internal compression state.
  16528. */
  16529. var LENGTH_CODES = 29;
  16530. /* number of length codes, not counting the special END_BLOCK code */
  16531. var LITERALS = 256;
  16532. /* number of literal bytes 0..255 */
  16533. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  16534. /* number of Literal or Length codes, including the END_BLOCK code */
  16535. var D_CODES = 30;
  16536. /* number of distance codes */
  16537. var BL_CODES = 19;
  16538. /* number of codes used to transfer the bit lengths */
  16539. var HEAP_SIZE = 2*L_CODES + 1;
  16540. /* maximum heap size */
  16541. var MAX_BITS = 15;
  16542. /* All codes must not exceed MAX_BITS bits */
  16543. var Buf_size = 16;
  16544. /* size of bit buffer in bi_buf */
  16545. /* ===========================================================================
  16546. * Constants
  16547. */
  16548. var MAX_BL_BITS = 7;
  16549. /* Bit length codes must not exceed MAX_BL_BITS bits */
  16550. var END_BLOCK = 256;
  16551. /* end of block literal code */
  16552. var REP_3_6 = 16;
  16553. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  16554. var REPZ_3_10 = 17;
  16555. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  16556. var REPZ_11_138 = 18;
  16557. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  16558. var extra_lbits = /* extra bits for each length code */
  16559. [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];
  16560. var extra_dbits = /* extra bits for each distance code */
  16561. [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];
  16562. var extra_blbits = /* extra bits for each bit length code */
  16563. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  16564. var bl_order =
  16565. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  16566. /* The lengths of the bit length codes are sent in order of decreasing
  16567. * probability, to avoid transmitting the lengths for unused bit length codes.
  16568. */
  16569. /* ===========================================================================
  16570. * Local data. These are initialized only once.
  16571. */
  16572. // We pre-fill arrays with 0 to avoid uninitialized gaps
  16573. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  16574. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  16575. var static_ltree = new Array((L_CODES+2) * 2);
  16576. zero(static_ltree);
  16577. /* The static literal tree. Since the bit lengths are imposed, there is no
  16578. * need for the L_CODES extra codes used during heap construction. However
  16579. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  16580. * below).
  16581. */
  16582. var static_dtree = new Array(D_CODES * 2);
  16583. zero(static_dtree);
  16584. /* The static distance tree. (Actually a trivial tree since all codes use
  16585. * 5 bits.)
  16586. */
  16587. var _dist_code = new Array(DIST_CODE_LEN);
  16588. zero(_dist_code);
  16589. /* Distance codes. The first 256 values correspond to the distances
  16590. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  16591. * the 15 bit distances.
  16592. */
  16593. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  16594. zero(_length_code);
  16595. /* length code for each normalized match length (0 == MIN_MATCH) */
  16596. var base_length = new Array(LENGTH_CODES);
  16597. zero(base_length);
  16598. /* First normalized length for each code (0 = MIN_MATCH) */
  16599. var base_dist = new Array(D_CODES);
  16600. zero(base_dist);
  16601. /* First normalized distance for each code (0 = distance of 1) */
  16602. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  16603. this.static_tree = static_tree; /* static tree or NULL */
  16604. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  16605. this.extra_base = extra_base; /* base index for extra_bits */
  16606. this.elems = elems; /* max number of elements in the tree */
  16607. this.max_length = max_length; /* max bit length for the codes */
  16608. // show if `static_tree` has data or dummy - needed for monomorphic objects
  16609. this.has_stree = static_tree && static_tree.length;
  16610. };
  16611. var static_l_desc;
  16612. var static_d_desc;
  16613. var static_bl_desc;
  16614. var TreeDesc = function(dyn_tree, stat_desc) {
  16615. this.dyn_tree = dyn_tree; /* the dynamic tree */
  16616. this.max_code = 0; /* largest code with non zero frequency */
  16617. this.stat_desc = stat_desc; /* the corresponding static tree */
  16618. };
  16619. function d_code(dist) {
  16620. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  16621. }
  16622. /* ===========================================================================
  16623. * Output a short LSB first on the stream.
  16624. * IN assertion: there is enough room in pendingBuf.
  16625. */
  16626. function put_short (s, w) {
  16627. // put_byte(s, (uch)((w) & 0xff));
  16628. // put_byte(s, (uch)((ush)(w) >> 8));
  16629. s.pending_buf[s.pending++] = (w) & 0xff;
  16630. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  16631. }
  16632. /* ===========================================================================
  16633. * Send a value on a given number of bits.
  16634. * IN assertion: length <= 16 and value fits in length bits.
  16635. */
  16636. function send_bits(s, value, length) {
  16637. if (s.bi_valid > (Buf_size - length)) {
  16638. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  16639. put_short(s, s.bi_buf);
  16640. s.bi_buf = value >> (Buf_size - s.bi_valid);
  16641. s.bi_valid += length - Buf_size;
  16642. } else {
  16643. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  16644. s.bi_valid += length;
  16645. }
  16646. }
  16647. function send_code(s, c, tree) {
  16648. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  16649. }
  16650. /* ===========================================================================
  16651. * Reverse the first len bits of a code, using straightforward code (a faster
  16652. * method would use a table)
  16653. * IN assertion: 1 <= len <= 15
  16654. */
  16655. function bi_reverse(code, len) {
  16656. var res = 0;
  16657. do {
  16658. res |= code & 1;
  16659. code >>>= 1;
  16660. res <<= 1;
  16661. } while (--len > 0);
  16662. return res >>> 1;
  16663. }
  16664. /* ===========================================================================
  16665. * Flush the bit buffer, keeping at most 7 bits in it.
  16666. */
  16667. function bi_flush(s) {
  16668. if (s.bi_valid === 16) {
  16669. put_short(s, s.bi_buf);
  16670. s.bi_buf = 0;
  16671. s.bi_valid = 0;
  16672. } else if (s.bi_valid >= 8) {
  16673. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  16674. s.bi_buf >>= 8;
  16675. s.bi_valid -= 8;
  16676. }
  16677. }
  16678. /* ===========================================================================
  16679. * Compute the optimal bit lengths for a tree and update the total bit length
  16680. * for the current block.
  16681. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  16682. * above are the tree nodes sorted by increasing frequency.
  16683. * OUT assertions: the field len is set to the optimal bit length, the
  16684. * array bl_count contains the frequencies for each bit length.
  16685. * The length opt_len is updated; static_len is also updated if stree is
  16686. * not null.
  16687. */
  16688. function gen_bitlen(s, desc)
  16689. // deflate_state *s;
  16690. // tree_desc *desc; /* the tree descriptor */
  16691. {
  16692. var tree = desc.dyn_tree;
  16693. var max_code = desc.max_code;
  16694. var stree = desc.stat_desc.static_tree;
  16695. var has_stree = desc.stat_desc.has_stree;
  16696. var extra = desc.stat_desc.extra_bits;
  16697. var base = desc.stat_desc.extra_base;
  16698. var max_length = desc.stat_desc.max_length;
  16699. var h; /* heap index */
  16700. var n, m; /* iterate over the tree elements */
  16701. var bits; /* bit length */
  16702. var xbits; /* extra bits */
  16703. var f; /* frequency */
  16704. var overflow = 0; /* number of elements with bit length too large */
  16705. for (bits = 0; bits <= MAX_BITS; bits++) {
  16706. s.bl_count[bits] = 0;
  16707. }
  16708. /* In a first pass, compute the optimal bit lengths (which may
  16709. * overflow in the case of the bit length tree).
  16710. */
  16711. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  16712. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  16713. n = s.heap[h];
  16714. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  16715. if (bits > max_length) {
  16716. bits = max_length;
  16717. overflow++;
  16718. }
  16719. tree[n*2 + 1]/*.Len*/ = bits;
  16720. /* We overwrite tree[n].Dad which is no longer needed */
  16721. if (n > max_code) { continue; } /* not a leaf node */
  16722. s.bl_count[bits]++;
  16723. xbits = 0;
  16724. if (n >= base) {
  16725. xbits = extra[n-base];
  16726. }
  16727. f = tree[n * 2]/*.Freq*/;
  16728. s.opt_len += f * (bits + xbits);
  16729. if (has_stree) {
  16730. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  16731. }
  16732. }
  16733. if (overflow === 0) { return; }
  16734. // Trace((stderr,"\nbit length overflow\n"));
  16735. /* This happens for example on obj2 and pic of the Calgary corpus */
  16736. /* Find the first bit length which could increase: */
  16737. do {
  16738. bits = max_length-1;
  16739. while (s.bl_count[bits] === 0) { bits--; }
  16740. s.bl_count[bits]--; /* move one leaf down the tree */
  16741. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  16742. s.bl_count[max_length]--;
  16743. /* The brother of the overflow item also moves one step up,
  16744. * but this does not affect bl_count[max_length]
  16745. */
  16746. overflow -= 2;
  16747. } while (overflow > 0);
  16748. /* Now recompute all bit lengths, scanning in increasing frequency.
  16749. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  16750. * lengths instead of fixing only the wrong ones. This idea is taken
  16751. * from 'ar' written by Haruhiko Okumura.)
  16752. */
  16753. for (bits = max_length; bits !== 0; bits--) {
  16754. n = s.bl_count[bits];
  16755. while (n !== 0) {
  16756. m = s.heap[--h];
  16757. if (m > max_code) { continue; }
  16758. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  16759. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  16760. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  16761. tree[m*2 + 1]/*.Len*/ = bits;
  16762. }
  16763. n--;
  16764. }
  16765. }
  16766. }
  16767. /* ===========================================================================
  16768. * Generate the codes for a given tree and bit counts (which need not be
  16769. * optimal).
  16770. * IN assertion: the array bl_count contains the bit length statistics for
  16771. * the given tree and the field len is set for all tree elements.
  16772. * OUT assertion: the field code is set for all tree elements of non
  16773. * zero code length.
  16774. */
  16775. function gen_codes(tree, max_code, bl_count)
  16776. // ct_data *tree; /* the tree to decorate */
  16777. // int max_code; /* largest code with non zero frequency */
  16778. // ushf *bl_count; /* number of codes at each bit length */
  16779. {
  16780. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  16781. var code = 0; /* running code value */
  16782. var bits; /* bit index */
  16783. var n; /* code index */
  16784. /* The distribution counts are first used to generate the code values
  16785. * without bit reversal.
  16786. */
  16787. for (bits = 1; bits <= MAX_BITS; bits++) {
  16788. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  16789. }
  16790. /* Check that the bit counts in bl_count are consistent. The last code
  16791. * must be all ones.
  16792. */
  16793. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  16794. // "inconsistent bit counts");
  16795. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  16796. for (n = 0; n <= max_code; n++) {
  16797. var len = tree[n*2 + 1]/*.Len*/;
  16798. if (len === 0) { continue; }
  16799. /* Now reverse the bits */
  16800. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  16801. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  16802. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  16803. }
  16804. }
  16805. /* ===========================================================================
  16806. * Initialize the various 'constant' tables.
  16807. */
  16808. function tr_static_init() {
  16809. var n; /* iterates over tree elements */
  16810. var bits; /* bit counter */
  16811. var length; /* length value */
  16812. var code; /* code value */
  16813. var dist; /* distance index */
  16814. var bl_count = new Array(MAX_BITS+1);
  16815. /* number of codes at each bit length for an optimal tree */
  16816. // do check in _tr_init()
  16817. //if (static_init_done) return;
  16818. /* For some embedded targets, global variables are not initialized: */
  16819. /*#ifdef NO_INIT_GLOBAL_POINTERS
  16820. static_l_desc.static_tree = static_ltree;
  16821. static_l_desc.extra_bits = extra_lbits;
  16822. static_d_desc.static_tree = static_dtree;
  16823. static_d_desc.extra_bits = extra_dbits;
  16824. static_bl_desc.extra_bits = extra_blbits;
  16825. #endif*/
  16826. /* Initialize the mapping length (0..255) -> length code (0..28) */
  16827. length = 0;
  16828. for (code = 0; code < LENGTH_CODES-1; code++) {
  16829. base_length[code] = length;
  16830. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  16831. _length_code[length++] = code;
  16832. }
  16833. }
  16834. //Assert (length == 256, "tr_static_init: length != 256");
  16835. /* Note that the length 255 (match length 258) can be represented
  16836. * in two different ways: code 284 + 5 bits or code 285, so we
  16837. * overwrite length_code[255] to use the best encoding:
  16838. */
  16839. _length_code[length-1] = code;
  16840. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  16841. dist = 0;
  16842. for (code = 0 ; code < 16; code++) {
  16843. base_dist[code] = dist;
  16844. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  16845. _dist_code[dist++] = code;
  16846. }
  16847. }
  16848. //Assert (dist == 256, "tr_static_init: dist != 256");
  16849. dist >>= 7; /* from now on, all distances are divided by 128 */
  16850. for (; code < D_CODES; code++) {
  16851. base_dist[code] = dist << 7;
  16852. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  16853. _dist_code[256 + dist++] = code;
  16854. }
  16855. }
  16856. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  16857. /* Construct the codes of the static literal tree */
  16858. for (bits = 0; bits <= MAX_BITS; bits++) {
  16859. bl_count[bits] = 0;
  16860. }
  16861. n = 0;
  16862. while (n <= 143) {
  16863. static_ltree[n*2 + 1]/*.Len*/ = 8;
  16864. n++;
  16865. bl_count[8]++;
  16866. }
  16867. while (n <= 255) {
  16868. static_ltree[n*2 + 1]/*.Len*/ = 9;
  16869. n++;
  16870. bl_count[9]++;
  16871. }
  16872. while (n <= 279) {
  16873. static_ltree[n*2 + 1]/*.Len*/ = 7;
  16874. n++;
  16875. bl_count[7]++;
  16876. }
  16877. while (n <= 287) {
  16878. static_ltree[n*2 + 1]/*.Len*/ = 8;
  16879. n++;
  16880. bl_count[8]++;
  16881. }
  16882. /* Codes 286 and 287 do not exist, but we must include them in the
  16883. * tree construction to get a canonical Huffman tree (longest code
  16884. * all ones)
  16885. */
  16886. gen_codes(static_ltree, L_CODES+1, bl_count);
  16887. /* The static distance tree is trivial: */
  16888. for (n = 0; n < D_CODES; n++) {
  16889. static_dtree[n*2 + 1]/*.Len*/ = 5;
  16890. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  16891. }
  16892. // Now data ready and we can init static trees
  16893. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  16894. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  16895. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  16896. //static_init_done = true;
  16897. }
  16898. /* ===========================================================================
  16899. * Initialize a new block.
  16900. */
  16901. function init_block(s) {
  16902. var n; /* iterates over tree elements */
  16903. /* Initialize the trees. */
  16904. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  16905. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  16906. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  16907. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  16908. s.opt_len = s.static_len = 0;
  16909. s.last_lit = s.matches = 0;
  16910. }
  16911. /* ===========================================================================
  16912. * Flush the bit buffer and align the output on a byte boundary
  16913. */
  16914. function bi_windup(s)
  16915. {
  16916. if (s.bi_valid > 8) {
  16917. put_short(s, s.bi_buf);
  16918. } else if (s.bi_valid > 0) {
  16919. //put_byte(s, (Byte)s->bi_buf);
  16920. s.pending_buf[s.pending++] = s.bi_buf;
  16921. }
  16922. s.bi_buf = 0;
  16923. s.bi_valid = 0;
  16924. }
  16925. /* ===========================================================================
  16926. * Copy a stored block, storing first the length and its
  16927. * one's complement if requested.
  16928. */
  16929. function copy_block(s, buf, len, header)
  16930. //DeflateState *s;
  16931. //charf *buf; /* the input data */
  16932. //unsigned len; /* its length */
  16933. //int header; /* true if block header must be written */
  16934. {
  16935. bi_windup(s); /* align on byte boundary */
  16936. if (header) {
  16937. put_short(s, len);
  16938. put_short(s, ~len);
  16939. }
  16940. // while (len--) {
  16941. // put_byte(s, *buf++);
  16942. // }
  16943. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  16944. s.pending += len;
  16945. }
  16946. /* ===========================================================================
  16947. * Compares to subtrees, using the tree depth as tie breaker when
  16948. * the subtrees have equal frequency. This minimizes the worst case length.
  16949. */
  16950. function smaller(tree, n, m, depth) {
  16951. var _n2 = n*2;
  16952. var _m2 = m*2;
  16953. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  16954. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  16955. }
  16956. /* ===========================================================================
  16957. * Restore the heap property by moving down the tree starting at node k,
  16958. * exchanging a node with the smallest of its two sons if necessary, stopping
  16959. * when the heap property is re-established (each father smaller than its
  16960. * two sons).
  16961. */
  16962. function pqdownheap(s, tree, k)
  16963. // deflate_state *s;
  16964. // ct_data *tree; /* the tree to restore */
  16965. // int k; /* node to move down */
  16966. {
  16967. var v = s.heap[k];
  16968. var j = k << 1; /* left son of k */
  16969. while (j <= s.heap_len) {
  16970. /* Set j to the smallest of the two sons: */
  16971. if (j < s.heap_len &&
  16972. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  16973. j++;
  16974. }
  16975. /* Exit if v is smaller than both sons */
  16976. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  16977. /* Exchange v with the smallest son */
  16978. s.heap[k] = s.heap[j];
  16979. k = j;
  16980. /* And continue down the tree, setting j to the left son of k */
  16981. j <<= 1;
  16982. }
  16983. s.heap[k] = v;
  16984. }
  16985. // inlined manually
  16986. // var SMALLEST = 1;
  16987. /* ===========================================================================
  16988. * Send the block data compressed using the given Huffman trees
  16989. */
  16990. function compress_block(s, ltree, dtree)
  16991. // deflate_state *s;
  16992. // const ct_data *ltree; /* literal tree */
  16993. // const ct_data *dtree; /* distance tree */
  16994. {
  16995. var dist; /* distance of matched string */
  16996. var lc; /* match length or unmatched char (if dist == 0) */
  16997. var lx = 0; /* running index in l_buf */
  16998. var code; /* the code to send */
  16999. var extra; /* number of extra bits to send */
  17000. if (s.last_lit !== 0) {
  17001. do {
  17002. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  17003. lc = s.pending_buf[s.l_buf + lx];
  17004. lx++;
  17005. if (dist === 0) {
  17006. send_code(s, lc, ltree); /* send a literal byte */
  17007. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  17008. } else {
  17009. /* Here, lc is the match length - MIN_MATCH */
  17010. code = _length_code[lc];
  17011. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  17012. extra = extra_lbits[code];
  17013. if (extra !== 0) {
  17014. lc -= base_length[code];
  17015. send_bits(s, lc, extra); /* send the extra length bits */
  17016. }
  17017. dist--; /* dist is now the match distance - 1 */
  17018. code = d_code(dist);
  17019. //Assert (code < D_CODES, "bad d_code");
  17020. send_code(s, code, dtree); /* send the distance code */
  17021. extra = extra_dbits[code];
  17022. if (extra !== 0) {
  17023. dist -= base_dist[code];
  17024. send_bits(s, dist, extra); /* send the extra distance bits */
  17025. }
  17026. } /* literal or match pair ? */
  17027. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  17028. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  17029. // "pendingBuf overflow");
  17030. } while (lx < s.last_lit);
  17031. }
  17032. send_code(s, END_BLOCK, ltree);
  17033. }
  17034. /* ===========================================================================
  17035. * Construct one Huffman tree and assigns the code bit strings and lengths.
  17036. * Update the total bit length for the current block.
  17037. * IN assertion: the field freq is set for all tree elements.
  17038. * OUT assertions: the fields len and code are set to the optimal bit length
  17039. * and corresponding code. The length opt_len is updated; static_len is
  17040. * also updated if stree is not null. The field max_code is set.
  17041. */
  17042. function build_tree(s, desc)
  17043. // deflate_state *s;
  17044. // tree_desc *desc; /* the tree descriptor */
  17045. {
  17046. var tree = desc.dyn_tree;
  17047. var stree = desc.stat_desc.static_tree;
  17048. var has_stree = desc.stat_desc.has_stree;
  17049. var elems = desc.stat_desc.elems;
  17050. var n, m; /* iterate over heap elements */
  17051. var max_code = -1; /* largest code with non zero frequency */
  17052. var node; /* new node being created */
  17053. /* Construct the initial heap, with least frequent element in
  17054. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17055. * heap[0] is not used.
  17056. */
  17057. s.heap_len = 0;
  17058. s.heap_max = HEAP_SIZE;
  17059. for (n = 0; n < elems; n++) {
  17060. if (tree[n * 2]/*.Freq*/ !== 0) {
  17061. s.heap[++s.heap_len] = max_code = n;
  17062. s.depth[n] = 0;
  17063. } else {
  17064. tree[n*2 + 1]/*.Len*/ = 0;
  17065. }
  17066. }
  17067. /* The pkzip format requires that at least one distance code exists,
  17068. * and that at least one bit should be sent even if there is only one
  17069. * possible code. So to avoid special checks later on we force at least
  17070. * two codes of non zero frequency.
  17071. */
  17072. while (s.heap_len < 2) {
  17073. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  17074. tree[node * 2]/*.Freq*/ = 1;
  17075. s.depth[node] = 0;
  17076. s.opt_len--;
  17077. if (has_stree) {
  17078. s.static_len -= stree[node*2 + 1]/*.Len*/;
  17079. }
  17080. /* node is 0 or 1 so it does not have extra bits */
  17081. }
  17082. desc.max_code = max_code;
  17083. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17084. * establish sub-heaps of increasing lengths:
  17085. */
  17086. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  17087. /* Construct the Huffman tree by repeatedly combining the least two
  17088. * frequent nodes.
  17089. */
  17090. node = elems; /* next internal node of the tree */
  17091. do {
  17092. //pqremove(s, tree, n); /* n = node of least frequency */
  17093. /*** pqremove ***/
  17094. n = s.heap[1/*SMALLEST*/];
  17095. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  17096. pqdownheap(s, tree, 1/*SMALLEST*/);
  17097. /***/
  17098. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  17099. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  17100. s.heap[--s.heap_max] = m;
  17101. /* Create a new node father of n and m */
  17102. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  17103. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  17104. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  17105. /* and insert the new node in the heap */
  17106. s.heap[1/*SMALLEST*/] = node++;
  17107. pqdownheap(s, tree, 1/*SMALLEST*/);
  17108. } while (s.heap_len >= 2);
  17109. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  17110. /* At this point, the fields freq and dad are set. We can now
  17111. * generate the bit lengths.
  17112. */
  17113. gen_bitlen(s, desc);
  17114. /* The field len is now set, we can generate the bit codes */
  17115. gen_codes(tree, max_code, s.bl_count);
  17116. }
  17117. /* ===========================================================================
  17118. * Scan a literal or distance tree to determine the frequencies of the codes
  17119. * in the bit length tree.
  17120. */
  17121. function scan_tree(s, tree, max_code)
  17122. // deflate_state *s;
  17123. // ct_data *tree; /* the tree to be scanned */
  17124. // int max_code; /* and its largest code of non zero frequency */
  17125. {
  17126. var n; /* iterates over all tree elements */
  17127. var prevlen = -1; /* last emitted length */
  17128. var curlen; /* length of current code */
  17129. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17130. var count = 0; /* repeat count of the current code */
  17131. var max_count = 7; /* max repeat count */
  17132. var min_count = 4; /* min repeat count */
  17133. if (nextlen === 0) {
  17134. max_count = 138;
  17135. min_count = 3;
  17136. }
  17137. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  17138. for (n = 0; n <= max_code; n++) {
  17139. curlen = nextlen;
  17140. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17141. if (++count < max_count && curlen === nextlen) {
  17142. continue;
  17143. } else if (count < min_count) {
  17144. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  17145. } else if (curlen !== 0) {
  17146. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  17147. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  17148. } else if (count <= 10) {
  17149. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  17150. } else {
  17151. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  17152. }
  17153. count = 0;
  17154. prevlen = curlen;
  17155. if (nextlen === 0) {
  17156. max_count = 138;
  17157. min_count = 3;
  17158. } else if (curlen === nextlen) {
  17159. max_count = 6;
  17160. min_count = 3;
  17161. } else {
  17162. max_count = 7;
  17163. min_count = 4;
  17164. }
  17165. }
  17166. }
  17167. /* ===========================================================================
  17168. * Send a literal or distance tree in compressed form, using the codes in
  17169. * bl_tree.
  17170. */
  17171. function send_tree(s, tree, max_code)
  17172. // deflate_state *s;
  17173. // ct_data *tree; /* the tree to be scanned */
  17174. // int max_code; /* and its largest code of non zero frequency */
  17175. {
  17176. var n; /* iterates over all tree elements */
  17177. var prevlen = -1; /* last emitted length */
  17178. var curlen; /* length of current code */
  17179. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17180. var count = 0; /* repeat count of the current code */
  17181. var max_count = 7; /* max repeat count */
  17182. var min_count = 4; /* min repeat count */
  17183. /* tree[max_code+1].Len = -1; */ /* guard already set */
  17184. if (nextlen === 0) {
  17185. max_count = 138;
  17186. min_count = 3;
  17187. }
  17188. for (n = 0; n <= max_code; n++) {
  17189. curlen = nextlen;
  17190. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17191. if (++count < max_count && curlen === nextlen) {
  17192. continue;
  17193. } else if (count < min_count) {
  17194. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  17195. } else if (curlen !== 0) {
  17196. if (curlen !== prevlen) {
  17197. send_code(s, curlen, s.bl_tree);
  17198. count--;
  17199. }
  17200. //Assert(count >= 3 && count <= 6, " 3_6?");
  17201. send_code(s, REP_3_6, s.bl_tree);
  17202. send_bits(s, count-3, 2);
  17203. } else if (count <= 10) {
  17204. send_code(s, REPZ_3_10, s.bl_tree);
  17205. send_bits(s, count-3, 3);
  17206. } else {
  17207. send_code(s, REPZ_11_138, s.bl_tree);
  17208. send_bits(s, count-11, 7);
  17209. }
  17210. count = 0;
  17211. prevlen = curlen;
  17212. if (nextlen === 0) {
  17213. max_count = 138;
  17214. min_count = 3;
  17215. } else if (curlen === nextlen) {
  17216. max_count = 6;
  17217. min_count = 3;
  17218. } else {
  17219. max_count = 7;
  17220. min_count = 4;
  17221. }
  17222. }
  17223. }
  17224. /* ===========================================================================
  17225. * Construct the Huffman tree for the bit lengths and return the index in
  17226. * bl_order of the last bit length code to send.
  17227. */
  17228. function build_bl_tree(s) {
  17229. var max_blindex; /* index of last bit length code of non zero freq */
  17230. /* Determine the bit length frequencies for literal and distance trees */
  17231. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  17232. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  17233. /* Build the bit length tree: */
  17234. build_tree(s, s.bl_desc);
  17235. /* opt_len now includes the length of the tree representations, except
  17236. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  17237. */
  17238. /* Determine the number of bit length codes to send. The pkzip format
  17239. * requires that at least 4 bit length codes be sent. (appnote.txt says
  17240. * 3 but the actual value used is 4.)
  17241. */
  17242. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  17243. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  17244. break;
  17245. }
  17246. }
  17247. /* Update opt_len to include the bit length tree and counts */
  17248. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  17249. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  17250. // s->opt_len, s->static_len));
  17251. return max_blindex;
  17252. }
  17253. /* ===========================================================================
  17254. * Send the header for a block using dynamic Huffman trees: the counts, the
  17255. * lengths of the bit length codes, the literal tree and the distance tree.
  17256. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  17257. */
  17258. function send_all_trees(s, lcodes, dcodes, blcodes)
  17259. // deflate_state *s;
  17260. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  17261. {
  17262. var rank; /* index in bl_order */
  17263. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  17264. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  17265. // "too many codes");
  17266. //Tracev((stderr, "\nbl counts: "));
  17267. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  17268. send_bits(s, dcodes-1, 5);
  17269. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  17270. for (rank = 0; rank < blcodes; rank++) {
  17271. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  17272. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  17273. }
  17274. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  17275. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  17276. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  17277. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  17278. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  17279. }
  17280. /* ===========================================================================
  17281. * Check if the data type is TEXT or BINARY, using the following algorithm:
  17282. * - TEXT if the two conditions below are satisfied:
  17283. * a) There are no non-portable control characters belonging to the
  17284. * "black list" (0..6, 14..25, 28..31).
  17285. * b) There is at least one printable character belonging to the
  17286. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  17287. * - BINARY otherwise.
  17288. * - The following partially-portable control characters form a
  17289. * "gray list" that is ignored in this detection algorithm:
  17290. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  17291. * IN assertion: the fields Freq of dyn_ltree are set.
  17292. */
  17293. function detect_data_type(s) {
  17294. /* black_mask is the bit mask of black-listed bytes
  17295. * set bits 0..6, 14..25, and 28..31
  17296. * 0xf3ffc07f = binary 11110011111111111100000001111111
  17297. */
  17298. var black_mask = 0xf3ffc07f;
  17299. var n;
  17300. /* Check for non-textual ("black-listed") bytes. */
  17301. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  17302. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  17303. return Z_BINARY;
  17304. }
  17305. }
  17306. /* Check for textual ("white-listed") bytes. */
  17307. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  17308. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  17309. return Z_TEXT;
  17310. }
  17311. for (n = 32; n < LITERALS; n++) {
  17312. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  17313. return Z_TEXT;
  17314. }
  17315. }
  17316. /* There are no "black-listed" or "white-listed" bytes:
  17317. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  17318. */
  17319. return Z_BINARY;
  17320. }
  17321. var static_init_done = false;
  17322. /* ===========================================================================
  17323. * Initialize the tree data structures for a new zlib stream.
  17324. */
  17325. function _tr_init(s)
  17326. {
  17327. if (!static_init_done) {
  17328. tr_static_init();
  17329. static_init_done = true;
  17330. }
  17331. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  17332. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  17333. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  17334. s.bi_buf = 0;
  17335. s.bi_valid = 0;
  17336. /* Initialize the first block of the first file: */
  17337. init_block(s);
  17338. }
  17339. /* ===========================================================================
  17340. * Send a stored block
  17341. */
  17342. function _tr_stored_block(s, buf, stored_len, last)
  17343. //DeflateState *s;
  17344. //charf *buf; /* input block */
  17345. //ulg stored_len; /* length of input block */
  17346. //int last; /* one if this is the last block for a file */
  17347. {
  17348. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  17349. copy_block(s, buf, stored_len, true); /* with header */
  17350. }
  17351. /* ===========================================================================
  17352. * Send one empty static block to give enough lookahead for inflate.
  17353. * This takes 10 bits, of which 7 may remain in the bit buffer.
  17354. */
  17355. function _tr_align(s) {
  17356. send_bits(s, STATIC_TREES<<1, 3);
  17357. send_code(s, END_BLOCK, static_ltree);
  17358. bi_flush(s);
  17359. }
  17360. /* ===========================================================================
  17361. * Determine the best encoding for the current block: dynamic trees, static
  17362. * trees or store, and output the encoded block to the zip file.
  17363. */
  17364. function _tr_flush_block(s, buf, stored_len, last)
  17365. //DeflateState *s;
  17366. //charf *buf; /* input block, or NULL if too old */
  17367. //ulg stored_len; /* length of input block */
  17368. //int last; /* one if this is the last block for a file */
  17369. {
  17370. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  17371. var max_blindex = 0; /* index of last bit length code of non zero freq */
  17372. /* Build the Huffman trees unless a stored block is forced */
  17373. if (s.level > 0) {
  17374. /* Check if the file is binary or text */
  17375. if (s.strm.data_type === Z_UNKNOWN) {
  17376. s.strm.data_type = detect_data_type(s);
  17377. }
  17378. /* Construct the literal and distance trees */
  17379. build_tree(s, s.l_desc);
  17380. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  17381. // s->static_len));
  17382. build_tree(s, s.d_desc);
  17383. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  17384. // s->static_len));
  17385. /* At this point, opt_len and static_len are the total bit lengths of
  17386. * the compressed block data, excluding the tree representations.
  17387. */
  17388. /* Build the bit length tree for the above two trees, and get the index
  17389. * in bl_order of the last bit length code to send.
  17390. */
  17391. max_blindex = build_bl_tree(s);
  17392. /* Determine the best encoding. Compute the block lengths in bytes. */
  17393. opt_lenb = (s.opt_len+3+7) >>> 3;
  17394. static_lenb = (s.static_len+3+7) >>> 3;
  17395. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  17396. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  17397. // s->last_lit));
  17398. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  17399. } else {
  17400. // Assert(buf != (char*)0, "lost buf");
  17401. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  17402. }
  17403. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  17404. /* 4: two words for the lengths */
  17405. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  17406. * Otherwise we can't have processed more than WSIZE input bytes since
  17407. * the last block flush, because compression would have been
  17408. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  17409. * transform a block into a stored block.
  17410. */
  17411. _tr_stored_block(s, buf, stored_len, last);
  17412. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  17413. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  17414. compress_block(s, static_ltree, static_dtree);
  17415. } else {
  17416. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  17417. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  17418. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  17419. }
  17420. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  17421. /* The above check is made mod 2^32, for files larger than 512 MB
  17422. * and uLong implemented on 32 bits.
  17423. */
  17424. init_block(s);
  17425. if (last) {
  17426. bi_windup(s);
  17427. }
  17428. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  17429. // s->compressed_len-7*last));
  17430. }
  17431. /* ===========================================================================
  17432. * Save the match info and tally the frequency counts. Return true if
  17433. * the current block must be flushed.
  17434. */
  17435. function _tr_tally(s, dist, lc)
  17436. // deflate_state *s;
  17437. // unsigned dist; /* distance of matched string */
  17438. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  17439. {
  17440. //var out_length, in_length, dcode;
  17441. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  17442. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  17443. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  17444. s.last_lit++;
  17445. if (dist === 0) {
  17446. /* lc is the unmatched char */
  17447. s.dyn_ltree[lc*2]/*.Freq*/++;
  17448. } else {
  17449. s.matches++;
  17450. /* Here, lc is the match length - MIN_MATCH */
  17451. dist--; /* dist = match distance - 1 */
  17452. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  17453. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  17454. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  17455. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  17456. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  17457. }
  17458. // (!) This block is disabled in zlib defailts,
  17459. // don't enable it for binary compatibility
  17460. //#ifdef TRUNCATE_BLOCK
  17461. // /* Try to guess if it is profitable to stop the current block here */
  17462. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  17463. // /* Compute an upper bound for the compressed length */
  17464. // out_length = s.last_lit*8;
  17465. // in_length = s.strstart - s.block_start;
  17466. //
  17467. // for (dcode = 0; dcode < D_CODES; dcode++) {
  17468. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  17469. // }
  17470. // out_length >>>= 3;
  17471. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  17472. // // s->last_lit, in_length, out_length,
  17473. // // 100L - out_length*100L/in_length));
  17474. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  17475. // return true;
  17476. // }
  17477. // }
  17478. //#endif
  17479. return (s.last_lit === s.lit_bufsize-1);
  17480. /* We avoid equality with lit_bufsize because of wraparound at 64K
  17481. * on 16 bit machines and because stored blocks are restricted to
  17482. * 64K-1 bytes.
  17483. */
  17484. }
  17485. exports._tr_init = _tr_init;
  17486. exports._tr_stored_block = _tr_stored_block;
  17487. exports._tr_flush_block = _tr_flush_block;
  17488. exports._tr_tally = _tr_tally;
  17489. exports._tr_align = _tr_align;
  17490. },{"../utils/common":48}],60:[function(require,module,exports){
  17491. 'use strict';
  17492. function ZStream() {
  17493. /* next input byte */
  17494. this.input = null; // JS specific, because we have no pointers
  17495. this.next_in = 0;
  17496. /* number of bytes available at input */
  17497. this.avail_in = 0;
  17498. /* total number of input bytes read so far */
  17499. this.total_in = 0;
  17500. /* next output byte should be put there */
  17501. this.output = null; // JS specific, because we have no pointers
  17502. this.next_out = 0;
  17503. /* remaining free space at output */
  17504. this.avail_out = 0;
  17505. /* total number of bytes output so far */
  17506. this.total_out = 0;
  17507. /* last error message, NULL if no error */
  17508. this.msg = ''/*Z_NULL*/;
  17509. /* not visible by applications */
  17510. this.state = null;
  17511. /* best guess about the data type: binary or text */
  17512. this.data_type = 2/*Z_UNKNOWN*/;
  17513. /* adler32 value of the uncompressed data */
  17514. this.adler = 0;
  17515. }
  17516. module.exports = ZStream;
  17517. },{}],61:[function(require,module,exports){
  17518. /* Copyright @ 2015 Atlassian Pty Ltd
  17519. *
  17520. * Licensed under the Apache License, Version 2.0 (the "License");
  17521. * you may not use this file except in compliance with the License.
  17522. * You may obtain a copy of the License at
  17523. *
  17524. * http://www.apache.org/licenses/LICENSE-2.0
  17525. *
  17526. * Unless required by applicable law or agreed to in writing, software
  17527. * distributed under the License is distributed on an "AS IS" BASIS,
  17528. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17529. * See the License for the specific language governing permissions and
  17530. * limitations under the License.
  17531. */
  17532. module.exports = function arrayEquals(array) {
  17533. // if the other array is a falsy value, return
  17534. if (!array)
  17535. return false;
  17536. // compare lengths - can save a lot of time
  17537. if (this.length != array.length)
  17538. return false;
  17539. for (var i = 0, l = this.length; i < l; i++) {
  17540. // Check if we have nested arrays
  17541. if (this[i] instanceof Array && array[i] instanceof Array) {
  17542. // recurse into the nested arrays
  17543. if (!arrayEquals.apply(this[i], [array[i]]))
  17544. return false;
  17545. } else if (this[i] != array[i]) {
  17546. // Warning - two different object instances will never be equal:
  17547. // {x:20} != {x:20}
  17548. return false;
  17549. }
  17550. }
  17551. return true;
  17552. };
  17553. },{}],62:[function(require,module,exports){
  17554. /* Copyright @ 2015 Atlassian Pty Ltd
  17555. *
  17556. * Licensed under the Apache License, Version 2.0 (the "License");
  17557. * you may not use this file except in compliance with the License.
  17558. * You may obtain a copy of the License at
  17559. *
  17560. * http://www.apache.org/licenses/LICENSE-2.0
  17561. *
  17562. * Unless required by applicable law or agreed to in writing, software
  17563. * distributed under the License is distributed on an "AS IS" BASIS,
  17564. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17565. * See the License for the specific language governing permissions and
  17566. * limitations under the License.
  17567. */
  17568. exports.Interop = require('./interop');
  17569. },{"./interop":63}],63:[function(require,module,exports){
  17570. /* Copyright @ 2015 Atlassian Pty Ltd
  17571. *
  17572. * Licensed under the Apache License, Version 2.0 (the "License");
  17573. * you may not use this file except in compliance with the License.
  17574. * You may obtain a copy of the License at
  17575. *
  17576. * http://www.apache.org/licenses/LICENSE-2.0
  17577. *
  17578. * Unless required by applicable law or agreed to in writing, software
  17579. * distributed under the License is distributed on an "AS IS" BASIS,
  17580. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17581. * See the License for the specific language governing permissions and
  17582. * limitations under the License.
  17583. */
  17584. /* global RTCSessionDescription */
  17585. /* jshint -W097 */
  17586. "use strict";
  17587. var transform = require('./transform');
  17588. var arrayEquals = require('./array-equals');
  17589. function Interop() {
  17590. /**
  17591. * This map holds the most recent Unified Plan offer/answer SDP that was
  17592. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  17593. * the SDP string as values.
  17594. *
  17595. * @type {{}}
  17596. */
  17597. this.cache = {};
  17598. }
  17599. module.exports = Interop;
  17600. /**
  17601. * Returns the index of the first m-line with the given media type and with a
  17602. * direction which allows sending, in the last Unified Plan description with
  17603. * type "answer" converted to Plan B. Returns {null} if there is no saved
  17604. * answer, or if none of its m-lines with the given type allow sending.
  17605. * @param type the media type ("audio" or "video").
  17606. * @returns {*}
  17607. */
  17608. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  17609. if (!this.cache.answer) {
  17610. return null;
  17611. }
  17612. var session = transform.parse(this.cache.answer);
  17613. if (session && session.media && Array.isArray(session.media)){
  17614. for (var i = 0; i < session.media.length; i++) {
  17615. if (session.media[i].type == type &&
  17616. (!session.media[i].direction /* default to sendrecv */ ||
  17617. session.media[i].direction === 'sendrecv' ||
  17618. session.media[i].direction === 'sendonly')){
  17619. return i;
  17620. }
  17621. }
  17622. }
  17623. return null;
  17624. };
  17625. /**
  17626. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  17627. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  17628. * application.
  17629. *
  17630. * @param desc
  17631. * @returns {*}
  17632. */
  17633. Interop.prototype.toPlanB = function(desc) {
  17634. var self = this;
  17635. //#region Preliminary input validation.
  17636. if (typeof desc !== 'object' || desc === null ||
  17637. typeof desc.sdp !== 'string') {
  17638. console.warn('An empty description was passed as an argument.');
  17639. return desc;
  17640. }
  17641. // Objectify the SDP for easier manipulation.
  17642. var session = transform.parse(desc.sdp);
  17643. // If the SDP contains no media, there's nothing to transform.
  17644. if (typeof session.media === 'undefined' ||
  17645. !Array.isArray(session.media) || session.media.length === 0) {
  17646. console.warn('The description has no media.');
  17647. return desc;
  17648. }
  17649. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  17650. // SDP has a video, an audio and a data "channel" at most.
  17651. if (session.media.length <= 3 && session.media.every(function(m) {
  17652. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  17653. })) {
  17654. console.warn('This description does not look like Unified Plan.');
  17655. return desc;
  17656. }
  17657. //#endregion
  17658. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  17659. var sdp = desc.sdp;
  17660. var rewrite = false;
  17661. for (var i = 0; i < session.media.length; i++) {
  17662. var uLine = session.media[i];
  17663. uLine.rtp.forEach(function(rtp) {
  17664. if (rtp.codec === 'NULL')
  17665. {
  17666. rewrite = true;
  17667. var offer = transform.parse(self.cache['offer']);
  17668. rtp.codec = offer.media[i].rtp[0].codec;
  17669. }
  17670. });
  17671. };
  17672. if (rewrite) {
  17673. sdp = transform.write(session);
  17674. }
  17675. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  17676. // -> Unified Plan transformation.
  17677. this.cache[desc.type] = sdp;
  17678. //#region Convert from Unified Plan to Plan B.
  17679. // We rebuild the session.media array.
  17680. var media = session.media;
  17681. session.media = [];
  17682. // Associative array that maps channel types to channel objects for fast
  17683. // access to channel objects by their type, e.g. type2bl['audio']->channel
  17684. // obj.
  17685. var type2bl = {};
  17686. // Used to build the group:BUNDLE value after the channels construction
  17687. // loop.
  17688. var types = [];
  17689. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  17690. media.forEach(function(uLine) {
  17691. // rtcp-mux is required in the Plan B SDP.
  17692. if ((typeof uLine.rtcpMux !== 'string' ||
  17693. uLine.rtcpMux !== 'rtcp-mux') &&
  17694. uLine.direction !== 'inactive') {
  17695. throw new Error('Cannot convert to Plan B because m-lines ' +
  17696. 'without the rtcp-mux attribute were found.');
  17697. }
  17698. if (uLine.type === 'application') {
  17699. session.media.push(uLine);
  17700. types.push(uLine.mid);
  17701. return;
  17702. }
  17703. // If we don't have a channel for this uLine.type, then use this
  17704. // uLine as the channel basis.
  17705. if (typeof type2bl[uLine.type] === 'undefined') {
  17706. type2bl[uLine.type] = uLine;
  17707. }
  17708. // Add sources to the channel and handle a=msid.
  17709. if (typeof uLine.sources === 'object') {
  17710. Object.keys(uLine.sources).forEach(function(ssrc) {
  17711. if (typeof type2bl[uLine.type].sources !== 'object')
  17712. type2bl[uLine.type].sources = {};
  17713. // Assign the sources to the channel.
  17714. type2bl[uLine.type].sources[ssrc] =
  17715. uLine.sources[ssrc];
  17716. if (typeof uLine.msid !== 'undefined') {
  17717. // In Plan B the msid is an SSRC attribute. Also, we don't
  17718. // care about the obsolete label and mslabel attributes.
  17719. //
  17720. // Note that it is not guaranteed that the uLine will
  17721. // have an msid. recvonly channels in particular don't have
  17722. // one.
  17723. type2bl[uLine.type].sources[ssrc].msid =
  17724. uLine.msid;
  17725. }
  17726. // NOTE ssrcs in ssrc groups will share msids, as
  17727. // draft-uberti-rtcweb-plan-00 mandates.
  17728. });
  17729. }
  17730. // Add ssrc groups to the channel.
  17731. if (typeof uLine.ssrcGroups !== 'undefined' &&
  17732. Array.isArray(uLine.ssrcGroups)) {
  17733. // Create the ssrcGroups array, if it's not defined.
  17734. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  17735. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  17736. type2bl[uLine.type].ssrcGroups = [];
  17737. }
  17738. type2bl[uLine.type].ssrcGroups =
  17739. type2bl[uLine.type].ssrcGroups.concat(
  17740. uLine.ssrcGroups);
  17741. }
  17742. if (type2bl[uLine.type] === uLine) {
  17743. // Copy ICE related stuff from the principal media line.
  17744. uLine.candidates = media[0].candidates;
  17745. uLine.iceUfrag = media[0].iceUfrag;
  17746. uLine.icePwd = media[0].icePwd;
  17747. uLine.fingerprint = media[0].fingerprint;
  17748. // Plan B mids are in ['audio', 'video', 'data']
  17749. uLine.mid = uLine.type;
  17750. // Plan B doesn't support/need the bundle-only attribute.
  17751. delete uLine.bundleOnly;
  17752. // In Plan B the msid is an SSRC attribute.
  17753. delete uLine.msid;
  17754. // Used to build the group:BUNDLE value after this loop.
  17755. types.push(uLine.type);
  17756. // Add the channel to the new media array.
  17757. session.media.push(uLine);
  17758. }
  17759. });
  17760. // We regenerate the BUNDLE group with the new mids.
  17761. session.groups.some(function(group) {
  17762. if (group.type === 'BUNDLE') {
  17763. group.mids = types.join(' ');
  17764. return true;
  17765. }
  17766. });
  17767. // msid semantic
  17768. session.msidSemantic = {
  17769. semantic: 'WMS',
  17770. token: '*'
  17771. };
  17772. var resStr = transform.write(session);
  17773. return new RTCSessionDescription({
  17774. type: desc.type,
  17775. sdp: resStr
  17776. });
  17777. //#endregion
  17778. };
  17779. /**
  17780. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  17781. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  17782. * to FF.
  17783. *
  17784. * @param desc
  17785. * @returns {*}
  17786. */
  17787. Interop.prototype.toUnifiedPlan = function(desc) {
  17788. var self = this;
  17789. //#region Preliminary input validation.
  17790. if (typeof desc !== 'object' || desc === null ||
  17791. typeof desc.sdp !== 'string') {
  17792. console.warn('An empty description was passed as an argument.');
  17793. return desc;
  17794. }
  17795. var session = transform.parse(desc.sdp);
  17796. // If the SDP contains no media, there's nothing to transform.
  17797. if (typeof session.media === 'undefined' ||
  17798. !Array.isArray(session.media) || session.media.length === 0) {
  17799. console.warn('The description has no media.');
  17800. return desc;
  17801. }
  17802. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  17803. // a video, an audio and a data "channel" at most.
  17804. if (session.media.length > 3 || !session.media.every(function(m) {
  17805. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  17806. })) {
  17807. console.warn('This description does not look like Plan B.');
  17808. return desc;
  17809. }
  17810. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  17811. var mids = [];
  17812. session.media.forEach(function(m) {
  17813. mids.push(m.mid);
  17814. });
  17815. var hasBundle = false;
  17816. if (typeof session.groups !== 'undefined' &&
  17817. Array.isArray(session.groups)) {
  17818. hasBundle = session.groups.every(function(g) {
  17819. return g.type !== 'BUNDLE' ||
  17820. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  17821. });
  17822. }
  17823. if (!hasBundle) {
  17824. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  17825. " are not bundled were found.");
  17826. }
  17827. //#endregion
  17828. //#region Convert from Plan B to Unified Plan.
  17829. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  17830. // rebuild an equivalent Unified Plan offer/answer.
  17831. //
  17832. // For example, if this is a local answer (in Unified Plan style) that we
  17833. // convert to Plan B prior to handing it over to the application (the
  17834. // PeerConnection wrapper called us, for instance, after a successful
  17835. // createAnswer), we want to remember the m-line at which we've seen the
  17836. // (local) SSRC. That's because when the application wants to do call the
  17837. // SLD method, forcing us to do the inverse transformation (from Plan B to
  17838. // Unified Plan), we need to know to which m-line to assign the (local)
  17839. // SSRC. We also need to know all the other m-lines that the original
  17840. // answer had and include them in the transformed answer as well.
  17841. //
  17842. // Another example is if this is a remote offer that we convert to Plan B
  17843. // prior to giving it to the application, we want to remember the mid at
  17844. // which we've seen the (remote) SSRC.
  17845. //
  17846. // In the iteration that follows, we use the cached Unified Plan (if it
  17847. // exists) to assign mids to ssrcs.
  17848. var cached;
  17849. if (typeof this.cache[desc.type] !== 'undefined') {
  17850. cached = transform.parse(this.cache[desc.type]);
  17851. }
  17852. var recvonlySsrcs = {
  17853. audio: {},
  17854. video: {}
  17855. };
  17856. // A helper map that sends mids to m-line objects. We use it later to
  17857. // rebuild the Unified Plan style session.media array.
  17858. var mid2ul = {};
  17859. session.media.forEach(function(bLine) {
  17860. if ((typeof bLine.rtcpMux !== 'string' ||
  17861. bLine.rtcpMux !== 'rtcp-mux') &&
  17862. bLine.direction !== 'inactive') {
  17863. throw new Error("Cannot convert to Unified Plan because m-lines " +
  17864. "without the rtcp-mux attribute were found.");
  17865. }
  17866. if (bLine.type === 'application') {
  17867. mid2ul[bLine.mid] = bLine;
  17868. return;
  17869. }
  17870. // With rtcp-mux and bundle all the channels should have the same ICE
  17871. // stuff.
  17872. var sources = bLine.sources;
  17873. var ssrcGroups = bLine.ssrcGroups;
  17874. var candidates = bLine.candidates;
  17875. var iceUfrag = bLine.iceUfrag;
  17876. var icePwd = bLine.icePwd;
  17877. var fingerprint = bLine.fingerprint;
  17878. var port = bLine.port;
  17879. // We'll use the "bLine" object as a prototype for each new "mLine"
  17880. // that we create, but first we need to clean it up a bit.
  17881. delete bLine.sources;
  17882. delete bLine.ssrcGroups;
  17883. delete bLine.candidates;
  17884. delete bLine.iceUfrag;
  17885. delete bLine.icePwd;
  17886. delete bLine.fingerprint;
  17887. delete bLine.port;
  17888. delete bLine.mid;
  17889. // inverted ssrc group map
  17890. var ssrc2group = {};
  17891. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  17892. ssrcGroups.forEach(function (ssrcGroup) {
  17893. // TODO(gp) find out how to receive simulcast with FF. For the
  17894. // time being, hide it.
  17895. if (ssrcGroup.semantics === 'SIM') {
  17896. return;
  17897. }
  17898. // XXX This might brake if an SSRC is in more than one group
  17899. // for some reason.
  17900. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  17901. Array.isArray(ssrcGroup.ssrcs)) {
  17902. ssrcGroup.ssrcs.forEach(function (ssrc) {
  17903. if (typeof ssrc2group[ssrc] === 'undefined') {
  17904. ssrc2group[ssrc] = [];
  17905. }
  17906. ssrc2group[ssrc].push(ssrcGroup);
  17907. });
  17908. }
  17909. });
  17910. }
  17911. // ssrc to m-line index.
  17912. var ssrc2ml = {};
  17913. if (typeof sources === 'object') {
  17914. // Explode the Plan B channel sources with one m-line per source.
  17915. Object.keys(sources).forEach(function(ssrc) {
  17916. // The (unified) m-line for this SSRC. We either create it from
  17917. // scratch or, if it's a grouped SSRC, we re-use a related
  17918. // mline. In other words, if the source is grouped with another
  17919. // source, put the two together in the same m-line.
  17920. var uLine;
  17921. // We assume here that we are the answerer in the O/A, so any
  17922. // offers which we translate come from the remote side, while
  17923. // answers are local. So the check below is to make that we
  17924. // handle receive-only SSRCs in a special way only if they come
  17925. // from the remote side.
  17926. if (desc.type==='offer') {
  17927. // We want to detect SSRCs which are used by a remote peer
  17928. // in an m-line with direction=recvonly (i.e. they are
  17929. // being used for RTCP only).
  17930. // This information would have gotten lost if the remote
  17931. // peer used Unified Plan and their local description was
  17932. // translated to Plan B. So we use the lack of an MSID
  17933. // attribute to deduce a "receive only" SSRC.
  17934. if (!sources[ssrc].msid) {
  17935. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  17936. // Receive-only SSRCs must not create new m-lines. We
  17937. // will assign them to an existing m-line later.
  17938. return;
  17939. }
  17940. }
  17941. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  17942. Array.isArray(ssrc2group[ssrc])) {
  17943. ssrc2group[ssrc].some(function (ssrcGroup) {
  17944. // ssrcGroup.ssrcs *is* an Array, no need to check
  17945. // again here.
  17946. return ssrcGroup.ssrcs.some(function (related) {
  17947. if (typeof ssrc2ml[related] === 'object') {
  17948. uLine = ssrc2ml[related];
  17949. return true;
  17950. }
  17951. });
  17952. });
  17953. }
  17954. if (typeof uLine === 'object') {
  17955. // the m-line already exists. Just add the source.
  17956. uLine.sources[ssrc] = sources[ssrc];
  17957. delete sources[ssrc].msid;
  17958. } else {
  17959. // Use the "bLine" as a prototype for the "uLine".
  17960. uLine = Object.create(bLine);
  17961. ssrc2ml[ssrc] = uLine;
  17962. if (typeof sources[ssrc].msid !== 'undefined') {
  17963. // Assign the msid of the source to the m-line. Note
  17964. // that it is not guaranteed that the source will have
  17965. // msid. In particular "recvonly" sources don't have an
  17966. // msid. Note that "recvonly" is a term only defined
  17967. // for m-lines.
  17968. uLine.msid = sources[ssrc].msid;
  17969. uLine.direction = 'sendrecv';
  17970. delete sources[ssrc].msid;
  17971. }
  17972. // We assign one SSRC per media line.
  17973. uLine.sources = {};
  17974. uLine.sources[ssrc] = sources[ssrc];
  17975. uLine.ssrcGroups = ssrc2group[ssrc];
  17976. // Use the cached Unified Plan SDP (if it exists) to assign
  17977. // SSRCs to mids.
  17978. if (typeof cached !== 'undefined' &&
  17979. typeof cached.media !== 'undefined' &&
  17980. Array.isArray(cached.media)) {
  17981. cached.media.forEach(function (m) {
  17982. if (typeof m.sources === 'object') {
  17983. Object.keys(m.sources).forEach(function (s) {
  17984. if (s === ssrc) {
  17985. uLine.mid = m.mid;
  17986. }
  17987. });
  17988. }
  17989. });
  17990. }
  17991. if (typeof uLine.mid === 'undefined') {
  17992. // If this is an SSRC that we see for the first time
  17993. // assign it a new mid. This is typically the case when
  17994. // this method is called to transform a remote
  17995. // description for the first time or when there is a
  17996. // new SSRC in the remote description because a new
  17997. // peer has joined the conference. Local SSRCs should
  17998. // have already been added to the map in the toPlanB
  17999. // method.
  18000. //
  18001. // Because FF generates answers in Unified Plan style,
  18002. // we MUST already have a cached answer with all the
  18003. // local SSRCs mapped to some m-line/mid.
  18004. if (desc.type === 'answer') {
  18005. throw new Error("An unmapped SSRC was found.");
  18006. }
  18007. uLine.mid = [bLine.type, '-', ssrc].join('');
  18008. }
  18009. // Include the candidates in the 1st media line.
  18010. uLine.candidates = candidates;
  18011. uLine.iceUfrag = iceUfrag;
  18012. uLine.icePwd = icePwd;
  18013. uLine.fingerprint = fingerprint;
  18014. uLine.port = port;
  18015. mid2ul[uLine.mid] = uLine;
  18016. }
  18017. });
  18018. }
  18019. });
  18020. // Rebuild the media array in the right order and add the missing mLines
  18021. // (missing from the Plan B SDP).
  18022. session.media = [];
  18023. mids = []; // reuse
  18024. if (desc.type === 'answer') {
  18025. // The media lines in the answer must match the media lines in the
  18026. // offer. The order is important too. Here we assume that Firefox is
  18027. // the answerer, so we merely have to use the reconstructed (unified)
  18028. // answer to update the cached (unified) answer accordingly.
  18029. //
  18030. // In the general case, one would have to use the cached (unified)
  18031. // offer to find the m-lines that are missing from the reconstructed
  18032. // answer, potentially grabbing them from the cached (unified) answer.
  18033. // One has to be careful with this approach because inactive m-lines do
  18034. // not always have an mid, making it tricky (impossible?) to find where
  18035. // exactly and which m-lines are missing from the reconstructed answer.
  18036. for (var i = 0; i < cached.media.length; i++) {
  18037. var uLine = cached.media[i];
  18038. if (typeof mid2ul[uLine.mid] === 'undefined') {
  18039. // The mid isn't in the reconstructed (unified) answer.
  18040. // This is either a (unified) m-line containing a remote
  18041. // track only, or a (unified) m-line containing a remote
  18042. // track and a local track that has been removed.
  18043. // In either case, it MUST exist in the cached
  18044. // (unified) answer.
  18045. //
  18046. // In case this is a removed local track, clean-up
  18047. // the (unified) m-line and make sure it's 'recvonly' or
  18048. // 'inactive'.
  18049. delete uLine.msid;
  18050. delete uLine.sources;
  18051. delete uLine.ssrcGroups;
  18052. if (!uLine.direction
  18053. || uLine.direction === 'sendrecv')
  18054. uLine.direction = 'recvonly';
  18055. else if (uLine.direction === 'sendonly')
  18056. uLine.direction = 'inactive';
  18057. } else {
  18058. // This is an (unified) m-line/channel that contains a local
  18059. // track (sendrecv or sendonly channel) or it's a unified
  18060. // recvonly m-line/channel. In either case, since we're
  18061. // going from PlanB -> Unified Plan this m-line MUST
  18062. // exist in the cached answer.
  18063. }
  18064. session.media.push(uLine);
  18065. if (typeof uLine.mid === 'string') {
  18066. // inactive lines don't/may not have an mid.
  18067. mids.push(uLine.mid);
  18068. }
  18069. }
  18070. } else {
  18071. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  18072. // under any circumstances. If we are no longer interested in sending a
  18073. // track, we just remove the msid and ssrc attributes and set it to
  18074. // either a=recvonly (as the reofferer, we must use recvonly if the
  18075. // other side was previously sending on the m-section, but we can also
  18076. // leave the possibility open if it wasn't previously in use), or
  18077. // a=inactive.
  18078. if (typeof cached !== 'undefined' &&
  18079. typeof cached.media !== 'undefined' &&
  18080. Array.isArray(cached.media)) {
  18081. cached.media.forEach(function(uLine) {
  18082. mids.push(uLine.mid);
  18083. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  18084. session.media.push(mid2ul[uLine.mid]);
  18085. } else {
  18086. delete uLine.msid;
  18087. delete uLine.sources;
  18088. delete uLine.ssrcGroups;
  18089. if (!uLine.direction
  18090. || uLine.direction === 'sendrecv')
  18091. uLine.direction = 'recvonly';
  18092. if (!uLine.direction
  18093. || uLine.direction === 'sendonly')
  18094. uLine.direction = 'inactive';
  18095. session.media.push(uLine);
  18096. }
  18097. });
  18098. }
  18099. // Add all the remaining (new) m-lines of the transformed SDP.
  18100. Object.keys(mid2ul).forEach(function(mid) {
  18101. if (mids.indexOf(mid) === -1) {
  18102. mids.push(mid);
  18103. if (mid2ul[mid].direction === 'recvonly') {
  18104. // This is a remote recvonly channel. Add its SSRC to the
  18105. // appropriate sendrecv or sendonly channel.
  18106. // TODO(gp) what if we don't have sendrecv/sendonly
  18107. // channel?
  18108. session.media.some(function (uLine) {
  18109. if ((uLine.direction === 'sendrecv' ||
  18110. uLine.direction === 'sendonly') &&
  18111. uLine.type === mid2ul[mid].type) {
  18112. // mid2ul[mid] shouldn't have any ssrc-groups
  18113. Object.keys(mid2ul[mid].sources).forEach(
  18114. function (ssrc) {
  18115. uLine.sources[ssrc] =
  18116. mid2ul[mid].sources[ssrc];
  18117. });
  18118. return true;
  18119. }
  18120. });
  18121. } else {
  18122. session.media.push(mid2ul[mid]);
  18123. }
  18124. }
  18125. });
  18126. }
  18127. // After we have constructed the Plan Unified m-lines we can figure out
  18128. // where (in which m-line) to place the 'recvonly SSRCs'.
  18129. // Note: we assume here that we are the answerer in the O/A, so any offers
  18130. // which we translate come from the remote side, while answers are local
  18131. // (and so our last local description is cached as an 'answer').
  18132. ["audio", "video"].forEach(function (type) {
  18133. if (!session || !session.media || !Array.isArray(session.media))
  18134. return;
  18135. var idx = null;
  18136. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  18137. idx = self.getFirstSendingIndexFromAnswer(type);
  18138. if (idx === null){
  18139. // If this is the first offer we receive, we don't have a
  18140. // cached answer. Assume that we will be sending media using
  18141. // the first m-line for each media type.
  18142. for (var i = 0; i < session.media.length; i++) {
  18143. if (session.media[i].type === type) {
  18144. idx = i;
  18145. break;
  18146. }
  18147. }
  18148. }
  18149. }
  18150. if (idx && session.media.length > idx) {
  18151. var mLine = session.media[idx];
  18152. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  18153. if (mLine.sources && mLine.sources[ssrc]) {
  18154. console.warn("Replacing an existing SSRC.");
  18155. }
  18156. if (!mLine.sources) {
  18157. mLine.sources = {};
  18158. }
  18159. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  18160. });
  18161. }
  18162. });
  18163. // We regenerate the BUNDLE group (since we regenerated the mids)
  18164. session.groups.some(function(group) {
  18165. if (group.type === 'BUNDLE') {
  18166. group.mids = mids.join(' ');
  18167. return true;
  18168. }
  18169. });
  18170. // msid semantic
  18171. session.msidSemantic = {
  18172. semantic: 'WMS',
  18173. token: '*'
  18174. };
  18175. var resStr = transform.write(session);
  18176. // Cache the transformed SDP (Unified Plan) for later re-use in this
  18177. // function.
  18178. this.cache[desc.type] = resStr;
  18179. return new RTCSessionDescription({
  18180. type: desc.type,
  18181. sdp: resStr
  18182. });
  18183. //#endregion
  18184. };
  18185. },{"./array-equals":61,"./transform":64}],64:[function(require,module,exports){
  18186. /* Copyright @ 2015 Atlassian Pty Ltd
  18187. *
  18188. * Licensed under the Apache License, Version 2.0 (the "License");
  18189. * you may not use this file except in compliance with the License.
  18190. * You may obtain a copy of the License at
  18191. *
  18192. * http://www.apache.org/licenses/LICENSE-2.0
  18193. *
  18194. * Unless required by applicable law or agreed to in writing, software
  18195. * distributed under the License is distributed on an "AS IS" BASIS,
  18196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18197. * See the License for the specific language governing permissions and
  18198. * limitations under the License.
  18199. */
  18200. var transform = require('sdp-transform');
  18201. exports.write = function(session, opts) {
  18202. if (typeof session !== 'undefined' &&
  18203. typeof session.media !== 'undefined' &&
  18204. Array.isArray(session.media)) {
  18205. session.media.forEach(function (mLine) {
  18206. // expand sources to ssrcs
  18207. if (typeof mLine.sources !== 'undefined' &&
  18208. Object.keys(mLine.sources).length !== 0) {
  18209. mLine.ssrcs = [];
  18210. Object.keys(mLine.sources).forEach(function (ssrc) {
  18211. var source = mLine.sources[ssrc];
  18212. Object.keys(source).forEach(function (attribute) {
  18213. mLine.ssrcs.push({
  18214. id: ssrc,
  18215. attribute: attribute,
  18216. value: source[attribute]
  18217. });
  18218. });
  18219. });
  18220. delete mLine.sources;
  18221. }
  18222. // join ssrcs in ssrc groups
  18223. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18224. Array.isArray(mLine.ssrcGroups)) {
  18225. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18226. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18227. Array.isArray(ssrcGroup.ssrcs)) {
  18228. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  18229. }
  18230. });
  18231. }
  18232. });
  18233. }
  18234. // join group mids
  18235. if (typeof session !== 'undefined' &&
  18236. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18237. session.groups.forEach(function (g) {
  18238. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  18239. g.mids = g.mids.join(' ');
  18240. }
  18241. });
  18242. }
  18243. return transform.write(session, opts);
  18244. };
  18245. exports.parse = function(sdp) {
  18246. var session = transform.parse(sdp);
  18247. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  18248. Array.isArray(session.media)) {
  18249. session.media.forEach(function (mLine) {
  18250. // group sources attributes by ssrc
  18251. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  18252. mLine.sources = {};
  18253. mLine.ssrcs.forEach(function (ssrc) {
  18254. if (!mLine.sources[ssrc.id])
  18255. mLine.sources[ssrc.id] = {};
  18256. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  18257. });
  18258. delete mLine.ssrcs;
  18259. }
  18260. // split ssrcs in ssrc groups
  18261. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18262. Array.isArray(mLine.ssrcGroups)) {
  18263. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18264. if (typeof ssrcGroup.ssrcs === 'string') {
  18265. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  18266. }
  18267. });
  18268. }
  18269. });
  18270. }
  18271. // split group mids
  18272. if (typeof session !== 'undefined' &&
  18273. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18274. session.groups.forEach(function (g) {
  18275. if (typeof g.mids === 'string') {
  18276. g.mids = g.mids.split(' ');
  18277. }
  18278. });
  18279. }
  18280. return session;
  18281. };
  18282. },{"sdp-transform":72}],65:[function(require,module,exports){
  18283. var transform = require('sdp-transform');
  18284. var transformUtils = require('./transform-utils');
  18285. var parseSsrcs = transformUtils.parseSsrcs;
  18286. var writeSsrcs = transformUtils.writeSsrcs;
  18287. //region Constants
  18288. var DEFAULT_NUM_OF_LAYERS = 3;
  18289. //endregion
  18290. //region Ctor
  18291. function Simulcast(options) {
  18292. this.options = options ? options : {};
  18293. if (!this.options.numOfLayers) {
  18294. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  18295. }
  18296. this.layers = [];
  18297. }
  18298. //endregion
  18299. //region Stateless private utility functions
  18300. /**
  18301. * Returns a random integer between min (included) and max (excluded)
  18302. * Using Math.round() gives a non-uniform distribution!
  18303. * @returns {number}
  18304. */
  18305. function generateSSRC() {
  18306. var min = 0, max = 0xffffffff;
  18307. return Math.floor(Math.random() * (max - min)) + min;
  18308. };
  18309. function processVideo(session, action) {
  18310. if (session == null || !Array.isArray(session.media)) {
  18311. return;
  18312. }
  18313. session.media.forEach(function (mLine) {
  18314. if (mLine.type === 'video') {
  18315. action(mLine);
  18316. }
  18317. });
  18318. }
  18319. function validateDescription(desc)
  18320. {
  18321. return desc && desc != null
  18322. && desc.type && desc.type != ''
  18323. && desc.sdp && desc.sdp != '';
  18324. }
  18325. function explodeRemoteSimulcast(mLine) {
  18326. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18327. return;
  18328. }
  18329. var sources = parseSsrcs(mLine);
  18330. var order = [];
  18331. // Find the SIM group and explode its sources.
  18332. var j = mLine.ssrcGroups.length;
  18333. while (j--) {
  18334. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  18335. continue;
  18336. }
  18337. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  18338. for (var i = 0; i < simulcastSsrcs.length; i++) {
  18339. var ssrc = simulcastSsrcs[i];
  18340. order.push(ssrc);
  18341. var parts = sources[ssrc].msid.split(' ');
  18342. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  18343. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  18344. // Remove all the groups that this SSRC participates in.
  18345. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18346. if (relatedGroup.semantics === 'SIM') {
  18347. return;
  18348. }
  18349. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18350. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18351. return;
  18352. }
  18353. // Nuke all the related SSRCs.
  18354. relatedSsrcs.forEach(function (relatedSSRC) {
  18355. sources[relatedSSRC].msid = sources[ssrc].msid;
  18356. sources[relatedSSRC].cname = sources[ssrc].cname;
  18357. if (relatedSSRC !== ssrc) {
  18358. order.push(relatedSSRC);
  18359. }
  18360. });
  18361. // Schedule the related group for nuking.
  18362. })
  18363. }
  18364. mLine.ssrcs = writeSsrcs(sources, order);
  18365. mLine.ssrcGroups.splice(j, 1);
  18366. };
  18367. }
  18368. function squeezeRemoteSimulcast(mLine) {
  18369. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18370. return;
  18371. }
  18372. var sources = parseSsrcs(mLine);
  18373. // Find the SIM group and nuke it.
  18374. mLine.ssrcGroups.some(function (simulcastGroup) {
  18375. if (simulcastGroup.semantics !== 'SIM') {
  18376. return false;
  18377. }
  18378. // Schedule the SIM group for nuking.
  18379. simulcastGroup.nuke = true;
  18380. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  18381. // Nuke all the higher layer SSRCs.
  18382. for (var i = 1; i < simulcastSsrcs.length; i++) {
  18383. var ssrc = simulcastSsrcs[i];
  18384. delete sources[ssrc];
  18385. // Remove all the groups that this SSRC participates in.
  18386. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18387. if (relatedGroup.semantics === 'SIM') {
  18388. return;
  18389. }
  18390. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18391. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18392. return;
  18393. }
  18394. // Nuke all the related SSRCs.
  18395. relatedSsrcs.forEach(function (relatedSSRC) {
  18396. delete sources[relatedSSRC];
  18397. });
  18398. // Schedule the related group for nuking.
  18399. relatedGroup.nuke = true;
  18400. })
  18401. }
  18402. return true;
  18403. });
  18404. mLine.ssrcs = writeSsrcs(sources);
  18405. // Nuke all the scheduled groups.
  18406. var i = mLine.ssrcGroups.length;
  18407. while (i--) {
  18408. if (mLine.ssrcGroups[i].nuke) {
  18409. mLine.ssrcGroups.splice(i, 1);
  18410. }
  18411. }
  18412. }
  18413. function removeGoogConference(mLine) {
  18414. if (!mLine || !Array.isArray(mLine.invalid)) {
  18415. return;
  18416. }
  18417. var i = mLine.invalid.length;
  18418. while (i--) {
  18419. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  18420. mLine.invalid.splice(i, 1);
  18421. }
  18422. }
  18423. }
  18424. function assertGoogConference(mLine) {
  18425. if (!mLine) {
  18426. return;
  18427. }
  18428. if (!Array.isArray(mLine.invalid)) {
  18429. mLine.invalid = [];
  18430. }
  18431. if (!mLine.invalid.some(
  18432. function (i) { return i.value === 'x-google-flag:conference' })) {
  18433. mLine.invalid.push({'value': 'x-google-flag:conference'});
  18434. }
  18435. }
  18436. //endregion
  18437. //region "Private" functions
  18438. /**
  18439. *
  18440. * @param mLine
  18441. * @private
  18442. */
  18443. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  18444. if (!mLine || mLine.type !== 'video') {
  18445. return;
  18446. }
  18447. var sources = parseSsrcs(mLine);
  18448. if (Object.keys(sources).length === 0) {
  18449. // no sources, disable simulcast.
  18450. if (this.layers.length !== 0) {
  18451. this.layers = [];
  18452. }
  18453. return;
  18454. }
  18455. // find the base layer (we'll reuse its msid and cname).
  18456. var baseLayerSSRC = Object.keys(sources)[0];
  18457. var baseLayer = sources[baseLayerSSRC];
  18458. // todo(gp) handle screen sharing.
  18459. // check if base CNAME has changed and reinitialise layers.
  18460. if (this.layers.length > 0
  18461. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  18462. this.layers = [];
  18463. }
  18464. // (re)initialise layers
  18465. if (this.layers.length < 1) {
  18466. // first push the base layer.
  18467. this.layers.push({
  18468. ssrc: baseLayerSSRC,
  18469. msid: baseLayer.msid,
  18470. cname: baseLayer.cname
  18471. });
  18472. var rtx = false; // RFC 4588
  18473. if (Array.isArray(mLine.rtp)) {
  18474. rtx = mLine.rtp.some(
  18475. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  18476. }
  18477. if (rtx) {
  18478. this.layers[0].rtx = generateSSRC();
  18479. }
  18480. // now push additional layers.
  18481. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  18482. var layer = { ssrc: generateSSRC() };
  18483. if (rtx) {
  18484. layer.rtx = generateSSRC();
  18485. }
  18486. this.layers.push(layer);
  18487. }
  18488. }
  18489. };
  18490. /**
  18491. *
  18492. * @param mLine
  18493. * @private
  18494. */
  18495. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  18496. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  18497. var sources = {};
  18498. var msid = this.layers[0].msid;
  18499. var cname = this.layers[0].cname;
  18500. var simulcastSsrcs = [];
  18501. var ssrcGroups = [];
  18502. for (var i = 0; i < this.layers.length; i++) {
  18503. var layer = this.layers[i];
  18504. sources[layer.ssrc] = { msid: msid, cname: cname };
  18505. simulcastSsrcs.push(layer.ssrc);
  18506. if (layer.rtx) {
  18507. sources[layer.rtx] = {
  18508. msid: msid,
  18509. cname: cname
  18510. }
  18511. ssrcGroups.push({
  18512. semantics: 'FID',
  18513. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  18514. });
  18515. }
  18516. }
  18517. ssrcGroups.push({
  18518. semantics: 'SIM',
  18519. ssrcs: simulcastSsrcs.join(' ')
  18520. });
  18521. mLine.ssrcGroups = ssrcGroups;
  18522. mLine.ssrcs = writeSsrcs(sources);
  18523. }
  18524. }
  18525. //endregion
  18526. //region "Public" functions
  18527. Simulcast.prototype.isSupported = function () {
  18528. return window.chrome;
  18529. // TODO this needs improvements. For example I doubt that Chrome in Android
  18530. // has simulcast support. Also, only recent versions of Chromium have native
  18531. // simulcast support.
  18532. }
  18533. /**
  18534. *
  18535. * @param desc
  18536. * @returns {RTCSessionDescription}
  18537. */
  18538. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  18539. if (!validateDescription(desc)) {
  18540. return desc;
  18541. }
  18542. var session = transform.parse(desc.sdp);
  18543. var self = this;
  18544. processVideo(session, function (mLine) {
  18545. // Handle simulcast reception.
  18546. if (self.options.explodeRemoteSimulcast) {
  18547. explodeRemoteSimulcast(mLine);
  18548. } else {
  18549. squeezeRemoteSimulcast(mLine);
  18550. }
  18551. // If native simulcast is enabled, we must append the x-goog-conference
  18552. // attribute to the SDP.
  18553. if (self.layers.length < 1) {
  18554. removeGoogConference(mLine);
  18555. } else {
  18556. assertGoogConference(mLine);
  18557. }
  18558. });
  18559. return new RTCSessionDescription({
  18560. type: desc.type,
  18561. sdp: transform.write(session)
  18562. });
  18563. };
  18564. /**
  18565. *
  18566. * @param desc
  18567. * @returns {RTCSessionDescription}
  18568. */
  18569. Simulcast.prototype.mungeLocalDescription = function (desc) {
  18570. if (!validateDescription(desc) || !this.isSupported()) {
  18571. return desc;
  18572. }
  18573. var session = transform.parse(desc.sdp);
  18574. var self = this;
  18575. processVideo(session, function (mLine) {
  18576. // Initialize native simulcast layers, if not already done.
  18577. self._maybeInitializeLayers(mLine);
  18578. // Update the SDP with the simulcast layers.
  18579. self._restoreSimulcastView(mLine);
  18580. });
  18581. return new RTCSessionDescription({
  18582. type: desc.type,
  18583. sdp: transform.write(session)
  18584. });
  18585. };
  18586. //endregion
  18587. module.exports = Simulcast;
  18588. },{"./transform-utils":66,"sdp-transform":68}],66:[function(require,module,exports){
  18589. exports.writeSsrcs = function(sources, order) {
  18590. var ssrcs = [];
  18591. // expand sources to ssrcs
  18592. if (typeof sources !== 'undefined' &&
  18593. Object.keys(sources).length !== 0) {
  18594. if (Array.isArray(order)) {
  18595. for (var i = 0; i < order.length; i++) {
  18596. var ssrc = order[i];
  18597. var source = sources[ssrc];
  18598. Object.keys(source).forEach(function (attribute) {
  18599. ssrcs.push({
  18600. id: ssrc,
  18601. attribute: attribute,
  18602. value: source[attribute]
  18603. });
  18604. });
  18605. }
  18606. } else {
  18607. Object.keys(sources).forEach(function (ssrc) {
  18608. var source = sources[ssrc];
  18609. Object.keys(source).forEach(function (attribute) {
  18610. ssrcs.push({
  18611. id: ssrc,
  18612. attribute: attribute,
  18613. value: source[attribute]
  18614. });
  18615. });
  18616. });
  18617. }
  18618. }
  18619. return ssrcs;
  18620. };
  18621. exports.parseSsrcs = function (mLine) {
  18622. var sources = {};
  18623. // group sources attributes by ssrc.
  18624. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  18625. mLine.ssrcs.forEach(function (ssrc) {
  18626. if (!sources[ssrc.id])
  18627. sources[ssrc.id] = {};
  18628. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  18629. });
  18630. }
  18631. return sources;
  18632. };
  18633. },{}],67:[function(require,module,exports){
  18634. var grammar = module.exports = {
  18635. v: [{
  18636. name: 'version',
  18637. reg: /^(\d*)$/
  18638. }],
  18639. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  18640. // NB: sessionId will be a String in most cases because it is huge
  18641. name: 'origin',
  18642. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  18643. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  18644. format: "%s %s %d %s IP%d %s"
  18645. }],
  18646. // default parsing of these only (though some of these feel outdated)
  18647. s: [{ name: 'name' }],
  18648. i: [{ name: 'description' }],
  18649. u: [{ name: 'uri' }],
  18650. e: [{ name: 'email' }],
  18651. p: [{ name: 'phone' }],
  18652. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  18653. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  18654. //k: [{}], // outdated thing ignored
  18655. t: [{ //t=0 0
  18656. name: 'timing',
  18657. reg: /^(\d*) (\d*)/,
  18658. names: ['start', 'stop'],
  18659. format: "%d %d"
  18660. }],
  18661. c: [{ //c=IN IP4 10.47.197.26
  18662. name: 'connection',
  18663. reg: /^IN IP(\d) (\S*)/,
  18664. names: ['version', 'ip'],
  18665. format: "IN IP%d %s"
  18666. }],
  18667. b: [{ //b=AS:4000
  18668. push: 'bandwidth',
  18669. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  18670. names: ['type', 'limit'],
  18671. format: "%s:%s"
  18672. }],
  18673. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  18674. // NB: special - pushes to session
  18675. // TODO: rtp/fmtp should be filtered by the payloads found here?
  18676. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  18677. names: ['type', 'port', 'protocol', 'payloads'],
  18678. format: "%s %d %s %s"
  18679. }],
  18680. a: [
  18681. { //a=rtpmap:110 opus/48000/2
  18682. push: 'rtp',
  18683. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  18684. names: ['payload', 'codec', 'rate', 'encoding'],
  18685. format: function (o) {
  18686. return (o.encoding) ?
  18687. "rtpmap:%d %s/%s/%s":
  18688. "rtpmap:%d %s/%s";
  18689. }
  18690. },
  18691. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  18692. push: 'fmtp',
  18693. reg: /^fmtp:(\d*) (\S*)/,
  18694. names: ['payload', 'config'],
  18695. format: "fmtp:%d %s"
  18696. },
  18697. { //a=control:streamid=0
  18698. name: 'control',
  18699. reg: /^control:(.*)/,
  18700. format: "control:%s"
  18701. },
  18702. { //a=rtcp:65179 IN IP4 193.84.77.194
  18703. name: 'rtcp',
  18704. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  18705. names: ['port', 'netType', 'ipVer', 'address'],
  18706. format: function (o) {
  18707. return (o.address != null) ?
  18708. "rtcp:%d %s IP%d %s":
  18709. "rtcp:%d";
  18710. }
  18711. },
  18712. { //a=rtcp-fb:98 trr-int 100
  18713. push: 'rtcpFbTrrInt',
  18714. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  18715. names: ['payload', 'value'],
  18716. format: "rtcp-fb:%d trr-int %d"
  18717. },
  18718. { //a=rtcp-fb:98 nack rpsi
  18719. push: 'rtcpFb',
  18720. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  18721. names: ['payload', 'type', 'subtype'],
  18722. format: function (o) {
  18723. return (o.subtype != null) ?
  18724. "rtcp-fb:%s %s %s":
  18725. "rtcp-fb:%s %s";
  18726. }
  18727. },
  18728. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  18729. //a=extmap:1/recvonly URI-gps-string
  18730. push: 'ext',
  18731. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  18732. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  18733. format: function (o) {
  18734. return (o.config != null) ?
  18735. "extmap:%s %s %s":
  18736. "extmap:%s %s";
  18737. }
  18738. },
  18739. {
  18740. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  18741. push: 'crypto',
  18742. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  18743. names: ['id', 'suite', 'config', 'sessionConfig'],
  18744. format: function (o) {
  18745. return (o.sessionConfig != null) ?
  18746. "crypto:%d %s %s %s":
  18747. "crypto:%d %s %s";
  18748. }
  18749. },
  18750. { //a=setup:actpass
  18751. name: 'setup',
  18752. reg: /^setup:(\w*)/,
  18753. format: "setup:%s"
  18754. },
  18755. { //a=mid:1
  18756. name: 'mid',
  18757. reg: /^mid:([^\s]*)/,
  18758. format: "mid:%s"
  18759. },
  18760. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  18761. name: 'msid',
  18762. reg: /^msid:(.*)/,
  18763. format: "msid:%s"
  18764. },
  18765. { //a=ptime:20
  18766. name: 'ptime',
  18767. reg: /^ptime:(\d*)/,
  18768. format: "ptime:%d"
  18769. },
  18770. { //a=maxptime:60
  18771. name: 'maxptime',
  18772. reg: /^maxptime:(\d*)/,
  18773. format: "maxptime:%d"
  18774. },
  18775. { //a=sendrecv
  18776. name: 'direction',
  18777. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  18778. },
  18779. { //a=ice-lite
  18780. name: 'icelite',
  18781. reg: /^(ice-lite)/
  18782. },
  18783. { //a=ice-ufrag:F7gI
  18784. name: 'iceUfrag',
  18785. reg: /^ice-ufrag:(\S*)/,
  18786. format: "ice-ufrag:%s"
  18787. },
  18788. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  18789. name: 'icePwd',
  18790. reg: /^ice-pwd:(\S*)/,
  18791. format: "ice-pwd:%s"
  18792. },
  18793. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  18794. name: 'fingerprint',
  18795. reg: /^fingerprint:(\S*) (\S*)/,
  18796. names: ['type', 'hash'],
  18797. format: "fingerprint:%s %s"
  18798. },
  18799. {
  18800. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  18801. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  18802. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  18803. push:'candidates',
  18804. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  18805. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  18806. format: function (o) {
  18807. var str = "candidate:%s %d %s %d %s %d typ %s";
  18808. // NB: candidate has two optional chunks, so %void middle one if it's missing
  18809. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  18810. if (o.generation != null) {
  18811. str += " generation %d";
  18812. }
  18813. return str;
  18814. }
  18815. },
  18816. { //a=end-of-candidates (keep after the candidates line for readability)
  18817. name: 'endOfCandidates',
  18818. reg: /^(end-of-candidates)/
  18819. },
  18820. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  18821. name: 'remoteCandidates',
  18822. reg: /^remote-candidates:(.*)/,
  18823. format: "remote-candidates:%s"
  18824. },
  18825. { //a=ice-options:google-ice
  18826. name: 'iceOptions',
  18827. reg: /^ice-options:(\S*)/,
  18828. format: "ice-options:%s"
  18829. },
  18830. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  18831. push: "ssrcs",
  18832. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  18833. names: ['id', 'attribute', 'value'],
  18834. format: "ssrc:%d %s:%s"
  18835. },
  18836. { //a=ssrc-group:FEC 1 2
  18837. push: "ssrcGroups",
  18838. reg: /^ssrc-group:(\w*) (.*)/,
  18839. names: ['semantics', 'ssrcs'],
  18840. format: "ssrc-group:%s %s"
  18841. },
  18842. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  18843. name: "msidSemantic",
  18844. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  18845. names: ['semantic', 'token'],
  18846. format: "msid-semantic: %s %s" // space after ":" is not accidental
  18847. },
  18848. { //a=group:BUNDLE audio video
  18849. push: 'groups',
  18850. reg: /^group:(\w*) (.*)/,
  18851. names: ['type', 'mids'],
  18852. format: "group:%s %s"
  18853. },
  18854. { //a=rtcp-mux
  18855. name: 'rtcpMux',
  18856. reg: /^(rtcp-mux)/
  18857. },
  18858. { //a=rtcp-rsize
  18859. name: 'rtcpRsize',
  18860. reg: /^(rtcp-rsize)/
  18861. },
  18862. { // any a= that we don't understand is kepts verbatim on media.invalid
  18863. push: 'invalid',
  18864. names: ["value"]
  18865. }
  18866. ]
  18867. };
  18868. // set sensible defaults to avoid polluting the grammar with boring details
  18869. Object.keys(grammar).forEach(function (key) {
  18870. var objs = grammar[key];
  18871. objs.forEach(function (obj) {
  18872. if (!obj.reg) {
  18873. obj.reg = /(.*)/;
  18874. }
  18875. if (!obj.format) {
  18876. obj.format = "%s";
  18877. }
  18878. });
  18879. });
  18880. },{}],68:[function(require,module,exports){
  18881. var parser = require('./parser');
  18882. var writer = require('./writer');
  18883. exports.write = writer;
  18884. exports.parse = parser.parse;
  18885. exports.parseFmtpConfig = parser.parseFmtpConfig;
  18886. exports.parsePayloads = parser.parsePayloads;
  18887. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  18888. },{"./parser":69,"./writer":70}],69:[function(require,module,exports){
  18889. var toIntIfInt = function (v) {
  18890. return String(Number(v)) === v ? Number(v) : v;
  18891. };
  18892. var attachProperties = function (match, location, names, rawName) {
  18893. if (rawName && !names) {
  18894. location[rawName] = toIntIfInt(match[1]);
  18895. }
  18896. else {
  18897. for (var i = 0; i < names.length; i += 1) {
  18898. if (match[i+1] != null) {
  18899. location[names[i]] = toIntIfInt(match[i+1]);
  18900. }
  18901. }
  18902. }
  18903. };
  18904. var parseReg = function (obj, location, content) {
  18905. var needsBlank = obj.name && obj.names;
  18906. if (obj.push && !location[obj.push]) {
  18907. location[obj.push] = [];
  18908. }
  18909. else if (needsBlank && !location[obj.name]) {
  18910. location[obj.name] = {};
  18911. }
  18912. var keyLocation = obj.push ?
  18913. {} : // blank object that will be pushed
  18914. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  18915. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  18916. if (obj.push) {
  18917. location[obj.push].push(keyLocation);
  18918. }
  18919. };
  18920. var grammar = require('./grammar');
  18921. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  18922. exports.parse = function (sdp) {
  18923. var session = {}
  18924. , media = []
  18925. , location = session; // points at where properties go under (one of the above)
  18926. // parse lines we understand
  18927. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  18928. var type = l[0];
  18929. var content = l.slice(2);
  18930. if (type === 'm') {
  18931. media.push({rtp: [], fmtp: []});
  18932. location = media[media.length-1]; // point at latest media line
  18933. }
  18934. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  18935. var obj = grammar[type][j];
  18936. if (obj.reg.test(content)) {
  18937. return parseReg(obj, location, content);
  18938. }
  18939. }
  18940. });
  18941. session.media = media; // link it up
  18942. return session;
  18943. };
  18944. var fmtpReducer = function (acc, expr) {
  18945. var s = expr.split('=');
  18946. if (s.length === 2) {
  18947. acc[s[0]] = toIntIfInt(s[1]);
  18948. }
  18949. return acc;
  18950. };
  18951. exports.parseFmtpConfig = function (str) {
  18952. return str.split(';').reduce(fmtpReducer, {});
  18953. };
  18954. exports.parsePayloads = function (str) {
  18955. return str.split(' ').map(Number);
  18956. };
  18957. exports.parseRemoteCandidates = function (str) {
  18958. var candidates = [];
  18959. var parts = str.split(' ').map(toIntIfInt);
  18960. for (var i = 0; i < parts.length; i += 3) {
  18961. candidates.push({
  18962. component: parts[i],
  18963. ip: parts[i + 1],
  18964. port: parts[i + 2]
  18965. });
  18966. }
  18967. return candidates;
  18968. };
  18969. },{"./grammar":67}],70:[function(require,module,exports){
  18970. var grammar = require('./grammar');
  18971. // customized util.format - discards excess arguments and can void middle ones
  18972. var formatRegExp = /%[sdv%]/g;
  18973. var format = function (formatStr) {
  18974. var i = 1;
  18975. var args = arguments;
  18976. var len = args.length;
  18977. return formatStr.replace(formatRegExp, function (x) {
  18978. if (i >= len) {
  18979. return x; // missing argument
  18980. }
  18981. var arg = args[i];
  18982. i += 1;
  18983. switch (x) {
  18984. case '%%':
  18985. return '%';
  18986. case '%s':
  18987. return String(arg);
  18988. case '%d':
  18989. return Number(arg);
  18990. case '%v':
  18991. return '';
  18992. }
  18993. });
  18994. // NB: we discard excess arguments - they are typically undefined from makeLine
  18995. };
  18996. var makeLine = function (type, obj, location) {
  18997. var str = obj.format instanceof Function ?
  18998. (obj.format(obj.push ? location : location[obj.name])) :
  18999. obj.format;
  19000. var args = [type + '=' + str];
  19001. if (obj.names) {
  19002. for (var i = 0; i < obj.names.length; i += 1) {
  19003. var n = obj.names[i];
  19004. if (obj.name) {
  19005. args.push(location[obj.name][n]);
  19006. }
  19007. else { // for mLine and push attributes
  19008. args.push(location[obj.names[i]]);
  19009. }
  19010. }
  19011. }
  19012. else {
  19013. args.push(location[obj.name]);
  19014. }
  19015. return format.apply(null, args);
  19016. };
  19017. // RFC specified order
  19018. // TODO: extend this with all the rest
  19019. var defaultOuterOrder = [
  19020. 'v', 'o', 's', 'i',
  19021. 'u', 'e', 'p', 'c',
  19022. 'b', 't', 'r', 'z', 'a'
  19023. ];
  19024. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19025. module.exports = function (session, opts) {
  19026. opts = opts || {};
  19027. // ensure certain properties exist
  19028. if (session.version == null) {
  19029. session.version = 0; // "v=0" must be there (only defined version atm)
  19030. }
  19031. if (session.name == null) {
  19032. session.name = " "; // "s= " must be there if no meaningful name set
  19033. }
  19034. session.media.forEach(function (mLine) {
  19035. if (mLine.payloads == null) {
  19036. mLine.payloads = "";
  19037. }
  19038. });
  19039. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19040. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19041. var sdp = [];
  19042. // loop through outerOrder for matching properties on session
  19043. outerOrder.forEach(function (type) {
  19044. grammar[type].forEach(function (obj) {
  19045. if (obj.name in session && session[obj.name] != null) {
  19046. sdp.push(makeLine(type, obj, session));
  19047. }
  19048. else if (obj.push in session && session[obj.push] != null) {
  19049. session[obj.push].forEach(function (el) {
  19050. sdp.push(makeLine(type, obj, el));
  19051. });
  19052. }
  19053. });
  19054. });
  19055. // then for each media line, follow the innerOrder
  19056. session.media.forEach(function (mLine) {
  19057. sdp.push(makeLine('m', grammar.m[0], mLine));
  19058. innerOrder.forEach(function (type) {
  19059. grammar[type].forEach(function (obj) {
  19060. if (obj.name in mLine && mLine[obj.name] != null) {
  19061. sdp.push(makeLine(type, obj, mLine));
  19062. }
  19063. else if (obj.push in mLine && mLine[obj.push] != null) {
  19064. mLine[obj.push].forEach(function (el) {
  19065. sdp.push(makeLine(type, obj, el));
  19066. });
  19067. }
  19068. });
  19069. });
  19070. });
  19071. return sdp.join('\r\n') + '\r\n';
  19072. };
  19073. },{"./grammar":67}],71:[function(require,module,exports){
  19074. var grammar = module.exports = {
  19075. v: [{
  19076. name: 'version',
  19077. reg: /^(\d*)$/
  19078. }],
  19079. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19080. // NB: sessionId will be a String in most cases because it is huge
  19081. name: 'origin',
  19082. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19083. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19084. format: "%s %s %d %s IP%d %s"
  19085. }],
  19086. // default parsing of these only (though some of these feel outdated)
  19087. s: [{ name: 'name' }],
  19088. i: [{ name: 'description' }],
  19089. u: [{ name: 'uri' }],
  19090. e: [{ name: 'email' }],
  19091. p: [{ name: 'phone' }],
  19092. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19093. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19094. //k: [{}], // outdated thing ignored
  19095. t: [{ //t=0 0
  19096. name: 'timing',
  19097. reg: /^(\d*) (\d*)/,
  19098. names: ['start', 'stop'],
  19099. format: "%d %d"
  19100. }],
  19101. c: [{ //c=IN IP4 10.47.197.26
  19102. name: 'connection',
  19103. reg: /^IN IP(\d) (\S*)/,
  19104. names: ['version', 'ip'],
  19105. format: "IN IP%d %s"
  19106. }],
  19107. b: [{ //b=AS:4000
  19108. push: 'bandwidth',
  19109. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19110. names: ['type', 'limit'],
  19111. format: "%s:%s"
  19112. }],
  19113. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19114. // NB: special - pushes to session
  19115. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19116. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19117. names: ['type', 'port', 'protocol', 'payloads'],
  19118. format: "%s %d %s %s"
  19119. }],
  19120. a: [
  19121. { //a=rtpmap:110 opus/48000/2
  19122. push: 'rtp',
  19123. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19124. names: ['payload', 'codec', 'rate', 'encoding'],
  19125. format: function (o) {
  19126. return (o.encoding) ?
  19127. "rtpmap:%d %s/%s/%s":
  19128. "rtpmap:%d %s/%s";
  19129. }
  19130. },
  19131. {
  19132. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19133. //a=fmtp:111 minptime=10; useinbandfec=1
  19134. push: 'fmtp',
  19135. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19136. names: ['payload', 'config'],
  19137. format: "fmtp:%d %s"
  19138. },
  19139. { //a=control:streamid=0
  19140. name: 'control',
  19141. reg: /^control:(.*)/,
  19142. format: "control:%s"
  19143. },
  19144. { //a=rtcp:65179 IN IP4 193.84.77.194
  19145. name: 'rtcp',
  19146. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19147. names: ['port', 'netType', 'ipVer', 'address'],
  19148. format: function (o) {
  19149. return (o.address != null) ?
  19150. "rtcp:%d %s IP%d %s":
  19151. "rtcp:%d";
  19152. }
  19153. },
  19154. { //a=rtcp-fb:98 trr-int 100
  19155. push: 'rtcpFbTrrInt',
  19156. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19157. names: ['payload', 'value'],
  19158. format: "rtcp-fb:%d trr-int %d"
  19159. },
  19160. { //a=rtcp-fb:98 nack rpsi
  19161. push: 'rtcpFb',
  19162. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19163. names: ['payload', 'type', 'subtype'],
  19164. format: function (o) {
  19165. return (o.subtype != null) ?
  19166. "rtcp-fb:%s %s %s":
  19167. "rtcp-fb:%s %s";
  19168. }
  19169. },
  19170. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19171. //a=extmap:1/recvonly URI-gps-string
  19172. push: 'ext',
  19173. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19174. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19175. format: function (o) {
  19176. return (o.config != null) ?
  19177. "extmap:%s %s %s":
  19178. "extmap:%s %s";
  19179. }
  19180. },
  19181. {
  19182. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19183. push: 'crypto',
  19184. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19185. names: ['id', 'suite', 'config', 'sessionConfig'],
  19186. format: function (o) {
  19187. return (o.sessionConfig != null) ?
  19188. "crypto:%d %s %s %s":
  19189. "crypto:%d %s %s";
  19190. }
  19191. },
  19192. { //a=setup:actpass
  19193. name: 'setup',
  19194. reg: /^setup:(\w*)/,
  19195. format: "setup:%s"
  19196. },
  19197. { //a=mid:1
  19198. name: 'mid',
  19199. reg: /^mid:([^\s]*)/,
  19200. format: "mid:%s"
  19201. },
  19202. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19203. name: 'msid',
  19204. reg: /^msid:(.*)/,
  19205. format: "msid:%s"
  19206. },
  19207. { //a=ptime:20
  19208. name: 'ptime',
  19209. reg: /^ptime:(\d*)/,
  19210. format: "ptime:%d"
  19211. },
  19212. { //a=maxptime:60
  19213. name: 'maxptime',
  19214. reg: /^maxptime:(\d*)/,
  19215. format: "maxptime:%d"
  19216. },
  19217. { //a=sendrecv
  19218. name: 'direction',
  19219. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19220. },
  19221. { //a=ice-lite
  19222. name: 'icelite',
  19223. reg: /^(ice-lite)/
  19224. },
  19225. { //a=ice-ufrag:F7gI
  19226. name: 'iceUfrag',
  19227. reg: /^ice-ufrag:(\S*)/,
  19228. format: "ice-ufrag:%s"
  19229. },
  19230. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19231. name: 'icePwd',
  19232. reg: /^ice-pwd:(\S*)/,
  19233. format: "ice-pwd:%s"
  19234. },
  19235. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19236. name: 'fingerprint',
  19237. reg: /^fingerprint:(\S*) (\S*)/,
  19238. names: ['type', 'hash'],
  19239. format: "fingerprint:%s %s"
  19240. },
  19241. {
  19242. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19243. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19244. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19245. push:'candidates',
  19246. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19247. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19248. format: function (o) {
  19249. var str = "candidate:%s %d %s %d %s %d typ %s";
  19250. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19251. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19252. if (o.generation != null) {
  19253. str += " generation %d";
  19254. }
  19255. return str;
  19256. }
  19257. },
  19258. { //a=end-of-candidates (keep after the candidates line for readability)
  19259. name: 'endOfCandidates',
  19260. reg: /^(end-of-candidates)/
  19261. },
  19262. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19263. name: 'remoteCandidates',
  19264. reg: /^remote-candidates:(.*)/,
  19265. format: "remote-candidates:%s"
  19266. },
  19267. { //a=ice-options:google-ice
  19268. name: 'iceOptions',
  19269. reg: /^ice-options:(\S*)/,
  19270. format: "ice-options:%s"
  19271. },
  19272. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19273. push: "ssrcs",
  19274. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19275. names: ['id', 'attribute', 'value'],
  19276. format: "ssrc:%d %s:%s"
  19277. },
  19278. { //a=ssrc-group:FEC 1 2
  19279. push: "ssrcGroups",
  19280. reg: /^ssrc-group:(\w*) (.*)/,
  19281. names: ['semantics', 'ssrcs'],
  19282. format: "ssrc-group:%s %s"
  19283. },
  19284. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19285. name: "msidSemantic",
  19286. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19287. names: ['semantic', 'token'],
  19288. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19289. },
  19290. { //a=group:BUNDLE audio video
  19291. push: 'groups',
  19292. reg: /^group:(\w*) (.*)/,
  19293. names: ['type', 'mids'],
  19294. format: "group:%s %s"
  19295. },
  19296. { //a=rtcp-mux
  19297. name: 'rtcpMux',
  19298. reg: /^(rtcp-mux)/
  19299. },
  19300. { //a=rtcp-rsize
  19301. name: 'rtcpRsize',
  19302. reg: /^(rtcp-rsize)/
  19303. },
  19304. { // any a= that we don't understand is kepts verbatim on media.invalid
  19305. push: 'invalid',
  19306. names: ["value"]
  19307. }
  19308. ]
  19309. };
  19310. // set sensible defaults to avoid polluting the grammar with boring details
  19311. Object.keys(grammar).forEach(function (key) {
  19312. var objs = grammar[key];
  19313. objs.forEach(function (obj) {
  19314. if (!obj.reg) {
  19315. obj.reg = /(.*)/;
  19316. }
  19317. if (!obj.format) {
  19318. obj.format = "%s";
  19319. }
  19320. });
  19321. });
  19322. },{}],72:[function(require,module,exports){
  19323. arguments[4][68][0].apply(exports,arguments)
  19324. },{"./parser":73,"./writer":74,"dup":68}],73:[function(require,module,exports){
  19325. var toIntIfInt = function (v) {
  19326. return String(Number(v)) === v ? Number(v) : v;
  19327. };
  19328. var attachProperties = function (match, location, names, rawName) {
  19329. if (rawName && !names) {
  19330. location[rawName] = toIntIfInt(match[1]);
  19331. }
  19332. else {
  19333. for (var i = 0; i < names.length; i += 1) {
  19334. if (match[i+1] != null) {
  19335. location[names[i]] = toIntIfInt(match[i+1]);
  19336. }
  19337. }
  19338. }
  19339. };
  19340. var parseReg = function (obj, location, content) {
  19341. var needsBlank = obj.name && obj.names;
  19342. if (obj.push && !location[obj.push]) {
  19343. location[obj.push] = [];
  19344. }
  19345. else if (needsBlank && !location[obj.name]) {
  19346. location[obj.name] = {};
  19347. }
  19348. var keyLocation = obj.push ?
  19349. {} : // blank object that will be pushed
  19350. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19351. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19352. if (obj.push) {
  19353. location[obj.push].push(keyLocation);
  19354. }
  19355. };
  19356. var grammar = require('./grammar');
  19357. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19358. exports.parse = function (sdp) {
  19359. var session = {}
  19360. , media = []
  19361. , location = session; // points at where properties go under (one of the above)
  19362. // parse lines we understand
  19363. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19364. var type = l[0];
  19365. var content = l.slice(2);
  19366. if (type === 'm') {
  19367. media.push({rtp: [], fmtp: []});
  19368. location = media[media.length-1]; // point at latest media line
  19369. }
  19370. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19371. var obj = grammar[type][j];
  19372. if (obj.reg.test(content)) {
  19373. return parseReg(obj, location, content);
  19374. }
  19375. }
  19376. });
  19377. session.media = media; // link it up
  19378. return session;
  19379. };
  19380. var fmtpReducer = function (acc, expr) {
  19381. var s = expr.split('=');
  19382. if (s.length === 2) {
  19383. acc[s[0]] = toIntIfInt(s[1]);
  19384. }
  19385. return acc;
  19386. };
  19387. exports.parseFmtpConfig = function (str) {
  19388. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  19389. };
  19390. exports.parsePayloads = function (str) {
  19391. return str.split(' ').map(Number);
  19392. };
  19393. exports.parseRemoteCandidates = function (str) {
  19394. var candidates = [];
  19395. var parts = str.split(' ').map(toIntIfInt);
  19396. for (var i = 0; i < parts.length; i += 3) {
  19397. candidates.push({
  19398. component: parts[i],
  19399. ip: parts[i + 1],
  19400. port: parts[i + 2]
  19401. });
  19402. }
  19403. return candidates;
  19404. };
  19405. },{"./grammar":71}],74:[function(require,module,exports){
  19406. arguments[4][70][0].apply(exports,arguments)
  19407. },{"./grammar":71,"dup":70}],75:[function(require,module,exports){
  19408. var MediaStreamType = {
  19409. VIDEO_TYPE: "Video",
  19410. AUDIO_TYPE: "Audio"
  19411. };
  19412. module.exports = MediaStreamType;
  19413. },{}],76:[function(require,module,exports){
  19414. var RTCEvents = {
  19415. RTC_READY: "rtc.ready",
  19416. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  19417. LASTN_CHANGED: "rtc.lastn_changed",
  19418. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  19419. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  19420. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  19421. };
  19422. module.exports = RTCEvents;
  19423. },{}],77:[function(require,module,exports){
  19424. var Resolutions = {
  19425. "1080": {
  19426. width: 1920,
  19427. height: 1080,
  19428. order: 7
  19429. },
  19430. "fullhd": {
  19431. width: 1920,
  19432. height: 1080,
  19433. order: 7
  19434. },
  19435. "720": {
  19436. width: 1280,
  19437. height: 720,
  19438. order: 6
  19439. },
  19440. "hd": {
  19441. width: 1280,
  19442. height: 720,
  19443. order: 6
  19444. },
  19445. "960": {
  19446. width: 960,
  19447. height: 720,
  19448. order: 5
  19449. },
  19450. "640": {
  19451. width: 640,
  19452. height: 480,
  19453. order: 4
  19454. },
  19455. "vga": {
  19456. width: 640,
  19457. height: 480,
  19458. order: 4
  19459. },
  19460. "360": {
  19461. width: 640,
  19462. height: 360,
  19463. order: 3
  19464. },
  19465. "320": {
  19466. width: 320,
  19467. height: 240,
  19468. order: 2
  19469. },
  19470. "180": {
  19471. width: 320,
  19472. height: 180,
  19473. order: 1
  19474. }
  19475. };
  19476. module.exports = Resolutions;
  19477. },{}],78:[function(require,module,exports){
  19478. var StreamEventTypes = {
  19479. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  19480. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  19481. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  19482. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  19483. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  19484. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  19485. };
  19486. module.exports = StreamEventTypes;
  19487. },{}],79:[function(require,module,exports){
  19488. var AuthenticationEvents = {
  19489. /**
  19490. * Event callback arguments:
  19491. * function(authenticationEnabled, userIdentity)
  19492. * authenticationEnabled - indicates whether authentication has been enabled
  19493. * in this session
  19494. * userIdentity - if user has been logged in then it contains user name. If
  19495. * contains 'null' or 'undefined' then user is not logged in.
  19496. */
  19497. IDENTITY_UPDATED: "authentication.identity_updated"
  19498. };
  19499. module.exports = AuthenticationEvents;
  19500. },{}],80:[function(require,module,exports){
  19501. var DesktopSharingEventTypes = {
  19502. INIT: "ds.init",
  19503. SWITCHING_DONE: "ds.switching_done",
  19504. NEW_STREAM_CREATED: "ds.new_stream_created"
  19505. };
  19506. module.exports = DesktopSharingEventTypes;
  19507. },{}],81:[function(require,module,exports){
  19508. var Constants = {
  19509. LOCAL_JID: 'local'
  19510. };
  19511. module.exports = Constants;
  19512. },{}],82:[function(require,module,exports){
  19513. var XMPPEvents = {
  19514. // Designates an event indicating that the connection to the XMPP server
  19515. // failed.
  19516. CONNECTION_FAILED: "xmpp.connection.failed",
  19517. // Designates an event indicating that the media (ICE) connection was
  19518. // interrupted. This should go to the RTC module.
  19519. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  19520. // Designates an event indicating that the media (ICE) connection was
  19521. // restored. This should go to the RTC module.
  19522. CONNECTION_RESTORED: "xmpp.connection.restored",
  19523. // Designates an event indicating that an offer (e.g. Jingle
  19524. // session-initiate) was received.
  19525. CALL_INCOMING: "xmpp.callincoming.jingle",
  19526. // Designates an event indicating that we were kicked from the XMPP MUC.
  19527. KICKED: "xmpp.kicked",
  19528. // Designates an event indicating that the userID for a specific JID has
  19529. // changed.
  19530. USER_ID_CHANGED: "xmpp.user_id_changed",
  19531. // Designates an event indicating that we have joined the XMPP MUC.
  19532. MUC_JOINED: "xmpp.muc_joined",
  19533. // Designates an event indicating that a participant joined the XMPP MUC.
  19534. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  19535. // Designates an event indicating that a participant left the XMPP MUC.
  19536. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  19537. // Designates an event indicating that the MUC role of a participant has
  19538. // changed.
  19539. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  19540. // Designates an event indicating that the XMPP MUC was destroyed.
  19541. MUC_DESTROYED: "xmpp.muc_destroyed",
  19542. // Designates an event indicating that the display name of a participant
  19543. // has changed.
  19544. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  19545. // Designates an event indicating that we received statistics from a
  19546. // participant in the MUC.
  19547. REMOTE_STATS: "xmpp.remote_stats",
  19548. // Designates an event indicating that our role in the XMPP MUC has changed.
  19549. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  19550. // Designates an event indicating that the subject of the XMPP MUC has
  19551. // changed.
  19552. SUBJECT_CHANGED: "xmpp.subject_changed",
  19553. // Designates an event indicating that an XMPP message in the MUC was
  19554. // received.
  19555. MESSAGE_RECEIVED: "xmpp.message_received",
  19556. // Designates an event indicating that we sent an XMPP message to the MUC.
  19557. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  19558. // Designates an event indicating that the video type (e.g. 'camera' or
  19559. // 'screen') for a participant has changed.
  19560. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  19561. // Designates an event indicating that a participant in the XMPP MUC has
  19562. // advertised that they have audio muted (or unmuted).
  19563. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  19564. // Designates an event indicating that a participant in the XMPP MUC has
  19565. // advertised that they have video muted (or unmuted).
  19566. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  19567. // Designates an event indicating that the focus has asked us to mute our
  19568. // audio.
  19569. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  19570. // Designates an event indicating that a moderator in the room changed the
  19571. // "start muted" settings for the conference.
  19572. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  19573. // Designates an event indicating that we should join the conference with
  19574. // audio and/or video muted.
  19575. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  19576. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  19577. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  19578. PASSWORD_REQUIRED: "xmpp.password_required",
  19579. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  19580. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  19581. ETHERPAD: "xmpp.etherpad",
  19582. DEVICE_AVAILABLE: "xmpp.device_available",
  19583. BRIDGE_DOWN: "xmpp.bridge_down",
  19584. PRESENCE_STATUS: "xmpp.presence_status",
  19585. RESERVATION_ERROR: "xmpp.room_reservation_error",
  19586. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  19587. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  19588. // TODO: only used in a hack, should probably be removed.
  19589. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  19590. // TODO: only used in a hack, should probably be removed.
  19591. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  19592. // TODO: only used in a hack, should probably be removed.
  19593. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  19594. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  19595. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  19596. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  19597. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  19598. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  19599. // xmpp is connected and obtained user media
  19600. READY_TO_JOIN: 'xmpp.ready_to_join',
  19601. FOCUS_LEFT: "xmpp.focus_left",
  19602. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  19603. };
  19604. module.exports = XMPPEvents;
  19605. },{}]},{},[7])(7)
  19606. });