Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

lib-jitsi-meet.js 757KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. /**
  18. * Creates a JitsiConference object with the given name and properties.
  19. * Note: this constructor is not a part of the public API (objects should be
  20. * created using JitsiConnection.createConference).
  21. * @param options.config properties / settings related to the conference that will be created.
  22. * @param options.name the name of the conference
  23. * @param options.connection the JitsiConnection object for this JitsiConference.
  24. * @constructor
  25. */
  26. function JitsiConference(options) {
  27. if(!options.name || options.name.toLowerCase() !== options.name) {
  28. logger.error("Invalid conference name (no conference name passed or it"
  29. + "contains invalid characters like capital letters)!");
  30. return;
  31. }
  32. this.options = options;
  33. this.connection = this.options.connection;
  34. this.xmpp = this.connection.xmpp;
  35. this.eventEmitter = new EventEmitter();
  36. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  37. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  38. this.rtc = new RTC(this.room, options);
  39. if(!RTC.options.disableAudioLevels)
  40. this.statistics = new Statistics();
  41. setupListeners(this);
  42. this.participants = {};
  43. this.lastActiveSpeaker = null;
  44. this.dtmfManager = null;
  45. this.somebodySupportsDTMF = false;
  46. }
  47. /**
  48. * Joins the conference.
  49. * @param password {string} the password
  50. */
  51. JitsiConference.prototype.join = function (password) {
  52. if(this.room)
  53. this.room.join(password, this.connection.tokenPassword);
  54. };
  55. /**
  56. * Check if joined to the conference.
  57. */
  58. JitsiConference.prototype.isJoined = function () {
  59. return this.room && this.room.joined;
  60. };
  61. /**
  62. * Leaves the conference.
  63. */
  64. JitsiConference.prototype.leave = function () {
  65. if(this.xmpp && this.room)
  66. this.xmpp.leaveRoom(this.room.roomjid);
  67. this.room = null;
  68. };
  69. /**
  70. * Returns name of this conference.
  71. */
  72. JitsiConference.prototype.getName = function () {
  73. return this.options.name;
  74. };
  75. /**
  76. * Check if external authentication is enabled for this conference.
  77. */
  78. JitsiConference.prototype.isExternalAuthEnabled = function () {
  79. return this.room && this.room.moderator.isExternalAuthEnabled();
  80. };
  81. /**
  82. * Get url for external authentication.
  83. * @param {boolean} [urlForPopup] if true then return url for login popup,
  84. * else url of login page.
  85. * @returns {Promise}
  86. */
  87. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  88. return new Promise(function (resolve, reject) {
  89. if (!this.isExternalAuthEnabled()) {
  90. reject();
  91. return;
  92. }
  93. if (urlForPopup) {
  94. this.room.moderator.getPopupLoginUrl(resolve, reject);
  95. } else {
  96. this.room.moderator.getLoginUrl(resolve, reject);
  97. }
  98. }.bind(this));
  99. };
  100. /**
  101. * Returns the local tracks.
  102. */
  103. JitsiConference.prototype.getLocalTracks = function () {
  104. if (this.rtc) {
  105. return this.rtc.localStreams;
  106. } else {
  107. return [];
  108. }
  109. };
  110. /**
  111. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  112. * in JitsiConferenceEvents.
  113. * @param eventId the event ID.
  114. * @param handler handler for the event.
  115. *
  116. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  117. */
  118. JitsiConference.prototype.on = function (eventId, handler) {
  119. if(this.eventEmitter)
  120. this.eventEmitter.on(eventId, handler);
  121. };
  122. /**
  123. * Removes event listener
  124. * @param eventId the event ID.
  125. * @param [handler] optional, the specific handler to unbind
  126. *
  127. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  128. */
  129. JitsiConference.prototype.off = function (eventId, handler) {
  130. if(this.eventEmitter)
  131. this.eventEmitter.removeListener(eventId, handler);
  132. };
  133. // Common aliases for event emitter
  134. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  135. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  136. /**
  137. * Receives notifications from another participants for commands / custom events
  138. * (send by sendPresenceCommand method).
  139. * @param command {String} the name of the command
  140. * @param handler {Function} handler for the command
  141. */
  142. JitsiConference.prototype.addCommandListener = function (command, handler) {
  143. if(this.room)
  144. this.room.addPresenceListener(command, handler);
  145. };
  146. /**
  147. * Removes command listener
  148. * @param command {String} the name of the command
  149. */
  150. JitsiConference.prototype.removeCommandListener = function (command) {
  151. if(this.room)
  152. this.room.removePresenceListener(command);
  153. };
  154. /**
  155. * Sends text message to the other participants in the conference
  156. * @param message the text message.
  157. */
  158. JitsiConference.prototype.sendTextMessage = function (message) {
  159. if(this.room)
  160. this.room.sendMessage(message);
  161. };
  162. /**
  163. * Send presence command.
  164. * @param name the name of the command.
  165. * @param values Object with keys and values that will be send.
  166. **/
  167. JitsiConference.prototype.sendCommand = function (name, values) {
  168. if(this.room) {
  169. this.room.addToPresence(name, values);
  170. this.room.sendPresence();
  171. }
  172. };
  173. /**
  174. * Send presence command one time.
  175. * @param name the name of the command.
  176. * @param values Object with keys and values that will be send.
  177. **/
  178. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  179. this.sendCommand(name, values);
  180. this.removeCommand(name);
  181. };
  182. /**
  183. * Send presence command.
  184. * @param name the name of the command.
  185. * @param values Object with keys and values that will be send.
  186. * @param persistent if false the command will be sent only one time
  187. **/
  188. JitsiConference.prototype.removeCommand = function (name) {
  189. if(this.room)
  190. this.room.removeFromPresence(name);
  191. };
  192. /**
  193. * Sets the display name for this conference.
  194. * @param name the display name to set
  195. */
  196. JitsiConference.prototype.setDisplayName = function(name) {
  197. if(this.room){
  198. // remove previously set nickname
  199. this.room.removeFromPresence("nick");
  200. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  201. this.room.sendPresence();
  202. }
  203. };
  204. /**
  205. * Adds JitsiLocalTrack object to the conference.
  206. * @param track the JitsiLocalTrack object.
  207. */
  208. JitsiConference.prototype.addTrack = function (track) {
  209. this.room.addStream(track.getOriginalStream(), function () {
  210. this.rtc.addLocalStream(track);
  211. var muteHandler = this._fireMuteChangeEvent.bind(this, track);
  212. var stopHandler = this.removeTrack.bind(this, track);
  213. var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  214. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  215. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  216. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  217. this.addEventListener(JitsiConferenceEvents.TRACK_REMOVED, function (someTrack) {
  218. if (someTrack !== track) {
  219. return;
  220. }
  221. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  222. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  223. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  224. });
  225. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  226. }.bind(this));
  227. };
  228. /**
  229. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  230. * @param audioLevel the audio level
  231. */
  232. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  233. this.eventEmitter.emit(
  234. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  235. this.myUserId(), audioLevel);
  236. };
  237. /**
  238. * Fires TRACK_MUTE_CHANGED change conference event.
  239. * @param track the JitsiTrack object related to the event.
  240. */
  241. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  242. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  243. };
  244. /**
  245. * Removes JitsiLocalTrack object to the conference.
  246. * @param track the JitsiLocalTrack object.
  247. */
  248. JitsiConference.prototype.removeTrack = function (track) {
  249. if(!this.room){
  250. if(this.rtc)
  251. this.rtc.removeLocalStream(track);
  252. return;
  253. }
  254. this.room.removeStream(track.getOriginalStream(), function(){
  255. this.rtc.removeLocalStream(track);
  256. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  257. }.bind(this));
  258. };
  259. /**
  260. * Get role of the local user.
  261. * @returns {string} user role: 'moderator' or 'none'
  262. */
  263. JitsiConference.prototype.getRole = function () {
  264. return this.room.role;
  265. };
  266. /**
  267. * Check if local user is moderator.
  268. * @returns {boolean} true if local user is moderator, false otherwise.
  269. */
  270. JitsiConference.prototype.isModerator = function () {
  271. return this.room.isModerator();
  272. };
  273. /**
  274. * Set password for the room.
  275. * @param {string} password new password for the room.
  276. * @returns {Promise}
  277. */
  278. JitsiConference.prototype.lock = function (password) {
  279. if (!this.isModerator()) {
  280. return Promise.reject();
  281. }
  282. var conference = this;
  283. return new Promise(function (resolve, reject) {
  284. conference.xmpp.lockRoom(password, function () {
  285. resolve();
  286. }, function (err) {
  287. reject(err);
  288. }, function () {
  289. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  290. });
  291. });
  292. };
  293. /**
  294. * Remove password from the room.
  295. * @returns {Promise}
  296. */
  297. JitsiConference.prototype.unlock = function () {
  298. return this.lock(undefined);
  299. };
  300. /**
  301. * Elects the participant with the given id to be the selected participant or the speaker.
  302. * @param id the identifier of the participant
  303. */
  304. JitsiConference.prototype.selectParticipant = function(participantId) {
  305. if (this.rtc) {
  306. this.rtc.selectedEndpoint(participantId);
  307. }
  308. };
  309. /**
  310. *
  311. * @param id the identifier of the participant
  312. */
  313. JitsiConference.prototype.pinParticipant = function(participantId) {
  314. if (this.rtc) {
  315. this.rtc.pinEndpoint(participantId);
  316. }
  317. };
  318. /**
  319. * Returns the list of participants for this conference.
  320. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  321. */
  322. JitsiConference.prototype.getParticipants = function() {
  323. return Object.keys(this.participants).map(function (key) {
  324. return this.participants[key];
  325. }, this);
  326. };
  327. /**
  328. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  329. * undefined if there isn't one).
  330. * @param id the id of the participant.
  331. */
  332. JitsiConference.prototype.getParticipantById = function(id) {
  333. return this.participants[id];
  334. };
  335. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  336. var id = Strophe.getResourceFromJid(jid);
  337. if (id === 'focus') {
  338. return;
  339. }
  340. var participant = new JitsiParticipant(id, this, nick);
  341. this.participants[id] = participant;
  342. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  343. this.xmpp.connection.disco.info(
  344. jid, "node", function(iq) {
  345. participant._supportsDTMF = $(iq).find(
  346. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  347. this.updateDTMFSupport();
  348. }.bind(this)
  349. );
  350. };
  351. JitsiConference.prototype.onMemberLeft = function (jid) {
  352. var id = Strophe.getResourceFromJid(jid);
  353. var participant = this.participants[id];
  354. delete this.participants[id];
  355. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  356. };
  357. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  358. var id = Strophe.getResourceFromJid(jid);
  359. var participant = this.getParticipantById(id);
  360. if (!participant) {
  361. return;
  362. }
  363. participant._role = role;
  364. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  365. };
  366. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  367. var id = Strophe.getResourceFromJid(jid);
  368. var participant = this.getParticipantById(id);
  369. if (!participant) {
  370. return;
  371. }
  372. participant._displayName = displayName;
  373. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  374. };
  375. JitsiConference.prototype.onTrackAdded = function (track) {
  376. var id = track.getParticipantId();
  377. var participant = this.getParticipantById(id);
  378. if (!participant) {
  379. return;
  380. }
  381. // add track to JitsiParticipant
  382. participant._tracks.push(track);
  383. var emitter = this.eventEmitter;
  384. track.addEventListener(
  385. JitsiTrackEvents.TRACK_STOPPED,
  386. function () {
  387. // remove track from JitsiParticipant
  388. var pos = participant._tracks.indexOf(track);
  389. if (pos > -1) {
  390. participant._tracks.splice(pos, 1);
  391. }
  392. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  393. }
  394. );
  395. track.addEventListener(
  396. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  397. function () {
  398. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  399. }
  400. );
  401. track.addEventListener(
  402. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  403. function (audioLevel) {
  404. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  405. }
  406. );
  407. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  408. };
  409. JitsiConference.prototype.updateDTMFSupport = function () {
  410. var somebodySupportsDTMF = false;
  411. var participants = this.getParticipants();
  412. // check if at least 1 participant supports DTMF
  413. for (var i = 0; i < participants.length; i += 1) {
  414. if (participants[i].supportsDTMF()) {
  415. somebodySupportsDTMF = true;
  416. break;
  417. }
  418. }
  419. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  420. this.somebodySupportsDTMF = somebodySupportsDTMF;
  421. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  422. }
  423. };
  424. /**
  425. * Allows to check if there is at least one user in the conference
  426. * that supports DTMF.
  427. * @returns {boolean} true if somebody supports DTMF, false otherwise
  428. */
  429. JitsiConference.prototype.isDTMFSupported = function () {
  430. return this.somebodySupportsDTMF;
  431. };
  432. /**
  433. * Returns the local user's ID
  434. * @return {string} local user's ID
  435. */
  436. JitsiConference.prototype.myUserId = function () {
  437. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  438. };
  439. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  440. if (!this.dtmfManager) {
  441. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  442. if (!connection) {
  443. logger.warn("cannot sendTones: no conneciton");
  444. return;
  445. }
  446. var tracks = this.getLocalTracks().filter(function (track) {
  447. return track.isAudioTrack();
  448. });
  449. if (!tracks.length) {
  450. logger.warn("cannot sendTones: no local audio stream");
  451. return;
  452. }
  453. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  454. }
  455. this.dtmfManager.sendTones(tones, duration, pause);
  456. };
  457. /**
  458. * Setups the listeners needed for the conference.
  459. * @param conference the conference
  460. */
  461. function setupListeners(conference) {
  462. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  463. conference.rtc.onIncommingCall(event);
  464. if(conference.statistics)
  465. conference.statistics.startRemoteStats(event.peerconnection);
  466. });
  467. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  468. function (data, sid, thessrc) {
  469. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  470. if (track) {
  471. conference.onTrackAdded(track);
  472. }
  473. }
  474. );
  475. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  476. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  477. });
  478. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  479. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  480. });
  481. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  482. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  483. });
  484. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  485. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  486. });
  487. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  488. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  489. });
  490. // FIXME
  491. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  492. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  493. // });
  494. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  495. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  496. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  497. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  498. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  499. });
  500. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  501. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  502. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  503. });
  504. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  505. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  506. });
  507. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  508. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  509. });
  510. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  511. console.error(authEnabled, authIdentity);
  512. });
  513. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  514. var id = Strophe.getResourceFromJid(jid);
  515. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  516. });
  517. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  518. if(conference.lastActiveSpeaker !== id && conference.room) {
  519. conference.lastActiveSpeaker = id;
  520. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  521. }
  522. });
  523. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  524. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  525. });
  526. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  527. function (lastNEndpoints, endpointsEnteringLastN) {
  528. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  529. lastNEndpoints, endpointsEnteringLastN);
  530. });
  531. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  532. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  533. });
  534. if(conference.statistics) {
  535. //FIXME: Maybe remove event should not be associated with the conference.
  536. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  537. var userId = null;
  538. var jid = conference.room.getJidBySSRC(ssrc);
  539. if (!jid)
  540. return;
  541. conference.rtc.setAudioLevel(jid, level);
  542. });
  543. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  544. function () {
  545. conference.statistics.dispose();
  546. });
  547. // FIXME: Maybe we should move this.
  548. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  549. // conference.room.updateDeviceAvailability(devices);
  550. // });
  551. }
  552. }
  553. module.exports = JitsiConference;
  554. }).call(this,"/JitsiConference.js")
  555. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":79,"./service/authentication/AuthenticationEvents":81,"./service/xmpp/XMPPEvents":85,"events":43,"jitsi-meet-logger":47}],2:[function(require,module,exports){
  556. /**
  557. * Enumeration with the errors for the conference.
  558. * @type {{string: string}}
  559. */
  560. var JitsiConferenceErrors = {
  561. /**
  562. * Indicates that a password is required in order to join the conference.
  563. */
  564. PASSWORD_REQUIRED: "conference.passwordRequired",
  565. /**
  566. * Indicates that client must be authenticated to create the conference.
  567. */
  568. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  569. /**
  570. * Indicates that password cannot be set for this conference.
  571. */
  572. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  573. /**
  574. * Indicates that a connection error occurred when trying to join a
  575. * conference.
  576. */
  577. CONNECTION_ERROR: "conference.connectionError",
  578. /**
  579. * Indicates that the conference setup failed.
  580. */
  581. SETUP_FAILED: "conference.setup_failed",
  582. /**
  583. * Indicates that there is no available videobridge.
  584. */
  585. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  586. /**
  587. * Many more errors TBD here.
  588. */
  589. };
  590. module.exports = JitsiConferenceErrors;
  591. },{}],3:[function(require,module,exports){
  592. /**
  593. * Enumeration with the events for the conference.
  594. * @type {{string: string}}
  595. */
  596. var JitsiConferenceEvents = {
  597. /**
  598. * A new media track was added to the conference.
  599. */
  600. TRACK_ADDED: "conference.trackAdded",
  601. /**
  602. * The media track was removed from the conference.
  603. */
  604. TRACK_REMOVED: "conference.trackRemoved",
  605. /**
  606. * The active speaker was changed.
  607. */
  608. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  609. /**
  610. * A new user joinned the conference.
  611. */
  612. USER_JOINED: "conference.userJoined",
  613. /**
  614. * A user has left the conference.
  615. */
  616. USER_LEFT: "conference.userLeft",
  617. /**
  618. * User role changed.
  619. */
  620. USER_ROLE_CHANGED: "conference.roleChanged",
  621. /**
  622. * New text message was received.
  623. */
  624. MESSAGE_RECEIVED: "conference.messageReceived",
  625. /**
  626. * A user has changed it display name
  627. */
  628. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  629. /**
  630. * A participant avatar has changed.
  631. */
  632. AVATAR_CHANGED: "conference.avatarChanged",
  633. /**
  634. * New connection statistics are received.
  635. */
  636. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  637. /**
  638. * The Last N set is changed.
  639. */
  640. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  641. /**
  642. * You are included / excluded in somebody's last N set
  643. */
  644. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  645. /**
  646. * A media track ( attached to the conference) mute status was changed.
  647. */
  648. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  649. /**
  650. * Audio levels of a media track ( attached to the conference) was changed.
  651. */
  652. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  653. /**
  654. * Indicates that the connection to the conference has been interrupted
  655. * for some reason.
  656. */
  657. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  658. /**
  659. * Indicates that the connection to the conference has been restored.
  660. */
  661. CONNECTION_RESTORED: "conference.connectionRestored",
  662. /**
  663. * Indicates that conference failed.
  664. */
  665. CONFERENCE_FAILED: "conference.failed",
  666. /**
  667. * Indicates that conference has been joined.
  668. */
  669. CONFERENCE_JOINED: "conference.joined",
  670. /**
  671. * Indicates that conference has been left.
  672. */
  673. CONFERENCE_LEFT: "conference.left",
  674. /**
  675. * Indicates that DTMF support changed.
  676. */
  677. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged"
  678. };
  679. module.exports = JitsiConferenceEvents;
  680. },{}],4:[function(require,module,exports){
  681. var JitsiConference = require("./JitsiConference");
  682. var XMPP = require("./modules/xmpp/xmpp");
  683. var RandomUtil = require("./modules/util/RandomUtil");
  684. /**
  685. * Utility method that generates user name based on random hex values.
  686. * Eg. 12345678-1234-1234-12345678
  687. * @returns {string}
  688. */
  689. function generateUserName() {
  690. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  691. "-" + RandomUtil.randomHexString(4) + "-" +
  692. RandomUtil.randomHexDigit(8);
  693. }
  694. /**
  695. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  696. * JitsiConference interface.
  697. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  698. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  699. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  700. * The format is:
  701. * passwordToken = token + "_" + roomName + "_" + ts
  702. * See doc/tokens.md for more info on how tokens are generated.
  703. * @param options Object with properties / settings related to connection with the server.
  704. * @constructor
  705. */
  706. function JitsiConnection(appID, tokenPassword, options) {
  707. this.appID = appID;
  708. this.tokenPassword = tokenPassword;
  709. this.options = options;
  710. this.xmpp = new XMPP(options);
  711. this.conferences = {};
  712. }
  713. /**
  714. * Connect the client with the server.
  715. * @param options {object} connecting options (for example authentications parameters).
  716. */
  717. JitsiConnection.prototype.connect = function (options) {
  718. if(!options)
  719. options = {};
  720. // If we have token provided use it as a password and generate random username
  721. if (this.tokenPassword) {
  722. options.password = this.tokenPassword;
  723. if (!options.id) {
  724. options.id = generateUserName() + "@" + this.options.hosts.domain;
  725. }
  726. }
  727. this.xmpp.connect(options.id, options.password);
  728. }
  729. /**
  730. * Disconnect the client from the server.
  731. */
  732. JitsiConnection.prototype.disconnect = function () {
  733. this.xmpp.disconnect();
  734. }
  735. /**
  736. * This method allows renewal of the tokens if they are expiring.
  737. * @param token the new token.
  738. */
  739. JitsiConnection.prototype.setToken = function (token) {
  740. this.token = token;
  741. }
  742. /**
  743. * Creates and joins new conference.
  744. * @param name the name of the conference; if null - a generated name will be provided from the api
  745. * @param options Object with properties / settings related to the conference that will be created.
  746. * @returns {JitsiConference} returns the new conference object.
  747. */
  748. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  749. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  750. return this.conferences[name];
  751. }
  752. /**
  753. * Subscribes the passed listener to the event.
  754. * @param event {JitsiConnectionEvents} the connection event.
  755. * @param listener {Function} the function that will receive the event
  756. */
  757. JitsiConnection.prototype.addEventListener = function (event, listener) {
  758. this.xmpp.addListener(event, listener);
  759. }
  760. /**
  761. * Unsubscribes the passed handler.
  762. * @param event {JitsiConnectionEvents} the connection event.
  763. * @param listener {Function} the function that will receive the event
  764. */
  765. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  766. this.xmpp.removeListener(event, listener);
  767. }
  768. module.exports = JitsiConnection;
  769. },{"./JitsiConference":1,"./modules/util/RandomUtil":25,"./modules/xmpp/xmpp":41}],5:[function(require,module,exports){
  770. /**
  771. * Enumeration with the errors for the connection.
  772. * @type {{string: string}}
  773. */
  774. var JitsiConnectionErrors = {
  775. /**
  776. * Indicates that a password is required in order to join the conference.
  777. */
  778. PASSWORD_REQUIRED: "connection.passwordRequired",
  779. /**
  780. * Indicates that a connection error occurred when trying to join a
  781. * conference.
  782. */
  783. CONNECTION_ERROR: "connection.connectionError",
  784. /**
  785. * Not specified errors.
  786. */
  787. OTHER_ERROR: "connection.otherError"
  788. };
  789. module.exports = JitsiConnectionErrors;
  790. },{}],6:[function(require,module,exports){
  791. /**
  792. * Enumeration with the events for the connection.
  793. * @type {{string: string}}
  794. */
  795. var JitsiConnnectionEvents = {
  796. /**
  797. * Indicates that the connection has been failed for some reason.
  798. */
  799. CONNECTION_FAILED: "connection.connectionFailed",
  800. /**
  801. * Indicates that the connection has been established.
  802. */
  803. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  804. /**
  805. * Indicates that the connection has been disconnected.
  806. */
  807. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  808. /**
  809. * Indicates that the perfomed action cannot be executed because the
  810. * connection is not in the correct state(connected, disconnected, etc.)
  811. */
  812. WRONG_STATE: "connection.wrongState"
  813. };
  814. module.exports = JitsiConnnectionEvents;
  815. },{}],7:[function(require,module,exports){
  816. var JitsiConnection = require("./JitsiConnection");
  817. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  818. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  819. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  820. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  821. var JitsiTrackEvents = require("./JitsiTrackEvents");
  822. var JitsiTrackErrors = require("./JitsiTrackErrors");
  823. var Logger = require("jitsi-meet-logger");
  824. var RTC = require("./modules/RTC/RTC");
  825. var Statistics = require("./modules/statistics/statistics");
  826. /**
  827. * Namespace for the interface of Jitsi Meet Library.
  828. */
  829. var LibJitsiMeet = {
  830. JitsiConnection: JitsiConnection,
  831. events: {
  832. conference: JitsiConferenceEvents,
  833. connection: JitsiConnectionEvents,
  834. track: JitsiTrackEvents
  835. },
  836. errors: {
  837. conference: JitsiConferenceErrors,
  838. connection: JitsiConnectionErrors,
  839. track: JitsiTrackErrors
  840. },
  841. logLevels: Logger.levels,
  842. init: function (options) {
  843. return RTC.init(options || {});
  844. },
  845. setLogLevel: function (level) {
  846. Logger.setLogLevel(level);
  847. },
  848. /**
  849. * Creates the media tracks and returns them trough the callback.
  850. * @param options Object with properties / settings specifying the tracks which should be created.
  851. * should be created or some additional configurations about resolution for example.
  852. * @param {Array} options.devices the devices that will be requested
  853. * @param {string} options.resolution resolution constraints
  854. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  855. * type: "audio" or "video", videoType: "camera" or "desktop"}
  856. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  857. * @param {string} options.cameraDeviceId
  858. * @param {string} options.micDeviceId
  859. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  860. * A promise that returns an array of created JitsiTracks if resolved,
  861. * or a JitsiConferenceError if rejected.
  862. */
  863. createLocalTracks: function (options) {
  864. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  865. function(tracks) {
  866. if(!RTC.options.disableAudioLevels)
  867. for(var i = 0; i < tracks.length; i++) {
  868. var track = tracks[i];
  869. var mStream = track.getOriginalStream();
  870. if(track.getType() === "audio"){
  871. Statistics.startLocalStats(mStream,
  872. track.setAudioLevel.bind(track));
  873. track.addEventListener(
  874. JitsiTrackEvents.TRACK_STOPPED,
  875. function(){
  876. Statistics.stopLocalStats(mStream);
  877. });
  878. }
  879. }
  880. return tracks;
  881. });
  882. },
  883. /**
  884. * Checks if its possible to enumerate available cameras/micropones.
  885. * @returns {boolean} true if available, false otherwise.
  886. */
  887. isDeviceListAvailable: function () {
  888. return RTC.isDeviceListAvailable();
  889. },
  890. /**
  891. * Returns true if changing the camera / microphone device is supported and
  892. * false if not.
  893. * @returns {boolean} true if available, false otherwise.
  894. */
  895. isDeviceChangeAvailable: function () {
  896. return RTC.isDeviceChangeAvailable();
  897. },
  898. enumerateDevices: function (callback) {
  899. RTC.enumerateDevices(callback);
  900. }
  901. };
  902. require("es6-promise").polyfill()
  903. //Setups the promise object.
  904. window.Promise = window.Promise || require("es6-promise").Promise;
  905. module.exports = LibJitsiMeet;
  906. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"es6-promise":45,"jitsi-meet-logger":47}],8:[function(require,module,exports){
  907. /**
  908. * Represents a participant in (a member of) a conference.
  909. */
  910. function JitsiParticipant(id, conference, displayName){
  911. this._id = id;
  912. this._conference = conference;
  913. this._displayName = displayName;
  914. this._supportsDTMF = false;
  915. this._tracks = [];
  916. this._role = 'none';
  917. }
  918. /**
  919. * @returns {JitsiConference} The conference that this participant belongs to.
  920. */
  921. JitsiParticipant.prototype.getConference = function() {
  922. return this._conference;
  923. };
  924. /**
  925. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  926. */
  927. JitsiParticipant.prototype.getTracks = function() {
  928. return this._tracks;
  929. };
  930. /**
  931. * @returns {String} The ID (i.e. JID) of this participant.
  932. */
  933. JitsiParticipant.prototype.getId = function() {
  934. return this._id;
  935. };
  936. /**
  937. * @returns {String} The human-readable display name of this participant.
  938. */
  939. JitsiParticipant.prototype.getDisplayName = function() {
  940. return this._displayName;
  941. };
  942. /**
  943. * @returns {Boolean} Whether this participant is a moderator or not.
  944. */
  945. JitsiParticipant.prototype.isModerator = function() {
  946. return this._role === 'moderator';
  947. };
  948. // Gets a link to an etherpad instance advertised by the participant?
  949. //JitsiParticipant.prototype.getEtherpad = function() {
  950. //
  951. //}
  952. /*
  953. * @returns {Boolean} Whether this participant has muted their audio.
  954. */
  955. JitsiParticipant.prototype.isAudioMuted = function() {
  956. return this.getTracks().reduce(function (track, isAudioMuted) {
  957. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  958. }, true);
  959. };
  960. /*
  961. * @returns {Boolean} Whether this participant has muted their video.
  962. */
  963. JitsiParticipant.prototype.isVideoMuted = function() {
  964. return this.getTracks().reduce(function (track, isVideoMuted) {
  965. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  966. }, true);
  967. };
  968. /*
  969. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  970. * TODO: do we expose this or handle it internally?
  971. */
  972. JitsiParticipant.prototype.getLatestStats = function() {
  973. };
  974. /**
  975. * @returns {String} The role of this participant.
  976. */
  977. JitsiParticipant.prototype.getRole = function() {
  978. return this._role;
  979. };
  980. /*
  981. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  982. */
  983. JitsiParticipant.prototype.isFocus = function() {
  984. };
  985. /*
  986. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  987. */
  988. JitsiParticipant.prototype.isRecorder = function() {
  989. };
  990. /*
  991. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  992. */
  993. JitsiParticipant.prototype.isSipGateway = function() {
  994. };
  995. /**
  996. * @returns {Boolean} Whether this participant is currently sharing their screen.
  997. */
  998. JitsiParticipant.prototype.isScreenSharing = function() {
  999. };
  1000. /**
  1001. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  1002. */
  1003. JitsiParticipant.prototype.getUserAgent = function() {
  1004. };
  1005. /**
  1006. * Kicks the participant from the conference (requires certain privileges).
  1007. */
  1008. JitsiParticipant.prototype.kick = function() {
  1009. };
  1010. /**
  1011. * Asks this participant to mute themselves.
  1012. */
  1013. JitsiParticipant.prototype.askToMute = function() {
  1014. };
  1015. JitsiParticipant.prototype.supportsDTMF = function () {
  1016. return this._supportsDTMF;
  1017. };
  1018. module.exports = JitsiParticipant;
  1019. },{}],9:[function(require,module,exports){
  1020. module.exports = {
  1021. /**
  1022. * Returns JitsiTrackErrors based on the error object passed by GUM
  1023. * @param error the error
  1024. * @param {Object} options the options object given to GUM.
  1025. */
  1026. parseError: function (error, options) {
  1027. options = options || {};
  1028. if (typeof error == "object" && error.constraintName && error.name
  1029. && (error.name == "ConstraintNotSatisfiedError" ||
  1030. error.name == "OverconstrainedError") &&
  1031. (error.constraintName == "minWidth" ||
  1032. error.constraintName == "maxWidth" ||
  1033. error.constraintName == "minHeight" ||
  1034. error.constraintName == "maxHeight") &&
  1035. options.devices.indexOf("video") !== -1) {
  1036. return this.UNSUPPORTED_RESOLUTION;
  1037. } else {
  1038. return this.GENERAL;
  1039. }
  1040. },
  1041. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1042. GENERAL: "gum.general"
  1043. };
  1044. },{}],10:[function(require,module,exports){
  1045. var JitsiTrackEvents = {
  1046. /**
  1047. * A media track mute status was changed.
  1048. */
  1049. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1050. /**
  1051. * Audio levels of a this track was changed.
  1052. */
  1053. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1054. /**
  1055. * The media track was removed to the conference.
  1056. */
  1057. TRACK_STOPPED: "track.stopped"
  1058. };
  1059. module.exports = JitsiTrackEvents;
  1060. },{}],11:[function(require,module,exports){
  1061. (function (__filename){
  1062. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1063. function JitsiDTMFManager (localAudio, peerConnection) {
  1064. var tracks = localAudio._getTracks();
  1065. if (!tracks.length) {
  1066. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1067. }
  1068. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1069. logger.debug("Initialized DTMFSender");
  1070. }
  1071. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1072. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1073. };
  1074. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1075. },{"jitsi-meet-logger":47}],12:[function(require,module,exports){
  1076. (function (__filename){
  1077. /* global config, APP, Strophe */
  1078. // cache datachannels to avoid garbage collection
  1079. // https://code.google.com/p/chromium/issues/detail?id=405545
  1080. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1081. var RTCEvents = require("../../service/RTC/RTCEvents");
  1082. /**
  1083. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1084. * @param peerConnection WebRTC peer connection instance.
  1085. */
  1086. function DataChannels(peerConnection, emitter) {
  1087. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1088. this.eventEmitter = emitter;
  1089. this._dataChannels = [];
  1090. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1091. // Although it's not a requirement to open separate channels from both bridge
  1092. // and peer as single channel can be used for sending and receiving data.
  1093. // So either channel opened by the bridge or the one opened here is enough
  1094. // for communication with the bridge.
  1095. /*var dataChannelOptions =
  1096. {
  1097. reliable: true
  1098. };
  1099. var dataChannel
  1100. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1101. // Can be used only when is in open state
  1102. dataChannel.onopen = function ()
  1103. {
  1104. dataChannel.send("My channel !!!");
  1105. };
  1106. dataChannel.onmessage = function (event)
  1107. {
  1108. var msgData = event.data;
  1109. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1110. };*/
  1111. };
  1112. /**
  1113. * Callback triggered by PeerConnection when new data channel is opened
  1114. * on the bridge.
  1115. * @param event the event info object.
  1116. */
  1117. DataChannels.prototype.onDataChannel = function (event) {
  1118. var dataChannel = event.channel;
  1119. var self = this;
  1120. dataChannel.onopen = function () {
  1121. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1122. // Code sample for sending string and/or binary data
  1123. // Sends String message to the bridge
  1124. //dataChannel.send("Hello bridge!");
  1125. // Sends 12 bytes binary message to the bridge
  1126. //dataChannel.send(new ArrayBuffer(12));
  1127. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1128. };
  1129. dataChannel.onerror = function (error) {
  1130. logger.error("Data Channel Error:", error, dataChannel);
  1131. };
  1132. dataChannel.onmessage = function (event) {
  1133. var data = event.data;
  1134. // JSON
  1135. var obj;
  1136. try {
  1137. obj = JSON.parse(data);
  1138. }
  1139. catch (e) {
  1140. logger.error(
  1141. "Failed to parse data channel message as JSON: ",
  1142. data,
  1143. dataChannel);
  1144. }
  1145. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1146. var colibriClass = obj.colibriClass;
  1147. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1148. // Endpoint ID from the Videobridge.
  1149. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1150. logger.info(
  1151. "Data channel new dominant speaker event: ",
  1152. dominantSpeakerEndpoint);
  1153. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1154. }
  1155. else if ("InLastNChangeEvent" === colibriClass) {
  1156. var oldValue = obj.oldValue;
  1157. var newValue = obj.newValue;
  1158. // Make sure that oldValue and newValue are of type boolean.
  1159. var type;
  1160. if ((type = typeof oldValue) !== 'boolean') {
  1161. if (type === 'string') {
  1162. oldValue = (oldValue == "true");
  1163. } else {
  1164. oldValue = new Boolean(oldValue).valueOf();
  1165. }
  1166. }
  1167. if ((type = typeof newValue) !== 'boolean') {
  1168. if (type === 'string') {
  1169. newValue = (newValue == "true");
  1170. } else {
  1171. newValue = new Boolean(newValue).valueOf();
  1172. }
  1173. }
  1174. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1175. }
  1176. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1177. // The new/latest list of last-n endpoint IDs.
  1178. var lastNEndpoints = obj.lastNEndpoints;
  1179. // The list of endpoint IDs which are entering the list of
  1180. // last-n at this time i.e. were not in the old list of last-n
  1181. // endpoint IDs.
  1182. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1183. logger.info(
  1184. "Data channel new last-n event: ",
  1185. lastNEndpoints, endpointsEnteringLastN, obj);
  1186. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1187. lastNEndpoints, endpointsEnteringLastN, obj);
  1188. }
  1189. else {
  1190. logger.debug("Data channel JSON-formatted message: ", obj);
  1191. // The received message appears to be appropriately formatted
  1192. // (i.e. is a JSON object which assigns a value to the mandatory
  1193. // property colibriClass) so don't just swallow it, expose it to
  1194. // public consumption.
  1195. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1196. }
  1197. }
  1198. };
  1199. dataChannel.onclose = function () {
  1200. logger.info("The Data Channel closed", dataChannel);
  1201. var idx = self._dataChannels.indexOf(dataChannel);
  1202. if (idx > -1)
  1203. self._dataChannels = self._dataChannels.splice(idx, 1);
  1204. };
  1205. this._dataChannels.push(dataChannel);
  1206. };
  1207. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1208. this._onXXXEndpointChanged("selected", userResource);
  1209. }
  1210. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1211. this._onXXXEndpointChanged("pinnned", userResource);
  1212. }
  1213. /**
  1214. * Notifies Videobridge about a change in the value of a specific
  1215. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1216. *
  1217. * @param xxx the name of the endpoint-related property whose value changed
  1218. * @param userResource the new value of the endpoint-related property after the
  1219. * change
  1220. */
  1221. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1222. // Derive the correct words from xxx such as selected and Selected, pinned
  1223. // and Pinned.
  1224. var head = xxx.charAt(0);
  1225. var tail = xxx.substring(1);
  1226. var lower = head.toLowerCase() + tail;
  1227. var upper = head.toUpperCase() + tail;
  1228. // Notify Videobridge about the specified endpoint change.
  1229. console.log(lower + ' endpoint changed: ', userResource);
  1230. this._some(function (dataChannel) {
  1231. if (dataChannel.readyState == 'open') {
  1232. console.log(
  1233. 'sending ' + lower
  1234. + ' endpoint changed notification to the bridge: ',
  1235. userResource);
  1236. var jsonObject = {};
  1237. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1238. jsonObject[lower + "Endpoint"]
  1239. = (userResource ? userResource : null);
  1240. dataChannel.send(JSON.stringify(jsonObject));
  1241. return true;
  1242. }
  1243. });
  1244. }
  1245. DataChannels.prototype._some = function (callback, thisArg) {
  1246. var dataChannels = this._dataChannels;
  1247. if (dataChannels && dataChannels.length !== 0) {
  1248. if (thisArg)
  1249. return dataChannels.some(callback, thisArg);
  1250. else
  1251. return dataChannels.some(callback);
  1252. } else {
  1253. return false;
  1254. }
  1255. }
  1256. module.exports = DataChannels;
  1257. }).call(this,"/modules/RTC/DataChannels.js")
  1258. },{"../../service/RTC/RTCEvents":79,"jitsi-meet-logger":47}],13:[function(require,module,exports){
  1259. var JitsiTrack = require("./JitsiTrack");
  1260. var RTCBrowserType = require("./RTCBrowserType");
  1261. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1262. var RTC = require("./RTCUtils");
  1263. /**
  1264. * Represents a single media track (either audio or video).
  1265. * @constructor
  1266. */
  1267. function JitsiLocalTrack(stream, videoType,
  1268. resolution)
  1269. {
  1270. this.videoType = videoType;
  1271. this.dontFireRemoveEvent = false;
  1272. this.resolution = resolution;
  1273. this.startMuted = false;
  1274. var self = this;
  1275. JitsiTrack.call(this, null, stream,
  1276. function () {
  1277. if(!this.dontFireRemoveEvent)
  1278. this.eventEmitter.emit(
  1279. JitsiTrackEvents.TRACK_STOPPED);
  1280. this.dontFireRemoveEvent = false;
  1281. }.bind(this));
  1282. }
  1283. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1284. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1285. /**
  1286. * Mutes / unmutes the track.
  1287. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1288. */
  1289. JitsiLocalTrack.prototype._setMute = function (mute) {
  1290. if(!this.rtc) {
  1291. this.startMuted = mute;
  1292. return;
  1293. }
  1294. var isAudio = this.type === JitsiTrack.AUDIO;
  1295. this.dontFireRemoveEvent = false;
  1296. if ((window.location.protocol != "https:") ||
  1297. (isAudio) || this.videoType === "desktop" ||
  1298. // FIXME FF does not support 'removeStream' method used to mute
  1299. RTCBrowserType.isFirefox()) {
  1300. var tracks = this._getTracks();
  1301. for (var idx = 0; idx < tracks.length; idx++) {
  1302. tracks[idx].enabled = !mute;
  1303. }
  1304. if(isAudio)
  1305. this.rtc.room.setAudioMute(mute);
  1306. else
  1307. this.rtc.room.setVideoMute(mute);
  1308. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1309. } else {
  1310. if (mute) {
  1311. this.dontFireRemoveEvent = true;
  1312. this.rtc.room.removeStream(this.stream, function () {});
  1313. RTC.stopMediaStream(this.stream);
  1314. if(isAudio)
  1315. this.rtc.room.setAudioMute(mute);
  1316. else
  1317. this.rtc.room.setVideoMute(mute);
  1318. this.stream = null;
  1319. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1320. //FIXME: Maybe here we should set the SRC for the containers to something
  1321. } else {
  1322. var self = this;
  1323. RTC.obtainAudioAndVideoPermissions({
  1324. devices: (isAudio ? ["audio"] : ["video"]),
  1325. resolution: self.resolution})
  1326. .then(function (streams) {
  1327. var stream = null;
  1328. for(var i = 0; i < streams.length; i++) {
  1329. stream = streams[i];
  1330. if(stream.type === self.type) {
  1331. self.stream = stream.stream;
  1332. self.videoType = stream.videoType;
  1333. break;
  1334. }
  1335. }
  1336. if(!stream)
  1337. return;
  1338. for(var i = 0; i < self.containers.length; i++)
  1339. {
  1340. RTC.attachMediaStream(self.containers[i], self.stream);
  1341. }
  1342. self.rtc.room.addStream(stream.stream,
  1343. function () {
  1344. if(isAudio)
  1345. self.rtc.room.setAudioMute(mute);
  1346. else
  1347. self.rtc.room.setVideoMute(mute);
  1348. self.eventEmitter.emit(
  1349. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1350. });
  1351. });
  1352. }
  1353. }
  1354. }
  1355. /**
  1356. * Stops sending the media track. And removes it from the HTML.
  1357. * NOTE: Works for local tracks only.
  1358. */
  1359. JitsiLocalTrack.prototype.stop = function () {
  1360. if(!this.stream)
  1361. return;
  1362. if(this.rtc)
  1363. this.rtc.room.removeStream(this.stream, function () {});
  1364. RTC.stopMediaStream(this.stream);
  1365. this.detach();
  1366. }
  1367. /**
  1368. * Returns <tt>true</tt> - if the stream is muted
  1369. * and <tt>false</tt> otherwise.
  1370. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1371. * and <tt>false</tt> otherwise.
  1372. */
  1373. JitsiLocalTrack.prototype.isMuted = function () {
  1374. if (!this.stream)
  1375. return true;
  1376. var tracks = [];
  1377. var isAudio = this.type === JitsiTrack.AUDIO;
  1378. if (isAudio) {
  1379. tracks = this.stream.getAudioTracks();
  1380. } else {
  1381. if (!this.isActive())
  1382. return true;
  1383. tracks = this.stream.getVideoTracks();
  1384. }
  1385. for (var idx = 0; idx < tracks.length; idx++) {
  1386. if(tracks[idx].enabled)
  1387. return false;
  1388. }
  1389. return true;
  1390. };
  1391. /**
  1392. * Private method. Updates rtc property of the track.
  1393. * @param rtc the rtc instance.
  1394. */
  1395. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1396. this.rtc = rtc;
  1397. };
  1398. /**
  1399. * Return true;
  1400. */
  1401. JitsiLocalTrack.prototype.isLocal = function () {
  1402. return true;
  1403. }
  1404. module.exports = JitsiLocalTrack;
  1405. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1406. var JitsiTrack = require("./JitsiTrack");
  1407. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1408. /**
  1409. * Represents a single media track (either audio or video).
  1410. * @param RTC the rtc instance.
  1411. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1412. * @param sid sid for the Media Stream
  1413. * @param ssrc ssrc for the Media Stream
  1414. * @param eventEmitter the event emitter
  1415. * @constructor
  1416. */
  1417. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1418. JitsiTrack.call(this, RTC, data.stream,
  1419. function () {
  1420. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1421. }.bind(this));
  1422. this.rtc = RTC;
  1423. this.sid = sid;
  1424. this.stream = data.stream;
  1425. this.peerjid = data.peerjid;
  1426. this.videoType = data.videoType;
  1427. this.ssrc = ssrc;
  1428. this.muted = false;
  1429. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1430. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1431. this.muted = true;
  1432. }
  1433. }
  1434. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1435. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1436. /**
  1437. * Sets current muted status and fires an events for the change.
  1438. * @param value the muted status.
  1439. */
  1440. JitsiRemoteTrack.prototype.setMute = function (value) {
  1441. this.stream.muted = value;
  1442. this.muted = value;
  1443. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1444. };
  1445. /**
  1446. * Returns the current muted status of the track.
  1447. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1448. */
  1449. JitsiRemoteTrack.prototype.isMuted = function () {
  1450. return this.muted;
  1451. };
  1452. /**
  1453. * Returns the participant id which owns the track.
  1454. * @returns {string} the id of the participants.
  1455. */
  1456. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1457. return Strophe.getResourceFromJid(this.peerjid);
  1458. };
  1459. /**
  1460. * Return false;
  1461. */
  1462. JitsiRemoteTrack.prototype.isLocal = function () {
  1463. return false;
  1464. };
  1465. delete JitsiRemoteTrack.prototype.stop;
  1466. delete JitsiRemoteTrack.prototype.start;
  1467. module.exports = JitsiRemoteTrack;
  1468. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1469. var RTCBrowserType = require("./RTCBrowserType");
  1470. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1471. var EventEmitter = require("events");
  1472. /**
  1473. * This implements 'onended' callback normally fired by WebRTC after the stream
  1474. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1475. * @param jitsiTrack our track object holding the original WebRTC stream object
  1476. * to which 'onended' handling will be added.
  1477. */
  1478. function implementOnEndedHandling(jitsiTrack) {
  1479. var stream = jitsiTrack.getOriginalStream();
  1480. var originalStop = stream.stop;
  1481. stream.stop = function () {
  1482. originalStop.apply(stream);
  1483. if (jitsiTrack.isActive()) {
  1484. stream.onended();
  1485. }
  1486. };
  1487. }
  1488. /**
  1489. * Adds onended/oninactive handler to a MediaStream.
  1490. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1491. * @param handler the handler
  1492. */
  1493. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1494. if(RTCBrowserType.isTemasysPluginUsed()) {
  1495. // themasys
  1496. //FIXME: Seems that not working properly.
  1497. if(mediaStream.onended) {
  1498. mediaStream.onended = handler;
  1499. } else if(mediaStream.addEventListener) {
  1500. mediaStream.addEventListener('ended', function () {
  1501. handler(mediaStream);
  1502. });
  1503. } else if(mediaStream.attachEvent) {
  1504. mediaStream.attachEvent('ended', function () {
  1505. handler(mediaStream);
  1506. });
  1507. }
  1508. }
  1509. else {
  1510. if(typeof mediaStream.active !== "undefined")
  1511. mediaStream.oninactive = handler;
  1512. else
  1513. mediaStream.onended = handler;
  1514. }
  1515. }
  1516. /**
  1517. * Represents a single media track (either audio or video).
  1518. * @constructor
  1519. * @param rtc the rtc instance
  1520. * @param stream the stream
  1521. * @param streamInactiveHandler the function that will handle
  1522. * onended/oninactive events of the stream.
  1523. */
  1524. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1525. {
  1526. /**
  1527. * Array with the HTML elements that are displaying the streams.
  1528. * @type {Array}
  1529. */
  1530. this.containers = [];
  1531. this.rtc = rtc;
  1532. this.stream = stream;
  1533. this.eventEmitter = new EventEmitter();
  1534. this.audioLevel = -1;
  1535. this.type = (this.stream.getVideoTracks().length > 0)?
  1536. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1537. if(this.type == "audio") {
  1538. this._getTracks = function () {
  1539. return this.stream.getAudioTracks();
  1540. }.bind(this);
  1541. } else {
  1542. this._getTracks = function () {
  1543. return this.stream.getVideoTracks();
  1544. }.bind(this);
  1545. }
  1546. if (RTCBrowserType.isFirefox() && this.stream) {
  1547. implementOnEndedHandling(this);
  1548. }
  1549. if(stream)
  1550. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1551. }
  1552. /**
  1553. * JitsiTrack video type.
  1554. * @type {string}
  1555. */
  1556. JitsiTrack.VIDEO = "video";
  1557. /**
  1558. * JitsiTrack audio type.
  1559. * @type {string}
  1560. */
  1561. JitsiTrack.AUDIO = "audio";
  1562. /**
  1563. * Returns the type (audio or video) of this track.
  1564. */
  1565. JitsiTrack.prototype.getType = function() {
  1566. return this.type;
  1567. };
  1568. /**
  1569. * Check if this is audiotrack.
  1570. */
  1571. JitsiTrack.prototype.isAudioTrack = function () {
  1572. return this.getType() === JitsiTrack.AUDIO;
  1573. };
  1574. /**
  1575. * Check if this is videotrack.
  1576. */
  1577. JitsiTrack.prototype.isVideoTrack = function () {
  1578. return this.getType() === JitsiTrack.VIDEO;
  1579. };
  1580. /**
  1581. * Returns the RTCMediaStream from the browser (?).
  1582. */
  1583. JitsiTrack.prototype.getOriginalStream = function() {
  1584. return this.stream;
  1585. }
  1586. /**
  1587. * Mutes the track.
  1588. */
  1589. JitsiTrack.prototype.mute = function () {
  1590. this._setMute(true);
  1591. }
  1592. /**
  1593. * Unmutes the stream.
  1594. */
  1595. JitsiTrack.prototype.unmute = function () {
  1596. this._setMute(false);
  1597. }
  1598. /**
  1599. * Attaches the MediaStream of this track to an HTML container (?).
  1600. * Adds the container to the list of containers that are displaying the track.
  1601. * @param container the HTML container
  1602. */
  1603. JitsiTrack.prototype.attach = function (container) {
  1604. if(this.stream)
  1605. require("./RTCUtils").attachMediaStream(container, this.stream);
  1606. this.containers.push(container);
  1607. }
  1608. /**
  1609. * Removes the track from the passed HTML container.
  1610. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1611. */
  1612. JitsiTrack.prototype.detach = function (container) {
  1613. for(var i = 0; i < this.containers.length; i++)
  1614. {
  1615. if(this.containers[i].is(container))
  1616. {
  1617. this.containers.splice(i,1);
  1618. }
  1619. if(!container)
  1620. {
  1621. this.containers[i].find(">video").remove();
  1622. }
  1623. }
  1624. if(container)
  1625. $(container).find(">video").remove();
  1626. }
  1627. /**
  1628. * Stops sending the media track. And removes it from the HTML.
  1629. * NOTE: Works for local tracks only.
  1630. */
  1631. JitsiTrack.prototype.stop = function () {
  1632. }
  1633. /**
  1634. * Returns true if this is a video track and the source of the video is a
  1635. * screen capture as opposed to a camera.
  1636. */
  1637. JitsiTrack.prototype.isScreenSharing = function(){
  1638. }
  1639. /**
  1640. * Returns id of the track.
  1641. * @returns {string} id of the track or null if this is fake track.
  1642. */
  1643. JitsiTrack.prototype.getId = function () {
  1644. var tracks = this.stream.getTracks();
  1645. if(!tracks || tracks.length === 0)
  1646. return null;
  1647. return tracks[0].id;
  1648. };
  1649. /**
  1650. * Checks whether the MediaStream is avtive/not ended.
  1651. * When there is no check for active we don't have information and so
  1652. * will return that stream is active (in case of FF).
  1653. * @returns {boolean} whether MediaStream is active.
  1654. */
  1655. JitsiTrack.prototype.isActive = function () {
  1656. if((typeof this.stream.active !== "undefined"))
  1657. return this.stream.active;
  1658. else
  1659. return true;
  1660. };
  1661. /**
  1662. * Attaches a handler for events(For example - "audio level changed".).
  1663. * All possible event are defined in JitsiTrackEvents.
  1664. * @param eventId the event ID.
  1665. * @param handler handler for the event.
  1666. */
  1667. JitsiTrack.prototype.on = function (eventId, handler) {
  1668. if(this.eventEmitter)
  1669. this.eventEmitter.on(eventId, handler);
  1670. }
  1671. /**
  1672. * Removes event listener
  1673. * @param eventId the event ID.
  1674. * @param [handler] optional, the specific handler to unbind
  1675. */
  1676. JitsiTrack.prototype.off = function (eventId, handler) {
  1677. if(this.eventEmitter)
  1678. this.eventEmitter.removeListener(eventId, handler);
  1679. }
  1680. // Common aliases for event emitter
  1681. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1682. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1683. /**
  1684. * Sets the audio level for the stream
  1685. * @param audioLevel the new audio level
  1686. */
  1687. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  1688. if(this.audioLevel !== audioLevel) {
  1689. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1690. audioLevel);
  1691. this.audioLevel = audioLevel;
  1692. }
  1693. }
  1694. module.exports = JitsiTrack;
  1695. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":43}],16:[function(require,module,exports){
  1696. /* global APP */
  1697. var EventEmitter = require("events");
  1698. var RTCBrowserType = require("./RTCBrowserType");
  1699. var RTCUtils = require("./RTCUtils.js");
  1700. var JitsiTrack = require("./JitsiTrack");
  1701. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1702. var DataChannels = require("./DataChannels");
  1703. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1704. var DesktopSharingEventTypes
  1705. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1706. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1707. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1708. function createLocalTracks(streams) {
  1709. var newStreams = []
  1710. for (var i = 0; i < streams.length; i++) {
  1711. var localStream = new JitsiLocalTrack(streams[i].stream,
  1712. streams[i].videoType, streams[i].resolution);
  1713. newStreams.push(localStream);
  1714. if (streams[i].isMuted === true)
  1715. localStream.setMute(true);
  1716. }
  1717. return newStreams;
  1718. }
  1719. function RTC(room, options) {
  1720. this.room = room;
  1721. this.localStreams = [];
  1722. //FIXME: we should start removing those streams.
  1723. //FIXME: We should support multiple streams per jid.
  1724. this.remoteStreams = {};
  1725. this.localAudio = null;
  1726. this.localVideo = null;
  1727. this.eventEmitter = new EventEmitter();
  1728. var self = this;
  1729. this.options = options || {};
  1730. room.addPresenceListener("videomuted", function (values, from) {
  1731. if(self.remoteStreams[from]) {
  1732. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1733. }
  1734. });
  1735. room.addPresenceListener("audiomuted", function (values, from) {
  1736. if(self.remoteStreams[from]) {
  1737. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1738. }
  1739. });
  1740. }
  1741. /**
  1742. * Creates the local MediaStreams.
  1743. * @param {Object} [options] optional parameters
  1744. * @param {Array} options.devices the devices that will be requested
  1745. * @param {string} options.resolution resolution constraints
  1746. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1747. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1748. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1749. * @param {string} options.cameraDeviceId
  1750. * @param {string} options.micDeviceId
  1751. * @returns {*} Promise object that will receive the new JitsiTracks
  1752. */
  1753. RTC.obtainAudioAndVideoPermissions = function (options) {
  1754. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1755. }
  1756. RTC.prototype.onIncommingCall = function(event) {
  1757. if(this.options.config.openSctp)
  1758. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1759. for(var i = 0; i < this.localStreams.length; i++)
  1760. if(this.localStreams[i])
  1761. {
  1762. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1763. }
  1764. }
  1765. RTC.prototype.selectedEndpoint = function (id) {
  1766. if(this.dataChannels)
  1767. this.dataChannels.handleSelectedEndpointEvent(id);
  1768. }
  1769. RTC.prototype.pinEndpoint = function (id) {
  1770. if(this.dataChannels)
  1771. this.dataChannels.handlePinnedEndpointEvent(id);
  1772. }
  1773. RTC.prototype.addListener = function (type, listener) {
  1774. this.eventEmitter.on(type, listener);
  1775. };
  1776. RTC.prototype.removeListener = function (eventType, listener) {
  1777. this.eventEmitter.removeListener(eventType, listener);
  1778. };
  1779. RTC.addListener = function (eventType, listener) {
  1780. RTCUtils.addListener(eventType, listener);
  1781. }
  1782. RTC.removeListener = function (eventType, listener) {
  1783. RTCUtils.removeListener(eventType, listener)
  1784. }
  1785. RTC.isRTCReady = function () {
  1786. return RTCUtils.isRTCReady();
  1787. }
  1788. RTC.init = function (options) {
  1789. this.options = options || {};
  1790. return RTCUtils.init(this.options);
  1791. }
  1792. RTC.getDeviceAvailability = function () {
  1793. return RTCUtils.getDeviceAvailability();
  1794. }
  1795. RTC.prototype.addLocalStream = function (stream) {
  1796. this.localStreams.push(stream);
  1797. stream._setRTC(this);
  1798. if (stream.type == "audio") {
  1799. this.localAudio = stream;
  1800. } else {
  1801. this.localVideo = stream;
  1802. }
  1803. };
  1804. RTC.prototype.removeLocalStream = function (stream) {
  1805. for(var i = 0; i < this.localStreams.length; i++) {
  1806. if(this.localStreams[i].getOriginalStream() === stream) {
  1807. delete this.localStreams[i];
  1808. return;
  1809. }
  1810. }
  1811. };
  1812. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1813. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  1814. if(!data.peerjid)
  1815. return;
  1816. var jid = data.peerjid;
  1817. if(!this.remoteStreams[jid]) {
  1818. this.remoteStreams[jid] = {};
  1819. }
  1820. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1821. return remoteStream;
  1822. };
  1823. RTC.getPCConstraints = function () {
  1824. return RTCUtils.pc_constraints;
  1825. };
  1826. RTC.attachMediaStream = function (elSelector, stream) {
  1827. RTCUtils.attachMediaStream(elSelector, stream);
  1828. };
  1829. RTC.getStreamID = function (stream) {
  1830. return RTCUtils.getStreamID(stream);
  1831. };
  1832. RTC.getVideoSrc = function (element) {
  1833. return RTCUtils.getVideoSrc(element);
  1834. };
  1835. /**
  1836. * Returns true if retrieving the the list of input devices is supported and
  1837. * false if not.
  1838. */
  1839. RTC.isDeviceListAvailable = function () {
  1840. return RTCUtils.isDeviceListAvailable();
  1841. };
  1842. /**
  1843. * Returns true if changing the camera / microphone device is supported and
  1844. * false if not.
  1845. */
  1846. RTC.isDeviceChangeAvailable = function () {
  1847. return RTCUtils.isDeviceChangeAvailable();
  1848. }
  1849. /**
  1850. * Allows to receive list of available cameras/microphones.
  1851. * @param {function} callback would receive array of devices as an argument
  1852. */
  1853. RTC.enumerateDevices = function (callback) {
  1854. RTCUtils.enumerateDevices(callback);
  1855. };
  1856. RTC.setVideoSrc = function (element, src) {
  1857. RTCUtils.setVideoSrc(element, src);
  1858. };
  1859. /**
  1860. * A method to handle stopping of the stream.
  1861. * One point to handle the differences in various implementations.
  1862. * @param mediaStream MediaStream object to stop.
  1863. */
  1864. RTC.stopMediaStream = function (mediaStream) {
  1865. RTCUtils.stopMediaStream(mediaStream);
  1866. };
  1867. RTC.prototype.getVideoElementName = function () {
  1868. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1869. };
  1870. RTC.prototype.dispose = function() {
  1871. };
  1872. RTC.prototype.switchVideoStreams = function (newStream) {
  1873. this.localVideo.stream = newStream;
  1874. this.localStreams = [];
  1875. //in firefox we have only one stream object
  1876. if (this.localAudio.getOriginalStream() != newStream)
  1877. this.localStreams.push(this.localAudio);
  1878. this.localStreams.push(this.localVideo);
  1879. };
  1880. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  1881. if(this.remoteStreams[jid] && this.remoteStreams[jid][JitsiTrack.AUDIO])
  1882. this.remoteStreams[jid][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  1883. }
  1884. module.exports = RTC;
  1885. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/RTCEvents.js":79,"../../service/desktopsharing/DesktopSharingEventTypes":82,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":43}],17:[function(require,module,exports){
  1886. var currentBrowser;
  1887. var browserVersion;
  1888. var isAndroid;
  1889. var RTCBrowserType = {
  1890. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1891. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1892. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1893. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1894. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1895. getBrowserType: function () {
  1896. return currentBrowser;
  1897. },
  1898. isChrome: function () {
  1899. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1900. },
  1901. isOpera: function () {
  1902. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1903. },
  1904. isFirefox: function () {
  1905. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1906. },
  1907. isIExplorer: function () {
  1908. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1909. },
  1910. isSafari: function () {
  1911. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1912. },
  1913. isTemasysPluginUsed: function () {
  1914. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1915. },
  1916. getFirefoxVersion: function () {
  1917. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1918. },
  1919. getChromeVersion: function () {
  1920. return RTCBrowserType.isChrome() ? browserVersion : null;
  1921. },
  1922. usesPlanB: function() {
  1923. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1924. RTCBrowserType.isTemasysPluginUsed();
  1925. },
  1926. usesUnifiedPlan: function() {
  1927. return RTCBrowserType.isFirefox();
  1928. },
  1929. /**
  1930. * Whether the browser is running on an android device.
  1931. */
  1932. isAndroid: function() {
  1933. return isAndroid;
  1934. }
  1935. // Add version getters for other browsers when needed
  1936. };
  1937. // detectOpera() must be called before detectChrome() !!!
  1938. // otherwise Opera wil be detected as Chrome
  1939. function detectChrome() {
  1940. if (navigator.webkitGetUserMedia) {
  1941. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1942. var userAgent = navigator.userAgent.toLowerCase();
  1943. // We can assume that user agent is chrome, because it's
  1944. // enforced when 'ext' streaming method is set
  1945. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1946. console.log("This appears to be Chrome, ver: " + ver);
  1947. return ver;
  1948. }
  1949. return null;
  1950. }
  1951. function detectOpera() {
  1952. var userAgent = navigator.userAgent;
  1953. if (userAgent.match(/Opera|OPR/)) {
  1954. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1955. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1956. console.info("This appears to be Opera, ver: " + version);
  1957. return version;
  1958. }
  1959. return null;
  1960. }
  1961. function detectFirefox() {
  1962. if (navigator.mozGetUserMedia) {
  1963. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1964. var version = parseInt(
  1965. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1966. console.log('This appears to be Firefox, ver: ' + version);
  1967. return version;
  1968. }
  1969. return null;
  1970. }
  1971. function detectSafari() {
  1972. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1973. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1974. console.info("This appears to be Safari");
  1975. // FIXME detect Safari version when needed
  1976. return 1;
  1977. }
  1978. return null;
  1979. }
  1980. function detectIE() {
  1981. var version;
  1982. var ua = window.navigator.userAgent;
  1983. var msie = ua.indexOf('MSIE ');
  1984. if (msie > 0) {
  1985. // IE 10 or older => return version number
  1986. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1987. }
  1988. var trident = ua.indexOf('Trident/');
  1989. if (!version && trident > 0) {
  1990. // IE 11 => return version number
  1991. var rv = ua.indexOf('rv:');
  1992. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1993. }
  1994. var edge = ua.indexOf('Edge/');
  1995. if (!version && edge > 0) {
  1996. // IE 12 => return version number
  1997. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1998. }
  1999. if (version) {
  2000. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2001. console.info("This appears to be IExplorer, ver: " + version);
  2002. }
  2003. return version;
  2004. }
  2005. function detectBrowser() {
  2006. var version;
  2007. var detectors = [
  2008. detectOpera,
  2009. detectChrome,
  2010. detectFirefox,
  2011. detectIE,
  2012. detectSafari
  2013. ];
  2014. // Try all browser detectors
  2015. for (var i = 0; i < detectors.length; i++) {
  2016. version = detectors[i]();
  2017. if (version)
  2018. return version;
  2019. }
  2020. console.error("Failed to detect browser type");
  2021. return undefined;
  2022. }
  2023. browserVersion = detectBrowser();
  2024. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2025. module.exports = RTCBrowserType;
  2026. },{}],18:[function(require,module,exports){
  2027. (function (__filename){
  2028. /* global config, require, attachMediaStream, getUserMedia,
  2029. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2030. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2031. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2032. */
  2033. /* jshint -W101 */
  2034. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2035. var RTCBrowserType = require("./RTCBrowserType");
  2036. var Resolutions = require("../../service/RTC/Resolutions");
  2037. var RTCEvents = require("../../service/RTC/RTCEvents");
  2038. var AdapterJS = require("./adapter.screenshare");
  2039. var SDPUtil = require("../xmpp/SDPUtil");
  2040. var EventEmitter = require("events");
  2041. var screenObtainer = require("./ScreenObtainer");
  2042. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2043. var eventEmitter = new EventEmitter();
  2044. var devices = {
  2045. audio: true,
  2046. video: true
  2047. };
  2048. var rtcReady = false;
  2049. function setResolutionConstraints(constraints, resolution) {
  2050. var isAndroid = RTCBrowserType.isAndroid();
  2051. if (Resolutions[resolution]) {
  2052. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2053. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2054. }
  2055. else if (isAndroid) {
  2056. // FIXME can't remember if the purpose of this was to always request
  2057. // low resolution on Android ? if yes it should be moved up front
  2058. constraints.video.mandatory.minWidth = 320;
  2059. constraints.video.mandatory.minHeight = 240;
  2060. constraints.video.mandatory.maxFrameRate = 15;
  2061. }
  2062. if (constraints.video.mandatory.minWidth)
  2063. constraints.video.mandatory.maxWidth =
  2064. constraints.video.mandatory.minWidth;
  2065. if (constraints.video.mandatory.minHeight)
  2066. constraints.video.mandatory.maxHeight =
  2067. constraints.video.mandatory.minHeight;
  2068. }
  2069. /**
  2070. * @param {string[]} um required user media types
  2071. *
  2072. * @param {Object} [options={}] optional parameters
  2073. * @param {string} options.resolution
  2074. * @param {number} options.bandwidth
  2075. * @param {number} options.fps
  2076. * @param {string} options.desktopStream
  2077. * @param {string} options.cameraDeviceId
  2078. * @param {string} options.micDeviceId
  2079. * @param {bool} firefox_fake_device
  2080. */
  2081. function getConstraints(um, options) {
  2082. var constraints = {audio: false, video: false};
  2083. if (um.indexOf('video') >= 0) {
  2084. // same behaviour as true
  2085. constraints.video = { mandatory: {}, optional: [] };
  2086. if (options.cameraDeviceId) {
  2087. constraints.video.optional.push({
  2088. sourceId: options.cameraDeviceId
  2089. });
  2090. }
  2091. constraints.video.optional.push({ googLeakyBucket: true });
  2092. setResolutionConstraints(constraints, options.resolution);
  2093. }
  2094. if (um.indexOf('audio') >= 0) {
  2095. if (!RTCBrowserType.isFirefox()) {
  2096. // same behaviour as true
  2097. constraints.audio = { mandatory: {}, optional: []};
  2098. if (options.micDeviceId) {
  2099. constraints.audio.optional.push({
  2100. sourceId: options.micDeviceId
  2101. });
  2102. }
  2103. // if it is good enough for hangouts...
  2104. constraints.audio.optional.push(
  2105. {googEchoCancellation: true},
  2106. {googAutoGainControl: true},
  2107. {googNoiseSupression: true},
  2108. {googHighpassFilter: true},
  2109. {googNoisesuppression2: true},
  2110. {googEchoCancellation2: true},
  2111. {googAutoGainControl2: true}
  2112. );
  2113. } else {
  2114. if (options.micDeviceId) {
  2115. constraints.audio = {
  2116. mandatory: {},
  2117. optional: [{
  2118. sourceId: options.micDeviceId
  2119. }]};
  2120. } else {
  2121. constraints.audio = true;
  2122. }
  2123. }
  2124. }
  2125. if (um.indexOf('screen') >= 0) {
  2126. if (RTCBrowserType.isChrome()) {
  2127. constraints.video = {
  2128. mandatory: {
  2129. chromeMediaSource: "screen",
  2130. googLeakyBucket: true,
  2131. maxWidth: window.screen.width,
  2132. maxHeight: window.screen.height,
  2133. maxFrameRate: 3
  2134. },
  2135. optional: []
  2136. };
  2137. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2138. constraints.video = {
  2139. optional: [
  2140. {
  2141. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2142. }
  2143. ]
  2144. };
  2145. } else if (RTCBrowserType.isFirefox()) {
  2146. constraints.video = {
  2147. mozMediaSource: "window",
  2148. mediaSource: "window"
  2149. };
  2150. } else {
  2151. logger.error(
  2152. "'screen' WebRTC media source is supported only in Chrome" +
  2153. " and with Temasys plugin");
  2154. }
  2155. }
  2156. if (um.indexOf('desktop') >= 0) {
  2157. constraints.video = {
  2158. mandatory: {
  2159. chromeMediaSource: "desktop",
  2160. chromeMediaSourceId: options.desktopStream,
  2161. googLeakyBucket: true,
  2162. maxWidth: window.screen.width,
  2163. maxHeight: window.screen.height,
  2164. maxFrameRate: 3
  2165. },
  2166. optional: []
  2167. };
  2168. }
  2169. if (options.bandwidth) {
  2170. if (!constraints.video) {
  2171. //same behaviour as true
  2172. constraints.video = {mandatory: {}, optional: []};
  2173. }
  2174. constraints.video.optional.push({bandwidth: options.bandwidth});
  2175. }
  2176. if (options.fps) {
  2177. // for some cameras it might be necessary to request 30fps
  2178. // so they choose 30fps mjpg over 10fps yuy2
  2179. if (!constraints.video) {
  2180. // same behaviour as true;
  2181. constraints.video = {mandatory: {}, optional: []};
  2182. }
  2183. constraints.video.mandatory.minFrameRate = options.fps;
  2184. }
  2185. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2186. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2187. // this later can be a problem with some of the tests
  2188. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2189. {
  2190. // seems to be fixed now, removing this experimental fix, as having
  2191. // multiple audio tracks brake the tests
  2192. //constraints.audio = true;
  2193. constraints.fake = true;
  2194. }
  2195. return constraints;
  2196. }
  2197. function setAvailableDevices(um, available) {
  2198. if (um.indexOf("video") != -1) {
  2199. devices.video = available;
  2200. }
  2201. if (um.indexOf("audio") != -1) {
  2202. devices.audio = available;
  2203. }
  2204. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2205. }
  2206. // In case of IE we continue from 'onReady' callback
  2207. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2208. // once it is initialized.
  2209. function onReady (options, GUM) {
  2210. rtcReady = true;
  2211. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2212. screenObtainer.init(eventEmitter, options, GUM);
  2213. }
  2214. /**
  2215. * Apply function with arguments if function exists.
  2216. * Do nothing if function not provided.
  2217. * @param {function} [fn] function to apply
  2218. * @param {Array} [args=[]] arguments for function
  2219. */
  2220. function maybeApply(fn, args) {
  2221. if (fn) {
  2222. fn.apply(null, args || []);
  2223. }
  2224. }
  2225. var getUserMediaStatus = {
  2226. initialized: false,
  2227. callbacks: []
  2228. };
  2229. /**
  2230. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2231. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2232. * @param {Function} getUserMedia native function
  2233. * @returns {Function} wrapped function
  2234. */
  2235. function wrapGetUserMedia(getUserMedia) {
  2236. return function (constraints, successCallback, errorCallback) {
  2237. getUserMedia(constraints, function (stream) {
  2238. maybeApply(successCallback, [stream]);
  2239. if (!getUserMediaStatus.initialized) {
  2240. getUserMediaStatus.initialized = true;
  2241. getUserMediaStatus.callbacks.forEach(function (callback) {
  2242. callback();
  2243. });
  2244. getUserMediaStatus.callbacks.length = 0;
  2245. }
  2246. }, function (error) {
  2247. maybeApply(errorCallback, [error]);
  2248. });
  2249. };
  2250. }
  2251. /**
  2252. * Create stub device which equals to auto selected device.
  2253. * @param {string} kind if that should be `audio` or `video` device
  2254. * @returns {Object} stub device description in `enumerateDevices` format
  2255. */
  2256. function createAutoDeviceInfo(kind) {
  2257. return {
  2258. facing: null,
  2259. label: 'Auto',
  2260. kind: kind,
  2261. deviceId: '',
  2262. groupId: null
  2263. };
  2264. }
  2265. /**
  2266. * Execute function after getUserMedia was executed at least once.
  2267. * @param {Function} callback function to execute after getUserMedia
  2268. */
  2269. function afterUserMediaInitialized(callback) {
  2270. if (getUserMediaStatus.initialized) {
  2271. callback();
  2272. } else {
  2273. getUserMediaStatus.callbacks.push(callback);
  2274. }
  2275. }
  2276. /**
  2277. * Wrapper function which makes enumerateDevices to wait
  2278. * until someone executes getUserMedia first time.
  2279. * @param {Function} enumerateDevices native function
  2280. * @returns {Funtion} wrapped function
  2281. */
  2282. function wrapEnumerateDevices(enumerateDevices) {
  2283. return function (callback) {
  2284. // enumerate devices only after initial getUserMedia
  2285. afterUserMediaInitialized(function () {
  2286. enumerateDevices().then(function (devices) {
  2287. //add auto devices
  2288. devices.unshift(
  2289. createAutoDeviceInfo('audioinput'),
  2290. createAutoDeviceInfo('videoinput')
  2291. );
  2292. callback(devices);
  2293. }, function (err) {
  2294. console.error('cannot enumerate devices: ', err);
  2295. // return only auto devices
  2296. callback([createAutoDeviceInfo('audioInput'),
  2297. createAutoDeviceInfo('videoinput')]);
  2298. });
  2299. });
  2300. };
  2301. }
  2302. /**
  2303. * Use old MediaStreamTrack to get devices list and
  2304. * convert it to enumerateDevices format.
  2305. * @param {Function} callback function to call when received devices list.
  2306. */
  2307. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2308. MediaStreamTrack.getSources(function (sources) {
  2309. var devices = sources.map(function (source) {
  2310. var kind = (source.kind || '').toLowerCase();
  2311. return {
  2312. facing: source.facing || null,
  2313. label: source.label,
  2314. kind: kind ? kind + 'input': null,
  2315. deviceId: source.id,
  2316. groupId: source.groupId || null
  2317. };
  2318. });
  2319. //add auto devices
  2320. devices.unshift(
  2321. createAutoDeviceInfo('audioinput'),
  2322. createAutoDeviceInfo('videoinput')
  2323. );
  2324. callback(devices);
  2325. });
  2326. }
  2327. function obtainDevices(options) {
  2328. if(!options.devices || options.devices.length === 0) {
  2329. return options.successCallback(options.streams || {});
  2330. }
  2331. var device = options.devices.splice(0, 1);
  2332. options.deviceGUM[device](function (stream) {
  2333. options.streams = options.streams || {};
  2334. options.streams[device] = stream;
  2335. obtainDevices(options);
  2336. },
  2337. function (error) {
  2338. logger.error(
  2339. "failed to obtain " + device + " stream - stop", error);
  2340. options.errorCallback(JitsiTrackErrors.parseError(error));
  2341. });
  2342. }
  2343. /**
  2344. * Handles the newly created Media Streams.
  2345. * @param streams the new Media Streams
  2346. * @param resolution the resolution of the video streams
  2347. * @returns {*[]} object that describes the new streams
  2348. */
  2349. function handleLocalStream(streams, resolution) {
  2350. var audioStream, videoStream, desktopStream, res = [];
  2351. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2352. // an object with two properties: audioStream, videoStream.
  2353. if (window.webkitMediaStream) {
  2354. var audioVideo = streams.audioVideo;
  2355. if (audioVideo) {
  2356. var audioTracks = audioVideo.getAudioTracks();
  2357. if(audioTracks.length) {
  2358. audioStream = new webkitMediaStream();
  2359. for (var i = 0; i < audioTracks.length; i++) {
  2360. audioStream.addTrack(audioTracks[i]);
  2361. }
  2362. }
  2363. var videoTracks = audioVideo.getVideoTracks();
  2364. if(videoTracks.length) {
  2365. videoStream = new webkitMediaStream();
  2366. for (var j = 0; j < videoTracks.length; j++) {
  2367. videoStream.addTrack(videoTracks[j]);
  2368. }
  2369. }
  2370. }
  2371. if (streams && streams.desktopStream)
  2372. desktopStream = streams.desktopStream;
  2373. }
  2374. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2375. if (streams && streams.audio)
  2376. audioStream = streams.audio;
  2377. if (streams && streams.video)
  2378. videoStream = streams.video;
  2379. if(streams && streams.desktop)
  2380. desktopStream = streams.desktop;
  2381. }
  2382. if (desktopStream)
  2383. res.push({stream: desktopStream,
  2384. type: "video", videoType: "desktop"});
  2385. if(audioStream)
  2386. res.push({stream: audioStream, type: "audio", videoType: null});
  2387. if(videoStream)
  2388. res.push({stream: videoStream, type: "video", videoType: "camera",
  2389. resolution: resolution});
  2390. return res;
  2391. }
  2392. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2393. var RTCUtils = {
  2394. init: function (options) {
  2395. return new Promise(function(resolve, reject) {
  2396. if (RTCBrowserType.isFirefox()) {
  2397. var FFversion = RTCBrowserType.getFirefoxVersion();
  2398. if (FFversion < 40) {
  2399. logger.error(
  2400. "Firefox version too old: " + FFversion +
  2401. ". Required >= 40.");
  2402. reject(new Error("Firefox version too old: " + FFversion +
  2403. ". Required >= 40."));
  2404. return;
  2405. }
  2406. this.peerconnection = mozRTCPeerConnection;
  2407. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2408. this.enumerateDevices = wrapEnumerateDevices(
  2409. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2410. );
  2411. this.pc_constraints = {};
  2412. this.attachMediaStream = function (element, stream) {
  2413. // srcObject is being standardized and FF will eventually
  2414. // support that unprefixed. FF also supports the
  2415. // "element.src = URL.createObjectURL(...)" combo, but that
  2416. // will be deprecated in favour of srcObject.
  2417. //
  2418. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2419. // https://github.com/webrtc/samples/issues/302
  2420. if (!element[0])
  2421. return;
  2422. element[0].mozSrcObject = stream;
  2423. element[0].play();
  2424. };
  2425. this.getStreamID = function (stream) {
  2426. var id = stream.id;
  2427. if (!id) {
  2428. var tracks = stream.getVideoTracks();
  2429. if (!tracks || tracks.length === 0) {
  2430. tracks = stream.getAudioTracks();
  2431. }
  2432. id = tracks[0].id;
  2433. }
  2434. return SDPUtil.filter_special_chars(id);
  2435. };
  2436. this.getVideoSrc = function (element) {
  2437. if (!element)
  2438. return null;
  2439. return element.mozSrcObject;
  2440. };
  2441. this.setVideoSrc = function (element, src) {
  2442. if (element)
  2443. element.mozSrcObject = src;
  2444. };
  2445. RTCSessionDescription = mozRTCSessionDescription;
  2446. RTCIceCandidate = mozRTCIceCandidate;
  2447. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2448. this.peerconnection = webkitRTCPeerConnection;
  2449. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2450. if (navigator.mediaDevices) {
  2451. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2452. this.enumerateDevices = wrapEnumerateDevices(
  2453. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2454. );
  2455. } else {
  2456. this.getUserMedia = getUserMedia;
  2457. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2458. }
  2459. this.attachMediaStream = function (element, stream) {
  2460. element.attr('src', webkitURL.createObjectURL(stream));
  2461. };
  2462. this.getStreamID = function (stream) {
  2463. // streams from FF endpoints have the characters '{' and '}'
  2464. // that make jQuery choke.
  2465. return SDPUtil.filter_special_chars(stream.id);
  2466. };
  2467. this.getVideoSrc = function (element) {
  2468. if (!element)
  2469. return null;
  2470. return element.getAttribute("src");
  2471. };
  2472. this.setVideoSrc = function (element, src) {
  2473. if (element)
  2474. element.setAttribute("src", src);
  2475. };
  2476. // DTLS should now be enabled by default but..
  2477. this.pc_constraints = {'optional': [
  2478. {'DtlsSrtpKeyAgreement': 'true'}
  2479. ]};
  2480. if (options.useIPv6) {
  2481. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2482. this.pc_constraints.optional.push({googIPv6: true});
  2483. }
  2484. if (RTCBrowserType.isAndroid()) {
  2485. this.pc_constraints = {}; // disable DTLS on Android
  2486. }
  2487. if (!webkitMediaStream.prototype.getVideoTracks) {
  2488. webkitMediaStream.prototype.getVideoTracks = function () {
  2489. return this.videoTracks;
  2490. };
  2491. }
  2492. if (!webkitMediaStream.prototype.getAudioTracks) {
  2493. webkitMediaStream.prototype.getAudioTracks = function () {
  2494. return this.audioTracks;
  2495. };
  2496. }
  2497. }
  2498. // Detect IE/Safari
  2499. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2500. //AdapterJS.WebRTCPlugin.setLogLevel(
  2501. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2502. var self = this;
  2503. AdapterJS.webRTCReady(function (isPlugin) {
  2504. self.peerconnection = RTCPeerConnection;
  2505. self.getUserMedia = window.getUserMedia;
  2506. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2507. self.attachMediaStream = function (elSel, stream) {
  2508. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2509. return;
  2510. }
  2511. attachMediaStream(elSel[0], stream);
  2512. };
  2513. self.getStreamID = function (stream) {
  2514. var id = SDPUtil.filter_special_chars(stream.label);
  2515. return id;
  2516. };
  2517. self.getVideoSrc = function (element) {
  2518. if (!element) {
  2519. logger.warn("Attempt to get video SRC of null element");
  2520. return null;
  2521. }
  2522. var children = element.children;
  2523. for (var i = 0; i !== children.length; ++i) {
  2524. if (children[i].name === 'streamId') {
  2525. return children[i].value;
  2526. }
  2527. }
  2528. //logger.info(element.id + " SRC: " + src);
  2529. return null;
  2530. };
  2531. self.setVideoSrc = function (element, src) {
  2532. //logger.info("Set video src: ", element, src);
  2533. if (!src) {
  2534. logger.warn("Not attaching video stream, 'src' is null");
  2535. return;
  2536. }
  2537. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2538. var stream = AdapterJS.WebRTCPlugin.plugin
  2539. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2540. attachMediaStream(element, stream);
  2541. };
  2542. onReady(options, self.getUserMediaWithConstraints);
  2543. resolve();
  2544. });
  2545. } else {
  2546. try {
  2547. logger.error('Browser does not appear to be WebRTC-capable');
  2548. } catch (e) {
  2549. }
  2550. reject('Browser does not appear to be WebRTC-capable');
  2551. return;
  2552. }
  2553. // Call onReady() if Temasys plugin is not used
  2554. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2555. onReady(options, this.getUserMediaWithConstraints);
  2556. resolve();
  2557. }
  2558. }.bind(this));
  2559. },
  2560. /**
  2561. * @param {string[]} um required user media types
  2562. * @param {function} success_callback
  2563. * @param {Function} failure_callback
  2564. * @param {Object} [options] optional parameters
  2565. * @param {string} options.resolution
  2566. * @param {number} options.bandwidth
  2567. * @param {number} options.fps
  2568. * @param {string} options.desktopStream
  2569. * @param {string} options.cameraDeviceId
  2570. * @param {string} options.micDeviceId
  2571. **/
  2572. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2573. options = options || {};
  2574. var resolution = options.resolution;
  2575. var constraints = getConstraints(um, options);
  2576. logger.info("Get media constraints", constraints);
  2577. try {
  2578. this.getUserMedia(constraints,
  2579. function (stream) {
  2580. logger.log('onUserMediaSuccess');
  2581. setAvailableDevices(um, true);
  2582. success_callback(stream);
  2583. },
  2584. function (error) {
  2585. setAvailableDevices(um, false);
  2586. logger.warn('Failed to get access to local media. Error ',
  2587. error, constraints);
  2588. if (failure_callback) {
  2589. failure_callback(error, resolution);
  2590. }
  2591. });
  2592. } catch (e) {
  2593. logger.error('GUM failed: ', e);
  2594. if (failure_callback) {
  2595. failure_callback(e);
  2596. }
  2597. }
  2598. },
  2599. /**
  2600. * Creates the local MediaStreams.
  2601. * @param {Object} [options] optional parameters
  2602. * @param {Array} options.devices the devices that will be requested
  2603. * @param {string} options.resolution resolution constraints
  2604. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2605. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2606. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2607. * @param {string} options.cameraDeviceId
  2608. * @param {string} options.micDeviceId
  2609. * @returns {*} Promise object that will receive the new JitsiTracks
  2610. */
  2611. obtainAudioAndVideoPermissions: function (options) {
  2612. var self = this;
  2613. options = options || {};
  2614. return new Promise(function (resolve, reject) {
  2615. var successCallback = function (stream) {
  2616. resolve(handleLocalStream(stream, options.resolution));
  2617. };
  2618. options.devices = options.devices || ['audio', 'video'];
  2619. if(!screenObtainer.isSupported()
  2620. && options.devices.indexOf("desktop") !== -1){
  2621. reject(new Error("Desktop sharing is not supported!"));
  2622. }
  2623. if (RTCBrowserType.isFirefox() ||
  2624. RTCBrowserType.isTemasysPluginUsed()) {
  2625. var GUM = function (device, s, e) {
  2626. this.getUserMediaWithConstraints(device, s, e, options);
  2627. };
  2628. var deviceGUM = {
  2629. "audio": GUM.bind(self, ["audio"]),
  2630. "video": GUM.bind(self, ["video"]),
  2631. "desktop": screenObtainer.obtainStream
  2632. };
  2633. // With FF/IE we can't split the stream into audio and video because FF
  2634. // doesn't support media stream constructors. So, we need to get the
  2635. // audio stream separately from the video stream using two distinct GUM
  2636. // calls. Not very user friendly :-( but we don't have many other
  2637. // options neither.
  2638. //
  2639. // Note that we pack those 2 streams in a single object and pass it to
  2640. // the successCallback method.
  2641. obtainDevices({
  2642. devices: options.devices,
  2643. streams: [],
  2644. successCallback: successCallback,
  2645. errorCallback: reject,
  2646. deviceGUM: deviceGUM
  2647. });
  2648. } else {
  2649. var hasDesktop = options.devices.indexOf('desktop') > -1;
  2650. if (hasDesktop) {
  2651. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2652. }
  2653. options.resolution = options.resolution || '360';
  2654. if(options.devices.length) {
  2655. this.getUserMediaWithConstraints(
  2656. options.devices,
  2657. function (stream) {
  2658. if(hasDesktop) {
  2659. screenObtainer.obtainStream(
  2660. function (desktopStream) {
  2661. successCallback({audioVideo: stream,
  2662. desktopStream: desktopStream});
  2663. }, function (error) {
  2664. reject(
  2665. JitsiTrackErrors.parseError(error));
  2666. });
  2667. } else {
  2668. successCallback({audioVideo: stream});
  2669. }
  2670. },
  2671. function (error) {
  2672. reject(JitsiTrackErrors.parseError(error));
  2673. },
  2674. options);
  2675. } else if (hasDesktop) {
  2676. screenObtainer.obtainStream(
  2677. function (stream) {
  2678. successCallback({desktopStream: stream});
  2679. }, function (error) {
  2680. reject(
  2681. JitsiTrackErrors.parseError(error));
  2682. });
  2683. }
  2684. }
  2685. }.bind(this));
  2686. },
  2687. addListener: function (eventType, listener) {
  2688. eventEmitter.on(eventType, listener);
  2689. },
  2690. removeListener: function (eventType, listener) {
  2691. eventEmitter.removeListener(eventType, listener);
  2692. },
  2693. getDeviceAvailability: function () {
  2694. return devices;
  2695. },
  2696. isRTCReady: function () {
  2697. return rtcReady;
  2698. },
  2699. /**
  2700. * Checks if its possible to enumerate available cameras/micropones.
  2701. * @returns {boolean} true if available, false otherwise.
  2702. */
  2703. isDeviceListAvailable: function () {
  2704. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2705. if (isEnumerateDevicesAvailable) {
  2706. return true;
  2707. }
  2708. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2709. },
  2710. /**
  2711. * Returns true if changing the camera / microphone device is supported and
  2712. * false if not.
  2713. */
  2714. isDeviceChangeAvailable: function () {
  2715. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2716. RTCBrowserType.isTemasysPluginUsed())
  2717. return true;
  2718. return false;
  2719. },
  2720. /**
  2721. * A method to handle stopping of the stream.
  2722. * One point to handle the differences in various implementations.
  2723. * @param mediaStream MediaStream object to stop.
  2724. */
  2725. stopMediaStream: function (mediaStream) {
  2726. mediaStream.getTracks().forEach(function (track) {
  2727. // stop() not supported with IE
  2728. if (track.stop) {
  2729. track.stop();
  2730. }
  2731. });
  2732. // leave stop for implementation still using it
  2733. if (mediaStream.stop) {
  2734. mediaStream.stop();
  2735. }
  2736. }
  2737. };
  2738. module.exports = RTCUtils;
  2739. }).call(this,"/modules/RTC/RTCUtils.js")
  2740. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":79,"../../service/RTC/Resolutions":80,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":43,"jitsi-meet-logger":47}],19:[function(require,module,exports){
  2741. (function (__filename){
  2742. /* global chrome, $, alert */
  2743. /* jshint -W003 */
  2744. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2745. var RTCBrowserType = require("./RTCBrowserType");
  2746. var AdapterJS = require("./adapter.screenshare");
  2747. var DesktopSharingEventTypes
  2748. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2749. /**
  2750. * Indicates whether the Chrome desktop sharing extension is installed.
  2751. * @type {boolean}
  2752. */
  2753. var chromeExtInstalled = false;
  2754. /**
  2755. * Indicates whether an update of the Chrome desktop sharing extension is
  2756. * required.
  2757. * @type {boolean}
  2758. */
  2759. var chromeExtUpdateRequired = false;
  2760. /**
  2761. * Whether the jidesha extension for firefox is installed for the domain on
  2762. * which we are running. Null designates an unknown value.
  2763. * @type {null}
  2764. */
  2765. var firefoxExtInstalled = null;
  2766. /**
  2767. * If set to true, detection of an installed firefox extension will be started
  2768. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2769. * user tries to enable screen sharing).
  2770. */
  2771. var reDetectFirefoxExtension = false;
  2772. var GUM = null;
  2773. /**
  2774. * Handles obtaining a stream from a screen capture on different browsers.
  2775. */
  2776. var ScreenObtainer = {
  2777. /**
  2778. * The EventEmitter to use to emit events.
  2779. * @type {null}
  2780. */
  2781. eventEmitter: null,
  2782. obtainStream: null,
  2783. /**
  2784. * Initializes the function used to obtain a screen capture
  2785. * (this.obtainStream).
  2786. *
  2787. * If the browser is Chrome, it uses the value of
  2788. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2789. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2790. * use the "screen" media source (if the value is 'webrtc'),
  2791. * or disable screen capture (if the value is other).
  2792. * Note that for the "screen" media source to work the
  2793. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2794. */
  2795. init: function(eventEmitter, options, gum) {
  2796. this.eventEmitter = eventEmitter;
  2797. var obtainDesktopStream = null;
  2798. this.options = options = options || {};
  2799. GUM = gum;
  2800. if (RTCBrowserType.isFirefox())
  2801. initFirefoxExtensionDetection(options);
  2802. // TODO remove this, options.desktopSharing is deprecated.
  2803. var chromeMethod =
  2804. (options.desktopSharingChromeMethod || options.desktopSharing);
  2805. if (RTCBrowserType.isTemasysPluginUsed()) {
  2806. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  2807. logger.info("Screensharing not supported by this plugin " +
  2808. "version");
  2809. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2810. logger.info(
  2811. "Screensharing not available with Temasys plugin on" +
  2812. " this site");
  2813. } else {
  2814. obtainDesktopStream = obtainWebRTCScreen;
  2815. logger.info("Using Temasys plugin for desktop sharing");
  2816. }
  2817. } else if (RTCBrowserType.isChrome()) {
  2818. if (chromeMethod == "ext") {
  2819. if (RTCBrowserType.getChromeVersion() >= 34) {
  2820. obtainDesktopStream =
  2821. this.obtainScreenFromExtension;
  2822. logger.info("Using Chrome extension for desktop sharing");
  2823. initChromeExtension(options);
  2824. } else {
  2825. logger.info("Chrome extension not supported until ver 34");
  2826. }
  2827. } else if (chromeMethod == "webrtc") {
  2828. obtainDesktopStream = obtainWebRTCScreen;
  2829. logger.info("Using Chrome WebRTC for desktop sharing");
  2830. }
  2831. } else if (RTCBrowserType.isFirefox()) {
  2832. if (options.desktopSharingFirefoxDisabled) {
  2833. obtainDesktopStream = null;
  2834. } else if (window.location.protocol === "http:"){
  2835. logger.log("Screen sharing is not supported over HTTP. " +
  2836. "Use of HTTPS is required.");
  2837. obtainDesktopStream = null;
  2838. } else {
  2839. obtainDesktopStream = this.obtainScreenOnFirefox;
  2840. }
  2841. }
  2842. if (!obtainDesktopStream) {
  2843. logger.info("Desktop sharing disabled");
  2844. }
  2845. this.obtainStream = obtainDesktopStream;
  2846. },
  2847. /**
  2848. * Checks whether obtaining a screen capture is supported in the current
  2849. * environment.
  2850. * @returns {boolean}
  2851. */
  2852. isSupported: function() {
  2853. return !!this.obtainStream;
  2854. },
  2855. /**
  2856. * Obtains a screen capture stream on Firefox.
  2857. * @param callback
  2858. * @param errorCallback
  2859. */
  2860. obtainScreenOnFirefox:
  2861. function (callback, errorCallback) {
  2862. var self = this;
  2863. var extensionRequired = false;
  2864. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  2865. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  2866. RTCBrowserType.getFirefoxVersion() <=
  2867. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  2868. extensionRequired = true;
  2869. logger.log("Jidesha extension required on firefox version " +
  2870. RTCBrowserType.getFirefoxVersion());
  2871. }
  2872. if (!extensionRequired || firefoxExtInstalled === true) {
  2873. obtainWebRTCScreen(callback, errorCallback);
  2874. return;
  2875. }
  2876. if (reDetectFirefoxExtension) {
  2877. reDetectFirefoxExtension = false;
  2878. initFirefoxExtensionDetection(this.options);
  2879. }
  2880. // Give it some (more) time to initialize, and assume lack of
  2881. // extension if it hasn't.
  2882. if (firefoxExtInstalled === null) {
  2883. window.setTimeout(
  2884. function() {
  2885. if (firefoxExtInstalled === null)
  2886. firefoxExtInstalled = false;
  2887. self.obtainScreenOnFirefox(callback, errorCallback);
  2888. },
  2889. 300
  2890. );
  2891. logger.log("Waiting for detection of jidesha on firefox to " +
  2892. "finish.");
  2893. return;
  2894. }
  2895. // We need an extension and it isn't installed.
  2896. // Make sure we check for the extension when the user clicks again.
  2897. firefoxExtInstalled = null;
  2898. reDetectFirefoxExtension = true;
  2899. // Prompt the user to install the extension
  2900. this.eventEmitter.emit(
  2901. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  2902. this.options.desktopSharingFirefoxExtensionURL);
  2903. // Make sure desktopsharing knows that we failed, so that it doesn't get
  2904. // stuck in 'switching' mode.
  2905. errorCallback('Firefox extension required.');
  2906. },
  2907. /**
  2908. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  2909. * 'desktop' stream for returned stream token.
  2910. */
  2911. obtainScreenFromExtension: function (streamCallback, failCallback) {
  2912. if (chromeExtInstalled) {
  2913. doGetStreamFromExtension(this.options, streamCallback,
  2914. failCallback);
  2915. } else {
  2916. if (chromeExtUpdateRequired) {
  2917. alert(
  2918. 'Jitsi Desktop Streamer requires update. ' +
  2919. 'Changes will take effect after next Chrome restart.');
  2920. }
  2921. chrome.webstore.install(
  2922. getWebStoreInstallUrl(this.options),
  2923. function (arg) {
  2924. logger.log("Extension installed successfully", arg);
  2925. chromeExtInstalled = true;
  2926. // We need to give a moment for the endpoint to become
  2927. // available
  2928. window.setTimeout(function () {
  2929. doGetStreamFromExtension(this.options, streamCallback,
  2930. failCallback);
  2931. }, 500);
  2932. },
  2933. function (arg) {
  2934. logger.log("Failed to install the extension", arg);
  2935. failCallback(arg);
  2936. }
  2937. );
  2938. }
  2939. }
  2940. };
  2941. /**
  2942. * Obtains a desktop stream using getUserMedia.
  2943. * For this to work on Chrome, the
  2944. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  2945. *
  2946. * On firefox, the document's domain must be white-listed in the
  2947. * 'media.getusermedia.screensharing.allowed_domains' preference in
  2948. * 'about:config'.
  2949. */
  2950. function obtainWebRTCScreen(streamCallback, failCallback) {
  2951. GUM(
  2952. ['screen'],
  2953. streamCallback,
  2954. failCallback
  2955. );
  2956. }
  2957. /**
  2958. * Constructs inline install URL for Chrome desktop streaming extension.
  2959. * The 'chromeExtensionId' must be defined in options parameter.
  2960. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2961. * @returns {string}
  2962. */
  2963. function getWebStoreInstallUrl(options)
  2964. {
  2965. //TODO remove chromeExtensionId (deprecated)
  2966. return "https://chrome.google.com/webstore/detail/" +
  2967. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  2968. }
  2969. /**
  2970. * Checks whether an update of the Chrome extension is required.
  2971. * @param minVersion minimal required version
  2972. * @param extVersion current extension version
  2973. * @returns {boolean}
  2974. */
  2975. function isUpdateRequired(minVersion, extVersion) {
  2976. try {
  2977. var s1 = minVersion.split('.');
  2978. var s2 = extVersion.split('.');
  2979. var len = Math.max(s1.length, s2.length);
  2980. for (var i = 0; i < len; i++) {
  2981. var n1 = 0,
  2982. n2 = 0;
  2983. if (i < s1.length)
  2984. n1 = parseInt(s1[i]);
  2985. if (i < s2.length)
  2986. n2 = parseInt(s2[i]);
  2987. if (isNaN(n1) || isNaN(n2)) {
  2988. return true;
  2989. } else if (n1 !== n2) {
  2990. return n1 > n2;
  2991. }
  2992. }
  2993. // will happen if both versions have identical numbers in
  2994. // their components (even if one of them is longer, has more components)
  2995. return false;
  2996. }
  2997. catch (e) {
  2998. logger.error("Failed to parse extension version", e);
  2999. return true;
  3000. }
  3001. }
  3002. function checkChromeExtInstalled(callback, options) {
  3003. if (!chrome || !chrome.runtime) {
  3004. // No API, so no extension for sure
  3005. callback(false, false);
  3006. return;
  3007. }
  3008. chrome.runtime.sendMessage(
  3009. //TODO: remove chromeExtensionId (deprecated)
  3010. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3011. { getVersion: true },
  3012. function (response) {
  3013. if (!response || !response.version) {
  3014. // Communication failure - assume that no endpoint exists
  3015. logger.warn(
  3016. "Extension not installed?: ", chrome.runtime.lastError);
  3017. callback(false, false);
  3018. return;
  3019. }
  3020. // Check installed extension version
  3021. var extVersion = response.version;
  3022. logger.log('Extension version is: ' + extVersion);
  3023. //TODO: remove minChromeExtVersion (deprecated)
  3024. var updateRequired
  3025. = isUpdateRequired(
  3026. (options.desktopSharingChromeMinExtVersion ||
  3027. options.minChromeExtVersion),
  3028. extVersion);
  3029. callback(!updateRequired, updateRequired);
  3030. }
  3031. );
  3032. }
  3033. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3034. // Sends 'getStream' msg to the extension.
  3035. // Extension id must be defined in the config.
  3036. chrome.runtime.sendMessage(
  3037. //TODO: remove chromeExtensionId (deprecated)
  3038. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3039. {
  3040. getStream: true,
  3041. //TODO: remove desktopSharingSources (deprecated).
  3042. sources: (options.desktopSharingChromeSources ||
  3043. options.desktopSharingSources)
  3044. },
  3045. function (response) {
  3046. if (!response) {
  3047. failCallback(chrome.runtime.lastError);
  3048. return;
  3049. }
  3050. logger.log("Response from extension: " + response);
  3051. if (response.streamId) {
  3052. GUM(
  3053. ['desktop'],
  3054. function (stream) {
  3055. streamCallback(stream);
  3056. },
  3057. failCallback,
  3058. {desktopStream: response.streamId});
  3059. } else {
  3060. failCallback("Extension failed to get the stream");
  3061. }
  3062. }
  3063. );
  3064. }
  3065. /**
  3066. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3067. * config.js to support inline installs. Host site must be selected as main
  3068. * website of published extension.
  3069. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3070. */
  3071. function initInlineInstalls(options)
  3072. {
  3073. $("link[rel=chrome-webstore-item]").attr("href",
  3074. getWebStoreInstallUrl(options));
  3075. }
  3076. function initChromeExtension(options) {
  3077. // Initialize Chrome extension inline installs
  3078. initInlineInstalls(options);
  3079. // Check if extension is installed
  3080. checkChromeExtInstalled(function (installed, updateRequired) {
  3081. chromeExtInstalled = installed;
  3082. chromeExtUpdateRequired = updateRequired;
  3083. logger.info(
  3084. "Chrome extension installed: " + chromeExtInstalled +
  3085. " updateRequired: " + chromeExtUpdateRequired);
  3086. }, options);
  3087. }
  3088. /**
  3089. * Starts the detection of an installed jidesha extension for firefox.
  3090. * @param options supports "desktopSharingFirefoxDisabled",
  3091. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3092. */
  3093. function initFirefoxExtensionDetection(options) {
  3094. if (options.desktopSharingFirefoxDisabled) {
  3095. return;
  3096. }
  3097. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3098. return;
  3099. if (!options.desktopSharingFirefoxExtId) {
  3100. firefoxExtInstalled = false;
  3101. return;
  3102. }
  3103. var img = document.createElement('img');
  3104. img.onload = function(){
  3105. logger.log("Detected firefox screen sharing extension.");
  3106. firefoxExtInstalled = true;
  3107. };
  3108. img.onerror = function(){
  3109. logger.log("Detected lack of firefox screen sharing extension.");
  3110. firefoxExtInstalled = false;
  3111. };
  3112. // The jidesha extension exposes an empty image file under the url:
  3113. // "chrome://EXT_ID/content/DOMAIN.png"
  3114. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3115. // DOMAIN is a domain whitelisted by the extension.
  3116. var src = "chrome://" +
  3117. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3118. "/content/" + document.location.hostname + ".png";
  3119. img.setAttribute('src', src);
  3120. }
  3121. module.exports = ScreenObtainer;
  3122. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3123. },{"../../service/desktopsharing/DesktopSharingEventTypes":82,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":47}],20:[function(require,module,exports){
  3124. (function (__filename){
  3125. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3126. var console = require("jitsi-meet-logger").getLogger(__filename);
  3127. // Adapter's interface.
  3128. var AdapterJS = AdapterJS || {};
  3129. // Browserify compatibility
  3130. if(typeof exports !== 'undefined') {
  3131. module.exports = AdapterJS;
  3132. }
  3133. AdapterJS.options = AdapterJS.options || {};
  3134. // uncomment to get virtual webcams
  3135. // AdapterJS.options.getAllCams = true;
  3136. // uncomment to prevent the install prompt when the plugin in not yet installed
  3137. // AdapterJS.options.hidePluginInstallPrompt = true;
  3138. // AdapterJS version
  3139. AdapterJS.VERSION = '0.12.3';
  3140. // This function will be called when the WebRTC API is ready to be used
  3141. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3142. // the plugin
  3143. // You may Override this function to synchronise the start of your application
  3144. // with the WebRTC API being ready.
  3145. // If you decide not to override use this synchronisation, it may result in
  3146. // an extensive CPU usage on the plugin start (once per tab loaded)
  3147. // Params:
  3148. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3149. //
  3150. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3151. // The WebRTC API is ready.
  3152. // Override me and do whatever you want here
  3153. };
  3154. // Sets a callback function to be called when the WebRTC interface is ready.
  3155. // The first argument is the function to callback.\
  3156. // Throws an error if the first argument is not a function
  3157. AdapterJS.webRTCReady = function (callback) {
  3158. if (typeof callback !== 'function') {
  3159. throw new Error('Callback provided is not a function');
  3160. }
  3161. if (true === AdapterJS.onwebrtcreadyDone) {
  3162. // All WebRTC interfaces are ready, just call the callback
  3163. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3164. } else {
  3165. // will be triggered automatically when your browser/plugin is ready.
  3166. AdapterJS.onwebrtcready = callback;
  3167. }
  3168. };
  3169. // Plugin namespace
  3170. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3171. // The object to store plugin information
  3172. AdapterJS.WebRTCPlugin.pluginInfo = {
  3173. prefix : 'Tem',
  3174. plugName : 'TemWebRTCPlugin',
  3175. pluginId : 'plugin0',
  3176. type : 'application/x-temwebrtcplugin',
  3177. onload : '__TemWebRTCReady0',
  3178. portalLink : 'http://skylink.io/plugin/',
  3179. downloadLink : null, //set below
  3180. companyName: 'Temasys'
  3181. };
  3182. if(!!navigator.platform.match(/^Mac/i)) {
  3183. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3184. }
  3185. else if(!!navigator.platform.match(/^Win/i)) {
  3186. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3187. }
  3188. AdapterJS.WebRTCPlugin.TAGS = {
  3189. NONE : 'none',
  3190. AUDIO : 'audio',
  3191. VIDEO : 'video'
  3192. };
  3193. // Unique identifier of each opened page
  3194. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3195. // Use this whenever you want to call the plugin.
  3196. AdapterJS.WebRTCPlugin.plugin = null;
  3197. // Set log level for the plugin once it is ready.
  3198. // The different values are
  3199. // This is an asynchronous function that will run when the plugin is ready
  3200. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3201. // Defines webrtc's JS interface according to the plugin's implementation.
  3202. // Define plugin Browsers as WebRTC Interface.
  3203. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3204. // This function detects whether or not a plugin is installed.
  3205. // Checks if Not IE (firefox, for example), else if it's IE,
  3206. // we're running IE and do something. If not it is not supported.
  3207. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3208. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3209. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3210. // Inject the HTML DOM object element into the page.
  3211. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3212. // States of readiness that the plugin goes through when
  3213. // being injected and stated
  3214. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3215. NONE : 0, // no plugin use
  3216. INITIALIZING : 1, // Detected need for plugin
  3217. INJECTING : 2, // Injecting plugin
  3218. INJECTED: 3, // Plugin element injected but not usable yet
  3219. READY: 4 // Plugin ready to be used
  3220. };
  3221. // Current state of the plugin. You cannot use the plugin before this is
  3222. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3223. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3224. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3225. // Used to make sure AdapterJS.onwebrtcready is only called once
  3226. AdapterJS.onwebrtcreadyDone = false;
  3227. // Log levels for the plugin.
  3228. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3229. /*
  3230. Log outputs are prefixed in some cases.
  3231. INFO: Information reported by the plugin.
  3232. ERROR: Errors originating from within the plugin.
  3233. WEBRTC: Error originating from within the libWebRTC library
  3234. */
  3235. // From the least verbose to the most verbose
  3236. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3237. NONE : 'NONE',
  3238. ERROR : 'ERROR',
  3239. WARNING : 'WARNING',
  3240. INFO: 'INFO',
  3241. VERBOSE: 'VERBOSE',
  3242. SENSITIVE: 'SENSITIVE'
  3243. };
  3244. // Does a waiting check before proceeding to load the plugin.
  3245. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3246. // This methid will use an interval to wait for the plugin to be ready.
  3247. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3248. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3249. // This function will be called when plugin is ready. It sends necessary
  3250. // details to the plugin.
  3251. // The function will wait for the document to be ready and the set the
  3252. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3253. // indicating that it can start being requested.
  3254. // This function is not in the IE/Safari condition brackets so that
  3255. // TemPluginLoaded function might be called on Chrome/Firefox.
  3256. // This function is the only private function that is not encapsulated to
  3257. // allow the plugin method to be called.
  3258. __TemWebRTCReady0 = function () {
  3259. if (document.readyState === 'complete') {
  3260. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3261. AdapterJS.maybeThroughWebRTCReady();
  3262. } else {
  3263. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3264. if (document.readyState === 'complete') {
  3265. // TODO: update comments, we wait for the document to be ready
  3266. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3267. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3268. AdapterJS.maybeThroughWebRTCReady();
  3269. }
  3270. }, 100);
  3271. }
  3272. };
  3273. AdapterJS.maybeThroughWebRTCReady = function() {
  3274. if (!AdapterJS.onwebrtcreadyDone) {
  3275. AdapterJS.onwebrtcreadyDone = true;
  3276. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3277. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3278. }
  3279. }
  3280. };
  3281. // Text namespace
  3282. AdapterJS.TEXT = {
  3283. PLUGIN: {
  3284. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3285. 'to work on this browser.',
  3286. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3287. BUTTON: 'Install Now'
  3288. },
  3289. REFRESH: {
  3290. REQUIRE_REFRESH: 'Please refresh page',
  3291. BUTTON: 'Refresh Page'
  3292. }
  3293. };
  3294. // The result of ice connection states.
  3295. // - starting: Ice connection is starting.
  3296. // - checking: Ice connection is checking.
  3297. // - connected Ice connection is connected.
  3298. // - completed Ice connection is connected.
  3299. // - done Ice connection has been completed.
  3300. // - disconnected Ice connection has been disconnected.
  3301. // - failed Ice connection has failed.
  3302. // - closed Ice connection is closed.
  3303. AdapterJS._iceConnectionStates = {
  3304. starting : 'starting',
  3305. checking : 'checking',
  3306. connected : 'connected',
  3307. completed : 'connected',
  3308. done : 'completed',
  3309. disconnected : 'disconnected',
  3310. failed : 'failed',
  3311. closed : 'closed'
  3312. };
  3313. //The IceConnection states that has been fired for each peer.
  3314. AdapterJS._iceConnectionFiredStates = [];
  3315. // Check if WebRTC Interface is defined.
  3316. AdapterJS.isDefined = null;
  3317. // This function helps to retrieve the webrtc detected browser information.
  3318. // This sets:
  3319. // - webrtcDetectedBrowser: The browser agent name.
  3320. // - webrtcDetectedVersion: The browser version.
  3321. // - webrtcDetectedType: The types of webRTC support.
  3322. // - 'moz': Mozilla implementation of webRTC.
  3323. // - 'webkit': WebKit implementation of webRTC.
  3324. // - 'plugin': Using the plugin implementation.
  3325. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3326. var hasMatch, checkMatch = navigator.userAgent.match(
  3327. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3328. if (/trident/i.test(checkMatch[1])) {
  3329. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3330. webrtcDetectedBrowser = 'IE';
  3331. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3332. } else if (checkMatch[1] === 'Chrome') {
  3333. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3334. if (hasMatch !== null) {
  3335. webrtcDetectedBrowser = 'opera';
  3336. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3337. }
  3338. }
  3339. if (navigator.userAgent.indexOf('Safari')) {
  3340. if (typeof InstallTrigger !== 'undefined') {
  3341. webrtcDetectedBrowser = 'firefox';
  3342. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3343. webrtcDetectedBrowser = 'IE';
  3344. } else if (
  3345. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3346. webrtcDetectedBrowser = 'safari';
  3347. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3348. webrtcDetectedBrowser = 'opera';
  3349. } else if (!!window.chrome) {
  3350. webrtcDetectedBrowser = 'chrome';
  3351. }
  3352. }
  3353. if (!webrtcDetectedBrowser) {
  3354. webrtcDetectedVersion = checkMatch[1];
  3355. }
  3356. if (!webrtcDetectedVersion) {
  3357. try {
  3358. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3359. [navigator.appName, navigator.appVersion, '-?'];
  3360. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3361. checkMatch.splice(1, 1, hasMatch[1]);
  3362. }
  3363. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3364. } catch (error) { }
  3365. }
  3366. };
  3367. // To fix configuration as some browsers does not support
  3368. // the 'urls' attribute.
  3369. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3370. if (pcConfig === null) {
  3371. return;
  3372. }
  3373. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3374. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3375. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3376. delete pcConfig.iceServers[i].urls;
  3377. }
  3378. }
  3379. };
  3380. AdapterJS.addEvent = function(elem, evnt, func) {
  3381. if (elem.addEventListener) { // W3C DOM
  3382. elem.addEventListener(evnt, func, false);
  3383. } else if (elem.attachEvent) {// OLD IE DOM
  3384. elem.attachEvent('on'+evnt, func);
  3385. } else { // No much to do
  3386. elem[evnt] = func;
  3387. }
  3388. };
  3389. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3390. // only inject once the page is ready
  3391. if (document.readyState !== 'complete') {
  3392. return;
  3393. }
  3394. var w = window;
  3395. var i = document.createElement('iframe');
  3396. i.style.position = 'fixed';
  3397. i.style.top = '-41px';
  3398. i.style.left = 0;
  3399. i.style.right = 0;
  3400. i.style.width = '100%';
  3401. i.style.height = '40px';
  3402. i.style.backgroundColor = '#ffffe1';
  3403. i.style.border = 'none';
  3404. i.style.borderBottom = '1px solid #888888';
  3405. i.style.zIndex = '9999999';
  3406. if(typeof i.style.webkitTransition === 'string') {
  3407. i.style.webkitTransition = 'all .5s ease-out';
  3408. } else if(typeof i.style.transition === 'string') {
  3409. i.style.transition = 'all .5s ease-out';
  3410. }
  3411. document.body.appendChild(i);
  3412. c = (i.contentWindow) ? i.contentWindow :
  3413. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3414. c.document.open();
  3415. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3416. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3417. 'middle; cursor: default;">' + text + '</span>');
  3418. if(buttonText && buttonLink) {
  3419. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3420. c.document.close();
  3421. // On click on okay
  3422. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3423. if (!!displayRefreshBar) {
  3424. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3425. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3426. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3427. }
  3428. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3429. e.preventDefault();
  3430. try {
  3431. event.cancelBubble = true;
  3432. } catch(error) { }
  3433. var pluginInstallInterval = setInterval(function(){
  3434. if(! isIE) {
  3435. navigator.plugins.refresh(false);
  3436. }
  3437. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3438. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3439. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3440. function() { // plugin now installed
  3441. clearInterval(pluginInstallInterval);
  3442. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3443. },
  3444. function() {
  3445. // still no plugin detected, nothing to do
  3446. });
  3447. } , 500);
  3448. });
  3449. // On click on Cancel
  3450. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3451. w.document.body.removeChild(i);
  3452. });
  3453. } else {
  3454. c.document.close();
  3455. }
  3456. setTimeout(function() {
  3457. if(typeof i.style.webkitTransform === 'string') {
  3458. i.style.webkitTransform = 'translateY(40px)';
  3459. } else if(typeof i.style.transform === 'string') {
  3460. i.style.transform = 'translateY(40px)';
  3461. } else {
  3462. i.style.top = '0px';
  3463. }
  3464. }, 300);
  3465. };
  3466. // -----------------------------------------------------------
  3467. // Detected webrtc implementation. Types are:
  3468. // - 'moz': Mozilla implementation of webRTC.
  3469. // - 'webkit': WebKit implementation of webRTC.
  3470. // - 'plugin': Using the plugin implementation.
  3471. webrtcDetectedType = null;
  3472. // Detected webrtc datachannel support. Types are:
  3473. // - 'SCTP': SCTP datachannel support.
  3474. // - 'RTP': RTP datachannel support.
  3475. webrtcDetectedDCSupport = null;
  3476. // Set the settings for creating DataChannels, MediaStream for
  3477. // Cross-browser compability.
  3478. // - This is only for SCTP based support browsers.
  3479. // the 'urls' attribute.
  3480. checkMediaDataChannelSettings =
  3481. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3482. if (typeof callback !== 'function') {
  3483. return;
  3484. }
  3485. var beOfferer = true;
  3486. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3487. // Nightly version does not require MozDontOfferDataChannel for interop
  3488. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3489. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3490. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3491. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3492. // Resends an updated version of constraints for MozDataChannel to work
  3493. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3494. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3495. try {
  3496. delete constraints.mandatory.MozDontOfferDataChannel;
  3497. } catch (error) {
  3498. console.error('Failed deleting MozDontOfferDataChannel');
  3499. console.error(error);
  3500. }
  3501. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3502. constraints.mandatory.MozDontOfferDataChannel = true;
  3503. }
  3504. if (!isLocalFirefox) {
  3505. // temporary measure to remove Moz* constraints in non Firefox browsers
  3506. for (var prop in constraints.mandatory) {
  3507. if (constraints.mandatory.hasOwnProperty(prop)) {
  3508. if (prop.indexOf('Moz') !== -1) {
  3509. delete constraints.mandatory[prop];
  3510. }
  3511. }
  3512. }
  3513. }
  3514. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3515. // interopability of the media stream
  3516. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3517. beOfferer = false;
  3518. }
  3519. callback(beOfferer, constraints);
  3520. };
  3521. // Handles the differences for all browsers ice connection state output.
  3522. // - Tested outcomes are:
  3523. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3524. // - Chrome (answerer) : 'checking' > 'connected'
  3525. // - Firefox (offerer) : 'checking' > 'connected'
  3526. // - Firefox (answerer): 'checking' > 'connected'
  3527. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3528. if (typeof callback !== 'function') {
  3529. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3530. return;
  3531. }
  3532. peerId = (peerId) ? peerId : 'peer';
  3533. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3534. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3535. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3536. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3537. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3538. }
  3539. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3540. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3541. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3542. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3543. setTimeout(function () {
  3544. AdapterJS._iceConnectionFiredStates[peerId]
  3545. .push(AdapterJS._iceConnectionStates.done);
  3546. callback(AdapterJS._iceConnectionStates.done);
  3547. }, 1000);
  3548. }
  3549. callback(iceConnectionState);
  3550. }
  3551. return;
  3552. };
  3553. // Firefox:
  3554. // - Creates iceServer from the url for Firefox.
  3555. // - Create iceServer with stun url.
  3556. // - Create iceServer with turn url.
  3557. // - Ignore the transport parameter from TURN url for FF version <=27.
  3558. // - Return null for createIceServer if transport=tcp.
  3559. // - FF 27 and above supports transport parameters in TURN url,
  3560. // - So passing in the full url to create iceServer.
  3561. // Chrome:
  3562. // - Creates iceServer from the url for Chrome M33 and earlier.
  3563. // - Create iceServer with stun url.
  3564. // - Chrome M28 & above uses below TURN format.
  3565. // Plugin:
  3566. // - Creates Ice Server for Plugin Browsers
  3567. // - If Stun - Create iceServer with stun url.
  3568. // - Else - Create iceServer with turn url
  3569. // - This is a WebRTC Function
  3570. createIceServer = null;
  3571. // Firefox:
  3572. // - Creates IceServers for Firefox
  3573. // - Use .url for FireFox.
  3574. // - Multiple Urls support
  3575. // Chrome:
  3576. // - Creates iceServers from the urls for Chrome M34 and above.
  3577. // - .urls is supported since Chrome M34.
  3578. // - Multiple Urls support
  3579. // Plugin:
  3580. // - Creates Ice Servers for Plugin Browsers
  3581. // - Multiple Urls support
  3582. // - This is a WebRTC Function
  3583. createIceServers = null;
  3584. //------------------------------------------------------------
  3585. //The RTCPeerConnection object.
  3586. RTCPeerConnection = null;
  3587. // Creates RTCSessionDescription object for Plugin Browsers
  3588. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3589. RTCSessionDescription : null;
  3590. // Creates RTCIceCandidate object for Plugin Browsers
  3591. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3592. RTCIceCandidate : null;
  3593. // Get UserMedia (only difference is the prefix).
  3594. // Code from Adam Barth.
  3595. getUserMedia = null;
  3596. // Attach a media stream to an element.
  3597. attachMediaStream = null;
  3598. // Re-attach a media stream to an element.
  3599. reattachMediaStream = null;
  3600. // Detected browser agent name. Types are:
  3601. // - 'firefox': Firefox browser.
  3602. // - 'chrome': Chrome browser.
  3603. // - 'opera': Opera browser.
  3604. // - 'safari': Safari browser.
  3605. // - 'IE' - Internet Explorer browser.
  3606. webrtcDetectedBrowser = null;
  3607. // Detected browser version.
  3608. webrtcDetectedVersion = null;
  3609. // Check for browser types and react accordingly
  3610. if (navigator.mozGetUserMedia) {
  3611. webrtcDetectedBrowser = 'firefox';
  3612. webrtcDetectedVersion = parseInt(navigator
  3613. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3614. webrtcDetectedType = 'moz';
  3615. webrtcDetectedDCSupport = 'SCTP';
  3616. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3617. AdapterJS.maybeFixConfiguration(pcConfig);
  3618. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3619. };
  3620. // The RTCSessionDescription object.
  3621. RTCSessionDescription = mozRTCSessionDescription;
  3622. window.RTCSessionDescription = RTCSessionDescription;
  3623. // The RTCIceCandidate object.
  3624. RTCIceCandidate = mozRTCIceCandidate;
  3625. window.RTCIceCandidate = RTCIceCandidate;
  3626. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3627. navigator.getUserMedia = window.getUserMedia;
  3628. // Shim for MediaStreamTrack.getSources.
  3629. MediaStreamTrack.getSources = function(successCb) {
  3630. setTimeout(function() {
  3631. var infos = [
  3632. { kind: 'audio', id: 'default', label:'', facing:'' },
  3633. { kind: 'video', id: 'default', label:'', facing:'' }
  3634. ];
  3635. successCb(infos);
  3636. }, 0);
  3637. };
  3638. createIceServer = function (url, username, password) {
  3639. var iceServer = null;
  3640. var url_parts = url.split(':');
  3641. if (url_parts[0].indexOf('stun') === 0) {
  3642. iceServer = { url : url };
  3643. } else if (url_parts[0].indexOf('turn') === 0) {
  3644. if (webrtcDetectedVersion < 27) {
  3645. var turn_url_parts = url.split('?');
  3646. if (turn_url_parts.length === 1 ||
  3647. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3648. iceServer = {
  3649. url : turn_url_parts[0],
  3650. credential : password,
  3651. username : username
  3652. };
  3653. }
  3654. } else {
  3655. iceServer = {
  3656. url : url,
  3657. credential : password,
  3658. username : username
  3659. };
  3660. }
  3661. }
  3662. return iceServer;
  3663. };
  3664. createIceServers = function (urls, username, password) {
  3665. var iceServers = [];
  3666. for (var i = 0; i < urls.length; i++) {
  3667. var iceServer = createIceServer(urls[i], username, password);
  3668. if (iceServer !== null) {
  3669. iceServers.push(iceServer);
  3670. }
  3671. }
  3672. return iceServers;
  3673. };
  3674. attachMediaStream = function (element, stream) {
  3675. element.mozSrcObject = stream;
  3676. if (stream !== null)
  3677. element.play();
  3678. return element;
  3679. };
  3680. reattachMediaStream = function (to, from) {
  3681. to.mozSrcObject = from.mozSrcObject;
  3682. to.play();
  3683. return to;
  3684. };
  3685. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3686. if (!callback) {
  3687. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3688. ': 1 argument required, but only 0 present.');
  3689. }
  3690. return callback([]);
  3691. };
  3692. // Fake get{Video,Audio}Tracks
  3693. if (!MediaStream.prototype.getVideoTracks) {
  3694. MediaStream.prototype.getVideoTracks = function () {
  3695. return [];
  3696. };
  3697. }
  3698. if (!MediaStream.prototype.getAudioTracks) {
  3699. MediaStream.prototype.getAudioTracks = function () {
  3700. return [];
  3701. };
  3702. }
  3703. AdapterJS.maybeThroughWebRTCReady();
  3704. } else if (navigator.webkitGetUserMedia) {
  3705. webrtcDetectedBrowser = 'chrome';
  3706. webrtcDetectedType = 'webkit';
  3707. webrtcDetectedVersion = parseInt(navigator
  3708. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3709. // check if browser is opera 20+
  3710. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3711. if (checkIfOpera !== null) {
  3712. webrtcDetectedBrowser = 'opera';
  3713. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3714. }
  3715. // check browser datachannel support
  3716. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3717. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3718. webrtcDetectedDCSupport = 'SCTP';
  3719. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3720. webrtcDetectedVersion > 24) {
  3721. webrtcDetectedDCSupport = 'RTP';
  3722. } else {
  3723. webrtcDetectedDCSupport = '';
  3724. }
  3725. createIceServer = function (url, username, password) {
  3726. var iceServer = null;
  3727. var url_parts = url.split(':');
  3728. if (url_parts[0].indexOf('stun') === 0) {
  3729. iceServer = { 'url' : url };
  3730. } else if (url_parts[0].indexOf('turn') === 0) {
  3731. iceServer = {
  3732. 'url' : url,
  3733. 'credential' : password,
  3734. 'username' : username
  3735. };
  3736. }
  3737. return iceServer;
  3738. };
  3739. createIceServers = function (urls, username, password) {
  3740. var iceServers = [];
  3741. if (webrtcDetectedVersion >= 34) {
  3742. iceServers = {
  3743. 'urls' : urls,
  3744. 'credential' : password,
  3745. 'username' : username
  3746. };
  3747. } else {
  3748. for (var i = 0; i < urls.length; i++) {
  3749. var iceServer = createIceServer(urls[i], username, password);
  3750. if (iceServer !== null) {
  3751. iceServers.push(iceServer);
  3752. }
  3753. }
  3754. }
  3755. return iceServers;
  3756. };
  3757. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3758. if (webrtcDetectedVersion < 34) {
  3759. AdapterJS.maybeFixConfiguration(pcConfig);
  3760. }
  3761. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3762. };
  3763. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3764. navigator.getUserMedia = window.getUserMedia;
  3765. attachMediaStream = function (element, stream) {
  3766. if (typeof element.srcObject !== 'undefined') {
  3767. element.srcObject = stream;
  3768. } else if (typeof element.mozSrcObject !== 'undefined') {
  3769. element.mozSrcObject = stream;
  3770. } else if (typeof element.src !== 'undefined') {
  3771. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3772. } else {
  3773. console.log('Error attaching stream to element.');
  3774. }
  3775. return element;
  3776. };
  3777. reattachMediaStream = function (to, from) {
  3778. to.src = from.src;
  3779. return to;
  3780. };
  3781. AdapterJS.maybeThroughWebRTCReady();
  3782. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3783. /Edge\/(\d+).(\d+)$/)) {
  3784. webrtcDetectedBrowser = 'edge';
  3785. webrtcDetectedVersion =
  3786. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3787. // the minimum version still supported by adapter.
  3788. webrtcMinimumVersion = 12;
  3789. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3790. attachMediaStream = function(element, stream) {
  3791. element.srcObject = stream;
  3792. return element;
  3793. };
  3794. reattachMediaStream = function(to, from) {
  3795. to.srcObject = from.srcObject;
  3796. return to;
  3797. };
  3798. AdapterJS.maybeThroughWebRTCReady();
  3799. } else { // TRY TO USE PLUGIN
  3800. // IE 9 is not offering an implementation of console.log until you open a console
  3801. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3802. /* jshint -W020 */
  3803. console = {} || console;
  3804. // Implemented based on console specs from MDN
  3805. // You may override these functions
  3806. console.log = function (arg) {};
  3807. console.info = function (arg) {};
  3808. console.error = function (arg) {};
  3809. console.dir = function (arg) {};
  3810. console.exception = function (arg) {};
  3811. console.trace = function (arg) {};
  3812. console.warn = function (arg) {};
  3813. console.count = function (arg) {};
  3814. console.debug = function (arg) {};
  3815. console.count = function (arg) {};
  3816. console.time = function (arg) {};
  3817. console.timeEnd = function (arg) {};
  3818. console.group = function (arg) {};
  3819. console.groupCollapsed = function (arg) {};
  3820. console.groupEnd = function (arg) {};
  3821. /* jshint +W020 */
  3822. }
  3823. webrtcDetectedType = 'plugin';
  3824. webrtcDetectedDCSupport = 'plugin';
  3825. AdapterJS.parseWebrtcDetectedBrowser();
  3826. isIE = webrtcDetectedBrowser === 'IE';
  3827. /* jshint -W035 */
  3828. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3829. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3830. /* empty because it needs to prevent the function from running. */
  3831. }
  3832. };
  3833. /* jshint +W035 */
  3834. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3835. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3836. // Call immediately if possible
  3837. // Once the plugin is set, the code will always take this path
  3838. callback();
  3839. } else {
  3840. // otherwise start a 100ms interval
  3841. var checkPluginReadyState = setInterval(function () {
  3842. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3843. clearInterval(checkPluginReadyState);
  3844. callback();
  3845. }
  3846. }, 100);
  3847. }
  3848. };
  3849. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3850. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3851. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3852. });
  3853. };
  3854. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3855. // only inject once the page is ready
  3856. if (document.readyState !== 'complete') {
  3857. return;
  3858. }
  3859. // Prevent multiple injections
  3860. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3861. return;
  3862. }
  3863. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3864. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3865. var frag = document.createDocumentFragment();
  3866. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3867. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3868. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3869. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3870. '<param name="pluginId" value="' +
  3871. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3872. '<param name="windowless" value="false" /> ' +
  3873. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3874. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3875. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3876. // uncomment to be able to use virtual cams
  3877. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3878. '</object>';
  3879. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3880. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3881. }
  3882. document.body.appendChild(frag);
  3883. // Need to re-fetch the plugin
  3884. AdapterJS.WebRTCPlugin.plugin =
  3885. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3886. } else {
  3887. // Load Plugin
  3888. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3889. AdapterJS.WebRTCPlugin.plugin.id =
  3890. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3891. // IE will only start the plugin if it's ACTUALLY visible
  3892. if (isIE) {
  3893. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3894. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3895. } else { // The size of the plugin on Safari should be 0x0px
  3896. // so that the autorisation prompt is at the top
  3897. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3898. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3899. }
  3900. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3901. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3902. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3903. '<param name="pluginId" value="' +
  3904. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3905. '<param name="windowless" value="false" /> ' +
  3906. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3907. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3908. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3909. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3910. }
  3911. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3912. };
  3913. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3914. function (comName, plugName, installedCb, notInstalledCb) {
  3915. if (!isIE) {
  3916. var pluginArray = navigator.plugins;
  3917. for (var i = 0; i < pluginArray.length; i++) {
  3918. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3919. installedCb();
  3920. return;
  3921. }
  3922. }
  3923. notInstalledCb();
  3924. } else {
  3925. try {
  3926. var axo = new ActiveXObject(comName + '.' + plugName);
  3927. } catch (e) {
  3928. notInstalledCb();
  3929. return;
  3930. }
  3931. installedCb();
  3932. }
  3933. };
  3934. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3935. if (AdapterJS.WebRTCPlugin.pluginState ===
  3936. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3937. console.error("AdapterJS - WebRTC interface has already been defined");
  3938. return;
  3939. }
  3940. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3941. AdapterJS.isDefined = function (variable) {
  3942. return variable !== null && variable !== undefined;
  3943. };
  3944. createIceServer = function (url, username, password) {
  3945. var iceServer = null;
  3946. var url_parts = url.split(':');
  3947. if (url_parts[0].indexOf('stun') === 0) {
  3948. iceServer = {
  3949. 'url' : url,
  3950. 'hasCredentials' : false
  3951. };
  3952. } else if (url_parts[0].indexOf('turn') === 0) {
  3953. iceServer = {
  3954. 'url' : url,
  3955. 'hasCredentials' : true,
  3956. 'credential' : password,
  3957. 'username' : username
  3958. };
  3959. }
  3960. return iceServer;
  3961. };
  3962. createIceServers = function (urls, username, password) {
  3963. var iceServers = [];
  3964. for (var i = 0; i < urls.length; ++i) {
  3965. iceServers.push(createIceServer(urls[i], username, password));
  3966. }
  3967. return iceServers;
  3968. };
  3969. RTCSessionDescription = function (info) {
  3970. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3971. return AdapterJS.WebRTCPlugin.plugin.
  3972. ConstructSessionDescription(info.type, info.sdp);
  3973. };
  3974. RTCPeerConnection = function (servers, constraints) {
  3975. var iceServers = null;
  3976. if (servers) {
  3977. iceServers = servers.iceServers;
  3978. for (var i = 0; i < iceServers.length; i++) {
  3979. if (iceServers[i].urls && !iceServers[i].url) {
  3980. iceServers[i].url = iceServers[i].urls;
  3981. }
  3982. iceServers[i].hasCredentials = AdapterJS.
  3983. isDefined(iceServers[i].username) &&
  3984. AdapterJS.isDefined(iceServers[i].credential);
  3985. }
  3986. }
  3987. var mandatory = (constraints && constraints.mandatory) ?
  3988. constraints.mandatory : null;
  3989. var optional = (constraints && constraints.optional) ?
  3990. constraints.optional : null;
  3991. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3992. return AdapterJS.WebRTCPlugin.plugin.
  3993. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3994. iceServers, mandatory, optional);
  3995. };
  3996. MediaStreamTrack = {};
  3997. MediaStreamTrack.getSources = function (callback) {
  3998. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3999. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4000. });
  4001. };
  4002. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4003. constraints.audio = constraints.audio || false;
  4004. constraints.video = constraints.video || false;
  4005. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4006. AdapterJS.WebRTCPlugin.plugin.
  4007. getUserMedia(constraints, successCallback, failureCallback);
  4008. });
  4009. };
  4010. window.navigator.getUserMedia = window.getUserMedia;
  4011. attachMediaStream = function (element, stream) {
  4012. if (!element || !element.parentNode) {
  4013. return;
  4014. }
  4015. var streamId;
  4016. if (stream === null) {
  4017. streamId = '';
  4018. } else {
  4019. if (typeof stream.enableSoundTracks !== 'undefined') {
  4020. stream.enableSoundTracks(true);
  4021. }
  4022. streamId = stream.id;
  4023. }
  4024. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4025. var nodeName = element.nodeName.toLowerCase();
  4026. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4027. var tag;
  4028. switch(nodeName) {
  4029. case 'audio':
  4030. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4031. break;
  4032. case 'video':
  4033. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4034. break;
  4035. default:
  4036. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4037. }
  4038. var frag = document.createDocumentFragment();
  4039. var temp = document.createElement('div');
  4040. var classHTML = '';
  4041. if (element.className) {
  4042. classHTML = 'class="' + element.className + '" ';
  4043. } else if (element.attributes && element.attributes['class']) {
  4044. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4045. }
  4046. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4047. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4048. '<param name="pluginId" value="' + elementId + '" /> ' +
  4049. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4050. '<param name="windowless" value="true" /> ' +
  4051. '<param name="streamId" value="' + streamId + '" /> ' +
  4052. '<param name="tag" value="' + tag + '" /> ' +
  4053. '</object>';
  4054. while (temp.firstChild) {
  4055. frag.appendChild(temp.firstChild);
  4056. }
  4057. var height = '';
  4058. var width = '';
  4059. if (element.clientWidth || element.clientHeight) {
  4060. width = element.clientWidth;
  4061. height = element.clientHeight;
  4062. }
  4063. else if (element.width || element.height) {
  4064. width = element.width;
  4065. height = element.height;
  4066. }
  4067. element.parentNode.insertBefore(frag, element);
  4068. frag = document.getElementById(elementId);
  4069. frag.width = width;
  4070. frag.height = height;
  4071. element.parentNode.removeChild(element);
  4072. } else { // already an <object> tag, just change the stream id
  4073. var children = element.children;
  4074. for (var i = 0; i !== children.length; ++i) {
  4075. if (children[i].name === 'streamId') {
  4076. children[i].value = streamId;
  4077. break;
  4078. }
  4079. }
  4080. element.setStreamId(streamId);
  4081. }
  4082. var newElement = document.getElementById(elementId);
  4083. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4084. return newElement;
  4085. };
  4086. reattachMediaStream = function (to, from) {
  4087. var stream = null;
  4088. var children = from.children;
  4089. for (var i = 0; i !== children.length; ++i) {
  4090. if (children[i].name === 'streamId') {
  4091. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4092. stream = AdapterJS.WebRTCPlugin.plugin
  4093. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4094. break;
  4095. }
  4096. }
  4097. if (stream !== null) {
  4098. return attachMediaStream(to, stream);
  4099. } else {
  4100. console.log('Could not find the stream associated with this element');
  4101. }
  4102. };
  4103. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4104. properties = Object.getOwnPropertyNames( prototype );
  4105. for(prop in properties) {
  4106. propName = properties[prop];
  4107. if (typeof(propName.slice) === 'function') {
  4108. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4109. if (isIE) {
  4110. destElem.attachEvent(propName,srcElem[propName]);
  4111. } else {
  4112. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4113. }
  4114. } else {
  4115. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4116. }
  4117. }
  4118. }
  4119. var subPrototype = Object.getPrototypeOf(prototype)
  4120. if(subPrototype != null) {
  4121. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4122. }
  4123. }
  4124. RTCIceCandidate = function (candidate) {
  4125. if (!candidate.sdpMid) {
  4126. candidate.sdpMid = '';
  4127. }
  4128. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4129. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4130. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4131. );
  4132. };
  4133. // inject plugin
  4134. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4135. AdapterJS.WebRTCPlugin.injectPlugin();
  4136. };
  4137. // This function will be called if the plugin is needed (browser different
  4138. // from Chrome or Firefox), but the plugin is not installed.
  4139. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4140. function() {
  4141. AdapterJS.addEvent(document,
  4142. 'readystatechange',
  4143. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4144. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4145. };
  4146. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4147. if (AdapterJS.options.hidePluginInstallPrompt) {
  4148. return;
  4149. }
  4150. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4151. if(downloadLink) { // if download link
  4152. var popupString;
  4153. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4154. popupString = 'This website requires you to install the ' +
  4155. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4156. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4157. ' WebRTC Plugin</a>' +
  4158. ' to work on this browser.';
  4159. } else { // no portal link, just print a generic explanation
  4160. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4161. }
  4162. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4163. } else { // no download link, just print a generic explanation
  4164. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4165. }
  4166. };
  4167. // Try to detect the plugin and act accordingly
  4168. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4169. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4170. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4171. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4172. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4173. }
  4174. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4175. },{"jitsi-meet-logger":47}],21:[function(require,module,exports){
  4176. (function (__filename){
  4177. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4178. function supportsLocalStorage() {
  4179. try {
  4180. return 'localStorage' in window && window.localStorage !== null;
  4181. } catch (e) {
  4182. logger.log("localstorage is not supported");
  4183. return false;
  4184. }
  4185. }
  4186. function generateUniqueId() {
  4187. function _p8() {
  4188. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4189. }
  4190. return _p8() + _p8() + _p8() + _p8();
  4191. }
  4192. function Settings(conferenceID) {
  4193. this.email = '';
  4194. this.displayName = '';
  4195. this.userId;
  4196. this.language = null;
  4197. this.confSettings = null;
  4198. this.conferenceID = conferenceID;
  4199. if (supportsLocalStorage()) {
  4200. if(!window.localStorage.getItem(conferenceID))
  4201. this.confSettings = {};
  4202. else
  4203. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4204. if(!this.confSettings.jitsiMeetId) {
  4205. this.confSettings.jitsiMeetId = generateUniqueId();
  4206. logger.log("generated id",
  4207. this.confSettings.jitsiMeetId);
  4208. this.save();
  4209. }
  4210. this.userId = this.confSettings.jitsiMeetId || '';
  4211. this.email = this.confSettings.email || '';
  4212. this.displayName = this.confSettings.displayname || '';
  4213. this.language = this.confSettings.language;
  4214. } else {
  4215. logger.log("local storage is not supported");
  4216. this.userId = generateUniqueId();
  4217. }
  4218. }
  4219. Settings.prototype.save = function () {
  4220. if(!supportsLocalStorage())
  4221. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4222. }
  4223. Settings.prototype.setDisplayName = function (newDisplayName) {
  4224. this.displayName = newDisplayName;
  4225. if(this.confSettings != null)
  4226. this.confSettings.displayname = displayName;
  4227. this.save();
  4228. return this.displayName;
  4229. },
  4230. Settings.prototype.setEmail = function (newEmail) {
  4231. this.email = newEmail;
  4232. if(this.confSettings != null)
  4233. this.confSettings.email = newEmail;
  4234. this.save();
  4235. return this.email;
  4236. },
  4237. Settings.prototype.getSettings = function () {
  4238. return {
  4239. email: this.email,
  4240. displayName: this.displayName,
  4241. uid: this.userId,
  4242. language: this.language
  4243. };
  4244. },
  4245. Settings.prototype.setLanguage = function (lang) {
  4246. this.language = lang;
  4247. if(this.confSettings != null)
  4248. this.confSettings.language = lang;
  4249. this.save();
  4250. }
  4251. module.exports = Settings;
  4252. }).call(this,"/modules/settings/Settings.js")
  4253. },{"jitsi-meet-logger":47}],22:[function(require,module,exports){
  4254. /* global config */
  4255. /**
  4256. * Provides statistics for the local stream.
  4257. */
  4258. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4259. /**
  4260. * Size of the webaudio analyzer buffer.
  4261. * @type {number}
  4262. */
  4263. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4264. /**
  4265. * Value of the webaudio analyzer smoothing time parameter.
  4266. * @type {number}
  4267. */
  4268. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4269. /**
  4270. * Converts time domain data array to audio level.
  4271. * @param samples the time domain data array.
  4272. * @returns {number} the audio level
  4273. */
  4274. function timeDomainDataToAudioLevel(samples) {
  4275. var maxVolume = 0;
  4276. var length = samples.length;
  4277. for (var i = 0; i < length; i++) {
  4278. if (maxVolume < samples[i])
  4279. maxVolume = samples[i];
  4280. }
  4281. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4282. }
  4283. /**
  4284. * Animates audio level change
  4285. * @param newLevel the new audio level
  4286. * @param lastLevel the last audio level
  4287. * @returns {Number} the audio level to be set
  4288. */
  4289. function animateLevel(newLevel, lastLevel) {
  4290. var value = 0;
  4291. var diff = lastLevel - newLevel;
  4292. if(diff > 0.2) {
  4293. value = lastLevel - 0.2;
  4294. }
  4295. else if(diff < -0.4) {
  4296. value = lastLevel + 0.4;
  4297. }
  4298. else {
  4299. value = newLevel;
  4300. }
  4301. return parseFloat(value.toFixed(3));
  4302. }
  4303. /**
  4304. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4305. *
  4306. * @param stream the local stream
  4307. * @param interval stats refresh interval given in ms.
  4308. * @param callback function that receives the audio levels.
  4309. * @constructor
  4310. */
  4311. function LocalStatsCollector(stream, interval, callback) {
  4312. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4313. this.stream = stream;
  4314. this.intervalId = null;
  4315. this.intervalMilis = interval;
  4316. this.audioLevel = 0;
  4317. this.callback = callback;
  4318. }
  4319. /**
  4320. * Starts the collecting the statistics.
  4321. */
  4322. LocalStatsCollector.prototype.start = function () {
  4323. if (!window.AudioContext ||
  4324. RTCBrowserType.isTemasysPluginUsed())
  4325. return;
  4326. var context = new AudioContext();
  4327. var analyser = context.createAnalyser();
  4328. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4329. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4330. var source = context.createMediaStreamSource(this.stream);
  4331. source.connect(analyser);
  4332. var self = this;
  4333. this.intervalId = setInterval(
  4334. function () {
  4335. var array = new Uint8Array(analyser.frequencyBinCount);
  4336. analyser.getByteTimeDomainData(array);
  4337. var audioLevel = timeDomainDataToAudioLevel(array);
  4338. if (audioLevel != self.audioLevel) {
  4339. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4340. self.callback(self.audioLevel);
  4341. }
  4342. },
  4343. this.intervalMilis
  4344. );
  4345. };
  4346. /**
  4347. * Stops collecting the statistics.
  4348. */
  4349. LocalStatsCollector.prototype.stop = function () {
  4350. if (this.intervalId) {
  4351. clearInterval(this.intervalId);
  4352. this.intervalId = null;
  4353. }
  4354. };
  4355. module.exports = LocalStatsCollector;
  4356. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4357. (function (__filename){
  4358. /* global require, ssrc2jid */
  4359. /* jshint -W117 */
  4360. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4361. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4362. var StatisticsEvents = require("../../service/statistics/Events");
  4363. /* Whether we support the browser we are running into for logging statistics */
  4364. var browserSupported = RTCBrowserType.isChrome() ||
  4365. RTCBrowserType.isOpera();
  4366. var keyMap = {};
  4367. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4368. "ssrc": "ssrc",
  4369. "packetsReceived": "packetsReceived",
  4370. "packetsLost": "packetsLost",
  4371. "packetsSent": "packetsSent",
  4372. "bytesReceived": "bytesReceived",
  4373. "bytesSent": "bytesSent"
  4374. };
  4375. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4376. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4377. "sendBandwidth": "googAvailableSendBandwidth",
  4378. "remoteAddress": "googRemoteAddress",
  4379. "transportType": "googTransportType",
  4380. "localAddress": "googLocalAddress",
  4381. "activeConnection": "googActiveConnection",
  4382. "ssrc": "ssrc",
  4383. "packetsReceived": "packetsReceived",
  4384. "packetsSent": "packetsSent",
  4385. "packetsLost": "packetsLost",
  4386. "bytesReceived": "bytesReceived",
  4387. "bytesSent": "bytesSent",
  4388. "googFrameHeightReceived": "googFrameHeightReceived",
  4389. "googFrameWidthReceived": "googFrameWidthReceived",
  4390. "googFrameHeightSent": "googFrameHeightSent",
  4391. "googFrameWidthSent": "googFrameWidthSent",
  4392. "audioInputLevel": "audioInputLevel",
  4393. "audioOutputLevel": "audioOutputLevel"
  4394. };
  4395. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4396. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4397. /**
  4398. * Calculates packet lost percent using the number of lost packets and the
  4399. * number of all packet.
  4400. * @param lostPackets the number of lost packets
  4401. * @param totalPackets the number of all packets.
  4402. * @returns {number} packet loss percent
  4403. */
  4404. function calculatePacketLoss(lostPackets, totalPackets) {
  4405. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4406. return 0;
  4407. return Math.round((lostPackets/totalPackets)*100);
  4408. }
  4409. function getStatValue(item, name) {
  4410. var browserType = RTCBrowserType.getBrowserType();
  4411. if (!keyMap[browserType][name])
  4412. throw "The property isn't supported!";
  4413. var key = keyMap[browserType][name];
  4414. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4415. item.stat(key) : item[key];
  4416. }
  4417. function formatAudioLevel(audioLevel) {
  4418. return Math.min(Math.max(audioLevel, 0), 1);
  4419. }
  4420. /**
  4421. * Checks whether a certain record should be included in the logged statistics.
  4422. */
  4423. function acceptStat(reportId, reportType, statName) {
  4424. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4425. return false;
  4426. if (reportType == "ssrc") {
  4427. if (statName == "googTrackId" ||
  4428. statName == "transportId" ||
  4429. statName == "ssrc")
  4430. return false;
  4431. }
  4432. return true;
  4433. }
  4434. /**
  4435. * Checks whether a certain record should be included in the logged statistics.
  4436. */
  4437. function acceptReport(id, type) {
  4438. if (id.substring(0, 15) == "googCertificate" ||
  4439. id.substring(0, 9) == "googTrack" ||
  4440. id.substring(0, 20) == "googLibjingleSession")
  4441. return false;
  4442. if (type == "googComponent")
  4443. return false;
  4444. return true;
  4445. }
  4446. /**
  4447. * Peer statistics data holder.
  4448. * @constructor
  4449. */
  4450. function PeerStats()
  4451. {
  4452. this.ssrc2Loss = {};
  4453. this.ssrc2AudioLevel = {};
  4454. this.ssrc2bitrate = {};
  4455. this.ssrc2resolution = {};
  4456. }
  4457. /**
  4458. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4459. * represented by this instance.
  4460. * @param lossRate new packet loss rate value to be set.
  4461. */
  4462. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4463. {
  4464. this.ssrc2Loss = lossRate;
  4465. };
  4466. /**
  4467. * Sets resolution that belong to the ssrc
  4468. * represented by this instance.
  4469. * @param resolution new resolution value to be set.
  4470. */
  4471. PeerStats.prototype.setSsrcResolution = function (resolution)
  4472. {
  4473. if(resolution === null && this.ssrc2resolution[ssrc])
  4474. {
  4475. delete this.ssrc2resolution[ssrc];
  4476. }
  4477. else if(resolution !== null)
  4478. this.ssrc2resolution[ssrc] = resolution;
  4479. };
  4480. /**
  4481. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4482. * represented by this instance.
  4483. * @param ssrc audio or video RTP stream SSRC.
  4484. * @param bitrate new bitrate value to be set.
  4485. */
  4486. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4487. {
  4488. if(this.ssrc2bitrate[ssrc])
  4489. {
  4490. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4491. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4492. }
  4493. else {
  4494. this.ssrc2bitrate[ssrc] = bitrate;
  4495. }
  4496. };
  4497. /**
  4498. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4499. * the stream which belongs to the peer represented by this instance.
  4500. * @param ssrc RTP stream SSRC for which current audio level value will be
  4501. * updated.
  4502. * @param audioLevel the new audio level value to be set. Value is truncated to
  4503. * fit the range from 0 to 1.
  4504. */
  4505. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4506. {
  4507. // Range limit 0 - 1
  4508. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4509. };
  4510. function ConferenceStats() {
  4511. /**
  4512. * The bandwidth
  4513. * @type {{}}
  4514. */
  4515. this.bandwidth = {};
  4516. /**
  4517. * The bit rate
  4518. * @type {{}}
  4519. */
  4520. this.bitrate = {};
  4521. /**
  4522. * The packet loss rate
  4523. * @type {{}}
  4524. */
  4525. this.packetLoss = null;
  4526. /**
  4527. * Array with the transport information.
  4528. * @type {Array}
  4529. */
  4530. this.transport = [];
  4531. }
  4532. /**
  4533. * <tt>StatsCollector</tt> registers for stats updates of given
  4534. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4535. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4536. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4537. * instance as an event source.
  4538. *
  4539. * @param peerconnection webRTC peer connection object.
  4540. * @param interval stats refresh interval given in ms.
  4541. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4542. * called on stats update.
  4543. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4544. * @constructor
  4545. */
  4546. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4547. {
  4548. this.peerconnection = peerconnection;
  4549. this.baselineAudioLevelsReport = null;
  4550. this.currentAudioLevelsReport = null;
  4551. this.currentStatsReport = null;
  4552. this.baselineStatsReport = null;
  4553. this.audioLevelsIntervalId = null;
  4554. this.eventEmitter = eventEmitter;
  4555. this.config = config || {};
  4556. this.conferenceStats = new ConferenceStats();
  4557. /**
  4558. * Gather PeerConnection stats once every this many milliseconds.
  4559. */
  4560. this.GATHER_INTERVAL = 15000;
  4561. /**
  4562. * Log stats via the focus once every this many milliseconds.
  4563. */
  4564. this.LOG_INTERVAL = 60000;
  4565. /**
  4566. * Gather stats and store them in this.statsToBeLogged.
  4567. */
  4568. this.gatherStatsIntervalId = null;
  4569. /**
  4570. * Send the stats already saved in this.statsToBeLogged to be logged via
  4571. * the focus.
  4572. */
  4573. this.logStatsIntervalId = null;
  4574. /**
  4575. * Stores the statistics which will be send to the focus to be logged.
  4576. */
  4577. this.statsToBeLogged =
  4578. {
  4579. timestamps: [],
  4580. stats: {}
  4581. };
  4582. // Updates stats interval
  4583. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4584. this.statsIntervalId = null;
  4585. this.statsIntervalMilis = statsInterval;
  4586. // Map of ssrcs to PeerStats
  4587. this.ssrc2stats = {};
  4588. }
  4589. module.exports = StatsCollector;
  4590. /**
  4591. * Stops stats updates.
  4592. */
  4593. StatsCollector.prototype.stop = function () {
  4594. if (this.audioLevelsIntervalId) {
  4595. clearInterval(this.audioLevelsIntervalId);
  4596. this.audioLevelsIntervalId = null;
  4597. }
  4598. if (this.statsIntervalId)
  4599. {
  4600. clearInterval(this.statsIntervalId);
  4601. this.statsIntervalId = null;
  4602. }
  4603. if(this.logStatsIntervalId)
  4604. {
  4605. clearInterval(this.logStatsIntervalId);
  4606. this.logStatsIntervalId = null;
  4607. }
  4608. if(this.gatherStatsIntervalId)
  4609. {
  4610. clearInterval(this.gatherStatsIntervalId);
  4611. this.gatherStatsIntervalId = null;
  4612. }
  4613. };
  4614. /**
  4615. * Callback passed to <tt>getStats</tt> method.
  4616. * @param error an error that occurred on <tt>getStats</tt> call.
  4617. */
  4618. StatsCollector.prototype.errorCallback = function (error)
  4619. {
  4620. logger.error("Get stats error", error);
  4621. this.stop();
  4622. };
  4623. /**
  4624. * Starts stats updates.
  4625. */
  4626. StatsCollector.prototype.start = function ()
  4627. {
  4628. var self = this;
  4629. this.audioLevelsIntervalId = setInterval(
  4630. function () {
  4631. // Interval updates
  4632. self.peerconnection.getStats(
  4633. function (report) {
  4634. var results = null;
  4635. if (!report || !report.result ||
  4636. typeof report.result != 'function') {
  4637. results = report;
  4638. }
  4639. else {
  4640. results = report.result();
  4641. }
  4642. //logger.error("Got interval report", results);
  4643. self.currentAudioLevelsReport = results;
  4644. self.processAudioLevelReport();
  4645. self.baselineAudioLevelsReport =
  4646. self.currentAudioLevelsReport;
  4647. },
  4648. self.errorCallback
  4649. );
  4650. },
  4651. self.audioLevelsIntervalMilis
  4652. );
  4653. // if (!this.config.disableStats && browserSupported) {
  4654. // this.statsIntervalId = setInterval(
  4655. // function () {
  4656. // // Interval updates
  4657. // self.peerconnection.getStats(
  4658. // function (report) {
  4659. // var results = null;
  4660. // if (!report || !report.result ||
  4661. // typeof report.result != 'function') {
  4662. // //firefox
  4663. // results = report;
  4664. // }
  4665. // else {
  4666. // //chrome
  4667. // results = report.result();
  4668. // }
  4669. // //logger.error("Got interval report", results);
  4670. // self.currentStatsReport = results;
  4671. // try {
  4672. // self.processStatsReport();
  4673. // }
  4674. // catch (e) {
  4675. // logger.error("Unsupported key:" + e, e);
  4676. // }
  4677. //
  4678. // self.baselineStatsReport = self.currentStatsReport;
  4679. // },
  4680. // self.errorCallback
  4681. // );
  4682. // },
  4683. // self.statsIntervalMilis
  4684. // );
  4685. // }
  4686. //
  4687. // if (this.config.logStats && browserSupported) {
  4688. // this.gatherStatsIntervalId = setInterval(
  4689. // function () {
  4690. // self.peerconnection.getStats(
  4691. // function (report) {
  4692. // self.addStatsToBeLogged(report.result());
  4693. // },
  4694. // function () {
  4695. // }
  4696. // );
  4697. // },
  4698. // this.GATHER_INTERVAL
  4699. // );
  4700. //
  4701. // this.logStatsIntervalId = setInterval(
  4702. // function() { self.logStats(); },
  4703. // this.LOG_INTERVAL);
  4704. // }
  4705. };
  4706. /**
  4707. * Converts the stats to the format used for logging, and saves the data in
  4708. * this.statsToBeLogged.
  4709. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4710. */
  4711. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4712. var self = this;
  4713. var num_records = this.statsToBeLogged.timestamps.length;
  4714. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4715. reports.map(function (report) {
  4716. if (!acceptReport(report.id, report.type))
  4717. return;
  4718. var stat = self.statsToBeLogged.stats[report.id];
  4719. if (!stat) {
  4720. stat = self.statsToBeLogged.stats[report.id] = {};
  4721. }
  4722. stat.type = report.type;
  4723. report.names().map(function (name) {
  4724. if (!acceptStat(report.id, report.type, name))
  4725. return;
  4726. var values = stat[name];
  4727. if (!values) {
  4728. values = stat[name] = [];
  4729. }
  4730. while (values.length < num_records) {
  4731. values.push(null);
  4732. }
  4733. values.push(report.stat(name));
  4734. });
  4735. });
  4736. };
  4737. //FIXME:
  4738. //StatsCollector.prototype.logStats = function () {
  4739. //
  4740. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4741. // return;
  4742. // // Reset the stats
  4743. // this.statsToBeLogged.stats = {};
  4744. // this.statsToBeLogged.timestamps = [];
  4745. //};
  4746. /**
  4747. * Stats processing logic.
  4748. */
  4749. StatsCollector.prototype.processStatsReport = function () {
  4750. if (!this.baselineStatsReport) {
  4751. return;
  4752. }
  4753. for (var idx in this.currentStatsReport) {
  4754. var now = this.currentStatsReport[idx];
  4755. try {
  4756. if (getStatValue(now, 'receiveBandwidth') ||
  4757. getStatValue(now, 'sendBandwidth')) {
  4758. this.conferenceStats.bandwidth = {
  4759. "download": Math.round(
  4760. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4761. "upload": Math.round(
  4762. (getStatValue(now, 'sendBandwidth')) / 1000)
  4763. };
  4764. }
  4765. }
  4766. catch(e){/*not supported*/}
  4767. if(now.type == 'googCandidatePair')
  4768. {
  4769. var ip, type, localIP, active;
  4770. try {
  4771. ip = getStatValue(now, 'remoteAddress');
  4772. type = getStatValue(now, "transportType");
  4773. localIP = getStatValue(now, "localAddress");
  4774. active = getStatValue(now, "activeConnection");
  4775. }
  4776. catch(e){/*not supported*/}
  4777. if(!ip || !type || !localIP || active != "true")
  4778. continue;
  4779. var addressSaved = false;
  4780. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4781. {
  4782. if(this.conferenceStats.transport[i].ip == ip &&
  4783. this.conferenceStats.transport[i].type == type &&
  4784. this.conferenceStats.transport[i].localip == localIP)
  4785. {
  4786. addressSaved = true;
  4787. }
  4788. }
  4789. if(addressSaved)
  4790. continue;
  4791. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4792. continue;
  4793. }
  4794. if(now.type == "candidatepair")
  4795. {
  4796. if(now.state == "succeeded")
  4797. continue;
  4798. var local = this.currentStatsReport[now.localCandidateId];
  4799. var remote = this.currentStatsReport[now.remoteCandidateId];
  4800. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4801. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4802. }
  4803. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4804. now.type != "inboundrtp") {
  4805. continue;
  4806. }
  4807. var before = this.baselineStatsReport[idx];
  4808. if (!before) {
  4809. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4810. continue;
  4811. }
  4812. var ssrc = getStatValue(now, 'ssrc');
  4813. if(!ssrc)
  4814. continue;
  4815. var ssrcStats = this.ssrc2stats[ssrc];
  4816. if (!ssrcStats) {
  4817. ssrcStats = new PeerStats();
  4818. this.ssrc2stats[ssrc] = ssrcStats;
  4819. }
  4820. var isDownloadStream = true;
  4821. var key = 'packetsReceived';
  4822. var packetsNow = getStatValue(now, key);
  4823. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4824. isDownloadStream = false;
  4825. key = 'packetsSent';
  4826. packetsNow = getStatValue(now, key);
  4827. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4828. console.warn("No packetsReceived nor packetsSent stat found");
  4829. continue;
  4830. }
  4831. }
  4832. if (!packetsNow || packetsNow < 0)
  4833. packetsNow = 0;
  4834. var packetsBefore = getStatValue(before, key);
  4835. if (!packetsBefore || packetsBefore < 0)
  4836. packetsBefore = 0;
  4837. var packetRate = packetsNow - packetsBefore;
  4838. if (!packetRate || packetRate < 0)
  4839. packetRate = 0;
  4840. var currentLoss = getStatValue(now, 'packetsLost');
  4841. if (!currentLoss || currentLoss < 0)
  4842. currentLoss = 0;
  4843. var previousLoss = getStatValue(before, 'packetsLost');
  4844. if (!previousLoss || previousLoss < 0)
  4845. previousLoss = 0;
  4846. var lossRate = currentLoss - previousLoss;
  4847. if (!lossRate || lossRate < 0)
  4848. lossRate = 0;
  4849. var packetsTotal = (packetRate + lossRate);
  4850. ssrcStats.setSsrcLoss(ssrc,
  4851. {"packetsTotal": packetsTotal,
  4852. "packetsLost": lossRate,
  4853. "isDownloadStream": isDownloadStream});
  4854. var bytesReceived = 0, bytesSent = 0;
  4855. if(getStatValue(now, "bytesReceived")) {
  4856. bytesReceived = getStatValue(now, "bytesReceived") -
  4857. getStatValue(before, "bytesReceived");
  4858. }
  4859. if (getStatValue(now, "bytesSent")) {
  4860. bytesSent = getStatValue(now, "bytesSent") -
  4861. getStatValue(before, "bytesSent");
  4862. }
  4863. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4864. if (bytesReceived <= 0 || time <= 0) {
  4865. bytesReceived = 0;
  4866. } else {
  4867. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4868. }
  4869. if (bytesSent <= 0 || time <= 0) {
  4870. bytesSent = 0;
  4871. } else {
  4872. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4873. }
  4874. ssrcStats.setSsrcBitrate(ssrc, {
  4875. "download": bytesReceived,
  4876. "upload": bytesSent});
  4877. var resolution = {height: null, width: null};
  4878. try {
  4879. if (getStatValue(now, "googFrameHeightReceived") &&
  4880. getStatValue(now, "googFrameWidthReceived")) {
  4881. resolution.height =
  4882. getStatValue(now, "googFrameHeightReceived");
  4883. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4884. }
  4885. else if (getStatValue(now, "googFrameHeightSent") &&
  4886. getStatValue(now, "googFrameWidthSent")) {
  4887. resolution.height = getStatValue(now, "googFrameHeightSent");
  4888. resolution.width = getStatValue(now, "googFrameWidthSent");
  4889. }
  4890. }
  4891. catch(e){/*not supported*/}
  4892. if (resolution.height && resolution.width) {
  4893. ssrcStats.setSsrcResolution(ssrc, resolution);
  4894. } else {
  4895. ssrcStats.setSsrcResolution(ssrc, null);
  4896. }
  4897. }
  4898. var self = this;
  4899. // Jid stats
  4900. var totalPackets = {download: 0, upload: 0};
  4901. var lostPackets = {download: 0, upload: 0};
  4902. var bitrateDownload = 0;
  4903. var bitrateUpload = 0;
  4904. var resolutions = {};
  4905. Object.keys(this.ssrc2stats).forEach(
  4906. function (jid) {
  4907. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4908. function (ssrc) {
  4909. var type = "upload";
  4910. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4911. type = "download";
  4912. totalPackets[type] +=
  4913. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4914. lostPackets[type] +=
  4915. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4916. }
  4917. );
  4918. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4919. function (ssrc) {
  4920. bitrateDownload +=
  4921. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4922. bitrateUpload +=
  4923. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4924. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4925. }
  4926. );
  4927. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4928. }
  4929. );
  4930. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4931. this.conferenceStats.packetLoss = {
  4932. total:
  4933. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4934. totalPackets.download + totalPackets.upload),
  4935. download:
  4936. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4937. upload:
  4938. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4939. };
  4940. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  4941. {
  4942. "bitrate": this.conferenceStats.bitrate,
  4943. "packetLoss": this.conferenceStats.packetLoss,
  4944. "bandwidth": this.conferenceStats.bandwidth,
  4945. "resolution": resolutions,
  4946. "transport": this.conferenceStats.transport
  4947. });
  4948. this.conferenceStats.transport = [];
  4949. };
  4950. /**
  4951. * Stats processing logic.
  4952. */
  4953. StatsCollector.prototype.processAudioLevelReport = function () {
  4954. if (!this.baselineAudioLevelsReport) {
  4955. return;
  4956. }
  4957. for (var idx in this.currentAudioLevelsReport) {
  4958. var now = this.currentAudioLevelsReport[idx];
  4959. //if we don't have "packetsReceived" this is local stream
  4960. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4961. continue;
  4962. }
  4963. var before = this.baselineAudioLevelsReport[idx];
  4964. if (!before) {
  4965. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4966. continue;
  4967. }
  4968. var ssrc = getStatValue(now, 'ssrc');
  4969. if (!ssrc) {
  4970. if((Date.now() - now.timestamp) < 3000)
  4971. logger.warn("No ssrc: ");
  4972. continue;
  4973. }
  4974. var ssrcStats = this.ssrc2stats[ssrc];
  4975. if (!ssrcStats) {
  4976. ssrcStats = new PeerStats();
  4977. this.ssrc2stats[ssrc] = ssrcStats;
  4978. }
  4979. // Audio level
  4980. var audioLevel = null;
  4981. try {
  4982. audioLevel = getStatValue(now, 'audioInputLevel');
  4983. if (!audioLevel)
  4984. audioLevel = getStatValue(now, 'audioOutputLevel');
  4985. }
  4986. catch(e) {/*not supported*/
  4987. logger.warn("Audio Levels are not available in the statistics.");
  4988. clearInterval(this.audioLevelsIntervalId);
  4989. return;
  4990. }
  4991. if (audioLevel) {
  4992. // TODO: can't find specs about what this value really is,
  4993. // but it seems to vary between 0 and around 32k.
  4994. audioLevel = audioLevel / 32767;
  4995. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4996. this.eventEmitter.emit(
  4997. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  4998. }
  4999. }
  5000. };
  5001. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5002. },{"../../service/statistics/Events":83,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],24:[function(require,module,exports){
  5003. /* global require, APP */
  5004. var LocalStats = require("./LocalStatsCollector.js");
  5005. var RTPStats = require("./RTPStatsCollector.js");
  5006. var EventEmitter = require("events");
  5007. var StatisticsEvents = require("../../service/statistics/Events");
  5008. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  5009. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5010. //var CallStats = require("./CallStats");
  5011. //var RTCEvents = require("../../service/RTC/RTCEvents");
  5012. //
  5013. //function onDisposeConference(onUnload) {
  5014. // CallStats.sendTerminateEvent();
  5015. // stopRemote();
  5016. // if(onUnload) {
  5017. // stopLocal();
  5018. // eventEmitter.removeAllListeners();
  5019. // }
  5020. //}
  5021. var eventEmitter = new EventEmitter();
  5022. function Statistics() {
  5023. this.rtpStats = null;
  5024. this.eventEmitter = new EventEmitter();
  5025. }
  5026. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5027. if (this.rtpStats) {
  5028. this.rtpStats.stop();
  5029. }
  5030. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5031. this.rtpStats.start();
  5032. }
  5033. Statistics.localStats = [];
  5034. Statistics.startLocalStats = function (stream, callback) {
  5035. var localStats = new LocalStats(stream, 200, callback);
  5036. this.localStats.push(localStats);
  5037. localStats.start();
  5038. }
  5039. Statistics.prototype.addAudioLevelListener = function(listener)
  5040. {
  5041. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5042. }
  5043. Statistics.prototype.removeAudioLevelListener = function(listener)
  5044. {
  5045. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5046. }
  5047. Statistics.prototype.dispose = function () {
  5048. Statistics.stopAllLocalStats();
  5049. this.stopRemote();
  5050. if(this.eventEmitter)
  5051. this.eventEmitter.removeAllListeners();
  5052. if(eventEmitter)
  5053. eventEmitter.removeAllListeners();
  5054. }
  5055. Statistics.stopAllLocalStats = function () {
  5056. for(var i = 0; i < this.localStats.length; i++)
  5057. this.localStats[i].stop();
  5058. this.localStats = [];
  5059. }
  5060. Statistics.stopLocalStats = function (stream) {
  5061. for(var i = 0; i < Statistics.localStats.length; i++)
  5062. if(Statistics.localStats[i].stream === stream){
  5063. var localStats = Statistics.localStats.splice(i, 1);
  5064. localStats.stop();
  5065. break;
  5066. }
  5067. }
  5068. Statistics.prototype.stopRemote = function () {
  5069. if (this.rtpStats) {
  5070. this.rtpStats.stop();
  5071. this.eventEmitter.emit(StatisticsEvents.STOP);
  5072. this.rtpStats = null;
  5073. }
  5074. };
  5075. /**
  5076. * Obtains audio level reported in the stats for specified peer.
  5077. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5078. * audio level.
  5079. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5080. * level.
  5081. * @returns {*} a float form 0 to 1 that represents current audio level or
  5082. * <tt>null</tt> if for any reason the value is not available
  5083. * at this time.
  5084. */
  5085. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5086. var peerStats = this.rtpStats.jid2stats[peerJid];
  5087. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5088. };
  5089. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5090. //
  5091. //var statistics = {
  5092. // /**
  5093. // * Indicates that this audio level is for local jid.
  5094. // * @type {string}
  5095. // */
  5096. // LOCAL_JID: 'local',
  5097. //
  5098. // addConnectionStatsListener: function(listener)
  5099. // {
  5100. // eventEmitter.on("statistics.connectionstats", listener);
  5101. // },
  5102. //
  5103. // removeConnectionStatsListener: function(listener)
  5104. // {
  5105. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5106. // },
  5107. //
  5108. //
  5109. // addRemoteStatsStopListener: function(listener)
  5110. // {
  5111. // eventEmitter.on("statistics.stop", listener);
  5112. // },
  5113. //
  5114. // removeRemoteStatsStopListener: function(listener)
  5115. // {
  5116. // eventEmitter.removeListener("statistics.stop", listener);
  5117. // },
  5118. //
  5119. //
  5120. // stopRemoteStatistics: function()
  5121. // {
  5122. // stopRemote();
  5123. // },
  5124. //
  5125. //// Already implemented with the constructor
  5126. // start: function () {
  5127. // APP.RTC.addStreamListener(onStreamCreated,
  5128. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5129. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5130. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5131. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5132. // startRemoteStats(event.peerconnection);
  5133. //// CallStats.init(event);
  5134. // });
  5135. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5136. //// CallStats.init(session);
  5137. //// });
  5138. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5139. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5140. //// CallStats.sendMuteEvent(mute, "audio");
  5141. //// });
  5142. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5143. //// CallStats.sendSetupFailedEvent();
  5144. //// });
  5145. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5146. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5147. //// CallStats.sendMuteEvent(mute, "video");
  5148. //// });
  5149. // }
  5150. //};
  5151. module.exports = Statistics;
  5152. },{"../../service/statistics/Events":83,"../../service/statistics/constants":84,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":43}],25:[function(require,module,exports){
  5153. /**
  5154. /**
  5155. * @const
  5156. */
  5157. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5158. /**
  5159. * Hexadecimal digits.
  5160. * @const
  5161. */
  5162. var HEX_DIGITS = '0123456789abcdef';
  5163. /**
  5164. * Generates random int within the range [min, max]
  5165. * @param min the minimum value for the generated number
  5166. * @param max the maximum value for the generated number
  5167. * @returns random int number
  5168. */
  5169. function randomInt(min, max) {
  5170. return Math.floor(Math.random() * (max - min + 1)) + min;
  5171. }
  5172. /**
  5173. * Get random element from array or string.
  5174. * @param {Array|string} arr source
  5175. * @returns array element or string character
  5176. */
  5177. function randomElement(arr) {
  5178. return arr[randomInt(0, arr.length - 1)];
  5179. }
  5180. /**
  5181. * Generate random alphanumeric string.
  5182. * @param {number} length expected string length
  5183. * @returns {string} random string of specified length
  5184. */
  5185. function randomAlphanumStr(length) {
  5186. var result = '';
  5187. for (var i = 0; i < length; i += 1) {
  5188. result += randomElement(ALPHANUM);
  5189. }
  5190. return result;
  5191. }
  5192. /**
  5193. * Exported interface.
  5194. */
  5195. var RandomUtil = {
  5196. /**
  5197. * Returns a random hex digit.
  5198. * @returns {*}
  5199. */
  5200. randomHexDigit: function() {
  5201. return randomElement(HEX_DIGITS);
  5202. },
  5203. /**
  5204. * Returns a random string of hex digits with length 'len'.
  5205. * @param len the length.
  5206. */
  5207. randomHexString: function (len) {
  5208. var ret = '';
  5209. while (len--) {
  5210. ret += this.randomHexDigit();
  5211. }
  5212. return ret;
  5213. },
  5214. randomElement: randomElement,
  5215. randomAlphanumStr: randomAlphanumStr
  5216. };
  5217. module.exports = RandomUtil;
  5218. },{}],26:[function(require,module,exports){
  5219. (function (__filename){
  5220. /* global Strophe, $, $pres, $iq, $msg */
  5221. /* jshint -W101,-W069 */
  5222. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5223. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5224. var Moderator = require("./moderator");
  5225. var EventEmitter = require("events");
  5226. var parser = {
  5227. packet2JSON: function (packet, nodes) {
  5228. var self = this;
  5229. $(packet).children().each(function (index) {
  5230. var tagName = $(this).prop("tagName");
  5231. var node = {
  5232. tagName: tagName
  5233. };
  5234. node.attributes = {};
  5235. $($(this)[0].attributes).each(function( index, attr ) {
  5236. node.attributes[ attr.name ] = attr.value;
  5237. });
  5238. var text = Strophe.getText($(this)[0]);
  5239. if (text) {
  5240. node.value = text;
  5241. }
  5242. node.children = [];
  5243. nodes.push(node);
  5244. self.packet2JSON($(this), node.children);
  5245. });
  5246. },
  5247. JSON2packet: function (nodes, packet) {
  5248. for(var i = 0; i < nodes.length; i++) {
  5249. var node = nodes[i];
  5250. if(!node || node === null){
  5251. continue;
  5252. }
  5253. packet.c(node.tagName, node.attributes);
  5254. if(node.value)
  5255. packet.t(node.value);
  5256. if(node.children)
  5257. this.JSON2packet(node.children, packet);
  5258. packet.up();
  5259. }
  5260. // packet.up();
  5261. }
  5262. };
  5263. /**
  5264. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5265. * @param pres the presence JSON
  5266. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5267. */
  5268. function filterNodeFromPresenceJSON(pres, nodeName){
  5269. var res = [];
  5270. for(var i = 0; i < pres.length; i++)
  5271. if(pres[i].tagName === nodeName)
  5272. res.push(pres[i]);
  5273. return res;
  5274. }
  5275. function ChatRoom(connection, jid, password, XMPP, options) {
  5276. this.eventEmitter = new EventEmitter();
  5277. this.xmpp = XMPP;
  5278. this.connection = connection;
  5279. this.roomjid = Strophe.getBareJidFromJid(jid);
  5280. this.myroomjid = jid;
  5281. this.password = password;
  5282. logger.info("Joined MUC as " + this.myroomjid);
  5283. this.members = {};
  5284. this.presMap = {};
  5285. this.presHandlers = {};
  5286. this.joined = false;
  5287. this.role = 'none';
  5288. this.focusMucJid = null;
  5289. this.bridgeIsDown = false;
  5290. this.options = options || {};
  5291. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5292. this.initPresenceMap();
  5293. this.session = null;
  5294. var self = this;
  5295. this.lastPresences = {};
  5296. }
  5297. ChatRoom.prototype.initPresenceMap = function () {
  5298. this.presMap['to'] = this.myroomjid;
  5299. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5300. this.presMap["nodes"] = [];
  5301. this.presMap["nodes"].push( {
  5302. "tagName": "user-agent",
  5303. "value": navigator.userAgent,
  5304. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5305. });
  5306. };
  5307. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5308. this.presMap["nodes"].push( {
  5309. "tagName": "devices",
  5310. "children": [
  5311. {
  5312. "tagName": "audio",
  5313. "value": devices.audio,
  5314. },
  5315. {
  5316. "tagName": "video",
  5317. "value": devices.video,
  5318. }
  5319. ]
  5320. });
  5321. };
  5322. ChatRoom.prototype.join = function (password, tokenPassword) {
  5323. if(password)
  5324. this.password = password;
  5325. var self = this;
  5326. this.moderator.allocateConferenceFocus(function()
  5327. {
  5328. self.sendPresence(tokenPassword);
  5329. }.bind(this));
  5330. };
  5331. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  5332. if (!this.presMap['to']) {
  5333. // Too early to send presence - not initialized
  5334. return;
  5335. }
  5336. var pres = $pres({to: this.presMap['to'] });
  5337. pres.c('x', {xmlns: this.presMap['xns']});
  5338. if (this.password) {
  5339. pres.c('password').t(this.password).up();
  5340. }
  5341. pres.up();
  5342. // Send XEP-0115 'c' stanza that contains our capabilities info
  5343. if (this.connection.caps) {
  5344. this.connection.caps.node = this.xmpp.options.clientNode;
  5345. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5346. }
  5347. if (tokenPassword) {
  5348. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  5349. .t(tokenPassword).up();
  5350. }
  5351. parser.JSON2packet(this.presMap.nodes, pres);
  5352. this.connection.send(pres);
  5353. };
  5354. ChatRoom.prototype.doLeave = function () {
  5355. logger.log("do leave", this.myroomjid);
  5356. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5357. this.presMap.length = 0;
  5358. this.connection.send(pres);
  5359. };
  5360. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5361. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5362. var getForm = $iq({type: 'get', to: this.roomjid})
  5363. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5364. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5365. var self = this;
  5366. this.connection.sendIQ(getForm, function (form) {
  5367. if (!$(form).find(
  5368. '>query>x[xmlns="jabber:x:data"]' +
  5369. '>field[var="muc#roomconfig_whois"]').length) {
  5370. logger.error('non-anonymous rooms not supported');
  5371. return;
  5372. }
  5373. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5374. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5375. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5376. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5377. .c('value')
  5378. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5379. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5380. .c('value').t('anyone').up().up();
  5381. self.connection.sendIQ(formSubmit);
  5382. }, function (error) {
  5383. logger.error("Error getting room configuration form");
  5384. });
  5385. };
  5386. ChatRoom.prototype.onPresence = function (pres) {
  5387. var from = pres.getAttribute('from');
  5388. // Parse roles.
  5389. var member = {};
  5390. member.show = $(pres).find('>show').text();
  5391. member.status = $(pres).find('>status').text();
  5392. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5393. member.affiliation = tmp.attr('affiliation');
  5394. member.role = tmp.attr('role');
  5395. // Focus recognition
  5396. member.jid = tmp.attr('jid');
  5397. member.isFocus = false;
  5398. if (member.jid
  5399. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5400. member.isFocus = true;
  5401. }
  5402. $(pres).find(">x").remove();
  5403. var nodes = [];
  5404. parser.packet2JSON(pres, nodes);
  5405. this.lastPresences[from] = nodes;
  5406. for(var i = 0; i < nodes.length; i++)
  5407. {
  5408. var node = nodes[i];
  5409. switch(node.tagName)
  5410. {
  5411. case "nick":
  5412. member.nick = node.value;
  5413. if(!member.isFocus) {
  5414. var displayName = !this.xmpp.options.displayJids
  5415. ? member.nick : Strophe.getResourceFromJid(from);
  5416. if (displayName && displayName.length > 0) {
  5417. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5418. }
  5419. logger.info("Display name: " + displayName, pres);
  5420. }
  5421. break;
  5422. case "userId":
  5423. member.id = node.value;
  5424. break;
  5425. case "email":
  5426. member.email = node.value;
  5427. break;
  5428. case "bridgeIsDown":
  5429. if(!this.bridgeIsDown) {
  5430. this.bridgeIsDown = true;
  5431. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5432. }
  5433. break;
  5434. default :
  5435. this.processNode(node, from);
  5436. }
  5437. }
  5438. if (from == this.myroomjid) {
  5439. if (member.affiliation == 'owner')
  5440. if (this.role !== member.role) {
  5441. this.role = member.role;
  5442. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5443. }
  5444. if (!this.joined) {
  5445. this.joined = true;
  5446. console.log("(TIME) MUC joined:\t", window.performance.now());
  5447. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5448. }
  5449. } else if (this.members[from] === undefined) {
  5450. // new participant
  5451. this.members[from] = member;
  5452. logger.log('entered', from, member);
  5453. if (member.isFocus) {
  5454. this.focusMucJid = from;
  5455. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5456. }
  5457. else {
  5458. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5459. }
  5460. } else {
  5461. // Presence update for existing participant
  5462. // Watch role change:
  5463. if (this.members[from].role != member.role) {
  5464. this.members[from].role = member.role;
  5465. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5466. }
  5467. // store the new display name
  5468. if(member.displayName)
  5469. this.members[from].displayName = member.displayName;
  5470. }
  5471. if(!member.isFocus)
  5472. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5473. // Trigger status message update
  5474. if (member.status) {
  5475. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5476. }
  5477. };
  5478. ChatRoom.prototype.processNode = function (node, from) {
  5479. if(this.presHandlers[node.tagName])
  5480. this.presHandlers[node.tagName](node, from);
  5481. };
  5482. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5483. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5484. msg.c('body', body).up();
  5485. if (nickname) {
  5486. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5487. }
  5488. this.connection.send(msg);
  5489. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5490. };
  5491. ChatRoom.prototype.setSubject = function (subject) {
  5492. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5493. msg.c('subject', subject);
  5494. this.connection.send(msg);
  5495. logger.log("topic changed to " + subject);
  5496. };
  5497. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5498. delete this.lastPresences[jid];
  5499. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5500. this.moderator.onMucMemberLeft(jid);
  5501. };
  5502. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5503. // room destroyed ?
  5504. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5505. '>destroy').length) {
  5506. var reason;
  5507. var reasonSelect = $(pres).find(
  5508. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5509. '>destroy>reason');
  5510. if (reasonSelect.length) {
  5511. reason = reasonSelect.text();
  5512. }
  5513. this.xmpp.disposeConference(false);
  5514. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5515. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5516. return true;
  5517. }
  5518. // Status code 110 indicates that this notification is "self-presence".
  5519. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5520. delete this.members[from];
  5521. this.onParticipantLeft(from);
  5522. }
  5523. // If the status code is 110 this means we're leaving and we would like
  5524. // to remove everyone else from our view, so we trigger the event.
  5525. else if (Object.keys(this.members).length > 1) {
  5526. for (var i in this.members) {
  5527. var member = this.members[i];
  5528. delete this.members[i];
  5529. this.onParticipantLeft(member);
  5530. }
  5531. }
  5532. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5533. if (this.myroomjid === from) {
  5534. this.xmpp.disposeConference(false);
  5535. this.eventEmitter.emit(XMPPEvents.KICKED);
  5536. }
  5537. }
  5538. };
  5539. ChatRoom.prototype.onMessage = function (msg, from) {
  5540. var nick =
  5541. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5542. .text() ||
  5543. Strophe.getResourceFromJid(from);
  5544. var txt = $(msg).find('>body').text();
  5545. var type = msg.getAttribute("type");
  5546. if (type == "error") {
  5547. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5548. $(msg).find('>text').text(), txt);
  5549. return true;
  5550. }
  5551. var subject = $(msg).find('>subject');
  5552. if (subject.length) {
  5553. var subjectText = subject.text();
  5554. if (subjectText || subjectText === "") {
  5555. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5556. logger.log("Subject is changed to " + subjectText);
  5557. }
  5558. }
  5559. // xep-0203 delay
  5560. var stamp = $(msg).find('>delay').attr('stamp');
  5561. if (!stamp) {
  5562. // or xep-0091 delay, UTC timestamp
  5563. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5564. if (stamp) {
  5565. // the format is CCYYMMDDThh:mm:ss
  5566. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5567. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5568. }
  5569. }
  5570. if (txt) {
  5571. logger.log('chat', nick, txt);
  5572. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5573. from, nick, txt, this.myroomjid, stamp);
  5574. }
  5575. };
  5576. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5577. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5578. logger.log('on password required', from);
  5579. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5580. } else if ($(pres).find(
  5581. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5582. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5583. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5584. // enter the room by replying with 'not-authorized'. This would
  5585. // result in reconnection from authorized domain.
  5586. // We're either missing Jicofo/Prosody config for anonymous
  5587. // domains or something is wrong.
  5588. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5589. } else {
  5590. logger.warn('onPresError ', pres);
  5591. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5592. }
  5593. } else {
  5594. logger.warn('onPresError ', pres);
  5595. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5596. }
  5597. };
  5598. ChatRoom.prototype.kick = function (jid) {
  5599. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5600. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5601. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5602. .c('reason').t('You have been kicked.').up().up().up();
  5603. this.connection.sendIQ(
  5604. kickIQ,
  5605. function (result) {
  5606. logger.log('Kick participant with jid: ', jid, result);
  5607. },
  5608. function (error) {
  5609. logger.log('Kick participant error: ', error);
  5610. });
  5611. };
  5612. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5613. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5614. var ob = this;
  5615. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5616. function (res) {
  5617. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5618. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5619. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5620. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5621. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5622. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5623. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5624. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5625. ob.connection.sendIQ(formsubmit,
  5626. onSuccess,
  5627. onError);
  5628. } else {
  5629. onNotSupported();
  5630. }
  5631. }, onError);
  5632. };
  5633. ChatRoom.prototype.addToPresence = function (key, values) {
  5634. values.tagName = key;
  5635. this.presMap["nodes"].push(values);
  5636. };
  5637. ChatRoom.prototype.removeFromPresence = function (key) {
  5638. for(var i = 0; i < this.presMap.nodes.length; i++)
  5639. {
  5640. if(key === this.presMap.nodes[i].tagName)
  5641. this.presMap.nodes.splice(i, 1);
  5642. }
  5643. };
  5644. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5645. this.presHandlers[name] = handler;
  5646. };
  5647. ChatRoom.prototype.removePresenceListener = function (name) {
  5648. delete this.presHandlers[name];
  5649. };
  5650. ChatRoom.prototype.isModerator = function () {
  5651. return this.role === 'moderator';
  5652. };
  5653. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5654. if (this.members[peerJid]) {
  5655. return this.members[peerJid].role;
  5656. }
  5657. return null;
  5658. };
  5659. ChatRoom.prototype.setJingleSession = function(session){
  5660. this.session = session;
  5661. this.session.room = this;
  5662. };
  5663. ChatRoom.prototype.removeStream = function (stream, callback) {
  5664. if(!this.session)
  5665. return;
  5666. this.session.removeStream(stream, callback);
  5667. };
  5668. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5669. if(this.session) {
  5670. // FIXME: will block switchInProgress on true value in case of exception
  5671. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5672. } else {
  5673. // We are done immediately
  5674. logger.warn("No conference handler or conference not started yet");
  5675. callback();
  5676. }
  5677. };
  5678. ChatRoom.prototype.addStream = function (stream, callback) {
  5679. if(this.session) {
  5680. // FIXME: will block switchInProgress on true value in case of exception
  5681. this.session.addStream(stream, callback);
  5682. } else {
  5683. // We are done immediately
  5684. logger.warn("No conference handler or conference not started yet");
  5685. callback();
  5686. }
  5687. };
  5688. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5689. var self = this;
  5690. var localCallback = function (mute) {
  5691. self.sendVideoInfoPresence(mute);
  5692. if(callback)
  5693. callback(mute);
  5694. };
  5695. if(this.session)
  5696. {
  5697. this.session.setVideoMute(
  5698. mute, localCallback, options);
  5699. }
  5700. else {
  5701. localCallback(mute);
  5702. }
  5703. };
  5704. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5705. //This will be for remote streams only
  5706. // if (this.forceMuted && !mute) {
  5707. // logger.info("Asking focus for unmute");
  5708. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5709. // // FIXME: wait for result before resetting muted status
  5710. // this.forceMuted = false;
  5711. // }
  5712. return this.sendAudioInfoPresence(mute, callback);
  5713. };
  5714. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5715. this.removeFromPresence("audiomuted");
  5716. this.addToPresence("audiomuted",
  5717. {attributes:
  5718. {"audions": "http://jitsi.org/jitmeet/audio"},
  5719. value: mute.toString()});
  5720. };
  5721. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5722. this.addAudioInfoToPresence(mute);
  5723. if(this.connection) {
  5724. this.sendPresence();
  5725. }
  5726. if(callback)
  5727. callback();
  5728. };
  5729. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5730. this.removeFromPresence("videomuted");
  5731. this.addToPresence("videomuted",
  5732. {attributes:
  5733. {"videons": "http://jitsi.org/jitmeet/video"},
  5734. value: mute.toString()});
  5735. };
  5736. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5737. this.addVideoInfoToPresence(mute);
  5738. if(!this.connection)
  5739. return;
  5740. this.sendPresence();
  5741. };
  5742. ChatRoom.prototype.addListener = function(type, listener) {
  5743. this.eventEmitter.on(type, listener);
  5744. };
  5745. ChatRoom.prototype.removeListener = function (type, listener) {
  5746. this.eventEmitter.removeListener(type, listener);
  5747. };
  5748. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5749. if(this.lastPresences[data.peerjid])
  5750. {
  5751. var pres = this.lastPresences[data.peerjid];
  5752. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5753. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5754. data.videomuted = ((videomuted.length > 0
  5755. && videomuted[0]
  5756. && videomuted[0]["value"] === "true")? true : false);
  5757. data.audiomuted = ((audiomuted.length > 0
  5758. && audiomuted[0]
  5759. && audiomuted[0]["value"] === "true")? true : false);
  5760. }
  5761. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5762. };
  5763. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5764. if (!this.session)
  5765. return null;
  5766. return this.session.getSsrcOwner(ssrc);
  5767. };
  5768. module.exports = ChatRoom;
  5769. }).call(this,"/modules/xmpp/ChatRoom.js")
  5770. },{"../../service/xmpp/XMPPEvents":85,"./moderator":34,"events":43,"jitsi-meet-logger":47}],27:[function(require,module,exports){
  5771. (function (__filename){
  5772. /*
  5773. * JingleSession provides an API to manage a single Jingle session. We will
  5774. * have different implementations depending on the underlying interface used
  5775. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5776. */
  5777. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5778. function JingleSession(me, sid, connection, service, eventEmitter) {
  5779. /**
  5780. * Our JID.
  5781. */
  5782. this.me = me;
  5783. /**
  5784. * The Jingle session identifier.
  5785. */
  5786. this.sid = sid;
  5787. /**
  5788. * The XMPP connection.
  5789. */
  5790. this.connection = connection;
  5791. /**
  5792. * The XMPP service.
  5793. */
  5794. this.service = service;
  5795. /**
  5796. * The event emitter.
  5797. */
  5798. this.eventEmitter = eventEmitter;
  5799. /**
  5800. * Whether to use dripping or not. Dripping is sending trickle candidates
  5801. * not one-by-one.
  5802. * Note: currently we do not support 'false'.
  5803. */
  5804. this.usedrip = true;
  5805. /**
  5806. * When dripping is used, stores ICE candidates which are to be sent.
  5807. */
  5808. this.drip_container = [];
  5809. // Media constraints. Is this WebRTC only?
  5810. this.media_constraints = null;
  5811. // ICE servers config (RTCConfiguration?).
  5812. this.ice_config = {};
  5813. // The chat room instance associated with the session.
  5814. this.room = null;
  5815. }
  5816. /**
  5817. * Prepares this object to initiate a session.
  5818. * @param peerjid the JID of the remote peer.
  5819. * @param isInitiator whether we will be the Jingle initiator.
  5820. * @param media_constraints
  5821. * @param ice_config
  5822. */
  5823. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5824. media_constraints, ice_config) {
  5825. this.media_constraints = media_constraints;
  5826. this.ice_config = ice_config;
  5827. if (this.state !== null) {
  5828. logger.error('attempt to initiate on session ' + this.sid +
  5829. 'in state ' + this.state);
  5830. return;
  5831. }
  5832. this.state = 'pending';
  5833. this.initiator = isInitiator ? this.me : peerjid;
  5834. this.responder = !isInitiator ? this.me : peerjid;
  5835. this.peerjid = peerjid;
  5836. this.doInitialize();
  5837. };
  5838. /**
  5839. * Finishes initialization.
  5840. */
  5841. JingleSession.prototype.doInitialize = function() {};
  5842. /**
  5843. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5844. * Note: currently only used on transport-info
  5845. */
  5846. JingleSession.prototype.addIceCandidates = function(contents) {};
  5847. /**
  5848. * Handles an 'add-source' event.
  5849. *
  5850. * @param contents an array of Jingle 'content' elements.
  5851. */
  5852. JingleSession.prototype.addSources = function(contents) {};
  5853. /**
  5854. * Handles a 'remove-source' event.
  5855. *
  5856. * @param contents an array of Jingle 'content' elements.
  5857. */
  5858. JingleSession.prototype.removeSources = function(contents) {};
  5859. /**
  5860. * Terminates this Jingle session (stops sending media and closes the streams?)
  5861. */
  5862. JingleSession.prototype.terminate = function() {};
  5863. /**
  5864. * Sends a Jingle session-terminate message to the peer and terminates the
  5865. * session.
  5866. * @param reason
  5867. * @param text
  5868. */
  5869. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5870. /**
  5871. * Handles an offer from the remote peer (prepares to accept a session).
  5872. * @param jingle the 'jingle' XML element.
  5873. */
  5874. JingleSession.prototype.setOffer = function(jingle) {};
  5875. /**
  5876. * Handles an answer from the remote peer (prepares to accept a session).
  5877. * @param jingle the 'jingle' XML element.
  5878. */
  5879. JingleSession.prototype.setAnswer = function(jingle) {};
  5880. module.exports = JingleSession;
  5881. }).call(this,"/modules/xmpp/JingleSession.js")
  5882. },{"jitsi-meet-logger":47}],28:[function(require,module,exports){
  5883. (function (__filename){
  5884. /* jshint -W117 */
  5885. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5886. var JingleSession = require("./JingleSession");
  5887. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5888. var SDPDiffer = require("./SDPDiffer");
  5889. var SDPUtil = require("./SDPUtil");
  5890. var SDP = require("./SDP");
  5891. var async = require("async");
  5892. var transform = require("sdp-transform");
  5893. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5894. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5895. var SSRCReplacement = require("./LocalSSRCReplacement");
  5896. var RTC = require("../RTC/RTC");
  5897. // Jingle stuff
  5898. function JingleSessionPC(me, sid, connection, service) {
  5899. JingleSession.call(this, me, sid, connection, service);
  5900. this.initiator = null;
  5901. this.responder = null;
  5902. this.peerjid = null;
  5903. this.state = null;
  5904. this.localSDP = null;
  5905. this.remoteSDP = null;
  5906. this.relayedStreams = [];
  5907. this.usetrickle = true;
  5908. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5909. this.hadstuncandidate = false;
  5910. this.hadturncandidate = false;
  5911. this.lasticecandidate = false;
  5912. this.statsinterval = null;
  5913. this.reason = null;
  5914. this.addssrc = [];
  5915. this.removessrc = [];
  5916. this.pendingop = null;
  5917. this.switchstreams = false;
  5918. this.addingStreams = false;
  5919. this.wait = true;
  5920. /**
  5921. * A map that stores SSRCs of local streams
  5922. * @type {{}} maps media type('audio' or 'video') to SSRC number
  5923. */
  5924. this.localStreamsSSRC = {};
  5925. this.ssrcOwners = {};
  5926. this.ssrcVideoTypes = {};
  5927. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  5928. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  5929. /**
  5930. * The indicator which determines whether the (local) video has been muted
  5931. * in response to a user command in contrast to an automatic decision made
  5932. * by the application logic.
  5933. */
  5934. this.videoMuteByUser = false;
  5935. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5936. // We start with the queue paused. We resume it when the signaling state is
  5937. // stable and the ice connection state is connected.
  5938. this.modifySourcesQueue.pause();
  5939. }
  5940. //XXX this is badly broken...
  5941. JingleSessionPC.prototype = JingleSession.prototype;
  5942. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5943. JingleSessionPC.prototype.setOffer = function(offer) {
  5944. this.setRemoteDescription(offer, 'offer');
  5945. };
  5946. JingleSessionPC.prototype.setAnswer = function(answer) {
  5947. this.setRemoteDescription(answer, 'answer');
  5948. };
  5949. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5950. var signalingState = this.peerconnection.signalingState;
  5951. var iceConnectionState = this.peerconnection.iceConnectionState;
  5952. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5953. this.modifySourcesQueue.resume();
  5954. } else {
  5955. this.modifySourcesQueue.pause();
  5956. }
  5957. };
  5958. JingleSessionPC.prototype.doInitialize = function () {
  5959. var self = this;
  5960. this.hadstuncandidate = false;
  5961. this.hadturncandidate = false;
  5962. this.lasticecandidate = false;
  5963. // True if reconnect is in progress
  5964. this.isreconnect = false;
  5965. // Set to true if the connection was ever stable
  5966. this.wasstable = false;
  5967. this.peerconnection = new TraceablePeerConnection(
  5968. this.connection.jingle.ice_config,
  5969. RTC.getPCConstraints(),
  5970. this);
  5971. this.peerconnection.onicecandidate = function (event) {
  5972. var protocol;
  5973. if (event && event.candidate) {
  5974. protocol = (typeof event.candidate.protocol === 'string')
  5975. ? event.candidate.protocol.toLowerCase() : '';
  5976. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  5977. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  5978. return;
  5979. }
  5980. }
  5981. self.sendIceCandidate(event.candidate);
  5982. };
  5983. this.peerconnection.onaddstream = function (event) {
  5984. if (event.stream.id !== 'default') {
  5985. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5986. self.remoteStreamAdded(event);
  5987. } else {
  5988. // This is a recvonly stream. Clients that implement Unified Plan,
  5989. // such as Firefox use recvonly "streams/channels/tracks" for
  5990. // receiving remote stream/tracks, as opposed to Plan B where there
  5991. // are only 3 channels: audio, video and data.
  5992. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5993. }
  5994. };
  5995. this.peerconnection.onremovestream = function (event) {
  5996. // Remove the stream from remoteStreams
  5997. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5998. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5999. };
  6000. this.peerconnection.onsignalingstatechange = function (event) {
  6001. if (!(self && self.peerconnection)) return;
  6002. if (self.peerconnection.signalingState === 'stable') {
  6003. self.wasstable = true;
  6004. }
  6005. self.updateModifySourcesQueue();
  6006. };
  6007. /**
  6008. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6009. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6010. * RTCPeerConnection.iceConnectionState changes.
  6011. *
  6012. * @param event the event containing information about the change
  6013. */
  6014. this.peerconnection.oniceconnectionstatechange = function (event) {
  6015. if (!(self && self.peerconnection)) return;
  6016. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6017. ":\t", window.performance.now());
  6018. self.updateModifySourcesQueue();
  6019. switch (self.peerconnection.iceConnectionState) {
  6020. case 'connected':
  6021. // Informs interested parties that the connection has been restored.
  6022. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6023. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6024. self.isreconnect = false;
  6025. break;
  6026. case 'disconnected':
  6027. self.isreconnect = true;
  6028. // Informs interested parties that the connection has been interrupted.
  6029. if (self.wasstable)
  6030. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6031. break;
  6032. case 'failed':
  6033. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6034. break;
  6035. }
  6036. onIceConnectionStateChange(self.sid, self);
  6037. };
  6038. this.peerconnection.onnegotiationneeded = function (event) {
  6039. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6040. };
  6041. this.relayedStreams.forEach(function(stream) {
  6042. self.peerconnection.addStream(stream);
  6043. });
  6044. };
  6045. function onIceConnectionStateChange(sid, session) {
  6046. switch (session.peerconnection.iceConnectionState) {
  6047. case 'checking':
  6048. session.timeChecking = (new Date()).getTime();
  6049. session.firstconnect = true;
  6050. break;
  6051. case 'completed': // on caller side
  6052. case 'connected':
  6053. if (session.firstconnect) {
  6054. session.firstconnect = false;
  6055. var metadata = {};
  6056. metadata.setupTime
  6057. = (new Date()).getTime() - session.timeChecking;
  6058. session.peerconnection.getStats(function (res) {
  6059. if(res && res.result) {
  6060. res.result().forEach(function (report) {
  6061. if (report.type == 'googCandidatePair' &&
  6062. report.stat('googActiveConnection') == 'true') {
  6063. metadata.localCandidateType
  6064. = report.stat('googLocalCandidateType');
  6065. metadata.remoteCandidateType
  6066. = report.stat('googRemoteCandidateType');
  6067. // log pair as well so we can get nice pie
  6068. // charts
  6069. metadata.candidatePair
  6070. = report.stat('googLocalCandidateType') +
  6071. ';' +
  6072. report.stat('googRemoteCandidateType');
  6073. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6074. {
  6075. metadata.ipv6 = true;
  6076. }
  6077. }
  6078. });
  6079. }
  6080. });
  6081. }
  6082. break;
  6083. }
  6084. }
  6085. JingleSessionPC.prototype.accept = function () {
  6086. this.state = 'active';
  6087. var pranswer = this.peerconnection.localDescription;
  6088. if (!pranswer || pranswer.type != 'pranswer') {
  6089. return;
  6090. }
  6091. logger.log('going from pranswer to answer');
  6092. if (this.usetrickle) {
  6093. // remove candidates already sent from session-accept
  6094. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6095. for (var i = 0; i < lines.length; i++) {
  6096. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6097. }
  6098. }
  6099. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6100. // FIXME: change any inactive to sendrecv or whatever they were originally
  6101. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6102. }
  6103. var prsdp = new SDP(pranswer.sdp);
  6104. if (self.webrtcIceTcpDisable) {
  6105. prsdp.removeTcpCandidates = true;
  6106. }
  6107. if (self.webrtcIceUdpDisable) {
  6108. prsdp.removeUdpCandidates = true;
  6109. }
  6110. var accept = $iq({to: this.peerjid,
  6111. type: 'set'})
  6112. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6113. action: 'session-accept',
  6114. initiator: this.initiator,
  6115. responder: this.responder,
  6116. sid: this.sid });
  6117. // FIXME why do we generate session-accept in 3 different places ?
  6118. prsdp.toJingle(
  6119. accept,
  6120. this.initiator == this.me ? 'initiator' : 'responder');
  6121. var sdp = this.peerconnection.localDescription.sdp;
  6122. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6123. // FIXME: change any inactive to sendrecv or whatever they were originally
  6124. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6125. }
  6126. var self = this;
  6127. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6128. function () {
  6129. //logger.log('setLocalDescription success');
  6130. self.setLocalDescription();
  6131. SSRCReplacement.processSessionInit(accept);
  6132. self.connection.sendIQ(accept,
  6133. function () {
  6134. var ack = {};
  6135. ack.source = 'answer';
  6136. $(document).trigger('ack.jingle', [self.sid, ack]);
  6137. },
  6138. function (stanza) {
  6139. var error = ($(stanza).find('error').length) ? {
  6140. code: $(stanza).find('error').attr('code'),
  6141. reason: $(stanza).find('error :first')[0].tagName
  6142. }:{};
  6143. error.source = 'answer';
  6144. JingleSessionPC.onJingleError(self.sid, error);
  6145. },
  6146. 10000);
  6147. },
  6148. function (e) {
  6149. logger.error('setLocalDescription failed', e);
  6150. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6151. }
  6152. );
  6153. };
  6154. JingleSessionPC.prototype.terminate = function (reason) {
  6155. this.state = 'ended';
  6156. this.reason = reason;
  6157. this.peerconnection.close();
  6158. if (this.statsinterval !== null) {
  6159. window.clearInterval(this.statsinterval);
  6160. this.statsinterval = null;
  6161. }
  6162. };
  6163. JingleSessionPC.prototype.active = function () {
  6164. return this.state == 'active';
  6165. };
  6166. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6167. var self = this;
  6168. if (candidate && !this.lasticecandidate) {
  6169. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6170. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6171. if (!(ice && jcand)) {
  6172. logger.error('failed to get ice && jcand');
  6173. return;
  6174. }
  6175. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6176. if (jcand.type === 'srflx') {
  6177. this.hadstuncandidate = true;
  6178. } else if (jcand.type === 'relay') {
  6179. this.hadturncandidate = true;
  6180. }
  6181. if (this.usetrickle) {
  6182. if (this.usedrip) {
  6183. if (this.drip_container.length === 0) {
  6184. // start 20ms callout
  6185. window.setTimeout(function () {
  6186. if (self.drip_container.length === 0) return;
  6187. self.sendIceCandidates(self.drip_container);
  6188. self.drip_container = [];
  6189. }, 20);
  6190. }
  6191. this.drip_container.push(candidate);
  6192. return;
  6193. } else {
  6194. self.sendIceCandidate([candidate]);
  6195. }
  6196. }
  6197. } else {
  6198. //logger.log('sendIceCandidate: last candidate.');
  6199. if (!this.usetrickle) {
  6200. //logger.log('should send full offer now...');
  6201. //FIXME why do we generate session-accept in 3 different places ?
  6202. var init = $iq({to: this.peerjid,
  6203. type: 'set'})
  6204. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6205. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6206. initiator: this.initiator,
  6207. sid: this.sid});
  6208. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6209. if (self.webrtcIceTcpDisable) {
  6210. this.localSDP.removeTcpCandidates = true;
  6211. }
  6212. if (self.webrtcIceUdpDisable) {
  6213. this.localSDP.removeUdpCandidates = true;
  6214. }
  6215. var sendJingle = function (ssrc) {
  6216. if(!ssrc)
  6217. ssrc = {};
  6218. self.localSDP.toJingle(
  6219. init,
  6220. self.initiator == self.me ? 'initiator' : 'responder',
  6221. ssrc);
  6222. SSRCReplacement.processSessionInit(init);
  6223. self.connection.sendIQ(init,
  6224. function () {
  6225. //logger.log('session initiate ack');
  6226. var ack = {};
  6227. ack.source = 'offer';
  6228. $(document).trigger('ack.jingle', [self.sid, ack]);
  6229. },
  6230. function (stanza) {
  6231. self.state = 'error';
  6232. self.peerconnection.close();
  6233. var error = ($(stanza).find('error').length) ? {
  6234. code: $(stanza).find('error').attr('code'),
  6235. reason: $(stanza).find('error :first')[0].tagName,
  6236. }:{};
  6237. error.source = 'offer';
  6238. JingleSessionPC.onJingleError(self.sid, error);
  6239. },
  6240. 10000);
  6241. };
  6242. sendJingle();
  6243. }
  6244. this.lasticecandidate = true;
  6245. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6246. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6247. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6248. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6249. }
  6250. }
  6251. };
  6252. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6253. logger.log('sendIceCandidates', candidates);
  6254. var cand = $iq({to: this.peerjid, type: 'set'})
  6255. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6256. action: 'transport-info',
  6257. initiator: this.initiator,
  6258. sid: this.sid});
  6259. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6260. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6261. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6262. if (cands.length > 0) {
  6263. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6264. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6265. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6266. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6267. }).c('transport', ice);
  6268. for (var i = 0; i < cands.length; i++) {
  6269. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6270. }
  6271. // add fingerprint
  6272. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6273. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6274. tmp.required = true;
  6275. cand.c(
  6276. 'fingerprint',
  6277. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6278. .t(tmp.fingerprint);
  6279. delete tmp.fingerprint;
  6280. cand.attrs(tmp);
  6281. cand.up();
  6282. }
  6283. cand.up(); // transport
  6284. cand.up(); // content
  6285. }
  6286. }
  6287. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6288. //logger.log('was this the last candidate', this.lasticecandidate);
  6289. this.connection.sendIQ(cand,
  6290. function () {
  6291. var ack = {};
  6292. ack.source = 'transportinfo';
  6293. $(document).trigger('ack.jingle', [this.sid, ack]);
  6294. },
  6295. function (stanza) {
  6296. var error = ($(stanza).find('error').length) ? {
  6297. code: $(stanza).find('error').attr('code'),
  6298. reason: $(stanza).find('error :first')[0].tagName,
  6299. }:{};
  6300. error.source = 'transportinfo';
  6301. JingleSessionPC.onJingleError(this.sid, error);
  6302. },
  6303. 10000);
  6304. };
  6305. JingleSessionPC.prototype.sendOffer = function () {
  6306. //logger.log('sendOffer...');
  6307. var self = this;
  6308. this.peerconnection.createOffer(function (sdp) {
  6309. self.createdOffer(sdp);
  6310. },
  6311. function (e) {
  6312. logger.error('createOffer failed', e);
  6313. },
  6314. this.media_constraints
  6315. );
  6316. };
  6317. // FIXME createdOffer is never used in jitsi-meet
  6318. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6319. //logger.log('createdOffer', sdp);
  6320. var self = this;
  6321. this.localSDP = new SDP(sdp.sdp);
  6322. //this.localSDP.mangle();
  6323. var sendJingle = function () {
  6324. var init = $iq({to: this.peerjid,
  6325. type: 'set'})
  6326. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6327. action: 'session-initiate',
  6328. initiator: this.initiator,
  6329. sid: this.sid});
  6330. self.localSDP.toJingle(
  6331. init,
  6332. this.initiator == this.me ? 'initiator' : 'responder');
  6333. SSRCReplacement.processSessionInit(init);
  6334. self.connection.sendIQ(init,
  6335. function () {
  6336. var ack = {};
  6337. ack.source = 'offer';
  6338. $(document).trigger('ack.jingle', [self.sid, ack]);
  6339. },
  6340. function (stanza) {
  6341. self.state = 'error';
  6342. self.peerconnection.close();
  6343. var error = ($(stanza).find('error').length) ? {
  6344. code: $(stanza).find('error').attr('code'),
  6345. reason: $(stanza).find('error :first')[0].tagName,
  6346. }:{};
  6347. error.source = 'offer';
  6348. JingleSessionPC.onJingleError(self.sid, error);
  6349. },
  6350. 10000);
  6351. }
  6352. sdp.sdp = this.localSDP.raw;
  6353. this.peerconnection.setLocalDescription(sdp,
  6354. function () {
  6355. if(self.usetrickle)
  6356. {
  6357. sendJingle();
  6358. }
  6359. self.setLocalDescription();
  6360. //logger.log('setLocalDescription success');
  6361. },
  6362. function (e) {
  6363. logger.error('setLocalDescription failed', e);
  6364. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6365. }
  6366. );
  6367. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6368. for (var i = 0; i < cands.length; i++) {
  6369. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6370. if (cand.type == 'srflx') {
  6371. this.hadstuncandidate = true;
  6372. } else if (cand.type == 'relay') {
  6373. this.hadturncandidate = true;
  6374. }
  6375. }
  6376. };
  6377. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6378. var self = this;
  6379. $(contents).each(function (idx, content) {
  6380. var name = $(content).attr('name');
  6381. var mediaType = this.getAttribute('name');
  6382. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6383. ssrcs.each(function () {
  6384. var ssrc = this.getAttribute('ssrc');
  6385. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6386. function () {
  6387. var owner = this.getAttribute('owner');
  6388. self.ssrcOwners[ssrc] = owner;
  6389. }
  6390. );
  6391. });
  6392. });
  6393. };
  6394. /**
  6395. * Returns the SSRC of local audio stream.
  6396. * @param mediaType 'audio' or 'video' media type
  6397. * @returns {*} the SSRC number of local audio or video stream.
  6398. */
  6399. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6400. return this.localStreamsSSRC[mediaType];
  6401. };
  6402. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6403. return this.ssrcOwners[ssrc];
  6404. };
  6405. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6406. //logger.log('setting remote description... ', desctype);
  6407. this.remoteSDP = new SDP('');
  6408. if (self.webrtcIceTcpDisable) {
  6409. this.remoteSDP.removeTcpCandidates = true;
  6410. }
  6411. if (self.webrtcIceUdpDisable) {
  6412. this.remoteSDP.removeUdpCandidates = true;
  6413. }
  6414. this.remoteSDP.fromJingle(elem);
  6415. this.readSsrcInfo($(elem).find(">content"));
  6416. if (this.peerconnection.remoteDescription) {
  6417. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6418. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6419. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6420. for (var i = 0; i < pranswer.media.length; i++) {
  6421. // make sure we have ice ufrag and pwd
  6422. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6423. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6424. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6425. } else {
  6426. logger.warn('no ice ufrag?');
  6427. }
  6428. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6429. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6430. } else {
  6431. logger.warn('no ice pwd?');
  6432. }
  6433. }
  6434. // copy over candidates
  6435. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6436. for (var j = 0; j < lines.length; j++) {
  6437. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6438. }
  6439. }
  6440. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6441. }
  6442. }
  6443. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6444. this.peerconnection.setRemoteDescription(remotedesc,
  6445. function () {
  6446. //logger.log('setRemoteDescription success');
  6447. },
  6448. function (e) {
  6449. logger.error('setRemoteDescription error', e);
  6450. JingleSessionPC.onJingleFatalError(self, e);
  6451. }
  6452. );
  6453. };
  6454. /**
  6455. * Adds remote ICE candidates to this Jingle session.
  6456. * @param elem An array of Jingle "content" elements?
  6457. */
  6458. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6459. var self = this;
  6460. if (this.peerconnection.signalingState == 'closed') {
  6461. return;
  6462. }
  6463. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6464. logger.log('trickle ice candidate arriving before session accept...');
  6465. // create a PRANSWER for setRemoteDescription
  6466. if (!this.remoteSDP) {
  6467. var cobbled = 'v=0\r\n' +
  6468. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6469. 's=-\r\n' +
  6470. 't=0 0\r\n';
  6471. // first, take some things from the local description
  6472. for (var i = 0; i < this.localSDP.media.length; i++) {
  6473. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6474. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6475. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6476. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6477. }
  6478. cobbled += 'a=inactive\r\n';
  6479. }
  6480. this.remoteSDP = new SDP(cobbled);
  6481. }
  6482. // then add things like ice and dtls from remote candidate
  6483. elem.each(function () {
  6484. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6485. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6486. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6487. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6488. var tmp = $(this).find('transport');
  6489. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6490. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6491. tmp = $(this).find('transport>fingerprint');
  6492. if (tmp.length) {
  6493. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6494. } else {
  6495. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6496. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6497. }
  6498. break;
  6499. }
  6500. }
  6501. }
  6502. });
  6503. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6504. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6505. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6506. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6507. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6508. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6509. }).length == this.remoteSDP.media.length;
  6510. if (iscomplete) {
  6511. logger.log('setting pranswer');
  6512. try {
  6513. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6514. function() {
  6515. },
  6516. function(e) {
  6517. logger.log('setRemoteDescription pranswer failed', e.toString());
  6518. });
  6519. } catch (e) {
  6520. logger.error('setting pranswer failed', e);
  6521. }
  6522. } else {
  6523. //logger.log('not yet setting pranswer');
  6524. }
  6525. }
  6526. // operate on each content element
  6527. elem.each(function () {
  6528. // would love to deactivate this, but firefox still requires it
  6529. var idx = -1;
  6530. var i;
  6531. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6532. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6533. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6534. idx = i;
  6535. break;
  6536. }
  6537. }
  6538. if (idx == -1) { // fall back to localdescription
  6539. for (i = 0; i < self.localSDP.media.length; i++) {
  6540. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6541. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6542. idx = i;
  6543. break;
  6544. }
  6545. }
  6546. }
  6547. var name = $(this).attr('name');
  6548. // TODO: check ice-pwd and ice-ufrag?
  6549. $(this).find('transport>candidate').each(function () {
  6550. var line, candidate;
  6551. var protocol = this.getAttribute('protocol');
  6552. protocol =
  6553. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6554. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6555. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6556. return;
  6557. }
  6558. line = SDPUtil.candidateFromJingle(this);
  6559. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6560. sdpMid: name,
  6561. candidate: line});
  6562. try {
  6563. self.peerconnection.addIceCandidate(candidate);
  6564. } catch (e) {
  6565. logger.error('addIceCandidate failed', e.toString(), line);
  6566. }
  6567. });
  6568. });
  6569. };
  6570. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6571. //logger.log('createAnswer', provisional);
  6572. var self = this;
  6573. this.peerconnection.createAnswer(
  6574. function (sdp) {
  6575. self.createdAnswer(sdp, provisional);
  6576. },
  6577. function (e) {
  6578. logger.error('createAnswer failed', e);
  6579. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6580. },
  6581. this.media_constraints
  6582. );
  6583. };
  6584. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6585. //logger.log('createAnswer callback');
  6586. var self = this;
  6587. this.localSDP = new SDP(sdp.sdp);
  6588. //this.localSDP.mangle();
  6589. this.usepranswer = provisional === true;
  6590. if (this.usetrickle) {
  6591. if (this.usepranswer) {
  6592. sdp.type = 'pranswer';
  6593. for (var i = 0; i < this.localSDP.media.length; i++) {
  6594. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6595. }
  6596. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6597. }
  6598. }
  6599. var self = this;
  6600. var sendJingle = function (ssrcs) {
  6601. // FIXME why do we generate session-accept in 3 different places ?
  6602. var accept = $iq({to: self.peerjid,
  6603. type: 'set'})
  6604. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6605. action: 'session-accept',
  6606. initiator: self.initiator,
  6607. responder: self.responder,
  6608. sid: self.sid });
  6609. if (self.webrtcIceTcpDisable) {
  6610. self.localSDP.removeTcpCandidates = true;
  6611. }
  6612. if (self.webrtcIceUdpDisable) {
  6613. self.localSDP.removeUdpCandidates = true;
  6614. }
  6615. self.localSDP.toJingle(
  6616. accept,
  6617. self.initiator == self.me ? 'initiator' : 'responder',
  6618. ssrcs);
  6619. SSRCReplacement.processSessionInit(accept);
  6620. self.connection.sendIQ(accept,
  6621. function () {
  6622. var ack = {};
  6623. ack.source = 'answer';
  6624. $(document).trigger('ack.jingle', [self.sid, ack]);
  6625. },
  6626. function (stanza) {
  6627. var error = ($(stanza).find('error').length) ? {
  6628. code: $(stanza).find('error').attr('code'),
  6629. reason: $(stanza).find('error :first')[0].tagName,
  6630. }:{};
  6631. error.source = 'answer';
  6632. JingleSessionPC.onJingleError(self.sid, error);
  6633. },
  6634. 10000);
  6635. }
  6636. sdp.sdp = this.localSDP.raw;
  6637. this.peerconnection.setLocalDescription(sdp,
  6638. function () {
  6639. //logger.log('setLocalDescription success');
  6640. if (self.usetrickle && !self.usepranswer) {
  6641. sendJingle();
  6642. }
  6643. self.setLocalDescription();
  6644. },
  6645. function (e) {
  6646. logger.error('setLocalDescription failed', e);
  6647. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6648. }
  6649. );
  6650. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6651. for (var j = 0; j < cands.length; j++) {
  6652. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6653. if (cand.type == 'srflx') {
  6654. this.hadstuncandidate = true;
  6655. } else if (cand.type == 'relay') {
  6656. this.hadturncandidate = true;
  6657. }
  6658. }
  6659. };
  6660. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6661. var self = this,
  6662. term = $iq({to: this.peerjid,
  6663. type: 'set'})
  6664. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6665. action: 'session-terminate',
  6666. initiator: this.initiator,
  6667. sid: this.sid})
  6668. .c('reason')
  6669. .c(reason || 'success');
  6670. if (text) {
  6671. term.up().c('text').t(text);
  6672. }
  6673. this.connection.sendIQ(term,
  6674. function () {
  6675. self.peerconnection.close();
  6676. self.peerconnection = null;
  6677. self.terminate();
  6678. var ack = {};
  6679. ack.source = 'terminate';
  6680. $(document).trigger('ack.jingle', [self.sid, ack]);
  6681. },
  6682. function (stanza) {
  6683. var error = ($(stanza).find('error').length) ? {
  6684. code: $(stanza).find('error').attr('code'),
  6685. reason: $(stanza).find('error :first')[0].tagName,
  6686. }:{};
  6687. $(document).trigger('ack.jingle', [self.sid, error]);
  6688. },
  6689. 10000);
  6690. if (this.statsinterval !== null) {
  6691. window.clearInterval(this.statsinterval);
  6692. this.statsinterval = null;
  6693. }
  6694. };
  6695. /**
  6696. * Handles a Jingle source-add message for this Jingle session.
  6697. * @param elem An array of Jingle "content" elements.
  6698. */
  6699. JingleSessionPC.prototype.addSource = function (elem) {
  6700. var self = this;
  6701. // FIXME: dirty waiting
  6702. if (!this.peerconnection.localDescription)
  6703. {
  6704. logger.warn("addSource - localDescription not ready yet")
  6705. setTimeout(function()
  6706. {
  6707. self.addSource(elem);
  6708. },
  6709. 200
  6710. );
  6711. return;
  6712. }
  6713. logger.log('addssrc', new Date().getTime());
  6714. logger.log('ice', this.peerconnection.iceConnectionState);
  6715. this.readSsrcInfo(elem);
  6716. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6717. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6718. $(elem).each(function (idx, content) {
  6719. var name = $(content).attr('name');
  6720. var lines = '';
  6721. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6722. var semantics = this.getAttribute('semantics');
  6723. var ssrcs = $(this).find('>source').map(function () {
  6724. return this.getAttribute('ssrc');
  6725. }).get();
  6726. if (ssrcs.length) {
  6727. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6728. }
  6729. });
  6730. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6731. tmp.each(function () {
  6732. var ssrc = $(this).attr('ssrc');
  6733. if(mySdp.containsSSRC(ssrc)){
  6734. /**
  6735. * This happens when multiple participants change their streams at the same time and
  6736. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6737. * addssrc are scheduled for update IQ. See
  6738. */
  6739. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6740. return;
  6741. }
  6742. if (sdp.containsSSRC(ssrc)) {
  6743. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6744. return;
  6745. }
  6746. $(this).find('>parameter').each(function () {
  6747. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6748. if ($(this).attr('value') && $(this).attr('value').length)
  6749. lines += ':' + $(this).attr('value');
  6750. lines += '\r\n';
  6751. });
  6752. });
  6753. sdp.media.forEach(function(media, idx) {
  6754. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6755. return;
  6756. sdp.media[idx] += lines;
  6757. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6758. self.addssrc[idx] += lines;
  6759. });
  6760. sdp.raw = sdp.session + sdp.media.join('');
  6761. });
  6762. this.modifySourcesQueue.push(function() {
  6763. // When a source is added and if this is FF, a new channel is allocated
  6764. // for receiving the added source. We need to diffuse the SSRC of this
  6765. // new recvonly channel to the rest of the peers.
  6766. logger.log('modify sources done');
  6767. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6768. logger.log("SDPs", mySdp, newSdp);
  6769. self.notifyMySSRCUpdate(mySdp, newSdp);
  6770. });
  6771. };
  6772. /**
  6773. * Handles a Jingle source-remove message for this Jingle session.
  6774. * @param elem An array of Jingle "content" elements.
  6775. */
  6776. JingleSessionPC.prototype.removeSource = function (elem) {
  6777. var self = this;
  6778. // FIXME: dirty waiting
  6779. if (!this.peerconnection.localDescription) {
  6780. logger.warn("removeSource - localDescription not ready yet");
  6781. setTimeout(function() {
  6782. self.removeSource(elem);
  6783. },
  6784. 200
  6785. );
  6786. return;
  6787. }
  6788. logger.log('removessrc', new Date().getTime());
  6789. logger.log('ice', this.peerconnection.iceConnectionState);
  6790. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6791. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6792. $(elem).each(function (idx, content) {
  6793. var name = $(content).attr('name');
  6794. var lines = '';
  6795. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6796. var semantics = this.getAttribute('semantics');
  6797. var ssrcs = $(this).find('>source').map(function () {
  6798. return this.getAttribute('ssrc');
  6799. }).get();
  6800. if (ssrcs.length) {
  6801. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6802. }
  6803. });
  6804. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6805. tmp.each(function () {
  6806. var ssrc = $(this).attr('ssrc');
  6807. // This should never happen, but can be useful for bug detection
  6808. if(mySdp.containsSSRC(ssrc)){
  6809. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6810. return;
  6811. }
  6812. $(this).find('>parameter').each(function () {
  6813. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6814. if ($(this).attr('value') && $(this).attr('value').length)
  6815. lines += ':' + $(this).attr('value');
  6816. lines += '\r\n';
  6817. });
  6818. });
  6819. sdp.media.forEach(function(media, idx) {
  6820. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6821. return;
  6822. sdp.media[idx] += lines;
  6823. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6824. self.removessrc[idx] += lines;
  6825. });
  6826. sdp.raw = sdp.session + sdp.media.join('');
  6827. });
  6828. this.modifySourcesQueue.push(function() {
  6829. // When a source is removed and if this is FF, the recvonly channel that
  6830. // receives the remote stream is deactivated . We need to diffuse the
  6831. // recvonly SSRC removal to the rest of the peers.
  6832. logger.log('modify sources done');
  6833. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6834. logger.log("SDPs", mySdp, newSdp);
  6835. self.notifyMySSRCUpdate(mySdp, newSdp);
  6836. });
  6837. };
  6838. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6839. var self = this;
  6840. if (this.peerconnection.signalingState == 'closed') return;
  6841. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6842. || this.switchstreams || this.addingStreams)){
  6843. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6844. this.setLocalDescription();
  6845. if(successCallback){
  6846. successCallback();
  6847. }
  6848. queueCallback();
  6849. return;
  6850. }
  6851. // Reset switch streams flags
  6852. this.switchstreams = false;
  6853. this.addingStreams = false;
  6854. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6855. // add sources
  6856. this.addssrc.forEach(function(lines, idx) {
  6857. sdp.media[idx] += lines;
  6858. });
  6859. this.addssrc = [];
  6860. // remove sources
  6861. this.removessrc.forEach(function(lines, idx) {
  6862. lines = lines.split('\r\n');
  6863. lines.pop(); // remove empty last element;
  6864. lines.forEach(function(line) {
  6865. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6866. });
  6867. });
  6868. this.removessrc = [];
  6869. sdp.raw = sdp.session + sdp.media.join('');
  6870. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6871. function() {
  6872. if(self.signalingState == 'closed') {
  6873. logger.error("createAnswer attempt on closed state");
  6874. queueCallback("createAnswer attempt on closed state");
  6875. return;
  6876. }
  6877. self.peerconnection.createAnswer(
  6878. function(modifiedAnswer) {
  6879. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6880. if (self.pendingop !== null) {
  6881. var sdp = new SDP(modifiedAnswer.sdp);
  6882. if (sdp.media.length > 1) {
  6883. switch(self.pendingop) {
  6884. case 'mute':
  6885. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6886. break;
  6887. case 'unmute':
  6888. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6889. break;
  6890. }
  6891. sdp.raw = sdp.session + sdp.media.join('');
  6892. modifiedAnswer.sdp = sdp.raw;
  6893. }
  6894. self.pendingop = null;
  6895. }
  6896. // FIXME: pushing down an answer while ice connection state
  6897. // is still checking is bad...
  6898. //logger.log(self.peerconnection.iceConnectionState);
  6899. // trying to work around another chrome bug
  6900. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6901. self.peerconnection.setLocalDescription(modifiedAnswer,
  6902. function() {
  6903. //logger.log('modified setLocalDescription ok');
  6904. self.setLocalDescription();
  6905. if(successCallback){
  6906. successCallback();
  6907. }
  6908. queueCallback();
  6909. },
  6910. function(error) {
  6911. logger.error('modified setLocalDescription failed', error);
  6912. queueCallback(error);
  6913. }
  6914. );
  6915. },
  6916. function(error) {
  6917. logger.error('modified answer failed', error);
  6918. queueCallback(error);
  6919. }
  6920. );
  6921. },
  6922. function(error) {
  6923. logger.error('modify failed', error);
  6924. queueCallback(error);
  6925. }
  6926. );
  6927. };
  6928. /**
  6929. * Switches video streams.
  6930. * @param newStream new stream that will be used as video of this session.
  6931. * @param oldStream old video stream of this session.
  6932. * @param successCallback callback executed after successful stream switch.
  6933. * @param isAudio whether the streams are audio (if true) or video (if false).
  6934. */
  6935. JingleSessionPC.prototype.switchStreams =
  6936. function (newStream, oldStream, successCallback, isAudio) {
  6937. var self = this;
  6938. var sender, newTrack;
  6939. var senderKind = isAudio ? 'audio' : 'video';
  6940. // Remember SDP to figure out added/removed SSRCs
  6941. var oldSdp = null;
  6942. if (self.peerconnection) {
  6943. if (self.peerconnection.localDescription) {
  6944. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6945. }
  6946. if (RTCBrowserType.getBrowserType() ===
  6947. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  6948. // On Firefox we don't replace MediaStreams as this messes up the
  6949. // m-lines (which can't be removed in Plan Unified) and brings a lot
  6950. // of complications. Instead, we use the RTPSender and replace just
  6951. // the track.
  6952. // Find the right sender (for audio or video)
  6953. self.peerconnection.peerconnection.getSenders().some(function (s) {
  6954. if (s.track && s.track.kind === senderKind) {
  6955. sender = s;
  6956. return true;
  6957. }
  6958. });
  6959. if (sender) {
  6960. // We assume that our streams have a single track, either audio
  6961. // or video.
  6962. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  6963. newStream.getVideoTracks()[0];
  6964. sender.replaceTrack(newTrack)
  6965. .then(function() {
  6966. console.log("Replaced a track, isAudio=" + isAudio);
  6967. })
  6968. .catch(function(err) {
  6969. console.log("Failed to replace a track: " + err);
  6970. });
  6971. } else {
  6972. console.log("Cannot switch tracks: no RTPSender.");
  6973. }
  6974. } else {
  6975. self.peerconnection.removeStream(oldStream, true);
  6976. if (newStream) {
  6977. self.peerconnection.addStream(newStream);
  6978. }
  6979. }
  6980. }
  6981. // Conference is not active
  6982. if (!oldSdp) {
  6983. successCallback();
  6984. return;
  6985. }
  6986. self.switchstreams = true;
  6987. self.modifySourcesQueue.push(function() {
  6988. logger.log('modify sources done');
  6989. successCallback();
  6990. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6991. logger.log("SDPs", oldSdp, newSdp);
  6992. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6993. });
  6994. };
  6995. /**
  6996. * Adds streams.
  6997. * @param stream new stream that will be added.
  6998. * @param success_callback callback executed after successful stream addition.
  6999. */
  7000. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7001. var self = this;
  7002. // Remember SDP to figure out added/removed SSRCs
  7003. var oldSdp = null;
  7004. if(this.peerconnection) {
  7005. if(this.peerconnection.localDescription) {
  7006. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7007. }
  7008. if(stream)
  7009. this.peerconnection.addStream(stream);
  7010. }
  7011. // Conference is not active
  7012. if(!oldSdp || !this.peerconnection) {
  7013. callback();
  7014. return;
  7015. }
  7016. this.addingStreams = true;
  7017. this.modifySourcesQueue.push(function() {
  7018. logger.log('modify sources done');
  7019. callback();
  7020. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7021. logger.log("SDPs", oldSdp, newSdp);
  7022. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7023. });
  7024. }
  7025. /**
  7026. * Remove streams.
  7027. * @param stream stream that will be removed.
  7028. * @param success_callback callback executed after successful stream addition.
  7029. */
  7030. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7031. var self = this;
  7032. // Remember SDP to figure out added/removed SSRCs
  7033. var oldSdp = null;
  7034. if(this.peerconnection) {
  7035. if(this.peerconnection.localDescription) {
  7036. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7037. }
  7038. if(stream)
  7039. this.peerconnection.removeStream(stream);
  7040. }
  7041. // Conference is not active
  7042. if(!oldSdp || !this.peerconnection) {
  7043. callback();
  7044. return;
  7045. }
  7046. this.addingStreams = true;
  7047. this.modifySourcesQueue.push(function() {
  7048. logger.log('modify sources done');
  7049. callback();
  7050. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7051. logger.log("SDPs", oldSdp, newSdp);
  7052. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7053. });
  7054. }
  7055. /**
  7056. * Figures out added/removed ssrcs and send update IQs.
  7057. * @param old_sdp SDP object for old description.
  7058. * @param new_sdp SDP object for new description.
  7059. */
  7060. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7061. if (!(this.peerconnection.signalingState == 'stable' &&
  7062. this.peerconnection.iceConnectionState == 'connected')){
  7063. logger.log("Too early to send updates");
  7064. return;
  7065. }
  7066. // send source-remove IQ.
  7067. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7068. var remove = $iq({to: this.peerjid, type: 'set'})
  7069. .c('jingle', {
  7070. xmlns: 'urn:xmpp:jingle:1',
  7071. action: 'source-remove',
  7072. initiator: this.initiator,
  7073. sid: this.sid
  7074. }
  7075. );
  7076. var removed = sdpDiffer.toJingle(remove);
  7077. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7078. // it in the current form
  7079. if (removed)
  7080. remove = SSRCReplacement.processSourceRemove(remove);
  7081. if (removed && remove) {
  7082. logger.info("Sending source-remove", remove);
  7083. this.connection.sendIQ(remove,
  7084. function (res) {
  7085. logger.info('got remove result', res);
  7086. },
  7087. function (err) {
  7088. logger.error('got remove error', err);
  7089. }
  7090. );
  7091. } else {
  7092. logger.log('removal not necessary');
  7093. }
  7094. // send source-add IQ.
  7095. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7096. var add = $iq({to: this.peerjid, type: 'set'})
  7097. .c('jingle', {
  7098. xmlns: 'urn:xmpp:jingle:1',
  7099. action: 'source-add',
  7100. initiator: this.initiator,
  7101. sid: this.sid
  7102. }
  7103. );
  7104. var added = sdpDiffer.toJingle(add);
  7105. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7106. // it in the current form
  7107. if (added)
  7108. add = SSRCReplacement.processSourceAdd(add);
  7109. if (added && add) {
  7110. logger.info("Sending source-add", add);
  7111. this.connection.sendIQ(add,
  7112. function (res) {
  7113. logger.info('got add result', res);
  7114. },
  7115. function (err) {
  7116. logger.error('got add error', err);
  7117. }
  7118. );
  7119. } else {
  7120. logger.log('addition not necessary');
  7121. }
  7122. };
  7123. /**
  7124. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7125. *
  7126. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7127. * tracks; otherwise, <tt>false</tt>
  7128. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7129. * tracks have been enabled/disabled. The function may, optionally, return
  7130. * another function which is to be invoked after the whole mute/unmute operation
  7131. * has completed successfully.
  7132. * @param options an object which specifies optional arguments such as the
  7133. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7134. * specifies whether the method was initiated in response to a user command (in
  7135. * contrast to an automatic decision made by the application logic)
  7136. */
  7137. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7138. var byUser;
  7139. if (options) {
  7140. byUser = options.byUser;
  7141. if (typeof byUser === 'undefined') {
  7142. byUser = true;
  7143. }
  7144. } else {
  7145. byUser = true;
  7146. }
  7147. // The user's command to mute the (local) video takes precedence over any
  7148. // automatic decision made by the application logic.
  7149. if (byUser) {
  7150. this.videoMuteByUser = mute;
  7151. } else if (this.videoMuteByUser) {
  7152. return;
  7153. }
  7154. this.hardMuteVideo(mute);
  7155. var self = this;
  7156. var oldSdp = null;
  7157. if(self.peerconnection) {
  7158. if(self.peerconnection.localDescription) {
  7159. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7160. }
  7161. }
  7162. this.modifySourcesQueue.push(function() {
  7163. logger.log('modify sources done');
  7164. callback(mute);
  7165. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7166. logger.log("SDPs", oldSdp, newSdp);
  7167. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7168. });
  7169. };
  7170. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7171. this.pendingop = muted ? 'mute' : 'unmute';
  7172. };
  7173. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7174. var info = $iq({to: this.peerjid,
  7175. type: 'set'})
  7176. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7177. action: 'session-info',
  7178. initiator: this.initiator,
  7179. sid: this.sid });
  7180. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7181. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7182. if (content) {
  7183. info.attrs({'name': content});
  7184. }
  7185. this.connection.send(info);
  7186. };
  7187. JingleSessionPC.prototype.sendRinging = function () {
  7188. var info = $iq({to: this.peerjid,
  7189. type: 'set'})
  7190. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7191. action: 'session-info',
  7192. initiator: this.initiator,
  7193. sid: this.sid });
  7194. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7195. this.connection.send(info);
  7196. };
  7197. JingleSessionPC.prototype.getStats = function (interval) {
  7198. var self = this;
  7199. var recv = {audio: 0, video: 0};
  7200. var lost = {audio: 0, video: 0};
  7201. var lastrecv = {audio: 0, video: 0};
  7202. var lastlost = {audio: 0, video: 0};
  7203. var loss = {audio: 0, video: 0};
  7204. var delta = {audio: 0, video: 0};
  7205. this.statsinterval = window.setInterval(function () {
  7206. if (self && self.peerconnection && self.peerconnection.getStats) {
  7207. self.peerconnection.getStats(function (stats) {
  7208. var results = stats.result();
  7209. // TODO: there are so much statistics you can get from this..
  7210. for (var i = 0; i < results.length; ++i) {
  7211. if (results[i].type == 'ssrc') {
  7212. var packetsrecv = results[i].stat('packetsReceived');
  7213. var packetslost = results[i].stat('packetsLost');
  7214. if (packetsrecv && packetslost) {
  7215. packetsrecv = parseInt(packetsrecv, 10);
  7216. packetslost = parseInt(packetslost, 10);
  7217. if (results[i].stat('googFrameRateReceived')) {
  7218. lastlost.video = lost.video;
  7219. lastrecv.video = recv.video;
  7220. recv.video = packetsrecv;
  7221. lost.video = packetslost;
  7222. } else {
  7223. lastlost.audio = lost.audio;
  7224. lastrecv.audio = recv.audio;
  7225. recv.audio = packetsrecv;
  7226. lost.audio = packetslost;
  7227. }
  7228. }
  7229. }
  7230. }
  7231. delta.audio = recv.audio - lastrecv.audio;
  7232. delta.video = recv.video - lastrecv.video;
  7233. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7234. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7235. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7236. });
  7237. }
  7238. }, interval || 3000);
  7239. return this.statsinterval;
  7240. };
  7241. JingleSessionPC.onJingleError = function (session, error)
  7242. {
  7243. logger.error("Jingle error", error);
  7244. }
  7245. JingleSessionPC.onJingleFatalError = function (session, error)
  7246. {
  7247. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7248. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7249. }
  7250. JingleSessionPC.prototype.setLocalDescription = function () {
  7251. var self = this;
  7252. var newssrcs = [];
  7253. if(!this.peerconnection.localDescription)
  7254. return;
  7255. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7256. var i;
  7257. session.media.forEach(function (media) {
  7258. if (media.ssrcs && media.ssrcs.length > 0) {
  7259. // TODO(gp) maybe exclude FID streams?
  7260. media.ssrcs.forEach(function (ssrc) {
  7261. if (ssrc.attribute !== 'cname') {
  7262. return;
  7263. }
  7264. newssrcs.push({
  7265. 'ssrc': ssrc.id,
  7266. 'type': media.type
  7267. });
  7268. // FIXME allows for only one SSRC per media type
  7269. self.localStreamsSSRC[media.type] = ssrc.id;
  7270. });
  7271. }
  7272. });
  7273. logger.log('new ssrcs', newssrcs);
  7274. // Bind us as local SSRCs owner
  7275. if (newssrcs.length > 0) {
  7276. for (i = 0; i < newssrcs.length; i++) {
  7277. var ssrc = newssrcs[i].ssrc;
  7278. var myJid = self.connection.emuc.myroomjid;
  7279. self.ssrcOwners[ssrc] = myJid;
  7280. }
  7281. }
  7282. }
  7283. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7284. JingleSessionPC.prototype.sendKeyframe = function () {
  7285. var pc = this.peerconnection;
  7286. logger.log('sendkeyframe', pc.iceConnectionState);
  7287. if (pc.iceConnectionState !== 'connected') return; // safe...
  7288. var self = this;
  7289. pc.setRemoteDescription(
  7290. pc.remoteDescription,
  7291. function () {
  7292. pc.createAnswer(
  7293. function (modifiedAnswer) {
  7294. pc.setLocalDescription(
  7295. modifiedAnswer,
  7296. function () {
  7297. // noop
  7298. },
  7299. function (error) {
  7300. logger.log('triggerKeyframe setLocalDescription failed', error);
  7301. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7302. }
  7303. );
  7304. },
  7305. function (error) {
  7306. logger.log('triggerKeyframe createAnswer failed', error);
  7307. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7308. }
  7309. );
  7310. },
  7311. function (error) {
  7312. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7313. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7314. }
  7315. );
  7316. }
  7317. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7318. var self = this;
  7319. var thessrc;
  7320. var streamId = RTC.getStreamID(data.stream);
  7321. // look up an associated JID for a stream id
  7322. if (!streamId) {
  7323. logger.error("No stream ID for", data.stream);
  7324. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7325. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7326. var ssrclines = this.peerconnection.remoteDescription?
  7327. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7328. ssrclines = ssrclines.filter(function (line) {
  7329. // NOTE(gp) previously we filtered on the mslabel, but that property
  7330. // is not always present.
  7331. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7332. if (RTCBrowserType.isTemasysPluginUsed()) {
  7333. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7334. } else {
  7335. return ((line.indexOf('msid:' + streamId) !== -1));
  7336. }
  7337. });
  7338. if (ssrclines.length) {
  7339. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7340. if (!self.ssrcOwners[thessrc]) {
  7341. logger.error("No SSRC owner known for: " + thessrc);
  7342. return;
  7343. }
  7344. data.peerjid = self.ssrcOwners[thessrc];
  7345. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7346. } else {
  7347. logger.error("No SSRC lines for ", streamId);
  7348. }
  7349. }
  7350. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7351. var isVideo = data.stream.getVideoTracks().length > 0;
  7352. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7353. if (isVideo &&
  7354. data.peerjid && this.peerjid === data.peerjid &&
  7355. data.stream.getVideoTracks().length === 0 &&
  7356. RTC.localVideo.getTracks().length > 0) {
  7357. window.setTimeout(function () {
  7358. self.sendKeyframe();
  7359. }, 3000);
  7360. }
  7361. }
  7362. module.exports = JingleSessionPC;
  7363. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7364. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":42,"jitsi-meet-logger":47,"sdp-transform":75}],29:[function(require,module,exports){
  7365. (function (__filename){
  7366. /* global $ */
  7367. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7368. /*
  7369. Here we do modifications of local video SSRCs. There are 2 situations we have
  7370. to handle:
  7371. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7372. have no local camera and it is not generated automatically, but SSRC=1 is
  7373. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7374. and we won't be able to request video key frames correctly.
  7375. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7376. in future. It turned out that Chrome may keep on using the SSRC of removed
  7377. video stream in RTCP even though a new one has been created. So we just
  7378. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7379. notifications are blocked once first video SSRC is advertised to the focus.
  7380. What this hack does:
  7381. 1. Stores the SSRC of the first video stream created by
  7382. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7383. b) watching for 'source-add' for new video stream if it has not been
  7384. created in step a)
  7385. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7386. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7387. returned to the other parts of the application.
  7388. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7389. blocks those notifications. This makes Jicofo and all participants think
  7390. that it exists all the time even if the video stream has been removed or
  7391. replaced locally. Thanks to that there is no additional signaling activity
  7392. on video mute or when switching to the desktop stream.
  7393. */
  7394. var SDP = require('./SDP');
  7395. var RandomUtil = require('../util/RandomUtil');
  7396. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7397. /**
  7398. * The hack is enabled on all browsers except FF by default
  7399. * FIXME finish the hack once removeStream method is implemented in FF
  7400. * @type {boolean}
  7401. */
  7402. var isEnabled = !RTCBrowserType.isFirefox();
  7403. /**
  7404. * Stored SSRC of local video stream.
  7405. */
  7406. var localVideoSSRC;
  7407. /**
  7408. * SSRC used for recvonly video stream when we have no local camera.
  7409. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7410. * instead of 1.
  7411. */
  7412. var localRecvOnlySSRC;
  7413. /**
  7414. * cname for <tt>localRecvOnlySSRC</tt>
  7415. */
  7416. var localRecvOnlyCName;
  7417. /**
  7418. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7419. * from given Jingle IQ.
  7420. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7421. * @param actionName display name of the action which will be printed in log
  7422. * messages.
  7423. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7424. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7425. * other SSRCs left to be signaled after removing it.
  7426. */
  7427. var filterOutSource = function (modifyIq, actionName) {
  7428. var modifyIqTree = $(modifyIq.tree());
  7429. if (!localVideoSSRC)
  7430. return modifyIqTree[0];
  7431. var videoSSRC = modifyIqTree.find(
  7432. '>jingle>content[name="video"]' +
  7433. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7434. if (!videoSSRC.length) {
  7435. return modifyIqTree[0];
  7436. }
  7437. logger.info(
  7438. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7439. videoSSRC.remove();
  7440. // Check if any sources still left to be added/removed
  7441. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7442. return modifyIqTree[0];
  7443. } else {
  7444. return null;
  7445. }
  7446. };
  7447. /**
  7448. * Scans given Jingle IQ for video SSRC and stores it.
  7449. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7450. */
  7451. var storeLocalVideoSSRC = function (jingleIq) {
  7452. var videoSSRCs =
  7453. $(jingleIq.tree())
  7454. .find('>jingle>content[name="video"]>description>source');
  7455. videoSSRCs.each(function (idx, ssrcElem) {
  7456. if (localVideoSSRC)
  7457. return;
  7458. // We consider SSRC real only if it has msid attribute
  7459. // recvonly streams in FF do not have it as well as local SSRCs
  7460. // we generate for recvonly streams in Chrome
  7461. var ssrSel = $(ssrcElem);
  7462. var msid = ssrSel.find('>parameter[name="msid"]');
  7463. if (msid.length) {
  7464. var ssrcVal = ssrSel.attr('ssrc');
  7465. if (ssrcVal) {
  7466. localVideoSSRC = ssrcVal;
  7467. logger.info('Stored local video SSRC' +
  7468. ' for future re-use: ' + localVideoSSRC);
  7469. }
  7470. }
  7471. });
  7472. };
  7473. /**
  7474. * Generates new SSRC for local video recvonly stream.
  7475. * FIXME what about eventual SSRC collision ?
  7476. */
  7477. function generateRecvonlySSRC() {
  7478. localRecvOnlySSRC =
  7479. localVideoSSRC ?
  7480. localVideoSSRC : Math.random().toString(10).substring(2, 11);
  7481. localRecvOnlyCName =
  7482. Math.random().toString(36).substring(2);
  7483. logger.info(
  7484. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7485. ", cname: " + localRecvOnlyCName);
  7486. }
  7487. var LocalSSRCReplacement = {
  7488. /**
  7489. * Method must be called before 'session-initiate' or 'session-invite' is
  7490. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7491. *
  7492. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7493. * which will be scanned for local video SSRC.
  7494. */
  7495. processSessionInit: function (sessionInit) {
  7496. if (!isEnabled)
  7497. return;
  7498. if (localVideoSSRC) {
  7499. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7500. return;
  7501. }
  7502. storeLocalVideoSSRC(sessionInit);
  7503. },
  7504. /**
  7505. * If we have local video SSRC stored searched given
  7506. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7507. * with the stored one.
  7508. * @param localDescription local description object that will have local
  7509. * video SSRC replaced with the stored one
  7510. * @returns modified <tt>localDescription</tt> object.
  7511. */
  7512. mungeLocalVideoSSRC: function (localDescription) {
  7513. if (!isEnabled)
  7514. return localDescription;
  7515. if (!localDescription) {
  7516. logger.warn("localDescription is null or undefined");
  7517. return localDescription;
  7518. }
  7519. // IF we have local video SSRC stored make sure it is replaced
  7520. // with old SSRC
  7521. var sdp = new SDP(localDescription.sdp);
  7522. if (sdp.media.length < 2)
  7523. return;
  7524. if (localVideoSSRC && sdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7525. !sdp.containsSSRC(localVideoSSRC)) {
  7526. // Get new video SSRC
  7527. var map = sdp.getMediaSsrcMap();
  7528. var videoPart = map[1];
  7529. var videoSSRCs = videoPart.ssrcs;
  7530. var newSSRC = Object.keys(videoSSRCs)[0];
  7531. logger.info(
  7532. "Replacing new video SSRC: " + newSSRC +
  7533. " with " + localVideoSSRC);
  7534. localDescription.sdp =
  7535. sdp.raw.replace(
  7536. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7537. 'a=ssrc:' + localVideoSSRC);
  7538. }
  7539. else if (sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7540. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7541. // Make sure we have any SSRC for recvonly video stream
  7542. if (!localRecvOnlySSRC) {
  7543. generateRecvonlySSRC();
  7544. }
  7545. logger.info('No SSRC in video recvonly stream' +
  7546. ' - adding SSRC: ' + localRecvOnlySSRC);
  7547. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7548. ' cname:' + localRecvOnlyCName + '\r\n';
  7549. localDescription.sdp = sdp.session + sdp.media.join('');
  7550. }
  7551. return localDescription;
  7552. },
  7553. /**
  7554. * Method must be called before 'source-add' notification is sent. In case
  7555. * we have local video SSRC advertised already it will be removed from the
  7556. * notification. If no other SSRCs are described by given IQ null will be
  7557. * returned which means that there is no point in sending the notification.
  7558. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7559. * @returns modified 'source-add' IQ which can be sent to the focus or
  7560. * <tt>null</tt> if no notification shall be sent. It is no longer
  7561. * a Strophe IQ Builder instance, but DOM element tree.
  7562. */
  7563. processSourceAdd: function (sourceAdd) {
  7564. if (!isEnabled)
  7565. return sourceAdd;
  7566. if (!localVideoSSRC) {
  7567. // Store local SSRC if available
  7568. storeLocalVideoSSRC(sourceAdd);
  7569. return sourceAdd;
  7570. } else {
  7571. return filterOutSource(sourceAdd, 'source-add');
  7572. }
  7573. },
  7574. /**
  7575. * Method must be called before 'source-remove' notification is sent.
  7576. * Removes local video SSRC from the notification. If there are no other
  7577. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7578. * means that there is no point in sending the notification.
  7579. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7580. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7581. * <tt>null</tt> if no notification shall be sent. It is no longer
  7582. * a Strophe IQ Builder instance, but DOM element tree.
  7583. */
  7584. processSourceRemove: function (sourceRemove) {
  7585. if (!isEnabled)
  7586. return sourceRemove;
  7587. return filterOutSource(sourceRemove, 'source-remove');
  7588. },
  7589. /**
  7590. * Turns the hack on or off
  7591. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7592. * to disable it
  7593. */
  7594. setEnabled: function (enabled) {
  7595. isEnabled = enabled;
  7596. }
  7597. };
  7598. module.exports = LocalSSRCReplacement;
  7599. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7600. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":47}],30:[function(require,module,exports){
  7601. (function (__filename){
  7602. /* jshint -W117 */
  7603. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7604. var SDPUtil = require("./SDPUtil");
  7605. // SDP STUFF
  7606. function SDP(sdp) {
  7607. /**
  7608. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7609. * @type {boolean}
  7610. */
  7611. this.removeTcpCandidates = false;
  7612. /**
  7613. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7614. * @type {boolean}
  7615. */
  7616. this.removeUdpCandidates = false;
  7617. this.media = sdp.split('\r\nm=');
  7618. for (var i = 1; i < this.media.length; i++) {
  7619. this.media[i] = 'm=' + this.media[i];
  7620. if (i != this.media.length - 1) {
  7621. this.media[i] += '\r\n';
  7622. }
  7623. }
  7624. this.session = this.media.shift() + '\r\n';
  7625. this.raw = this.session + this.media.join('');
  7626. }
  7627. /**
  7628. * Returns map of MediaChannel mapped per channel idx.
  7629. */
  7630. SDP.prototype.getMediaSsrcMap = function() {
  7631. var self = this;
  7632. var media_ssrcs = {};
  7633. var tmp;
  7634. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7635. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7636. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7637. var media = {
  7638. mediaindex: mediaindex,
  7639. mid: mid,
  7640. ssrcs: {},
  7641. ssrcGroups: []
  7642. };
  7643. media_ssrcs[mediaindex] = media;
  7644. tmp.forEach(function (line) {
  7645. var linessrc = line.substring(7).split(' ')[0];
  7646. // allocate new ChannelSsrc
  7647. if(!media.ssrcs[linessrc]) {
  7648. media.ssrcs[linessrc] = {
  7649. ssrc: linessrc,
  7650. lines: []
  7651. };
  7652. }
  7653. media.ssrcs[linessrc].lines.push(line);
  7654. });
  7655. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7656. tmp.forEach(function(line){
  7657. var idx = line.indexOf(' ');
  7658. var semantics = line.substr(0, idx).substr(13);
  7659. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7660. if (ssrcs.length) {
  7661. media.ssrcGroups.push({
  7662. semantics: semantics,
  7663. ssrcs: ssrcs
  7664. });
  7665. }
  7666. });
  7667. }
  7668. return media_ssrcs;
  7669. };
  7670. /**
  7671. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7672. * @param ssrc the ssrc to check.
  7673. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7674. */
  7675. SDP.prototype.containsSSRC = function (ssrc) {
  7676. // FIXME this code is really strange - improve it if you can
  7677. var medias = this.getMediaSsrcMap();
  7678. var result = false;
  7679. Object.keys(medias).forEach(function (mediaindex) {
  7680. if (result)
  7681. return;
  7682. if (medias[mediaindex].ssrcs[ssrc]) {
  7683. result = true;
  7684. }
  7685. });
  7686. return result;
  7687. };
  7688. // remove iSAC and CN from SDP
  7689. SDP.prototype.mangle = function () {
  7690. var i, j, mline, lines, rtpmap, newdesc;
  7691. for (i = 0; i < this.media.length; i++) {
  7692. lines = this.media[i].split('\r\n');
  7693. lines.pop(); // remove empty last element
  7694. mline = SDPUtil.parse_mline(lines.shift());
  7695. if (mline.media != 'audio')
  7696. continue;
  7697. newdesc = '';
  7698. mline.fmt.length = 0;
  7699. for (j = 0; j < lines.length; j++) {
  7700. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7701. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7702. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7703. continue;
  7704. mline.fmt.push(rtpmap.id);
  7705. newdesc += lines[j] + '\r\n';
  7706. } else {
  7707. newdesc += lines[j] + '\r\n';
  7708. }
  7709. }
  7710. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7711. this.media[i] += newdesc;
  7712. }
  7713. this.raw = this.session + this.media.join('');
  7714. };
  7715. // remove lines matching prefix from session section
  7716. SDP.prototype.removeSessionLines = function(prefix) {
  7717. var self = this;
  7718. var lines = SDPUtil.find_lines(this.session, prefix);
  7719. lines.forEach(function(line) {
  7720. self.session = self.session.replace(line + '\r\n', '');
  7721. });
  7722. this.raw = this.session + this.media.join('');
  7723. return lines;
  7724. }
  7725. // remove lines matching prefix from a media section specified by mediaindex
  7726. // TODO: non-numeric mediaindex could match mid
  7727. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7728. var self = this;
  7729. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7730. lines.forEach(function(line) {
  7731. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7732. });
  7733. this.raw = this.session + this.media.join('');
  7734. return lines;
  7735. }
  7736. // add content's to a jingle element
  7737. SDP.prototype.toJingle = function (elem, thecreator) {
  7738. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7739. var self = this;
  7740. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7741. // new bundle plan
  7742. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7743. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7744. for (i = 0; i < lines.length; i++) {
  7745. tmp = lines[i].split(' ');
  7746. var semantics = tmp.shift().substr(8);
  7747. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7748. for (j = 0; j < tmp.length; j++) {
  7749. elem.c('content', {name: tmp[j]}).up();
  7750. }
  7751. elem.up();
  7752. }
  7753. }
  7754. for (i = 0; i < this.media.length; i++) {
  7755. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7756. if (!(mline.media === 'audio' ||
  7757. mline.media === 'video' ||
  7758. mline.media === 'application'))
  7759. {
  7760. continue;
  7761. }
  7762. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7763. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7764. } else {
  7765. ssrc = false;
  7766. }
  7767. elem.c('content', {creator: thecreator, name: mline.media});
  7768. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7769. // prefer identifier from a=mid if present
  7770. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7771. elem.attrs({ name: mid });
  7772. }
  7773. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  7774. elem.c('description',
  7775. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7776. media: mline.media });
  7777. if (ssrc) {
  7778. elem.attrs({ssrc: ssrc});
  7779. }
  7780. for (j = 0; j < mline.fmt.length; j++) {
  7781. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7782. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7783. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7784. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7785. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7786. for (k = 0; k < tmp.length; k++) {
  7787. elem.c('parameter', tmp[k]).up();
  7788. }
  7789. }
  7790. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7791. elem.up();
  7792. }
  7793. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7794. elem.c('encryption', {required: 1});
  7795. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7796. crypto.forEach(function(line) {
  7797. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7798. });
  7799. elem.up(); // end of encryption
  7800. }
  7801. if (ssrc) {
  7802. // new style mapping
  7803. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7804. // FIXME: group by ssrc and support multiple different ssrcs
  7805. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7806. if(ssrclines.length > 0) {
  7807. ssrclines.forEach(function (line) {
  7808. var idx = line.indexOf(' ');
  7809. var linessrc = line.substr(0, idx).substr(7);
  7810. if (linessrc != ssrc) {
  7811. elem.up();
  7812. ssrc = linessrc;
  7813. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7814. }
  7815. var kv = line.substr(idx + 1);
  7816. elem.c('parameter');
  7817. if (kv.indexOf(':') == -1) {
  7818. elem.attrs({ name: kv });
  7819. } else {
  7820. var k = kv.split(':', 2)[0];
  7821. elem.attrs({ name: k });
  7822. var v = kv.split(':', 2)[1];
  7823. v = SDPUtil.filter_special_chars(v);
  7824. elem.attrs({ value: v });
  7825. }
  7826. elem.up();
  7827. });
  7828. } else {
  7829. elem.up();
  7830. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7831. elem.c('parameter');
  7832. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7833. elem.up();
  7834. var msid = null;
  7835. if(mline.media == "audio")
  7836. {
  7837. msid = APP.RTC.localAudio.getId();
  7838. }
  7839. else
  7840. {
  7841. msid = APP.RTC.localVideo.getId();
  7842. }
  7843. if(msid != null)
  7844. {
  7845. msid = SDPUtil.filter_special_chars(msid);
  7846. elem.c('parameter');
  7847. elem.attrs({name: "msid", value:msid});
  7848. elem.up();
  7849. elem.c('parameter');
  7850. elem.attrs({name: "mslabel", value:msid});
  7851. elem.up();
  7852. elem.c('parameter');
  7853. elem.attrs({name: "label", value:msid});
  7854. elem.up();
  7855. }
  7856. }
  7857. elem.up();
  7858. // XEP-0339 handle ssrc-group attributes
  7859. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7860. ssrc_group_lines.forEach(function(line) {
  7861. var idx = line.indexOf(' ');
  7862. var semantics = line.substr(0, idx).substr(13);
  7863. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7864. if (ssrcs.length) {
  7865. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7866. ssrcs.forEach(function(ssrc) {
  7867. elem.c('source', { ssrc: ssrc })
  7868. .up();
  7869. });
  7870. elem.up();
  7871. }
  7872. });
  7873. }
  7874. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7875. elem.c('rtcp-mux').up();
  7876. }
  7877. // XEP-0293 -- map a=rtcp-fb:*
  7878. this.rtcpFbToJingle(i, elem, '*');
  7879. // XEP-0294
  7880. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7881. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7882. for (j = 0; j < lines.length; j++) {
  7883. tmp = SDPUtil.parse_extmap(lines[j]);
  7884. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7885. uri: tmp.uri,
  7886. id: tmp.value });
  7887. if (tmp.hasOwnProperty('direction')) {
  7888. switch (tmp.direction) {
  7889. case 'sendonly':
  7890. elem.attrs({senders: 'responder'});
  7891. break;
  7892. case 'recvonly':
  7893. elem.attrs({senders: 'initiator'});
  7894. break;
  7895. case 'sendrecv':
  7896. elem.attrs({senders: 'both'});
  7897. break;
  7898. case 'inactive':
  7899. elem.attrs({senders: 'none'});
  7900. break;
  7901. }
  7902. }
  7903. // TODO: handle params
  7904. elem.up();
  7905. }
  7906. }
  7907. elem.up(); // end of description
  7908. }
  7909. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7910. this.transportToJingle(i, elem);
  7911. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7912. elem.attrs({senders: 'both'});
  7913. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7914. elem.attrs({senders: 'initiator'});
  7915. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7916. elem.attrs({senders: 'responder'});
  7917. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7918. elem.attrs({senders: 'none'});
  7919. }
  7920. if (mline.port == '0') {
  7921. // estos hack to reject an m-line
  7922. elem.attrs({senders: 'rejected'});
  7923. }
  7924. elem.up(); // end of content
  7925. }
  7926. elem.up();
  7927. return elem;
  7928. };
  7929. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  7930. var tmp, sctpmap, sctpAttrs, fingerprints;
  7931. var self = this;
  7932. elem.c('transport');
  7933. // XEP-0343 DTLS/SCTP
  7934. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7935. {
  7936. sctpmap = SDPUtil.find_line(
  7937. this.media[mediaindex], 'a=sctpmap:', self.session);
  7938. if (sctpmap)
  7939. {
  7940. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7941. elem.c('sctpmap',
  7942. {
  7943. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7944. number: sctpAttrs[0], /* SCTP port */
  7945. protocol: sctpAttrs[1] /* protocol */
  7946. });
  7947. // Optional stream count attribute
  7948. if (sctpAttrs.length > 2)
  7949. elem.attrs({ streams: sctpAttrs[2]});
  7950. elem.up();
  7951. }
  7952. }
  7953. // XEP-0320
  7954. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7955. fingerprints.forEach(function(line) {
  7956. tmp = SDPUtil.parse_fingerprint(line);
  7957. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7958. elem.c('fingerprint').t(tmp.fingerprint);
  7959. delete tmp.fingerprint;
  7960. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7961. if (line) {
  7962. tmp.setup = line.substr(8);
  7963. }
  7964. elem.attrs(tmp);
  7965. elem.up(); // end of fingerprint
  7966. });
  7967. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7968. if (tmp) {
  7969. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7970. elem.attrs(tmp);
  7971. // XEP-0176
  7972. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7973. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7974. lines.forEach(function (line) {
  7975. var candidate = SDPUtil.candidateToJingle(line);
  7976. var protocol = (candidate &&
  7977. typeof candidate.protocol === 'string')
  7978. ? candidate.protocol.toLowerCase() : '';
  7979. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7980. (self.removeUdpCandidates && protocol === 'udp')) {
  7981. return;
  7982. }
  7983. elem.c('candidate', candidate).up();
  7984. });
  7985. }
  7986. }
  7987. elem.up(); // end of transport
  7988. }
  7989. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7990. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7991. lines.forEach(function (line) {
  7992. var tmp = SDPUtil.parse_rtcpfb(line);
  7993. if (tmp.type == 'trr-int') {
  7994. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7995. elem.up();
  7996. } else {
  7997. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7998. if (tmp.params.length > 0) {
  7999. elem.attrs({'subtype': tmp.params[0]});
  8000. }
  8001. elem.up();
  8002. }
  8003. });
  8004. };
  8005. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8006. var media = '';
  8007. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8008. if (tmp.length) {
  8009. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8010. if (tmp.attr('value')) {
  8011. media += tmp.attr('value');
  8012. } else {
  8013. media += '0';
  8014. }
  8015. media += '\r\n';
  8016. }
  8017. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8018. tmp.each(function () {
  8019. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8020. if ($(this).attr('subtype')) {
  8021. media += ' ' + $(this).attr('subtype');
  8022. }
  8023. media += '\r\n';
  8024. });
  8025. return media;
  8026. };
  8027. // construct an SDP from a jingle stanza
  8028. SDP.prototype.fromJingle = function (jingle) {
  8029. var self = this;
  8030. this.raw = 'v=0\r\n' +
  8031. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8032. 's=-\r\n' +
  8033. 't=0 0\r\n';
  8034. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8035. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8036. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8037. var contents = $(group).find('>content').map(function (idx, content) {
  8038. return content.getAttribute('name');
  8039. }).get();
  8040. if (contents.length > 0) {
  8041. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8042. }
  8043. });
  8044. }
  8045. this.session = this.raw;
  8046. jingle.find('>content').each(function () {
  8047. var m = self.jingle2media($(this));
  8048. self.media.push(m);
  8049. });
  8050. // reconstruct msid-semantic -- apparently not necessary
  8051. /*
  8052. var msid = SDPUtil.parse_ssrc(this.raw);
  8053. if (msid.hasOwnProperty('mslabel')) {
  8054. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8055. }
  8056. */
  8057. this.raw = this.session + this.media.join('');
  8058. };
  8059. // translate a jingle content element into an an SDP media part
  8060. SDP.prototype.jingle2media = function (content) {
  8061. var media = '',
  8062. desc = content.find('description'),
  8063. ssrc = desc.attr('ssrc'),
  8064. self = this,
  8065. tmp;
  8066. var sctp = content.find(
  8067. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8068. tmp = { media: desc.attr('media') };
  8069. tmp.port = '1';
  8070. if (content.attr('senders') == 'rejected') {
  8071. // estos hack to reject an m-line.
  8072. tmp.port = '0';
  8073. }
  8074. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8075. if (sctp.length)
  8076. tmp.proto = 'DTLS/SCTP';
  8077. else
  8078. tmp.proto = 'RTP/SAVPF';
  8079. } else {
  8080. tmp.proto = 'RTP/AVPF';
  8081. }
  8082. if (!sctp.length) {
  8083. tmp.fmt = desc.find('payload-type').map(
  8084. function () { return this.getAttribute('id'); }).get();
  8085. media += SDPUtil.build_mline(tmp) + '\r\n';
  8086. } else {
  8087. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8088. media += 'a=sctpmap:' + sctp.attr('number') +
  8089. ' ' + sctp.attr('protocol');
  8090. var streamCount = sctp.attr('streams');
  8091. if (streamCount)
  8092. media += ' ' + streamCount + '\r\n';
  8093. else
  8094. media += '\r\n';
  8095. }
  8096. media += 'c=IN IP4 0.0.0.0\r\n';
  8097. if (!sctp.length)
  8098. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8099. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8100. if (tmp.length) {
  8101. if (tmp.attr('ufrag')) {
  8102. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8103. }
  8104. if (tmp.attr('pwd')) {
  8105. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8106. }
  8107. tmp.find('>fingerprint').each(function () {
  8108. // FIXME: check namespace at some point
  8109. media += 'a=fingerprint:' + this.getAttribute('hash');
  8110. media += ' ' + $(this).text();
  8111. media += '\r\n';
  8112. if (this.getAttribute('setup')) {
  8113. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8114. }
  8115. });
  8116. }
  8117. switch (content.attr('senders')) {
  8118. case 'initiator':
  8119. media += 'a=sendonly\r\n';
  8120. break;
  8121. case 'responder':
  8122. media += 'a=recvonly\r\n';
  8123. break;
  8124. case 'none':
  8125. media += 'a=inactive\r\n';
  8126. break;
  8127. case 'both':
  8128. media += 'a=sendrecv\r\n';
  8129. break;
  8130. }
  8131. media += 'a=mid:' + content.attr('name') + '\r\n';
  8132. // <description><rtcp-mux/></description>
  8133. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8134. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8135. if (desc.find('rtcp-mux').length) {
  8136. media += 'a=rtcp-mux\r\n';
  8137. }
  8138. if (desc.find('encryption').length) {
  8139. desc.find('encryption>crypto').each(function () {
  8140. media += 'a=crypto:' + this.getAttribute('tag');
  8141. media += ' ' + this.getAttribute('crypto-suite');
  8142. media += ' ' + this.getAttribute('key-params');
  8143. if (this.getAttribute('session-params')) {
  8144. media += ' ' + this.getAttribute('session-params');
  8145. }
  8146. media += '\r\n';
  8147. });
  8148. }
  8149. desc.find('payload-type').each(function () {
  8150. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8151. if ($(this).find('>parameter').length) {
  8152. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8153. media += $(this).find('parameter').map(function () {
  8154. return (this.getAttribute('name')
  8155. ? (this.getAttribute('name') + '=') : '') +
  8156. this.getAttribute('value');
  8157. }).get().join('; ');
  8158. media += '\r\n';
  8159. }
  8160. // xep-0293
  8161. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8162. });
  8163. // xep-0293
  8164. media += self.rtcpFbFromJingle(desc, '*');
  8165. // xep-0294
  8166. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8167. tmp.each(function () {
  8168. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8169. });
  8170. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8171. var protocol = this.getAttribute('protocol');
  8172. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8173. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8174. (self.removeUdpCandidates && protocol === 'udp')) {
  8175. return;
  8176. }
  8177. media += SDPUtil.candidateFromJingle(this);
  8178. });
  8179. // XEP-0339 handle ssrc-group attributes
  8180. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8181. var semantics = this.getAttribute('semantics');
  8182. var ssrcs = $(this).find('>source').map(function() {
  8183. return this.getAttribute('ssrc');
  8184. }).get();
  8185. if (ssrcs.length) {
  8186. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8187. }
  8188. });
  8189. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8190. tmp.each(function () {
  8191. var ssrc = this.getAttribute('ssrc');
  8192. $(this).find('>parameter').each(function () {
  8193. var name = this.getAttribute('name');
  8194. var value = this.getAttribute('value');
  8195. value = SDPUtil.filter_special_chars(value);
  8196. media += 'a=ssrc:' + ssrc + ' ' + name;
  8197. if (value && value.length)
  8198. media += ':' + value;
  8199. media += '\r\n';
  8200. });
  8201. });
  8202. return media;
  8203. };
  8204. module.exports = SDP;
  8205. }).call(this,"/modules/xmpp/SDP.js")
  8206. },{"./SDPUtil":32,"jitsi-meet-logger":47}],31:[function(require,module,exports){
  8207. var SDPUtil = require("./SDPUtil");
  8208. function SDPDiffer(mySDP, otherSDP)
  8209. {
  8210. this.mySDP = mySDP;
  8211. this.otherSDP = otherSDP;
  8212. }
  8213. /**
  8214. * Returns map of MediaChannel that contains media contained in
  8215. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8216. */
  8217. SDPDiffer.prototype.getNewMedia = function() {
  8218. // this could be useful in Array.prototype.
  8219. function arrayEquals(array) {
  8220. // if the other array is a falsy value, return
  8221. if (!array)
  8222. return false;
  8223. // compare lengths - can save a lot of time
  8224. if (this.length != array.length)
  8225. return false;
  8226. for (var i = 0, l=this.length; i < l; i++) {
  8227. // Check if we have nested arrays
  8228. if (this[i] instanceof Array && array[i] instanceof Array) {
  8229. // recurse into the nested arrays
  8230. if (!this[i].equals(array[i]))
  8231. return false;
  8232. }
  8233. else if (this[i] != array[i]) {
  8234. // Warning - two different object instances will never be
  8235. // equal: {x:20} != {x:20}
  8236. return false;
  8237. }
  8238. }
  8239. return true;
  8240. }
  8241. var myMedias = this.mySDP.getMediaSsrcMap();
  8242. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8243. var newMedia = {};
  8244. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8245. var myMedia = myMedias[othersMediaIdx];
  8246. var othersMedia = othersMedias[othersMediaIdx];
  8247. if(!myMedia && othersMedia) {
  8248. // Add whole channel
  8249. newMedia[othersMediaIdx] = othersMedia;
  8250. return;
  8251. }
  8252. // Look for new ssrcs across the channel
  8253. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8254. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8255. // Allocate channel if we've found ssrc that doesn't exist in
  8256. // our channel
  8257. if(!newMedia[othersMediaIdx]){
  8258. newMedia[othersMediaIdx] = {
  8259. mediaindex: othersMedia.mediaindex,
  8260. mid: othersMedia.mid,
  8261. ssrcs: {},
  8262. ssrcGroups: []
  8263. };
  8264. }
  8265. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8266. }
  8267. });
  8268. // Look for new ssrc groups across the channels
  8269. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8270. // try to match the other ssrc-group with an ssrc-group of ours
  8271. var matched = false;
  8272. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8273. var mySsrcGroup = myMedia.ssrcGroups[i];
  8274. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8275. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8276. [mySsrcGroup.ssrcs])) {
  8277. matched = true;
  8278. break;
  8279. }
  8280. }
  8281. if (!matched) {
  8282. // Allocate channel if we've found an ssrc-group that doesn't
  8283. // exist in our channel
  8284. if(!newMedia[othersMediaIdx]){
  8285. newMedia[othersMediaIdx] = {
  8286. mediaindex: othersMedia.mediaindex,
  8287. mid: othersMedia.mid,
  8288. ssrcs: {},
  8289. ssrcGroups: []
  8290. };
  8291. }
  8292. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8293. }
  8294. });
  8295. });
  8296. return newMedia;
  8297. };
  8298. /**
  8299. * TODO: document!
  8300. */
  8301. SDPDiffer.prototype.toJingle = function(modify) {
  8302. var sdpMediaSsrcs = this.getNewMedia();
  8303. var modified = false;
  8304. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8305. modified = true;
  8306. var media = sdpMediaSsrcs[mediaindex];
  8307. modify.c('content', {name: media.mid});
  8308. modify.c('description',
  8309. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8310. // FIXME: not completely sure this operates on blocks and / or handles
  8311. // different ssrcs correctly
  8312. // generate sources from lines
  8313. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8314. var mediaSsrc = media.ssrcs[ssrcNum];
  8315. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8316. modify.attrs({ssrc: mediaSsrc.ssrc});
  8317. // iterate over ssrc lines
  8318. mediaSsrc.lines.forEach(function (line) {
  8319. var idx = line.indexOf(' ');
  8320. var kv = line.substr(idx + 1);
  8321. modify.c('parameter');
  8322. if (kv.indexOf(':') == -1) {
  8323. modify.attrs({ name: kv });
  8324. } else {
  8325. var nv = kv.split(':', 2);
  8326. var name = nv[0];
  8327. var value = SDPUtil.filter_special_chars(nv[1]);
  8328. modify.attrs({ name: name });
  8329. modify.attrs({ value: value });
  8330. }
  8331. modify.up(); // end of parameter
  8332. });
  8333. modify.up(); // end of source
  8334. });
  8335. // generate source groups from lines
  8336. media.ssrcGroups.forEach(function(ssrcGroup) {
  8337. if (ssrcGroup.ssrcs.length) {
  8338. modify.c('ssrc-group', {
  8339. semantics: ssrcGroup.semantics,
  8340. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8341. });
  8342. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8343. modify.c('source', { ssrc: ssrc })
  8344. .up(); // end of source
  8345. });
  8346. modify.up(); // end of ssrc-group
  8347. }
  8348. });
  8349. modify.up(); // end of description
  8350. modify.up(); // end of content
  8351. });
  8352. return modified;
  8353. };
  8354. module.exports = SDPDiffer;
  8355. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8356. (function (__filename){
  8357. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8358. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8359. SDPUtil = {
  8360. filter_special_chars: function (text) {
  8361. return text.replace(/[\\\/\{,\}\+]/g, "");
  8362. },
  8363. iceparams: function (mediadesc, sessiondesc) {
  8364. var data = null;
  8365. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8366. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8367. data = {
  8368. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8369. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8370. };
  8371. }
  8372. return data;
  8373. },
  8374. parse_iceufrag: function (line) {
  8375. return line.substring(12);
  8376. },
  8377. build_iceufrag: function (frag) {
  8378. return 'a=ice-ufrag:' + frag;
  8379. },
  8380. parse_icepwd: function (line) {
  8381. return line.substring(10);
  8382. },
  8383. build_icepwd: function (pwd) {
  8384. return 'a=ice-pwd:' + pwd;
  8385. },
  8386. parse_mid: function (line) {
  8387. return line.substring(6);
  8388. },
  8389. parse_mline: function (line) {
  8390. var parts = line.substring(2).split(' '),
  8391. data = {};
  8392. data.media = parts.shift();
  8393. data.port = parts.shift();
  8394. data.proto = parts.shift();
  8395. if (parts[parts.length - 1] === '') { // trailing whitespace
  8396. parts.pop();
  8397. }
  8398. data.fmt = parts;
  8399. return data;
  8400. },
  8401. build_mline: function (mline) {
  8402. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8403. },
  8404. parse_rtpmap: function (line) {
  8405. var parts = line.substring(9).split(' '),
  8406. data = {};
  8407. data.id = parts.shift();
  8408. parts = parts[0].split('/');
  8409. data.name = parts.shift();
  8410. data.clockrate = parts.shift();
  8411. data.channels = parts.length ? parts.shift() : '1';
  8412. return data;
  8413. },
  8414. /**
  8415. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8416. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8417. * @returns [SCTP port number, protocol, streams]
  8418. */
  8419. parse_sctpmap: function (line)
  8420. {
  8421. var parts = line.substring(10).split(' ');
  8422. var sctpPort = parts[0];
  8423. var protocol = parts[1];
  8424. // Stream count is optional
  8425. var streamCount = parts.length > 2 ? parts[2] : null;
  8426. return [sctpPort, protocol, streamCount];// SCTP port
  8427. },
  8428. build_rtpmap: function (el) {
  8429. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8430. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8431. line += '/' + el.getAttribute('channels');
  8432. }
  8433. return line;
  8434. },
  8435. parse_crypto: function (line) {
  8436. var parts = line.substring(9).split(' '),
  8437. data = {};
  8438. data.tag = parts.shift();
  8439. data['crypto-suite'] = parts.shift();
  8440. data['key-params'] = parts.shift();
  8441. if (parts.length) {
  8442. data['session-params'] = parts.join(' ');
  8443. }
  8444. return data;
  8445. },
  8446. parse_fingerprint: function (line) { // RFC 4572
  8447. var parts = line.substring(14).split(' '),
  8448. data = {};
  8449. data.hash = parts.shift();
  8450. data.fingerprint = parts.shift();
  8451. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8452. return data;
  8453. },
  8454. parse_fmtp: function (line) {
  8455. var parts = line.split(' '),
  8456. i, key, value,
  8457. data = [];
  8458. parts.shift();
  8459. parts = parts.join(' ').split(';');
  8460. for (i = 0; i < parts.length; i++) {
  8461. key = parts[i].split('=')[0];
  8462. while (key.length && key[0] == ' ') {
  8463. key = key.substring(1);
  8464. }
  8465. value = parts[i].split('=')[1];
  8466. if (key && value) {
  8467. data.push({name: key, value: value});
  8468. } else if (key) {
  8469. // rfc 4733 (DTMF) style stuff
  8470. data.push({name: '', value: key});
  8471. }
  8472. }
  8473. return data;
  8474. },
  8475. parse_icecandidate: function (line) {
  8476. var candidate = {},
  8477. elems = line.split(' ');
  8478. candidate.foundation = elems[0].substring(12);
  8479. candidate.component = elems[1];
  8480. candidate.protocol = elems[2].toLowerCase();
  8481. candidate.priority = elems[3];
  8482. candidate.ip = elems[4];
  8483. candidate.port = elems[5];
  8484. // elems[6] => "typ"
  8485. candidate.type = elems[7];
  8486. candidate.generation = 0; // default value, may be overwritten below
  8487. for (var i = 8; i < elems.length; i += 2) {
  8488. switch (elems[i]) {
  8489. case 'raddr':
  8490. candidate['rel-addr'] = elems[i + 1];
  8491. break;
  8492. case 'rport':
  8493. candidate['rel-port'] = elems[i + 1];
  8494. break;
  8495. case 'generation':
  8496. candidate.generation = elems[i + 1];
  8497. break;
  8498. case 'tcptype':
  8499. candidate.tcptype = elems[i + 1];
  8500. break;
  8501. default: // TODO
  8502. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8503. }
  8504. }
  8505. candidate.network = '1';
  8506. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8507. return candidate;
  8508. },
  8509. build_icecandidate: function (cand) {
  8510. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8511. line += ' ';
  8512. switch (cand.type) {
  8513. case 'srflx':
  8514. case 'prflx':
  8515. case 'relay':
  8516. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8517. line += 'raddr';
  8518. line += ' ';
  8519. line += cand['rel-addr'];
  8520. line += ' ';
  8521. line += 'rport';
  8522. line += ' ';
  8523. line += cand['rel-port'];
  8524. line += ' ';
  8525. }
  8526. break;
  8527. }
  8528. if (cand.hasOwnAttribute('tcptype')) {
  8529. line += 'tcptype';
  8530. line += ' ';
  8531. line += cand.tcptype;
  8532. line += ' ';
  8533. }
  8534. line += 'generation';
  8535. line += ' ';
  8536. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8537. return line;
  8538. },
  8539. parse_ssrc: function (desc) {
  8540. // proprietary mapping of a=ssrc lines
  8541. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8542. // and parse according to that
  8543. var lines = desc.split('\r\n'),
  8544. data = {};
  8545. for (var i = 0; i < lines.length; i++) {
  8546. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8547. var idx = lines[i].indexOf(' ');
  8548. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8549. }
  8550. }
  8551. return data;
  8552. },
  8553. parse_rtcpfb: function (line) {
  8554. var parts = line.substr(10).split(' ');
  8555. var data = {};
  8556. data.pt = parts.shift();
  8557. data.type = parts.shift();
  8558. data.params = parts;
  8559. return data;
  8560. },
  8561. parse_extmap: function (line) {
  8562. var parts = line.substr(9).split(' ');
  8563. var data = {};
  8564. data.value = parts.shift();
  8565. if (data.value.indexOf('/') != -1) {
  8566. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8567. data.value = data.value.substr(0, data.value.indexOf('/'));
  8568. } else {
  8569. data.direction = 'both';
  8570. }
  8571. data.uri = parts.shift();
  8572. data.params = parts;
  8573. return data;
  8574. },
  8575. find_line: function (haystack, needle, sessionpart) {
  8576. var lines = haystack.split('\r\n');
  8577. for (var i = 0; i < lines.length; i++) {
  8578. if (lines[i].substring(0, needle.length) == needle) {
  8579. return lines[i];
  8580. }
  8581. }
  8582. if (!sessionpart) {
  8583. return false;
  8584. }
  8585. // search session part
  8586. lines = sessionpart.split('\r\n');
  8587. for (var j = 0; j < lines.length; j++) {
  8588. if (lines[j].substring(0, needle.length) == needle) {
  8589. return lines[j];
  8590. }
  8591. }
  8592. return false;
  8593. },
  8594. find_lines: function (haystack, needle, sessionpart) {
  8595. var lines = haystack.split('\r\n'),
  8596. needles = [];
  8597. for (var i = 0; i < lines.length; i++) {
  8598. if (lines[i].substring(0, needle.length) == needle)
  8599. needles.push(lines[i]);
  8600. }
  8601. if (needles.length || !sessionpart) {
  8602. return needles;
  8603. }
  8604. // search session part
  8605. lines = sessionpart.split('\r\n');
  8606. for (var j = 0; j < lines.length; j++) {
  8607. if (lines[j].substring(0, needle.length) == needle) {
  8608. needles.push(lines[j]);
  8609. }
  8610. }
  8611. return needles;
  8612. },
  8613. candidateToJingle: function (line) {
  8614. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8615. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8616. if (line.indexOf('candidate:') === 0) {
  8617. line = 'a=' + line;
  8618. } else if (line.substring(0, 12) != 'a=candidate:') {
  8619. logger.log('parseCandidate called with a line that is not a candidate line');
  8620. logger.log(line);
  8621. return null;
  8622. }
  8623. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8624. line = line.substring(0, line.length - 2);
  8625. var candidate = {},
  8626. elems = line.split(' '),
  8627. i;
  8628. if (elems[6] != 'typ') {
  8629. logger.log('did not find typ in the right place');
  8630. logger.log(line);
  8631. return null;
  8632. }
  8633. candidate.foundation = elems[0].substring(12);
  8634. candidate.component = elems[1];
  8635. candidate.protocol = elems[2].toLowerCase();
  8636. candidate.priority = elems[3];
  8637. candidate.ip = elems[4];
  8638. candidate.port = elems[5];
  8639. // elems[6] => "typ"
  8640. candidate.type = elems[7];
  8641. candidate.generation = '0'; // default, may be overwritten below
  8642. for (i = 8; i < elems.length; i += 2) {
  8643. switch (elems[i]) {
  8644. case 'raddr':
  8645. candidate['rel-addr'] = elems[i + 1];
  8646. break;
  8647. case 'rport':
  8648. candidate['rel-port'] = elems[i + 1];
  8649. break;
  8650. case 'generation':
  8651. candidate.generation = elems[i + 1];
  8652. break;
  8653. case 'tcptype':
  8654. candidate.tcptype = elems[i + 1];
  8655. break;
  8656. default: // TODO
  8657. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8658. }
  8659. }
  8660. candidate.network = '1';
  8661. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8662. return candidate;
  8663. },
  8664. candidateFromJingle: function (cand) {
  8665. var line = 'a=candidate:';
  8666. line += cand.getAttribute('foundation');
  8667. line += ' ';
  8668. line += cand.getAttribute('component');
  8669. line += ' ';
  8670. var protocol = cand.getAttribute('protocol');
  8671. // use tcp candidates for FF
  8672. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8673. protocol = 'tcp';
  8674. }
  8675. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  8676. line += ' ';
  8677. line += cand.getAttribute('priority');
  8678. line += ' ';
  8679. line += cand.getAttribute('ip');
  8680. line += ' ';
  8681. line += cand.getAttribute('port');
  8682. line += ' ';
  8683. line += 'typ';
  8684. line += ' ' + cand.getAttribute('type');
  8685. line += ' ';
  8686. switch (cand.getAttribute('type')) {
  8687. case 'srflx':
  8688. case 'prflx':
  8689. case 'relay':
  8690. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8691. line += 'raddr';
  8692. line += ' ';
  8693. line += cand.getAttribute('rel-addr');
  8694. line += ' ';
  8695. line += 'rport';
  8696. line += ' ';
  8697. line += cand.getAttribute('rel-port');
  8698. line += ' ';
  8699. }
  8700. break;
  8701. }
  8702. if (protocol.toLowerCase() == 'tcp') {
  8703. line += 'tcptype';
  8704. line += ' ';
  8705. line += cand.getAttribute('tcptype');
  8706. line += ' ';
  8707. }
  8708. line += 'generation';
  8709. line += ' ';
  8710. line += cand.getAttribute('generation') || '0';
  8711. return line + '\r\n';
  8712. }
  8713. };
  8714. module.exports = SDPUtil;
  8715. }).call(this,"/modules/xmpp/SDPUtil.js")
  8716. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],33:[function(require,module,exports){
  8717. (function (__filename){
  8718. /* global $ */
  8719. var RTC = require('../RTC/RTC');
  8720. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8721. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8722. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8723. var SSRCReplacement = require("./LocalSSRCReplacement");
  8724. function TraceablePeerConnection(ice_config, constraints, session) {
  8725. var self = this;
  8726. this.session = session;
  8727. var RTCPeerConnectionType = null;
  8728. if (RTCBrowserType.isFirefox()) {
  8729. RTCPeerConnectionType = mozRTCPeerConnection;
  8730. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8731. RTCPeerConnectionType = RTCPeerConnection;
  8732. } else {
  8733. RTCPeerConnectionType = webkitRTCPeerConnection;
  8734. }
  8735. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8736. this.updateLog = [];
  8737. this.stats = {};
  8738. this.statsinterval = null;
  8739. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8740. var Interop = require('sdp-interop').Interop;
  8741. this.interop = new Interop();
  8742. var Simulcast = require('sdp-simulcast');
  8743. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  8744. // override as desired
  8745. this.trace = function (what, info) {
  8746. /*logger.warn('WTRACE', what, info);
  8747. if (info && RTCBrowserType.isIExplorer()) {
  8748. if (info.length > 1024) {
  8749. logger.warn('WTRACE', what, info.substr(1024));
  8750. }
  8751. if (info.length > 2048) {
  8752. logger.warn('WTRACE', what, info.substr(2048));
  8753. }
  8754. }*/
  8755. self.updateLog.push({
  8756. time: new Date(),
  8757. type: what,
  8758. value: info || ""
  8759. });
  8760. };
  8761. this.onicecandidate = null;
  8762. this.peerconnection.onicecandidate = function (event) {
  8763. // FIXME: this causes stack overflow with Temasys Plugin
  8764. if (!RTCBrowserType.isTemasysPluginUsed())
  8765. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8766. if (self.onicecandidate !== null) {
  8767. self.onicecandidate(event);
  8768. }
  8769. };
  8770. this.onaddstream = null;
  8771. this.peerconnection.onaddstream = function (event) {
  8772. self.trace('onaddstream', event.stream.id);
  8773. if (self.onaddstream !== null) {
  8774. self.onaddstream(event);
  8775. }
  8776. };
  8777. this.onremovestream = null;
  8778. this.peerconnection.onremovestream = function (event) {
  8779. self.trace('onremovestream', event.stream.id);
  8780. if (self.onremovestream !== null) {
  8781. self.onremovestream(event);
  8782. }
  8783. };
  8784. this.onsignalingstatechange = null;
  8785. this.peerconnection.onsignalingstatechange = function (event) {
  8786. self.trace('onsignalingstatechange', self.signalingState);
  8787. if (self.onsignalingstatechange !== null) {
  8788. self.onsignalingstatechange(event);
  8789. }
  8790. };
  8791. this.oniceconnectionstatechange = null;
  8792. this.peerconnection.oniceconnectionstatechange = function (event) {
  8793. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8794. if (self.oniceconnectionstatechange !== null) {
  8795. self.oniceconnectionstatechange(event);
  8796. }
  8797. };
  8798. this.onnegotiationneeded = null;
  8799. this.peerconnection.onnegotiationneeded = function (event) {
  8800. self.trace('onnegotiationneeded');
  8801. if (self.onnegotiationneeded !== null) {
  8802. self.onnegotiationneeded(event);
  8803. }
  8804. };
  8805. self.ondatachannel = null;
  8806. this.peerconnection.ondatachannel = function (event) {
  8807. self.trace('ondatachannel', event);
  8808. if (self.ondatachannel !== null) {
  8809. self.ondatachannel(event);
  8810. }
  8811. };
  8812. // XXX: do all non-firefox browsers which we support also support this?
  8813. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8814. this.statsinterval = window.setInterval(function() {
  8815. self.peerconnection.getStats(function(stats) {
  8816. var results = stats.result();
  8817. var now = new Date();
  8818. for (var i = 0; i < results.length; ++i) {
  8819. results[i].names().forEach(function (name) {
  8820. var id = results[i].id + '-' + name;
  8821. if (!self.stats[id]) {
  8822. self.stats[id] = {
  8823. startTime: now,
  8824. endTime: now,
  8825. values: [],
  8826. times: []
  8827. };
  8828. }
  8829. self.stats[id].values.push(results[i].stat(name));
  8830. self.stats[id].times.push(now.getTime());
  8831. if (self.stats[id].values.length > self.maxstats) {
  8832. self.stats[id].values.shift();
  8833. self.stats[id].times.shift();
  8834. }
  8835. self.stats[id].endTime = now;
  8836. });
  8837. }
  8838. });
  8839. }, 1000);
  8840. }
  8841. }
  8842. /**
  8843. * Returns a string representation of a SessionDescription object.
  8844. */
  8845. var dumpSDP = function(description) {
  8846. if (typeof description === 'undefined' || description == null) {
  8847. return '';
  8848. }
  8849. return 'type: ' + description.type + '\r\n' + description.sdp;
  8850. };
  8851. /**
  8852. * Takes a SessionDescription object and returns a "normalized" version.
  8853. * Currently it only takes care of ordering the a=ssrc lines.
  8854. */
  8855. var normalizePlanB = function(desc) {
  8856. if (typeof desc !== 'object' || desc === null ||
  8857. typeof desc.sdp !== 'string') {
  8858. logger.warn('An empty description was passed as an argument.');
  8859. return desc;
  8860. }
  8861. var transform = require('sdp-transform');
  8862. var session = transform.parse(desc.sdp);
  8863. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8864. Array.isArray(session.media)) {
  8865. session.media.forEach(function (mLine) {
  8866. // Chrome appears to be picky about the order in which a=ssrc lines
  8867. // are listed in an m-line when rtx is enabled (and thus there are
  8868. // a=ssrc-group lines with FID semantics). Specifically if we have
  8869. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8870. // the "a=ssrc:S1" lines, SRD fails.
  8871. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8872. // first.
  8873. var firstSsrcs = [];
  8874. var newSsrcLines = [];
  8875. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8876. mLine.ssrcGroups.forEach(function (group) {
  8877. if (typeof group.semantics !== 'undefined' &&
  8878. group.semantics === 'FID') {
  8879. if (typeof group.ssrcs !== 'undefined') {
  8880. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8881. }
  8882. }
  8883. });
  8884. }
  8885. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8886. var i;
  8887. for (i = 0; i<mLine.ssrcs.length; i++){
  8888. if (typeof mLine.ssrcs[i] === 'object'
  8889. && typeof mLine.ssrcs[i].id !== 'undefined'
  8890. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  8891. newSsrcLines.push(mLine.ssrcs[i]);
  8892. delete mLine.ssrcs[i];
  8893. }
  8894. }
  8895. for (i = 0; i<mLine.ssrcs.length; i++){
  8896. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8897. newSsrcLines.push(mLine.ssrcs[i]);
  8898. }
  8899. }
  8900. mLine.ssrcs = newSsrcLines;
  8901. }
  8902. });
  8903. }
  8904. var resStr = transform.write(session);
  8905. return new RTCSessionDescription({
  8906. type: desc.type,
  8907. sdp: resStr
  8908. });
  8909. };
  8910. var getters = {
  8911. signalingState: function () {
  8912. return this.peerconnection.signalingState;
  8913. },
  8914. iceConnectionState: function () {
  8915. return this.peerconnection.iceConnectionState;
  8916. },
  8917. localDescription: function() {
  8918. var desc = this.peerconnection.localDescription;
  8919. // FIXME this should probably be after the Unified Plan -> Plan B
  8920. // transformation.
  8921. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8922. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8923. // if we're running on FF, transform to Plan B first.
  8924. if (RTCBrowserType.usesUnifiedPlan()) {
  8925. desc = this.interop.toPlanB(desc);
  8926. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8927. }
  8928. return desc;
  8929. },
  8930. remoteDescription: function() {
  8931. var desc = this.peerconnection.remoteDescription;
  8932. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8933. // if we're running on FF, transform to Plan B first.
  8934. if (RTCBrowserType.usesUnifiedPlan()) {
  8935. desc = this.interop.toPlanB(desc);
  8936. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8937. }
  8938. return desc;
  8939. }
  8940. };
  8941. Object.keys(getters).forEach(function (prop) {
  8942. Object.defineProperty(
  8943. TraceablePeerConnection.prototype,
  8944. prop, {
  8945. get: getters[prop]
  8946. }
  8947. );
  8948. });
  8949. TraceablePeerConnection.prototype.addStream = function (stream) {
  8950. this.trace('addStream', stream.id);
  8951. try
  8952. {
  8953. this.peerconnection.addStream(stream);
  8954. }
  8955. catch (e)
  8956. {
  8957. logger.error(e);
  8958. }
  8959. };
  8960. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8961. this.trace('removeStream', stream.id);
  8962. if(stopStreams) {
  8963. RTC.stopMediaStream(stream);
  8964. }
  8965. try {
  8966. // FF doesn't support this yet.
  8967. if (this.peerconnection.removeStream)
  8968. this.peerconnection.removeStream(stream);
  8969. } catch (e) {
  8970. logger.error(e);
  8971. }
  8972. };
  8973. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8974. this.trace('createDataChannel', label, opts);
  8975. return this.peerconnection.createDataChannel(label, opts);
  8976. };
  8977. TraceablePeerConnection.prototype.setLocalDescription
  8978. = function (description, successCallback, failureCallback) {
  8979. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8980. // if we're running on FF, transform to Plan A first.
  8981. if (RTCBrowserType.usesUnifiedPlan()) {
  8982. description = this.interop.toUnifiedPlan(description);
  8983. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8984. }
  8985. var self = this;
  8986. this.peerconnection.setLocalDescription(description,
  8987. function () {
  8988. self.trace('setLocalDescriptionOnSuccess');
  8989. successCallback();
  8990. },
  8991. function (err) {
  8992. self.trace('setLocalDescriptionOnFailure', err);
  8993. failureCallback(err);
  8994. }
  8995. );
  8996. /*
  8997. if (this.statsinterval === null && this.maxstats > 0) {
  8998. // start gathering stats
  8999. }
  9000. */
  9001. };
  9002. TraceablePeerConnection.prototype.setRemoteDescription
  9003. = function (description, successCallback, failureCallback) {
  9004. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9005. // TODO the focus should squeze or explode the remote simulcast
  9006. description = this.simulcast.mungeRemoteDescription(description);
  9007. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9008. // if we're running on FF, transform to Plan A first.
  9009. if (RTCBrowserType.usesUnifiedPlan()) {
  9010. description = this.interop.toUnifiedPlan(description);
  9011. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9012. }
  9013. if (RTCBrowserType.usesPlanB()) {
  9014. description = normalizePlanB(description);
  9015. }
  9016. var self = this;
  9017. this.peerconnection.setRemoteDescription(description,
  9018. function () {
  9019. self.trace('setRemoteDescriptionOnSuccess');
  9020. successCallback();
  9021. },
  9022. function (err) {
  9023. self.trace('setRemoteDescriptionOnFailure', err);
  9024. failureCallback(err);
  9025. }
  9026. );
  9027. /*
  9028. if (this.statsinterval === null && this.maxstats > 0) {
  9029. // start gathering stats
  9030. }
  9031. */
  9032. };
  9033. TraceablePeerConnection.prototype.close = function () {
  9034. this.trace('stop');
  9035. if (this.statsinterval !== null) {
  9036. window.clearInterval(this.statsinterval);
  9037. this.statsinterval = null;
  9038. }
  9039. this.peerconnection.close();
  9040. };
  9041. TraceablePeerConnection.prototype.createOffer
  9042. = function (successCallback, failureCallback, constraints) {
  9043. var self = this;
  9044. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9045. this.peerconnection.createOffer(
  9046. function (offer) {
  9047. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9048. // NOTE this is not tested because in meet the focus generates the
  9049. // offer.
  9050. // if we're running on FF, transform to Plan B first.
  9051. if (RTCBrowserType.usesUnifiedPlan()) {
  9052. offer = self.interop.toPlanB(offer);
  9053. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9054. }
  9055. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9056. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9057. offer = self.simulcast.mungeLocalDescription(offer);
  9058. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9059. }
  9060. successCallback(offer);
  9061. },
  9062. function(err) {
  9063. self.trace('createOfferOnFailure', err);
  9064. failureCallback(err);
  9065. },
  9066. constraints
  9067. );
  9068. };
  9069. TraceablePeerConnection.prototype.createAnswer
  9070. = function (successCallback, failureCallback, constraints) {
  9071. var self = this;
  9072. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9073. this.peerconnection.createAnswer(
  9074. function (answer) {
  9075. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9076. // if we're running on FF, transform to Plan A first.
  9077. if (RTCBrowserType.usesUnifiedPlan()) {
  9078. answer = self.interop.toPlanB(answer);
  9079. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9080. }
  9081. // munge local video SSRC
  9082. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9083. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9084. answer = self.simulcast.mungeLocalDescription(answer);
  9085. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9086. }
  9087. successCallback(answer);
  9088. },
  9089. function(err) {
  9090. self.trace('createAnswerOnFailure', err);
  9091. failureCallback(err);
  9092. },
  9093. constraints
  9094. );
  9095. };
  9096. TraceablePeerConnection.prototype.addIceCandidate
  9097. = function (candidate, successCallback, failureCallback) {
  9098. //var self = this;
  9099. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9100. this.peerconnection.addIceCandidate(candidate);
  9101. /* maybe later
  9102. this.peerconnection.addIceCandidate(candidate,
  9103. function () {
  9104. self.trace('addIceCandidateOnSuccess');
  9105. successCallback();
  9106. },
  9107. function (err) {
  9108. self.trace('addIceCandidateOnFailure', err);
  9109. failureCallback(err);
  9110. }
  9111. );
  9112. */
  9113. };
  9114. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9115. // TODO: Is this the correct way to handle Opera, Temasys?
  9116. if (RTCBrowserType.isFirefox()) {
  9117. // ignore for now...
  9118. if(!errback)
  9119. errback = function () {};
  9120. this.peerconnection.getStats(null, callback, errback);
  9121. } else {
  9122. this.peerconnection.getStats(callback);
  9123. }
  9124. };
  9125. module.exports = TraceablePeerConnection;
  9126. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9127. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":47,"sdp-interop":65,"sdp-simulcast":68,"sdp-transform":75}],34:[function(require,module,exports){
  9128. (function (__filename){
  9129. /* global $, $iq, APP, config, messageHandler,
  9130. roomName, sessionTerminated, Strophe, Util */
  9131. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9132. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9133. var Settings = require("../settings/Settings");
  9134. var AuthenticationEvents
  9135. = require("../../service/authentication/AuthenticationEvents");
  9136. function createExpBackoffTimer(step) {
  9137. var count = 1;
  9138. return function (reset) {
  9139. // Reset call
  9140. if (reset) {
  9141. count = 1;
  9142. return;
  9143. }
  9144. // Calculate next timeout
  9145. var timeout = Math.pow(2, count - 1);
  9146. count += 1;
  9147. return timeout * step;
  9148. };
  9149. }
  9150. function Moderator(roomName, xmpp, emitter) {
  9151. this.roomName = roomName;
  9152. this.xmppService = xmpp;
  9153. this.getNextTimeout = createExpBackoffTimer(1000);
  9154. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9155. // External authentication stuff
  9156. this.externalAuthEnabled = false;
  9157. this.settings = new Settings(roomName);
  9158. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9159. // it will be enabled automatically if focus detects the component through
  9160. // service discovery.
  9161. this.sipGatewayEnabled =
  9162. this.xmppService.options.hosts.call_control !== undefined;
  9163. this.eventEmitter = emitter;
  9164. this.connection = this.xmppService.connection;
  9165. this.focusUserJid;
  9166. //FIXME:
  9167. // Message listener that talks to POPUP window
  9168. function listener(event) {
  9169. if (event.data && event.data.sessionId) {
  9170. if (event.origin !== window.location.origin) {
  9171. logger.warn("Ignoring sessionId from different origin: " +
  9172. event.origin);
  9173. return;
  9174. }
  9175. localStorage.setItem('sessionId', event.data.sessionId);
  9176. // After popup is closed we will authenticate
  9177. }
  9178. }
  9179. // Register
  9180. if (window.addEventListener) {
  9181. window.addEventListener("message", listener, false);
  9182. } else {
  9183. window.attachEvent("onmessage", listener);
  9184. }
  9185. }
  9186. Moderator.prototype.isExternalAuthEnabled = function () {
  9187. return this.externalAuthEnabled;
  9188. };
  9189. Moderator.prototype.isSipGatewayEnabled = function () {
  9190. return this.sipGatewayEnabled;
  9191. };
  9192. Moderator.prototype.onMucMemberLeft = function (jid) {
  9193. logger.info("Someone left is it focus ? " + jid);
  9194. var resource = Strophe.getResourceFromJid(jid);
  9195. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9196. logger.info(
  9197. "Focus has left the room - leaving conference");
  9198. //hangUp();
  9199. // We'd rather reload to have everything re-initialized
  9200. //FIXME: show some message before reload
  9201. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9202. }
  9203. };
  9204. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9205. if (!this.focusUserJid) {
  9206. this.focusUserJid = focusJid;
  9207. logger.info("Focus jid set to: " + this.focusUserJid);
  9208. }
  9209. };
  9210. Moderator.prototype.getFocusUserJid = function () {
  9211. return this.focusUserJid;
  9212. };
  9213. Moderator.prototype.getFocusComponent = function () {
  9214. // Get focus component address
  9215. var focusComponent = this.xmppService.options.hosts.focus;
  9216. // If not specified use default: 'focus.domain'
  9217. if (!focusComponent) {
  9218. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9219. }
  9220. return focusComponent;
  9221. };
  9222. Moderator.prototype.createConferenceIq = function () {
  9223. // Generate create conference IQ
  9224. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9225. // Session Id used for authentication
  9226. var sessionId = localStorage.getItem('sessionId');
  9227. var machineUID = this.settings.getSettings().uid;
  9228. logger.info(
  9229. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9230. elem.c('conference', {
  9231. xmlns: 'http://jitsi.org/protocol/focus',
  9232. room: this.roomName,
  9233. 'machine-uid': machineUID
  9234. });
  9235. if (sessionId) {
  9236. elem.attrs({ 'session-id': sessionId});
  9237. }
  9238. if (this.xmppService.options.hosts.bridge !== undefined) {
  9239. elem.c(
  9240. 'property', {
  9241. name: 'bridge',
  9242. value: this.xmppService.options.hosts.bridge
  9243. }).up();
  9244. }
  9245. if (this.xmppService.options.enforcedBridge !== undefined) {
  9246. elem.c(
  9247. 'property', {
  9248. name: 'enforcedBridge',
  9249. value: this.xmppService.options.enforcedBridge
  9250. }).up();
  9251. }
  9252. // Tell the focus we have Jigasi configured
  9253. if (this.xmppService.options.hosts.call_control !== undefined) {
  9254. elem.c(
  9255. 'property', {
  9256. name: 'call_control',
  9257. value: this.xmppService.options.hosts.call_control
  9258. }).up();
  9259. }
  9260. if (this.xmppService.options.channelLastN !== undefined) {
  9261. elem.c(
  9262. 'property', {
  9263. name: 'channelLastN',
  9264. value: this.xmppService.options.channelLastN
  9265. }).up();
  9266. }
  9267. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9268. elem.c(
  9269. 'property', {
  9270. name: 'adaptiveLastN',
  9271. value: this.xmppService.options.adaptiveLastN
  9272. }).up();
  9273. }
  9274. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9275. elem.c(
  9276. 'property', {
  9277. name: 'adaptiveSimulcast',
  9278. value: this.xmppService.options.adaptiveSimulcast
  9279. }).up();
  9280. }
  9281. if (this.xmppService.options.openSctp !== undefined) {
  9282. elem.c(
  9283. 'property', {
  9284. name: 'openSctp',
  9285. value: this.xmppService.options.openSctp
  9286. }).up();
  9287. }
  9288. if (this.xmppService.options.startAudioMuted !== undefined)
  9289. {
  9290. elem.c(
  9291. 'property', {
  9292. name: 'startAudioMuted',
  9293. value: this.xmppService.options.startAudioMuted
  9294. }).up();
  9295. }
  9296. if (this.xmppService.options.startVideoMuted !== undefined)
  9297. {
  9298. elem.c(
  9299. 'property', {
  9300. name: 'startVideoMuted',
  9301. value: this.xmppService.options.startVideoMuted
  9302. }).up();
  9303. }
  9304. elem.c(
  9305. 'property', {
  9306. name: 'simulcastMode',
  9307. value: 'rewriting'
  9308. }).up();
  9309. elem.up();
  9310. return elem;
  9311. };
  9312. Moderator.prototype.parseSessionId = function (resultIq) {
  9313. var sessionId = $(resultIq).find('conference').attr('session-id');
  9314. if (sessionId) {
  9315. logger.info('Received sessionId: ' + sessionId);
  9316. localStorage.setItem('sessionId', sessionId);
  9317. }
  9318. };
  9319. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9320. this.setFocusUserJid(
  9321. $(resultIq).find('conference').attr('focusjid'));
  9322. var authenticationEnabled
  9323. = $(resultIq).find(
  9324. '>conference>property' +
  9325. '[name=\'authentication\'][value=\'true\']').length > 0;
  9326. logger.info("Authentication enabled: " + authenticationEnabled);
  9327. this.externalAuthEnabled = $(resultIq).find(
  9328. '>conference>property' +
  9329. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9330. console.info(
  9331. 'External authentication enabled: ' + this.externalAuthEnabled);
  9332. if (!this.externalAuthEnabled) {
  9333. // We expect to receive sessionId in 'internal' authentication mode
  9334. this.parseSessionId(resultIq);
  9335. }
  9336. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9337. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9338. authenticationEnabled, authIdentity);
  9339. // Check if focus has auto-detected Jigasi component(this will be also
  9340. // included if we have passed our host from the config)
  9341. if ($(resultIq).find(
  9342. '>conference>property' +
  9343. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9344. this.sipGatewayEnabled = true;
  9345. }
  9346. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9347. };
  9348. // FIXME = we need to show the fact that we're waiting for the focus
  9349. // to the user(or that focus is not available)
  9350. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9351. // Try to use focus user JID from the config
  9352. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9353. // Send create conference IQ
  9354. var iq = this.createConferenceIq();
  9355. var self = this;
  9356. this.connection.sendIQ(
  9357. iq,
  9358. function (result) {
  9359. // Setup config options
  9360. self.parseConfigOptions(result);
  9361. if ('true' === $(result).find('conference').attr('ready')) {
  9362. // Reset both timers
  9363. self.getNextTimeout(true);
  9364. self.getNextErrorTimeout(true);
  9365. // Exec callback
  9366. callback();
  9367. } else {
  9368. var waitMs = self.getNextTimeout();
  9369. logger.info("Waiting for the focus... " + waitMs);
  9370. // Reset error timeout
  9371. self.getNextErrorTimeout(true);
  9372. window.setTimeout(
  9373. function () {
  9374. self.allocateConferenceFocus(callback);
  9375. }, waitMs);
  9376. }
  9377. },
  9378. function (error) {
  9379. // Invalid session ? remove and try again
  9380. // without session ID to get a new one
  9381. var invalidSession
  9382. = $(error).find('>error>session-invalid').length;
  9383. if (invalidSession) {
  9384. logger.info("Session expired! - removing");
  9385. localStorage.removeItem("sessionId");
  9386. }
  9387. if ($(error).find('>error>graceful-shutdown').length) {
  9388. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9389. return;
  9390. }
  9391. // Check for error returned by the reservation system
  9392. var reservationErr = $(error).find('>error>reservation-error');
  9393. if (reservationErr.length) {
  9394. // Trigger error event
  9395. var errorCode = reservationErr.attr('error-code');
  9396. var errorMsg;
  9397. if ($(error).find('>error>text')) {
  9398. errorMsg = $(error).find('>error>text').text();
  9399. }
  9400. self.eventEmitter.emit(
  9401. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9402. return;
  9403. }
  9404. // Not authorized to create new room
  9405. if ($(error).find('>error>not-authorized').length) {
  9406. logger.warn("Unauthorized to start the conference", error);
  9407. var toDomain
  9408. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9409. if (toDomain !==
  9410. this.xmppService.options.hosts.anonymousdomain) {
  9411. //FIXME: "is external" should come either from
  9412. // the focus or config.js
  9413. self.externalAuthEnabled = true;
  9414. }
  9415. self.eventEmitter.emit(
  9416. XMPPEvents.AUTHENTICATION_REQUIRED,
  9417. function () {
  9418. self.allocateConferenceFocus(
  9419. callback);
  9420. });
  9421. return;
  9422. }
  9423. var waitMs = self.getNextErrorTimeout();
  9424. logger.error("Focus error, retry after " + waitMs, error);
  9425. // Show message
  9426. var focusComponent = self.getFocusComponent();
  9427. var retrySec = waitMs / 1000;
  9428. //FIXME: message is duplicated ?
  9429. // Do not show in case of session invalid
  9430. // which means just a retry
  9431. if (!invalidSession) {
  9432. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9433. focusComponent, retrySec);
  9434. }
  9435. // Reset response timeout
  9436. self.getNextTimeout(true);
  9437. window.setTimeout(
  9438. function () {
  9439. self.allocateConferenceFocus(callback);
  9440. }, waitMs);
  9441. }
  9442. );
  9443. };
  9444. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  9445. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9446. iq.c('login-url', {
  9447. xmlns: 'http://jitsi.org/protocol/focus',
  9448. room: this.roomName,
  9449. 'machine-uid': this.settings.getSettings().uid
  9450. });
  9451. this.connection.sendIQ(
  9452. iq,
  9453. function (result) {
  9454. var url = $(result).find('login-url').attr('url');
  9455. url = url = decodeURIComponent(url);
  9456. if (url) {
  9457. logger.info("Got auth url: " + url);
  9458. urlCallback(url);
  9459. } else {
  9460. logger.error(
  9461. "Failed to get auth url from the focus", result);
  9462. failureCallback(result);
  9463. }
  9464. },
  9465. function (error) {
  9466. logger.error("Get auth url error", error);
  9467. failureCallback(error);
  9468. }
  9469. );
  9470. };
  9471. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  9472. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9473. iq.c('login-url', {
  9474. xmlns: 'http://jitsi.org/protocol/focus',
  9475. room: this.roomName,
  9476. 'machine-uid': this.settings.getSettings().uid,
  9477. popup: true
  9478. });
  9479. this.connection.sendIQ(
  9480. iq,
  9481. function (result) {
  9482. var url = $(result).find('login-url').attr('url');
  9483. url = url = decodeURIComponent(url);
  9484. if (url) {
  9485. logger.info("Got POPUP auth url: " + url);
  9486. urlCallback(url);
  9487. } else {
  9488. logger.error(
  9489. "Failed to get POPUP auth url from the focus", result);
  9490. failureCallback(result);
  9491. }
  9492. },
  9493. function (error) {
  9494. logger.error('Get POPUP auth url error', error);
  9495. failureCallback(error);
  9496. }
  9497. );
  9498. };
  9499. Moderator.prototype.logout = function (callback) {
  9500. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9501. var sessionId = localStorage.getItem('sessionId');
  9502. if (!sessionId) {
  9503. callback();
  9504. return;
  9505. }
  9506. iq.c('logout', {
  9507. xmlns: 'http://jitsi.org/protocol/focus',
  9508. 'session-id': sessionId
  9509. });
  9510. this.connection.sendIQ(
  9511. iq,
  9512. function (result) {
  9513. var logoutUrl = $(result).find('logout').attr('logout-url');
  9514. if (logoutUrl) {
  9515. logoutUrl = decodeURIComponent(logoutUrl);
  9516. }
  9517. logger.info("Log out OK, url: " + logoutUrl, result);
  9518. localStorage.removeItem('sessionId');
  9519. callback(logoutUrl);
  9520. },
  9521. function (error) {
  9522. logger.error("Logout error", error);
  9523. }
  9524. );
  9525. };
  9526. module.exports = Moderator;
  9527. }).call(this,"/modules/xmpp/moderator.js")
  9528. },{"../../service/authentication/AuthenticationEvents":81,"../../service/xmpp/XMPPEvents":85,"../settings/Settings":21,"jitsi-meet-logger":47}],35:[function(require,module,exports){
  9529. (function (__filename){
  9530. /* jshint -W117 */
  9531. /* a simple MUC connection plugin
  9532. * can only handle a single MUC room
  9533. */
  9534. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9535. var ChatRoom = require("./ChatRoom");
  9536. module.exports = function(XMPP) {
  9537. Strophe.addConnectionPlugin('emuc', {
  9538. connection: null,
  9539. rooms: {},//map with the rooms
  9540. init: function (conn) {
  9541. this.connection = conn;
  9542. // add handlers (just once)
  9543. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9544. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9545. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9546. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9547. },
  9548. createRoom: function (jid, password, options) {
  9549. var roomJid = Strophe.getBareJidFromJid(jid);
  9550. if (this.rooms[roomJid]) {
  9551. logger.error("You are already in the room!");
  9552. return;
  9553. }
  9554. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9555. return this.rooms[roomJid];
  9556. },
  9557. doLeave: function (jid) {
  9558. this.rooms[jid].doLeave();
  9559. delete this.rooms[jid];
  9560. },
  9561. onPresence: function (pres) {
  9562. var from = pres.getAttribute('from');
  9563. // What is this for? A workaround for something?
  9564. if (pres.getAttribute('type')) {
  9565. return true;
  9566. }
  9567. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9568. if(!room)
  9569. return;
  9570. // Parse status.
  9571. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9572. room.createNonAnonymousRoom();
  9573. }
  9574. room.onPresence(pres);
  9575. return true;
  9576. },
  9577. onPresenceUnavailable: function (pres) {
  9578. var from = pres.getAttribute('from');
  9579. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9580. if(!room)
  9581. return;
  9582. room.onPresenceUnavailable(pres, from);
  9583. return true;
  9584. },
  9585. onPresenceError: function (pres) {
  9586. var from = pres.getAttribute('from');
  9587. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9588. if(!room)
  9589. return;
  9590. room.onPresenceError(pres, from);
  9591. return true;
  9592. },
  9593. onMessage: function (msg) {
  9594. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9595. var from = msg.getAttribute('from');
  9596. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9597. if(!room)
  9598. return;
  9599. room.onMessage(msg, from);
  9600. return true;
  9601. },
  9602. setJingleSession: function (from, session) {
  9603. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9604. if(!room)
  9605. return;
  9606. room.setJingleSession(session);
  9607. }
  9608. });
  9609. };
  9610. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9611. },{"./ChatRoom":26,"jitsi-meet-logger":47}],36:[function(require,module,exports){
  9612. (function (__filename){
  9613. /* jshint -W117 */
  9614. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9615. var JingleSession = require("./JingleSessionPC");
  9616. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9617. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9618. module.exports = function(XMPP, eventEmitter) {
  9619. Strophe.addConnectionPlugin('jingle', {
  9620. connection: null,
  9621. sessions: {},
  9622. jid2session: {},
  9623. ice_config: {iceServers: []},
  9624. media_constraints: {
  9625. mandatory: {
  9626. 'OfferToReceiveAudio': true,
  9627. 'OfferToReceiveVideo': true
  9628. }
  9629. // MozDontOfferDataChannel: true when this is firefox
  9630. },
  9631. init: function (conn) {
  9632. this.connection = conn;
  9633. if (this.connection.disco) {
  9634. // http://xmpp.org/extensions/xep-0167.html#support
  9635. // http://xmpp.org/extensions/xep-0176.html#support
  9636. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9637. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9638. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9639. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9640. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9641. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9642. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9643. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9644. || RTCBrowserType.isTemasysPluginUsed()) {
  9645. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9646. }
  9647. // this is dealt with by SDP O/A so we don't need to announce this
  9648. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9649. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9650. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9651. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9652. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9653. }
  9654. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9655. },
  9656. onJingle: function (iq) {
  9657. var sid = $(iq).find('jingle').attr('sid');
  9658. var action = $(iq).find('jingle').attr('action');
  9659. var fromJid = iq.getAttribute('from');
  9660. // send ack first
  9661. var ack = $iq({type: 'result',
  9662. to: fromJid,
  9663. id: iq.getAttribute('id')
  9664. });
  9665. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9666. var sess = this.sessions[sid];
  9667. if ('session-initiate' != action) {
  9668. if (sess === null) {
  9669. ack.type = 'error';
  9670. ack.c('error', {type: 'cancel'})
  9671. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9672. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9673. this.connection.send(ack);
  9674. return true;
  9675. }
  9676. // local jid is not checked
  9677. if (fromJid != sess.peerjid) {
  9678. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9679. ack.type = 'error';
  9680. ack.c('error', {type: 'cancel'})
  9681. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9682. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9683. this.connection.send(ack);
  9684. return true;
  9685. }
  9686. } else if (sess !== undefined) {
  9687. // existing session with same session id
  9688. // this might be out-of-order if the sess.peerjid is the same as from
  9689. ack.type = 'error';
  9690. ack.c('error', {type: 'cancel'})
  9691. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9692. logger.warn('duplicate session id', sid);
  9693. this.connection.send(ack);
  9694. return true;
  9695. }
  9696. // FIXME: check for a defined action
  9697. this.connection.send(ack);
  9698. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9699. switch (action) {
  9700. case 'session-initiate':
  9701. console.log("(TIME) received session-initiate:\t",
  9702. window.performance.now());
  9703. var startMuted = $(iq).find('jingle>startmuted');
  9704. if (startMuted && startMuted.length > 0) {
  9705. var audioMuted = startMuted.attr("audio");
  9706. var videoMuted = startMuted.attr("video");
  9707. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9708. audioMuted === "true", videoMuted === "true");
  9709. }
  9710. sess = new JingleSession(
  9711. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9712. this.connection, XMPP);
  9713. // configure session
  9714. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9715. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9716. sess.media_constraints = this.media_constraints;
  9717. sess.ice_config = this.ice_config;
  9718. sess.initialize(fromJid, false);
  9719. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9720. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9721. sess.setOffer($(iq).find('>jingle'));
  9722. this.sessions[sess.sid] = sess;
  9723. this.jid2session[sess.peerjid] = sess;
  9724. // the callback should either
  9725. // .sendAnswer and .accept
  9726. // or .sendTerminate -- not necessarily synchronous
  9727. sess.sendAnswer();
  9728. sess.accept();
  9729. break;
  9730. case 'session-accept':
  9731. sess.setAnswer($(iq).find('>jingle'));
  9732. sess.accept();
  9733. break;
  9734. case 'session-terminate':
  9735. // If this is not the focus sending the terminate, we have
  9736. // nothing more to do here.
  9737. if (Object.keys(this.sessions).length < 1
  9738. || !(this.sessions[Object.keys(this.sessions)[0]]
  9739. instanceof JingleSession))
  9740. {
  9741. break;
  9742. }
  9743. logger.log('terminating...', sess.sid);
  9744. sess.terminate();
  9745. this.terminate(sess.sid);
  9746. if ($(iq).find('>jingle>reason').length) {
  9747. $(document).trigger('callterminated.jingle', [
  9748. sess.sid,
  9749. sess.peerjid,
  9750. $(iq).find('>jingle>reason>:first')[0].tagName,
  9751. $(iq).find('>jingle>reason>text').text()
  9752. ]);
  9753. } else {
  9754. $(document).trigger('callterminated.jingle',
  9755. [sess.sid, sess.peerjid]);
  9756. }
  9757. break;
  9758. case 'transport-info':
  9759. sess.addIceCandidate($(iq).find('>jingle>content'));
  9760. break;
  9761. case 'session-info':
  9762. var affected;
  9763. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9764. $(document).trigger('ringing.jingle', [sess.sid]);
  9765. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9766. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9767. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9768. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9769. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9770. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9771. }
  9772. break;
  9773. case 'addsource': // FIXME: proprietary, un-jingleish
  9774. case 'source-add': // FIXME: proprietary
  9775. sess.addSource($(iq).find('>jingle>content'));
  9776. break;
  9777. case 'removesource': // FIXME: proprietary, un-jingleish
  9778. case 'source-remove': // FIXME: proprietary
  9779. sess.removeSource($(iq).find('>jingle>content'));
  9780. break;
  9781. default:
  9782. logger.warn('jingle action not implemented', action);
  9783. break;
  9784. }
  9785. return true;
  9786. },
  9787. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9788. if (sid === null || sid === undefined) {
  9789. for (sid in this.sessions) {
  9790. if (this.sessions[sid].state != 'ended') {
  9791. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9792. this.sessions[sid].terminate();
  9793. }
  9794. delete this.jid2session[this.sessions[sid].peerjid];
  9795. delete this.sessions[sid];
  9796. }
  9797. } else if (this.sessions.hasOwnProperty(sid)) {
  9798. if (this.sessions[sid].state != 'ended') {
  9799. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9800. this.sessions[sid].terminate();
  9801. }
  9802. delete this.jid2session[this.sessions[sid].peerjid];
  9803. delete this.sessions[sid];
  9804. }
  9805. },
  9806. getStunAndTurnCredentials: function () {
  9807. // get stun and turn configuration from server via xep-0215
  9808. // uses time-limited credentials as described in
  9809. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9810. //
  9811. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9812. // for a prosody module which implements this
  9813. //
  9814. // currently, this doesn't work with updateIce and therefore credentials with a long
  9815. // validity have to be fetched before creating the peerconnection
  9816. // TODO: implement refresh via updateIce as described in
  9817. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9818. var self = this;
  9819. this.connection.sendIQ(
  9820. $iq({type: 'get', to: this.connection.domain})
  9821. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9822. function (res) {
  9823. var iceservers = [];
  9824. $(res).find('>services>service').each(function (idx, el) {
  9825. el = $(el);
  9826. var dict = {};
  9827. var type = el.attr('type');
  9828. switch (type) {
  9829. case 'stun':
  9830. dict.url = 'stun:' + el.attr('host');
  9831. if (el.attr('port')) {
  9832. dict.url += ':' + el.attr('port');
  9833. }
  9834. iceservers.push(dict);
  9835. break;
  9836. case 'turn':
  9837. case 'turns':
  9838. dict.url = type + ':';
  9839. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  9840. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  9841. dict.url += el.attr('username') + '@';
  9842. } else {
  9843. dict.username = el.attr('username'); // only works in M28
  9844. }
  9845. }
  9846. dict.url += el.attr('host');
  9847. if (el.attr('port') && el.attr('port') != '3478') {
  9848. dict.url += ':' + el.attr('port');
  9849. }
  9850. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9851. dict.url += '?transport=' + el.attr('transport');
  9852. }
  9853. if (el.attr('password')) {
  9854. dict.credential = el.attr('password');
  9855. }
  9856. iceservers.push(dict);
  9857. break;
  9858. }
  9859. });
  9860. self.ice_config.iceServers = iceservers;
  9861. },
  9862. function (err) {
  9863. logger.warn('getting turn credentials failed', err);
  9864. logger.warn('is mod_turncredentials or similar installed?');
  9865. }
  9866. );
  9867. // implement push?
  9868. },
  9869. /**
  9870. * Returns the data saved in 'updateLog' in a format to be logged.
  9871. */
  9872. getLog: function () {
  9873. var data = {};
  9874. var self = this;
  9875. Object.keys(this.sessions).forEach(function (sid) {
  9876. var session = self.sessions[sid];
  9877. if (session.peerconnection && session.peerconnection.updateLog) {
  9878. // FIXME: should probably be a .dump call
  9879. data["jingle_" + session.sid] = {
  9880. updateLog: session.peerconnection.updateLog,
  9881. stats: session.peerconnection.stats,
  9882. url: window.location.href
  9883. };
  9884. }
  9885. });
  9886. return data;
  9887. }
  9888. });
  9889. };
  9890. }).call(this,"/modules/xmpp/strophe.jingle.js")
  9891. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":47}],37:[function(require,module,exports){
  9892. /* global Strophe */
  9893. module.exports = function () {
  9894. Strophe.addConnectionPlugin('logger', {
  9895. // logs raw stanzas and makes them available for download as JSON
  9896. connection: null,
  9897. log: [],
  9898. init: function (conn) {
  9899. this.connection = conn;
  9900. this.connection.rawInput = this.log_incoming.bind(this);
  9901. this.connection.rawOutput = this.log_outgoing.bind(this);
  9902. },
  9903. log_incoming: function (stanza) {
  9904. this.log.push([new Date().getTime(), 'incoming', stanza]);
  9905. },
  9906. log_outgoing: function (stanza) {
  9907. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  9908. }
  9909. });
  9910. };
  9911. },{}],38:[function(require,module,exports){
  9912. (function (__filename){
  9913. /* global $, $iq, Strophe */
  9914. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9915. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9916. /**
  9917. * Ping every 20 sec
  9918. */
  9919. var PING_INTERVAL = 20000;
  9920. /**
  9921. * Ping timeout error after 15 sec of waiting.
  9922. */
  9923. var PING_TIMEOUT = 15000;
  9924. /**
  9925. * Will close the connection after 3 consecutive ping errors.
  9926. */
  9927. var PING_THRESHOLD = 3;
  9928. /**
  9929. * XEP-0199 ping plugin.
  9930. *
  9931. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  9932. */
  9933. module.exports = function (XMPP, eventEmitter) {
  9934. Strophe.addConnectionPlugin('ping', {
  9935. connection: null,
  9936. failedPings: 0,
  9937. /**
  9938. * Initializes the plugin. Method called by Strophe.
  9939. * @param connection Strophe connection instance.
  9940. */
  9941. init: function (connection) {
  9942. this.connection = connection;
  9943. Strophe.addNamespace('PING', "urn:xmpp:ping");
  9944. },
  9945. /**
  9946. * Sends "ping" to given <tt>jid</tt>
  9947. * @param jid the JID to which ping request will be sent.
  9948. * @param success callback called on success.
  9949. * @param error callback called on error.
  9950. * @param timeout ms how long are we going to wait for the response. On
  9951. * timeout <tt>error<//t> callback is called with undefined error
  9952. * argument.
  9953. */
  9954. ping: function (jid, success, error, timeout) {
  9955. var iq = $iq({type: 'get', to: jid});
  9956. iq.c('ping', {xmlns: Strophe.NS.PING});
  9957. this.connection.sendIQ(iq, success, error, timeout);
  9958. },
  9959. /**
  9960. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  9961. * @param jid the JID to be checked for ping support.
  9962. * @param callback function with boolean argument which will be
  9963. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  9964. */
  9965. hasPingSupport: function (jid, callback) {
  9966. this.connection.disco.info(
  9967. jid, null,
  9968. function (result) {
  9969. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  9970. callback(ping.length > 0);
  9971. },
  9972. function (error) {
  9973. logger.error("Ping feature discovery error", error);
  9974. callback(false);
  9975. }
  9976. );
  9977. },
  9978. /**
  9979. * Starts to send ping in given interval to specified remote JID.
  9980. * This plugin supports only one such task and <tt>stopInterval</tt>
  9981. * must be called before starting a new one.
  9982. * @param remoteJid remote JID to which ping requests will be sent to.
  9983. * @param interval task interval in ms.
  9984. */
  9985. startInterval: function (remoteJid, interval) {
  9986. if (this.intervalId) {
  9987. logger.error("Ping task scheduled already");
  9988. return;
  9989. }
  9990. if (!interval)
  9991. interval = PING_INTERVAL;
  9992. var self = this;
  9993. this.intervalId = window.setInterval(function () {
  9994. self.ping(remoteJid,
  9995. function (result) {
  9996. // Ping OK
  9997. self.failedPings = 0;
  9998. },
  9999. function (error) {
  10000. self.failedPings += 1;
  10001. logger.error(
  10002. "Ping " + (error ? "error" : "timeout"), error);
  10003. if (self.failedPings >= PING_THRESHOLD) {
  10004. self.connection.disconnect();
  10005. }
  10006. }, PING_TIMEOUT);
  10007. }, interval);
  10008. logger.info("XMPP pings will be sent every " + interval + " ms");
  10009. },
  10010. /**
  10011. * Stops current "ping" interval task.
  10012. */
  10013. stopInterval: function () {
  10014. if (this.intervalId) {
  10015. window.clearInterval(this.intervalId);
  10016. this.intervalId = null;
  10017. this.failedPings = 0;
  10018. logger.info("Ping interval cleared");
  10019. }
  10020. }
  10021. });
  10022. };
  10023. }).call(this,"/modules/xmpp/strophe.ping.js")
  10024. },{"../../service/xmpp/XMPPEvents":85,"jitsi-meet-logger":47}],39:[function(require,module,exports){
  10025. (function (__filename){
  10026. /* jshint -W117 */
  10027. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10028. module.exports = function() {
  10029. Strophe.addConnectionPlugin('rayo',
  10030. {
  10031. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10032. connection: null,
  10033. init: function (conn) {
  10034. this.connection = conn;
  10035. if (this.connection.disco) {
  10036. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10037. }
  10038. this.connection.addHandler(
  10039. this.onRayo.bind(this),
  10040. this.RAYO_XMLNS, 'iq', 'set', null, null);
  10041. },
  10042. onRayo: function (iq) {
  10043. logger.info("Rayo IQ", iq);
  10044. },
  10045. dial: function (to, from, roomName, roomPass) {
  10046. var self = this;
  10047. var req = $iq(
  10048. {
  10049. type: 'set',
  10050. to: this.connection.emuc.focusMucJid
  10051. }
  10052. );
  10053. req.c('dial',
  10054. {
  10055. xmlns: this.RAYO_XMLNS,
  10056. to: to,
  10057. from: from
  10058. });
  10059. req.c('header',
  10060. {
  10061. name: 'JvbRoomName',
  10062. value: roomName
  10063. }).up();
  10064. if (roomPass !== null && roomPass.length) {
  10065. req.c('header',
  10066. {
  10067. name: 'JvbRoomPassword',
  10068. value: roomPass
  10069. }).up();
  10070. }
  10071. this.connection.sendIQ(
  10072. req,
  10073. function (result) {
  10074. logger.info('Dial result ', result);
  10075. var resource = $(result).find('ref').attr('uri');
  10076. this.call_resource = resource.substr('xmpp:'.length);
  10077. logger.info(
  10078. "Received call resource: " + this.call_resource);
  10079. },
  10080. function (error) {
  10081. logger.info('Dial error ', error);
  10082. }
  10083. );
  10084. },
  10085. hang_up: function () {
  10086. if (!this.call_resource) {
  10087. logger.warn("No call in progress");
  10088. return;
  10089. }
  10090. var self = this;
  10091. var req = $iq(
  10092. {
  10093. type: 'set',
  10094. to: this.call_resource
  10095. }
  10096. );
  10097. req.c('hangup',
  10098. {
  10099. xmlns: this.RAYO_XMLNS
  10100. });
  10101. this.connection.sendIQ(
  10102. req,
  10103. function (result) {
  10104. logger.info('Hangup result ', result);
  10105. self.call_resource = null;
  10106. },
  10107. function (error) {
  10108. logger.info('Hangup error ', error);
  10109. self.call_resource = null;
  10110. }
  10111. );
  10112. }
  10113. }
  10114. );
  10115. };
  10116. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10117. },{"jitsi-meet-logger":47}],40:[function(require,module,exports){
  10118. (function (__filename){
  10119. /* global Strophe */
  10120. /**
  10121. * Strophe logger implementation. Logs from level WARN and above.
  10122. */
  10123. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10124. module.exports = function () {
  10125. Strophe.log = function (level, msg) {
  10126. switch (level) {
  10127. case Strophe.LogLevel.WARN:
  10128. logger.warn("Strophe: " + msg);
  10129. break;
  10130. case Strophe.LogLevel.ERROR:
  10131. case Strophe.LogLevel.FATAL:
  10132. logger.error("Strophe: " + msg);
  10133. break;
  10134. }
  10135. };
  10136. Strophe.getStatusString = function (status) {
  10137. switch (status) {
  10138. case Strophe.Status.ERROR:
  10139. return "ERROR";
  10140. case Strophe.Status.CONNECTING:
  10141. return "CONNECTING";
  10142. case Strophe.Status.CONNFAIL:
  10143. return "CONNFAIL";
  10144. case Strophe.Status.AUTHENTICATING:
  10145. return "AUTHENTICATING";
  10146. case Strophe.Status.AUTHFAIL:
  10147. return "AUTHFAIL";
  10148. case Strophe.Status.CONNECTED:
  10149. return "CONNECTED";
  10150. case Strophe.Status.DISCONNECTED:
  10151. return "DISCONNECTED";
  10152. case Strophe.Status.DISCONNECTING:
  10153. return "DISCONNECTING";
  10154. case Strophe.Status.ATTACHED:
  10155. return "ATTACHED";
  10156. default:
  10157. return "unknown";
  10158. }
  10159. };
  10160. };
  10161. }).call(this,"/modules/xmpp/strophe.util.js")
  10162. },{"jitsi-meet-logger":47}],41:[function(require,module,exports){
  10163. (function (__filename){
  10164. /* global $, APP, config, Strophe*/
  10165. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10166. var EventEmitter = require("events");
  10167. var Pako = require("pako");
  10168. var RTCEvents = require("../../service/RTC/RTCEvents");
  10169. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10170. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10171. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10172. var RTC = require("../RTC/RTC");
  10173. var authenticatedUser = false;
  10174. function createConnection(bosh) {
  10175. bosh = bosh || '/http-bind';
  10176. return new Strophe.Connection(bosh);
  10177. };
  10178. //!!!!!!!!!! FIXME: ...
  10179. function initStrophePlugins(XMPP)
  10180. {
  10181. require("./strophe.emuc")(XMPP);
  10182. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10183. // require("./strophe.moderate")(XMPP, eventEmitter);
  10184. require("./strophe.util")();
  10185. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10186. require("./strophe.rayo")();
  10187. require("./strophe.logger")();
  10188. }
  10189. //!!!!!!!!!! FIXME: ...
  10190. ///**
  10191. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10192. // * video type in MUC presence.
  10193. // * @param localStream new or modified <tt>LocalStream</tt>.
  10194. // */
  10195. //function broadcastLocalVideoType(localStream) {
  10196. // if (localStream.videoType)
  10197. // XMPP.addToPresence('videoType', localStream.videoType);
  10198. //}
  10199. //
  10200. //function registerListeners() {
  10201. // RTC.addStreamListener(
  10202. // broadcastLocalVideoType,
  10203. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10204. // );
  10205. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10206. // XMPP.addToPresence("devices", devices);
  10207. // });
  10208. //}
  10209. function XMPP(options) {
  10210. this.eventEmitter = new EventEmitter();
  10211. this.connection = null;
  10212. this.disconnectInProgress = false;
  10213. this.forceMuted = false;
  10214. this.options = options;
  10215. initStrophePlugins(this);
  10216. // registerListeners();
  10217. this.connection = createConnection(options.bosh);
  10218. }
  10219. XMPP.prototype.getConnection = function(){ return connection; };
  10220. XMPP.prototype._connect = function (jid, password) {
  10221. var self = this;
  10222. // connection.connect() starts the connection process.
  10223. //
  10224. // As the connection process proceeds, the user supplied callback will
  10225. // be triggered multiple times with status updates. The callback should
  10226. // take two arguments - the status code and the error condition.
  10227. //
  10228. // The status code will be one of the values in the Strophe.Status
  10229. // constants. The error condition will be one of the conditions defined
  10230. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10231. //
  10232. // The Parameters wait, hold and route are optional and only relevant
  10233. // for BOSH connections. Please see XEP 124 for a more detailed
  10234. // explanation of the optional parameters.
  10235. //
  10236. // Connection status constants for use by the connection handler
  10237. // callback.
  10238. //
  10239. // Status.ERROR - An error has occurred (websockets specific)
  10240. // Status.CONNECTING - The connection is currently being made
  10241. // Status.CONNFAIL - The connection attempt failed
  10242. // Status.AUTHENTICATING - The connection is authenticating
  10243. // Status.AUTHFAIL - The authentication attempt failed
  10244. // Status.CONNECTED - The connection has succeeded
  10245. // Status.DISCONNECTED - The connection has been terminated
  10246. // Status.DISCONNECTING - The connection is currently being terminated
  10247. // Status.ATTACHED - The connection has been attached
  10248. var anonymousConnectionFailed = false;
  10249. var connectionFailed = false;
  10250. var lastErrorMsg;
  10251. this.connection.connect(jid, password, function (status, msg) {
  10252. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10253. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10254. if (status === Strophe.Status.CONNECTED) {
  10255. if (self.options.useStunTurn) {
  10256. self.connection.jingle.getStunAndTurnCredentials();
  10257. }
  10258. logger.info("My Jabber ID: " + self.connection.jid);
  10259. // Schedule ping ?
  10260. var pingJid = self.connection.domain;
  10261. self.connection.ping.hasPingSupport(
  10262. pingJid,
  10263. function (hasPing) {
  10264. if (hasPing)
  10265. self.connection.ping.startInterval(pingJid);
  10266. else
  10267. logger.warn("Ping NOT supported by " + pingJid);
  10268. }
  10269. );
  10270. if (password)
  10271. authenticatedUser = true;
  10272. if (self.connection && self.connection.connected &&
  10273. Strophe.getResourceFromJid(self.connection.jid)) {
  10274. // .connected is true while connecting?
  10275. // self.connection.send($pres());
  10276. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10277. Strophe.getResourceFromJid(self.connection.jid));
  10278. }
  10279. } else if (status === Strophe.Status.CONNFAIL) {
  10280. if (msg === 'x-strophe-bad-non-anon-jid') {
  10281. anonymousConnectionFailed = true;
  10282. }
  10283. else
  10284. {
  10285. connectionFailed = true;
  10286. }
  10287. lastErrorMsg = msg;
  10288. } else if (status === Strophe.Status.DISCONNECTED) {
  10289. // Stop ping interval
  10290. self.connection.ping.stopInterval();
  10291. self.disconnectInProgress = false;
  10292. if (anonymousConnectionFailed) {
  10293. // prompt user for username and password
  10294. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10295. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10296. } else if(connectionFailed) {
  10297. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10298. JitsiConnectionErrors.OTHER_ERROR,
  10299. msg ? msg : lastErrorMsg);
  10300. } else {
  10301. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10302. msg ? msg : lastErrorMsg);
  10303. }
  10304. } else if (status === Strophe.Status.AUTHFAIL) {
  10305. // wrong password or username, prompt user
  10306. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10307. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10308. }
  10309. });
  10310. }
  10311. XMPP.prototype.connect = function (jid, password) {
  10312. if(!jid) {
  10313. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10314. // Force authenticated domain if room is appended with '?login=true'
  10315. if (this.options.hosts.anonymousdomain &&
  10316. window.location.search.indexOf("login=true") !== -1) {
  10317. configDomain = this.options.hosts.domain;
  10318. }
  10319. jid = configDomain || window.location.hostname;
  10320. }
  10321. return this._connect(jid, password);
  10322. };
  10323. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  10324. var roomjid = roomName + '@' + this.options.hosts.muc;
  10325. if (useNicks) {
  10326. if (nick) {
  10327. roomjid += '/' + nick;
  10328. } else {
  10329. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10330. }
  10331. } else {
  10332. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10333. if(!authenticatedUser)
  10334. tmpJid = tmpJid.substr(0, 8);
  10335. roomjid += '/' + tmpJid;
  10336. }
  10337. return this.connection.emuc.createRoom(roomjid, null, options);
  10338. }
  10339. XMPP.prototype.addListener = function(type, listener) {
  10340. this.eventEmitter.on(type, listener);
  10341. };
  10342. XMPP.prototype.removeListener = function (type, listener) {
  10343. this.eventEmitter.removeListener(type, listener);
  10344. };
  10345. //FIXME: this should work with the room
  10346. XMPP.prototype.leaveRoom = function (jid) {
  10347. var handler = this.connection.jingle.jid2session[jid];
  10348. if (handler && handler.peerconnection) {
  10349. // FIXME: probably removing streams is not required and close() should
  10350. // be enough
  10351. if (RTC.localAudio) {
  10352. handler.peerconnection.removeStream(
  10353. RTC.localAudio.getOriginalStream(), true);
  10354. }
  10355. if (RTC.localVideo) {
  10356. handler.peerconnection.removeStream(
  10357. RTC.localVideo.getOriginalStream(), true);
  10358. }
  10359. handler.peerconnection.close();
  10360. }
  10361. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10362. this.connection.emuc.doLeave(jid);
  10363. };
  10364. /**
  10365. * Sends 'data' as a log message to the focus. Returns true iff a message
  10366. * was sent.
  10367. * @param data
  10368. * @returns {boolean} true iff a message was sent.
  10369. */
  10370. XMPP.prototype.sendLogs = function (data) {
  10371. if(!this.connection.emuc.focusMucJid)
  10372. return false;
  10373. var deflate = true;
  10374. var content = JSON.stringify(data);
  10375. if (deflate) {
  10376. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10377. }
  10378. content = Base64.encode(content);
  10379. // XEP-0337-ish
  10380. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10381. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10382. id: 'PeerConnectionStats'});
  10383. message.c('message').t(content).up();
  10384. if (deflate) {
  10385. message.c('tag', {name: "deflated", value: "true"}).up();
  10386. }
  10387. message.up();
  10388. this.connection.send(message);
  10389. return true;
  10390. };
  10391. // Gets the logs from strophe.jingle.
  10392. XMPP.prototype.getJingleLog = function () {
  10393. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10394. };
  10395. // Gets the logs from strophe.
  10396. XMPP.prototype.getXmppLog = function () {
  10397. return this.connection.logger ? this.connection.logger.log : null;
  10398. };
  10399. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10400. this.connection.rayo.dial(to, from, roomName,roomPass);
  10401. };
  10402. XMPP.prototype.setMute = function (jid, mute) {
  10403. this.connection.moderate.setMute(jid, mute);
  10404. };
  10405. XMPP.prototype.eject = function (jid) {
  10406. this.connection.moderate.eject(jid);
  10407. };
  10408. XMPP.prototype.getSessions = function () {
  10409. return this.connection.jingle.sessions;
  10410. };
  10411. XMPP.prototype.disconnect = function () {
  10412. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10413. {
  10414. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10415. return;
  10416. }
  10417. this.disconnectInProgress = true;
  10418. this.connection.disconnect();
  10419. };
  10420. /**
  10421. * Gets the SSRC of local media stream.
  10422. * @param mediaType the media type that tells whether we want to get
  10423. * the SSRC of local audio or video stream.
  10424. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  10425. * not available.
  10426. */
  10427. XMPP.prototype.getLocalSSRC = function (mediaType) {
  10428. if (this.connection.jingle.activecall &&
  10429. this.connection.jingle.activecall.peerconnection) {
  10430. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  10431. } else {
  10432. return null;
  10433. }
  10434. };
  10435. module.exports = XMPP;
  10436. }).call(this,"/modules/xmpp/xmpp.js")
  10437. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":79,"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"./strophe.emuc":35,"./strophe.jingle":36,"./strophe.logger":37,"./strophe.ping":38,"./strophe.rayo":39,"./strophe.util":40,"events":43,"jitsi-meet-logger":47,"pako":48}],42:[function(require,module,exports){
  10438. (function (process){
  10439. /*!
  10440. * async
  10441. * https://github.com/caolan/async
  10442. *
  10443. * Copyright 2010-2014 Caolan McMahon
  10444. * Released under the MIT license
  10445. */
  10446. /*jshint onevar: false, indent:4 */
  10447. /*global setImmediate: false, setTimeout: false, console: false */
  10448. (function () {
  10449. var async = {};
  10450. // global on the server, window in the browser
  10451. var root, previous_async;
  10452. root = this;
  10453. if (root != null) {
  10454. previous_async = root.async;
  10455. }
  10456. async.noConflict = function () {
  10457. root.async = previous_async;
  10458. return async;
  10459. };
  10460. function only_once(fn) {
  10461. var called = false;
  10462. return function() {
  10463. if (called) throw new Error("Callback was already called.");
  10464. called = true;
  10465. fn.apply(root, arguments);
  10466. }
  10467. }
  10468. //// cross-browser compatiblity functions ////
  10469. var _toString = Object.prototype.toString;
  10470. var _isArray = Array.isArray || function (obj) {
  10471. return _toString.call(obj) === '[object Array]';
  10472. };
  10473. var _each = function (arr, iterator) {
  10474. if (arr.forEach) {
  10475. return arr.forEach(iterator);
  10476. }
  10477. for (var i = 0; i < arr.length; i += 1) {
  10478. iterator(arr[i], i, arr);
  10479. }
  10480. };
  10481. var _map = function (arr, iterator) {
  10482. if (arr.map) {
  10483. return arr.map(iterator);
  10484. }
  10485. var results = [];
  10486. _each(arr, function (x, i, a) {
  10487. results.push(iterator(x, i, a));
  10488. });
  10489. return results;
  10490. };
  10491. var _reduce = function (arr, iterator, memo) {
  10492. if (arr.reduce) {
  10493. return arr.reduce(iterator, memo);
  10494. }
  10495. _each(arr, function (x, i, a) {
  10496. memo = iterator(memo, x, i, a);
  10497. });
  10498. return memo;
  10499. };
  10500. var _keys = function (obj) {
  10501. if (Object.keys) {
  10502. return Object.keys(obj);
  10503. }
  10504. var keys = [];
  10505. for (var k in obj) {
  10506. if (obj.hasOwnProperty(k)) {
  10507. keys.push(k);
  10508. }
  10509. }
  10510. return keys;
  10511. };
  10512. //// exported async module functions ////
  10513. //// nextTick implementation with browser-compatible fallback ////
  10514. if (typeof process === 'undefined' || !(process.nextTick)) {
  10515. if (typeof setImmediate === 'function') {
  10516. async.nextTick = function (fn) {
  10517. // not a direct alias for IE10 compatibility
  10518. setImmediate(fn);
  10519. };
  10520. async.setImmediate = async.nextTick;
  10521. }
  10522. else {
  10523. async.nextTick = function (fn) {
  10524. setTimeout(fn, 0);
  10525. };
  10526. async.setImmediate = async.nextTick;
  10527. }
  10528. }
  10529. else {
  10530. async.nextTick = process.nextTick;
  10531. if (typeof setImmediate !== 'undefined') {
  10532. async.setImmediate = function (fn) {
  10533. // not a direct alias for IE10 compatibility
  10534. setImmediate(fn);
  10535. };
  10536. }
  10537. else {
  10538. async.setImmediate = async.nextTick;
  10539. }
  10540. }
  10541. async.each = function (arr, iterator, callback) {
  10542. callback = callback || function () {};
  10543. if (!arr.length) {
  10544. return callback();
  10545. }
  10546. var completed = 0;
  10547. _each(arr, function (x) {
  10548. iterator(x, only_once(done) );
  10549. });
  10550. function done(err) {
  10551. if (err) {
  10552. callback(err);
  10553. callback = function () {};
  10554. }
  10555. else {
  10556. completed += 1;
  10557. if (completed >= arr.length) {
  10558. callback();
  10559. }
  10560. }
  10561. }
  10562. };
  10563. async.forEach = async.each;
  10564. async.eachSeries = function (arr, iterator, callback) {
  10565. callback = callback || function () {};
  10566. if (!arr.length) {
  10567. return callback();
  10568. }
  10569. var completed = 0;
  10570. var iterate = function () {
  10571. iterator(arr[completed], function (err) {
  10572. if (err) {
  10573. callback(err);
  10574. callback = function () {};
  10575. }
  10576. else {
  10577. completed += 1;
  10578. if (completed >= arr.length) {
  10579. callback();
  10580. }
  10581. else {
  10582. iterate();
  10583. }
  10584. }
  10585. });
  10586. };
  10587. iterate();
  10588. };
  10589. async.forEachSeries = async.eachSeries;
  10590. async.eachLimit = function (arr, limit, iterator, callback) {
  10591. var fn = _eachLimit(limit);
  10592. fn.apply(null, [arr, iterator, callback]);
  10593. };
  10594. async.forEachLimit = async.eachLimit;
  10595. var _eachLimit = function (limit) {
  10596. return function (arr, iterator, callback) {
  10597. callback = callback || function () {};
  10598. if (!arr.length || limit <= 0) {
  10599. return callback();
  10600. }
  10601. var completed = 0;
  10602. var started = 0;
  10603. var running = 0;
  10604. (function replenish () {
  10605. if (completed >= arr.length) {
  10606. return callback();
  10607. }
  10608. while (running < limit && started < arr.length) {
  10609. started += 1;
  10610. running += 1;
  10611. iterator(arr[started - 1], function (err) {
  10612. if (err) {
  10613. callback(err);
  10614. callback = function () {};
  10615. }
  10616. else {
  10617. completed += 1;
  10618. running -= 1;
  10619. if (completed >= arr.length) {
  10620. callback();
  10621. }
  10622. else {
  10623. replenish();
  10624. }
  10625. }
  10626. });
  10627. }
  10628. })();
  10629. };
  10630. };
  10631. var doParallel = function (fn) {
  10632. return function () {
  10633. var args = Array.prototype.slice.call(arguments);
  10634. return fn.apply(null, [async.each].concat(args));
  10635. };
  10636. };
  10637. var doParallelLimit = function(limit, fn) {
  10638. return function () {
  10639. var args = Array.prototype.slice.call(arguments);
  10640. return fn.apply(null, [_eachLimit(limit)].concat(args));
  10641. };
  10642. };
  10643. var doSeries = function (fn) {
  10644. return function () {
  10645. var args = Array.prototype.slice.call(arguments);
  10646. return fn.apply(null, [async.eachSeries].concat(args));
  10647. };
  10648. };
  10649. var _asyncMap = function (eachfn, arr, iterator, callback) {
  10650. arr = _map(arr, function (x, i) {
  10651. return {index: i, value: x};
  10652. });
  10653. if (!callback) {
  10654. eachfn(arr, function (x, callback) {
  10655. iterator(x.value, function (err) {
  10656. callback(err);
  10657. });
  10658. });
  10659. } else {
  10660. var results = [];
  10661. eachfn(arr, function (x, callback) {
  10662. iterator(x.value, function (err, v) {
  10663. results[x.index] = v;
  10664. callback(err);
  10665. });
  10666. }, function (err) {
  10667. callback(err, results);
  10668. });
  10669. }
  10670. };
  10671. async.map = doParallel(_asyncMap);
  10672. async.mapSeries = doSeries(_asyncMap);
  10673. async.mapLimit = function (arr, limit, iterator, callback) {
  10674. return _mapLimit(limit)(arr, iterator, callback);
  10675. };
  10676. var _mapLimit = function(limit) {
  10677. return doParallelLimit(limit, _asyncMap);
  10678. };
  10679. // reduce only has a series version, as doing reduce in parallel won't
  10680. // work in many situations.
  10681. async.reduce = function (arr, memo, iterator, callback) {
  10682. async.eachSeries(arr, function (x, callback) {
  10683. iterator(memo, x, function (err, v) {
  10684. memo = v;
  10685. callback(err);
  10686. });
  10687. }, function (err) {
  10688. callback(err, memo);
  10689. });
  10690. };
  10691. // inject alias
  10692. async.inject = async.reduce;
  10693. // foldl alias
  10694. async.foldl = async.reduce;
  10695. async.reduceRight = function (arr, memo, iterator, callback) {
  10696. var reversed = _map(arr, function (x) {
  10697. return x;
  10698. }).reverse();
  10699. async.reduce(reversed, memo, iterator, callback);
  10700. };
  10701. // foldr alias
  10702. async.foldr = async.reduceRight;
  10703. var _filter = function (eachfn, arr, iterator, callback) {
  10704. var results = [];
  10705. arr = _map(arr, function (x, i) {
  10706. return {index: i, value: x};
  10707. });
  10708. eachfn(arr, function (x, callback) {
  10709. iterator(x.value, function (v) {
  10710. if (v) {
  10711. results.push(x);
  10712. }
  10713. callback();
  10714. });
  10715. }, function (err) {
  10716. callback(_map(results.sort(function (a, b) {
  10717. return a.index - b.index;
  10718. }), function (x) {
  10719. return x.value;
  10720. }));
  10721. });
  10722. };
  10723. async.filter = doParallel(_filter);
  10724. async.filterSeries = doSeries(_filter);
  10725. // select alias
  10726. async.select = async.filter;
  10727. async.selectSeries = async.filterSeries;
  10728. var _reject = function (eachfn, arr, iterator, callback) {
  10729. var results = [];
  10730. arr = _map(arr, function (x, i) {
  10731. return {index: i, value: x};
  10732. });
  10733. eachfn(arr, function (x, callback) {
  10734. iterator(x.value, function (v) {
  10735. if (!v) {
  10736. results.push(x);
  10737. }
  10738. callback();
  10739. });
  10740. }, function (err) {
  10741. callback(_map(results.sort(function (a, b) {
  10742. return a.index - b.index;
  10743. }), function (x) {
  10744. return x.value;
  10745. }));
  10746. });
  10747. };
  10748. async.reject = doParallel(_reject);
  10749. async.rejectSeries = doSeries(_reject);
  10750. var _detect = function (eachfn, arr, iterator, main_callback) {
  10751. eachfn(arr, function (x, callback) {
  10752. iterator(x, function (result) {
  10753. if (result) {
  10754. main_callback(x);
  10755. main_callback = function () {};
  10756. }
  10757. else {
  10758. callback();
  10759. }
  10760. });
  10761. }, function (err) {
  10762. main_callback();
  10763. });
  10764. };
  10765. async.detect = doParallel(_detect);
  10766. async.detectSeries = doSeries(_detect);
  10767. async.some = function (arr, iterator, main_callback) {
  10768. async.each(arr, function (x, callback) {
  10769. iterator(x, function (v) {
  10770. if (v) {
  10771. main_callback(true);
  10772. main_callback = function () {};
  10773. }
  10774. callback();
  10775. });
  10776. }, function (err) {
  10777. main_callback(false);
  10778. });
  10779. };
  10780. // any alias
  10781. async.any = async.some;
  10782. async.every = function (arr, iterator, main_callback) {
  10783. async.each(arr, function (x, callback) {
  10784. iterator(x, function (v) {
  10785. if (!v) {
  10786. main_callback(false);
  10787. main_callback = function () {};
  10788. }
  10789. callback();
  10790. });
  10791. }, function (err) {
  10792. main_callback(true);
  10793. });
  10794. };
  10795. // all alias
  10796. async.all = async.every;
  10797. async.sortBy = function (arr, iterator, callback) {
  10798. async.map(arr, function (x, callback) {
  10799. iterator(x, function (err, criteria) {
  10800. if (err) {
  10801. callback(err);
  10802. }
  10803. else {
  10804. callback(null, {value: x, criteria: criteria});
  10805. }
  10806. });
  10807. }, function (err, results) {
  10808. if (err) {
  10809. return callback(err);
  10810. }
  10811. else {
  10812. var fn = function (left, right) {
  10813. var a = left.criteria, b = right.criteria;
  10814. return a < b ? -1 : a > b ? 1 : 0;
  10815. };
  10816. callback(null, _map(results.sort(fn), function (x) {
  10817. return x.value;
  10818. }));
  10819. }
  10820. });
  10821. };
  10822. async.auto = function (tasks, callback) {
  10823. callback = callback || function () {};
  10824. var keys = _keys(tasks);
  10825. var remainingTasks = keys.length
  10826. if (!remainingTasks) {
  10827. return callback();
  10828. }
  10829. var results = {};
  10830. var listeners = [];
  10831. var addListener = function (fn) {
  10832. listeners.unshift(fn);
  10833. };
  10834. var removeListener = function (fn) {
  10835. for (var i = 0; i < listeners.length; i += 1) {
  10836. if (listeners[i] === fn) {
  10837. listeners.splice(i, 1);
  10838. return;
  10839. }
  10840. }
  10841. };
  10842. var taskComplete = function () {
  10843. remainingTasks--
  10844. _each(listeners.slice(0), function (fn) {
  10845. fn();
  10846. });
  10847. };
  10848. addListener(function () {
  10849. if (!remainingTasks) {
  10850. var theCallback = callback;
  10851. // prevent final callback from calling itself if it errors
  10852. callback = function () {};
  10853. theCallback(null, results);
  10854. }
  10855. });
  10856. _each(keys, function (k) {
  10857. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  10858. var taskCallback = function (err) {
  10859. var args = Array.prototype.slice.call(arguments, 1);
  10860. if (args.length <= 1) {
  10861. args = args[0];
  10862. }
  10863. if (err) {
  10864. var safeResults = {};
  10865. _each(_keys(results), function(rkey) {
  10866. safeResults[rkey] = results[rkey];
  10867. });
  10868. safeResults[k] = args;
  10869. callback(err, safeResults);
  10870. // stop subsequent errors hitting callback multiple times
  10871. callback = function () {};
  10872. }
  10873. else {
  10874. results[k] = args;
  10875. async.setImmediate(taskComplete);
  10876. }
  10877. };
  10878. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  10879. var ready = function () {
  10880. return _reduce(requires, function (a, x) {
  10881. return (a && results.hasOwnProperty(x));
  10882. }, true) && !results.hasOwnProperty(k);
  10883. };
  10884. if (ready()) {
  10885. task[task.length - 1](taskCallback, results);
  10886. }
  10887. else {
  10888. var listener = function () {
  10889. if (ready()) {
  10890. removeListener(listener);
  10891. task[task.length - 1](taskCallback, results);
  10892. }
  10893. };
  10894. addListener(listener);
  10895. }
  10896. });
  10897. };
  10898. async.retry = function(times, task, callback) {
  10899. var DEFAULT_TIMES = 5;
  10900. var attempts = [];
  10901. // Use defaults if times not passed
  10902. if (typeof times === 'function') {
  10903. callback = task;
  10904. task = times;
  10905. times = DEFAULT_TIMES;
  10906. }
  10907. // Make sure times is a number
  10908. times = parseInt(times, 10) || DEFAULT_TIMES;
  10909. var wrappedTask = function(wrappedCallback, wrappedResults) {
  10910. var retryAttempt = function(task, finalAttempt) {
  10911. return function(seriesCallback) {
  10912. task(function(err, result){
  10913. seriesCallback(!err || finalAttempt, {err: err, result: result});
  10914. }, wrappedResults);
  10915. };
  10916. };
  10917. while (times) {
  10918. attempts.push(retryAttempt(task, !(times-=1)));
  10919. }
  10920. async.series(attempts, function(done, data){
  10921. data = data[data.length - 1];
  10922. (wrappedCallback || callback)(data.err, data.result);
  10923. });
  10924. }
  10925. // If a callback is passed, run this as a controll flow
  10926. return callback ? wrappedTask() : wrappedTask
  10927. };
  10928. async.waterfall = function (tasks, callback) {
  10929. callback = callback || function () {};
  10930. if (!_isArray(tasks)) {
  10931. var err = new Error('First argument to waterfall must be an array of functions');
  10932. return callback(err);
  10933. }
  10934. if (!tasks.length) {
  10935. return callback();
  10936. }
  10937. var wrapIterator = function (iterator) {
  10938. return function (err) {
  10939. if (err) {
  10940. callback.apply(null, arguments);
  10941. callback = function () {};
  10942. }
  10943. else {
  10944. var args = Array.prototype.slice.call(arguments, 1);
  10945. var next = iterator.next();
  10946. if (next) {
  10947. args.push(wrapIterator(next));
  10948. }
  10949. else {
  10950. args.push(callback);
  10951. }
  10952. async.setImmediate(function () {
  10953. iterator.apply(null, args);
  10954. });
  10955. }
  10956. };
  10957. };
  10958. wrapIterator(async.iterator(tasks))();
  10959. };
  10960. var _parallel = function(eachfn, tasks, callback) {
  10961. callback = callback || function () {};
  10962. if (_isArray(tasks)) {
  10963. eachfn.map(tasks, function (fn, callback) {
  10964. if (fn) {
  10965. fn(function (err) {
  10966. var args = Array.prototype.slice.call(arguments, 1);
  10967. if (args.length <= 1) {
  10968. args = args[0];
  10969. }
  10970. callback.call(null, err, args);
  10971. });
  10972. }
  10973. }, callback);
  10974. }
  10975. else {
  10976. var results = {};
  10977. eachfn.each(_keys(tasks), function (k, callback) {
  10978. tasks[k](function (err) {
  10979. var args = Array.prototype.slice.call(arguments, 1);
  10980. if (args.length <= 1) {
  10981. args = args[0];
  10982. }
  10983. results[k] = args;
  10984. callback(err);
  10985. });
  10986. }, function (err) {
  10987. callback(err, results);
  10988. });
  10989. }
  10990. };
  10991. async.parallel = function (tasks, callback) {
  10992. _parallel({ map: async.map, each: async.each }, tasks, callback);
  10993. };
  10994. async.parallelLimit = function(tasks, limit, callback) {
  10995. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  10996. };
  10997. async.series = function (tasks, callback) {
  10998. callback = callback || function () {};
  10999. if (_isArray(tasks)) {
  11000. async.mapSeries(tasks, function (fn, callback) {
  11001. if (fn) {
  11002. fn(function (err) {
  11003. var args = Array.prototype.slice.call(arguments, 1);
  11004. if (args.length <= 1) {
  11005. args = args[0];
  11006. }
  11007. callback.call(null, err, args);
  11008. });
  11009. }
  11010. }, callback);
  11011. }
  11012. else {
  11013. var results = {};
  11014. async.eachSeries(_keys(tasks), function (k, callback) {
  11015. tasks[k](function (err) {
  11016. var args = Array.prototype.slice.call(arguments, 1);
  11017. if (args.length <= 1) {
  11018. args = args[0];
  11019. }
  11020. results[k] = args;
  11021. callback(err);
  11022. });
  11023. }, function (err) {
  11024. callback(err, results);
  11025. });
  11026. }
  11027. };
  11028. async.iterator = function (tasks) {
  11029. var makeCallback = function (index) {
  11030. var fn = function () {
  11031. if (tasks.length) {
  11032. tasks[index].apply(null, arguments);
  11033. }
  11034. return fn.next();
  11035. };
  11036. fn.next = function () {
  11037. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11038. };
  11039. return fn;
  11040. };
  11041. return makeCallback(0);
  11042. };
  11043. async.apply = function (fn) {
  11044. var args = Array.prototype.slice.call(arguments, 1);
  11045. return function () {
  11046. return fn.apply(
  11047. null, args.concat(Array.prototype.slice.call(arguments))
  11048. );
  11049. };
  11050. };
  11051. var _concat = function (eachfn, arr, fn, callback) {
  11052. var r = [];
  11053. eachfn(arr, function (x, cb) {
  11054. fn(x, function (err, y) {
  11055. r = r.concat(y || []);
  11056. cb(err);
  11057. });
  11058. }, function (err) {
  11059. callback(err, r);
  11060. });
  11061. };
  11062. async.concat = doParallel(_concat);
  11063. async.concatSeries = doSeries(_concat);
  11064. async.whilst = function (test, iterator, callback) {
  11065. if (test()) {
  11066. iterator(function (err) {
  11067. if (err) {
  11068. return callback(err);
  11069. }
  11070. async.whilst(test, iterator, callback);
  11071. });
  11072. }
  11073. else {
  11074. callback();
  11075. }
  11076. };
  11077. async.doWhilst = function (iterator, test, callback) {
  11078. iterator(function (err) {
  11079. if (err) {
  11080. return callback(err);
  11081. }
  11082. var args = Array.prototype.slice.call(arguments, 1);
  11083. if (test.apply(null, args)) {
  11084. async.doWhilst(iterator, test, callback);
  11085. }
  11086. else {
  11087. callback();
  11088. }
  11089. });
  11090. };
  11091. async.until = function (test, iterator, callback) {
  11092. if (!test()) {
  11093. iterator(function (err) {
  11094. if (err) {
  11095. return callback(err);
  11096. }
  11097. async.until(test, iterator, callback);
  11098. });
  11099. }
  11100. else {
  11101. callback();
  11102. }
  11103. };
  11104. async.doUntil = function (iterator, test, callback) {
  11105. iterator(function (err) {
  11106. if (err) {
  11107. return callback(err);
  11108. }
  11109. var args = Array.prototype.slice.call(arguments, 1);
  11110. if (!test.apply(null, args)) {
  11111. async.doUntil(iterator, test, callback);
  11112. }
  11113. else {
  11114. callback();
  11115. }
  11116. });
  11117. };
  11118. async.queue = function (worker, concurrency) {
  11119. if (concurrency === undefined) {
  11120. concurrency = 1;
  11121. }
  11122. function _insert(q, data, pos, callback) {
  11123. if (!q.started){
  11124. q.started = true;
  11125. }
  11126. if (!_isArray(data)) {
  11127. data = [data];
  11128. }
  11129. if(data.length == 0) {
  11130. // call drain immediately if there are no tasks
  11131. return async.setImmediate(function() {
  11132. if (q.drain) {
  11133. q.drain();
  11134. }
  11135. });
  11136. }
  11137. _each(data, function(task) {
  11138. var item = {
  11139. data: task,
  11140. callback: typeof callback === 'function' ? callback : null
  11141. };
  11142. if (pos) {
  11143. q.tasks.unshift(item);
  11144. } else {
  11145. q.tasks.push(item);
  11146. }
  11147. if (q.saturated && q.tasks.length === q.concurrency) {
  11148. q.saturated();
  11149. }
  11150. async.setImmediate(q.process);
  11151. });
  11152. }
  11153. var workers = 0;
  11154. var q = {
  11155. tasks: [],
  11156. concurrency: concurrency,
  11157. saturated: null,
  11158. empty: null,
  11159. drain: null,
  11160. started: false,
  11161. paused: false,
  11162. push: function (data, callback) {
  11163. _insert(q, data, false, callback);
  11164. },
  11165. kill: function () {
  11166. q.drain = null;
  11167. q.tasks = [];
  11168. },
  11169. unshift: function (data, callback) {
  11170. _insert(q, data, true, callback);
  11171. },
  11172. process: function () {
  11173. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11174. var task = q.tasks.shift();
  11175. if (q.empty && q.tasks.length === 0) {
  11176. q.empty();
  11177. }
  11178. workers += 1;
  11179. var next = function () {
  11180. workers -= 1;
  11181. if (task.callback) {
  11182. task.callback.apply(task, arguments);
  11183. }
  11184. if (q.drain && q.tasks.length + workers === 0) {
  11185. q.drain();
  11186. }
  11187. q.process();
  11188. };
  11189. var cb = only_once(next);
  11190. worker(task.data, cb);
  11191. }
  11192. },
  11193. length: function () {
  11194. return q.tasks.length;
  11195. },
  11196. running: function () {
  11197. return workers;
  11198. },
  11199. idle: function() {
  11200. return q.tasks.length + workers === 0;
  11201. },
  11202. pause: function () {
  11203. if (q.paused === true) { return; }
  11204. q.paused = true;
  11205. q.process();
  11206. },
  11207. resume: function () {
  11208. if (q.paused === false) { return; }
  11209. q.paused = false;
  11210. q.process();
  11211. }
  11212. };
  11213. return q;
  11214. };
  11215. async.priorityQueue = function (worker, concurrency) {
  11216. function _compareTasks(a, b){
  11217. return a.priority - b.priority;
  11218. };
  11219. function _binarySearch(sequence, item, compare) {
  11220. var beg = -1,
  11221. end = sequence.length - 1;
  11222. while (beg < end) {
  11223. var mid = beg + ((end - beg + 1) >>> 1);
  11224. if (compare(item, sequence[mid]) >= 0) {
  11225. beg = mid;
  11226. } else {
  11227. end = mid - 1;
  11228. }
  11229. }
  11230. return beg;
  11231. }
  11232. function _insert(q, data, priority, callback) {
  11233. if (!q.started){
  11234. q.started = true;
  11235. }
  11236. if (!_isArray(data)) {
  11237. data = [data];
  11238. }
  11239. if(data.length == 0) {
  11240. // call drain immediately if there are no tasks
  11241. return async.setImmediate(function() {
  11242. if (q.drain) {
  11243. q.drain();
  11244. }
  11245. });
  11246. }
  11247. _each(data, function(task) {
  11248. var item = {
  11249. data: task,
  11250. priority: priority,
  11251. callback: typeof callback === 'function' ? callback : null
  11252. };
  11253. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11254. if (q.saturated && q.tasks.length === q.concurrency) {
  11255. q.saturated();
  11256. }
  11257. async.setImmediate(q.process);
  11258. });
  11259. }
  11260. // Start with a normal queue
  11261. var q = async.queue(worker, concurrency);
  11262. // Override push to accept second parameter representing priority
  11263. q.push = function (data, priority, callback) {
  11264. _insert(q, data, priority, callback);
  11265. };
  11266. // Remove unshift function
  11267. delete q.unshift;
  11268. return q;
  11269. };
  11270. async.cargo = function (worker, payload) {
  11271. var working = false,
  11272. tasks = [];
  11273. var cargo = {
  11274. tasks: tasks,
  11275. payload: payload,
  11276. saturated: null,
  11277. empty: null,
  11278. drain: null,
  11279. drained: true,
  11280. push: function (data, callback) {
  11281. if (!_isArray(data)) {
  11282. data = [data];
  11283. }
  11284. _each(data, function(task) {
  11285. tasks.push({
  11286. data: task,
  11287. callback: typeof callback === 'function' ? callback : null
  11288. });
  11289. cargo.drained = false;
  11290. if (cargo.saturated && tasks.length === payload) {
  11291. cargo.saturated();
  11292. }
  11293. });
  11294. async.setImmediate(cargo.process);
  11295. },
  11296. process: function process() {
  11297. if (working) return;
  11298. if (tasks.length === 0) {
  11299. if(cargo.drain && !cargo.drained) cargo.drain();
  11300. cargo.drained = true;
  11301. return;
  11302. }
  11303. var ts = typeof payload === 'number'
  11304. ? tasks.splice(0, payload)
  11305. : tasks.splice(0, tasks.length);
  11306. var ds = _map(ts, function (task) {
  11307. return task.data;
  11308. });
  11309. if(cargo.empty) cargo.empty();
  11310. working = true;
  11311. worker(ds, function () {
  11312. working = false;
  11313. var args = arguments;
  11314. _each(ts, function (data) {
  11315. if (data.callback) {
  11316. data.callback.apply(null, args);
  11317. }
  11318. });
  11319. process();
  11320. });
  11321. },
  11322. length: function () {
  11323. return tasks.length;
  11324. },
  11325. running: function () {
  11326. return working;
  11327. }
  11328. };
  11329. return cargo;
  11330. };
  11331. var _console_fn = function (name) {
  11332. return function (fn) {
  11333. var args = Array.prototype.slice.call(arguments, 1);
  11334. fn.apply(null, args.concat([function (err) {
  11335. var args = Array.prototype.slice.call(arguments, 1);
  11336. if (typeof console !== 'undefined') {
  11337. if (err) {
  11338. if (console.error) {
  11339. console.error(err);
  11340. }
  11341. }
  11342. else if (console[name]) {
  11343. _each(args, function (x) {
  11344. console[name](x);
  11345. });
  11346. }
  11347. }
  11348. }]));
  11349. };
  11350. };
  11351. async.log = _console_fn('log');
  11352. async.dir = _console_fn('dir');
  11353. /*async.info = _console_fn('info');
  11354. async.warn = _console_fn('warn');
  11355. async.error = _console_fn('error');*/
  11356. async.memoize = function (fn, hasher) {
  11357. var memo = {};
  11358. var queues = {};
  11359. hasher = hasher || function (x) {
  11360. return x;
  11361. };
  11362. var memoized = function () {
  11363. var args = Array.prototype.slice.call(arguments);
  11364. var callback = args.pop();
  11365. var key = hasher.apply(null, args);
  11366. if (key in memo) {
  11367. async.nextTick(function () {
  11368. callback.apply(null, memo[key]);
  11369. });
  11370. }
  11371. else if (key in queues) {
  11372. queues[key].push(callback);
  11373. }
  11374. else {
  11375. queues[key] = [callback];
  11376. fn.apply(null, args.concat([function () {
  11377. memo[key] = arguments;
  11378. var q = queues[key];
  11379. delete queues[key];
  11380. for (var i = 0, l = q.length; i < l; i++) {
  11381. q[i].apply(null, arguments);
  11382. }
  11383. }]));
  11384. }
  11385. };
  11386. memoized.memo = memo;
  11387. memoized.unmemoized = fn;
  11388. return memoized;
  11389. };
  11390. async.unmemoize = function (fn) {
  11391. return function () {
  11392. return (fn.unmemoized || fn).apply(null, arguments);
  11393. };
  11394. };
  11395. async.times = function (count, iterator, callback) {
  11396. var counter = [];
  11397. for (var i = 0; i < count; i++) {
  11398. counter.push(i);
  11399. }
  11400. return async.map(counter, iterator, callback);
  11401. };
  11402. async.timesSeries = function (count, iterator, callback) {
  11403. var counter = [];
  11404. for (var i = 0; i < count; i++) {
  11405. counter.push(i);
  11406. }
  11407. return async.mapSeries(counter, iterator, callback);
  11408. };
  11409. async.seq = function (/* functions... */) {
  11410. var fns = arguments;
  11411. return function () {
  11412. var that = this;
  11413. var args = Array.prototype.slice.call(arguments);
  11414. var callback = args.pop();
  11415. async.reduce(fns, args, function (newargs, fn, cb) {
  11416. fn.apply(that, newargs.concat([function () {
  11417. var err = arguments[0];
  11418. var nextargs = Array.prototype.slice.call(arguments, 1);
  11419. cb(err, nextargs);
  11420. }]))
  11421. },
  11422. function (err, results) {
  11423. callback.apply(that, [err].concat(results));
  11424. });
  11425. };
  11426. };
  11427. async.compose = function (/* functions... */) {
  11428. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11429. };
  11430. var _applyEach = function (eachfn, fns /*args...*/) {
  11431. var go = function () {
  11432. var that = this;
  11433. var args = Array.prototype.slice.call(arguments);
  11434. var callback = args.pop();
  11435. return eachfn(fns, function (fn, cb) {
  11436. fn.apply(that, args.concat([cb]));
  11437. },
  11438. callback);
  11439. };
  11440. if (arguments.length > 2) {
  11441. var args = Array.prototype.slice.call(arguments, 2);
  11442. return go.apply(this, args);
  11443. }
  11444. else {
  11445. return go;
  11446. }
  11447. };
  11448. async.applyEach = doParallel(_applyEach);
  11449. async.applyEachSeries = doSeries(_applyEach);
  11450. async.forever = function (fn, callback) {
  11451. function next(err) {
  11452. if (err) {
  11453. if (callback) {
  11454. return callback(err);
  11455. }
  11456. throw err;
  11457. }
  11458. fn(next);
  11459. }
  11460. next();
  11461. };
  11462. // Node.js
  11463. if (typeof module !== 'undefined' && module.exports) {
  11464. module.exports = async;
  11465. }
  11466. // AMD / RequireJS
  11467. else if (typeof define !== 'undefined' && define.amd) {
  11468. define([], function () {
  11469. return async;
  11470. });
  11471. }
  11472. // included directly via <script> tag
  11473. else {
  11474. root.async = async;
  11475. }
  11476. }());
  11477. }).call(this,require('_process'))
  11478. },{"_process":44}],43:[function(require,module,exports){
  11479. // Copyright Joyent, Inc. and other Node contributors.
  11480. //
  11481. // Permission is hereby granted, free of charge, to any person obtaining a
  11482. // copy of this software and associated documentation files (the
  11483. // "Software"), to deal in the Software without restriction, including
  11484. // without limitation the rights to use, copy, modify, merge, publish,
  11485. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11486. // persons to whom the Software is furnished to do so, subject to the
  11487. // following conditions:
  11488. //
  11489. // The above copyright notice and this permission notice shall be included
  11490. // in all copies or substantial portions of the Software.
  11491. //
  11492. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11493. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11494. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11495. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11496. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11497. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11498. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11499. function EventEmitter() {
  11500. this._events = this._events || {};
  11501. this._maxListeners = this._maxListeners || undefined;
  11502. }
  11503. module.exports = EventEmitter;
  11504. // Backwards-compat with node 0.10.x
  11505. EventEmitter.EventEmitter = EventEmitter;
  11506. EventEmitter.prototype._events = undefined;
  11507. EventEmitter.prototype._maxListeners = undefined;
  11508. // By default EventEmitters will print a warning if more than 10 listeners are
  11509. // added to it. This is a useful default which helps finding memory leaks.
  11510. EventEmitter.defaultMaxListeners = 10;
  11511. // Obviously not all Emitters should be limited to 10. This function allows
  11512. // that to be increased. Set to zero for unlimited.
  11513. EventEmitter.prototype.setMaxListeners = function(n) {
  11514. if (!isNumber(n) || n < 0 || isNaN(n))
  11515. throw TypeError('n must be a positive number');
  11516. this._maxListeners = n;
  11517. return this;
  11518. };
  11519. EventEmitter.prototype.emit = function(type) {
  11520. var er, handler, len, args, i, listeners;
  11521. if (!this._events)
  11522. this._events = {};
  11523. // If there is no 'error' event listener then throw.
  11524. if (type === 'error') {
  11525. if (!this._events.error ||
  11526. (isObject(this._events.error) && !this._events.error.length)) {
  11527. er = arguments[1];
  11528. if (er instanceof Error) {
  11529. throw er; // Unhandled 'error' event
  11530. }
  11531. throw TypeError('Uncaught, unspecified "error" event.');
  11532. }
  11533. }
  11534. handler = this._events[type];
  11535. if (isUndefined(handler))
  11536. return false;
  11537. if (isFunction(handler)) {
  11538. switch (arguments.length) {
  11539. // fast cases
  11540. case 1:
  11541. handler.call(this);
  11542. break;
  11543. case 2:
  11544. handler.call(this, arguments[1]);
  11545. break;
  11546. case 3:
  11547. handler.call(this, arguments[1], arguments[2]);
  11548. break;
  11549. // slower
  11550. default:
  11551. len = arguments.length;
  11552. args = new Array(len - 1);
  11553. for (i = 1; i < len; i++)
  11554. args[i - 1] = arguments[i];
  11555. handler.apply(this, args);
  11556. }
  11557. } else if (isObject(handler)) {
  11558. len = arguments.length;
  11559. args = new Array(len - 1);
  11560. for (i = 1; i < len; i++)
  11561. args[i - 1] = arguments[i];
  11562. listeners = handler.slice();
  11563. len = listeners.length;
  11564. for (i = 0; i < len; i++)
  11565. listeners[i].apply(this, args);
  11566. }
  11567. return true;
  11568. };
  11569. EventEmitter.prototype.addListener = function(type, listener) {
  11570. var m;
  11571. if (!isFunction(listener))
  11572. throw TypeError('listener must be a function');
  11573. if (!this._events)
  11574. this._events = {};
  11575. // To avoid recursion in the case that type === "newListener"! Before
  11576. // adding it to the listeners, first emit "newListener".
  11577. if (this._events.newListener)
  11578. this.emit('newListener', type,
  11579. isFunction(listener.listener) ?
  11580. listener.listener : listener);
  11581. if (!this._events[type])
  11582. // Optimize the case of one listener. Don't need the extra array object.
  11583. this._events[type] = listener;
  11584. else if (isObject(this._events[type]))
  11585. // If we've already got an array, just append.
  11586. this._events[type].push(listener);
  11587. else
  11588. // Adding the second element, need to change to array.
  11589. this._events[type] = [this._events[type], listener];
  11590. // Check for listener leak
  11591. if (isObject(this._events[type]) && !this._events[type].warned) {
  11592. var m;
  11593. if (!isUndefined(this._maxListeners)) {
  11594. m = this._maxListeners;
  11595. } else {
  11596. m = EventEmitter.defaultMaxListeners;
  11597. }
  11598. if (m && m > 0 && this._events[type].length > m) {
  11599. this._events[type].warned = true;
  11600. console.error('(node) warning: possible EventEmitter memory ' +
  11601. 'leak detected. %d listeners added. ' +
  11602. 'Use emitter.setMaxListeners() to increase limit.',
  11603. this._events[type].length);
  11604. if (typeof console.trace === 'function') {
  11605. // not supported in IE 10
  11606. console.trace();
  11607. }
  11608. }
  11609. }
  11610. return this;
  11611. };
  11612. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11613. EventEmitter.prototype.once = function(type, listener) {
  11614. if (!isFunction(listener))
  11615. throw TypeError('listener must be a function');
  11616. var fired = false;
  11617. function g() {
  11618. this.removeListener(type, g);
  11619. if (!fired) {
  11620. fired = true;
  11621. listener.apply(this, arguments);
  11622. }
  11623. }
  11624. g.listener = listener;
  11625. this.on(type, g);
  11626. return this;
  11627. };
  11628. // emits a 'removeListener' event iff the listener was removed
  11629. EventEmitter.prototype.removeListener = function(type, listener) {
  11630. var list, position, length, i;
  11631. if (!isFunction(listener))
  11632. throw TypeError('listener must be a function');
  11633. if (!this._events || !this._events[type])
  11634. return this;
  11635. list = this._events[type];
  11636. length = list.length;
  11637. position = -1;
  11638. if (list === listener ||
  11639. (isFunction(list.listener) && list.listener === listener)) {
  11640. delete this._events[type];
  11641. if (this._events.removeListener)
  11642. this.emit('removeListener', type, listener);
  11643. } else if (isObject(list)) {
  11644. for (i = length; i-- > 0;) {
  11645. if (list[i] === listener ||
  11646. (list[i].listener && list[i].listener === listener)) {
  11647. position = i;
  11648. break;
  11649. }
  11650. }
  11651. if (position < 0)
  11652. return this;
  11653. if (list.length === 1) {
  11654. list.length = 0;
  11655. delete this._events[type];
  11656. } else {
  11657. list.splice(position, 1);
  11658. }
  11659. if (this._events.removeListener)
  11660. this.emit('removeListener', type, listener);
  11661. }
  11662. return this;
  11663. };
  11664. EventEmitter.prototype.removeAllListeners = function(type) {
  11665. var key, listeners;
  11666. if (!this._events)
  11667. return this;
  11668. // not listening for removeListener, no need to emit
  11669. if (!this._events.removeListener) {
  11670. if (arguments.length === 0)
  11671. this._events = {};
  11672. else if (this._events[type])
  11673. delete this._events[type];
  11674. return this;
  11675. }
  11676. // emit removeListener for all listeners on all events
  11677. if (arguments.length === 0) {
  11678. for (key in this._events) {
  11679. if (key === 'removeListener') continue;
  11680. this.removeAllListeners(key);
  11681. }
  11682. this.removeAllListeners('removeListener');
  11683. this._events = {};
  11684. return this;
  11685. }
  11686. listeners = this._events[type];
  11687. if (isFunction(listeners)) {
  11688. this.removeListener(type, listeners);
  11689. } else {
  11690. // LIFO order
  11691. while (listeners.length)
  11692. this.removeListener(type, listeners[listeners.length - 1]);
  11693. }
  11694. delete this._events[type];
  11695. return this;
  11696. };
  11697. EventEmitter.prototype.listeners = function(type) {
  11698. var ret;
  11699. if (!this._events || !this._events[type])
  11700. ret = [];
  11701. else if (isFunction(this._events[type]))
  11702. ret = [this._events[type]];
  11703. else
  11704. ret = this._events[type].slice();
  11705. return ret;
  11706. };
  11707. EventEmitter.listenerCount = function(emitter, type) {
  11708. var ret;
  11709. if (!emitter._events || !emitter._events[type])
  11710. ret = 0;
  11711. else if (isFunction(emitter._events[type]))
  11712. ret = 1;
  11713. else
  11714. ret = emitter._events[type].length;
  11715. return ret;
  11716. };
  11717. function isFunction(arg) {
  11718. return typeof arg === 'function';
  11719. }
  11720. function isNumber(arg) {
  11721. return typeof arg === 'number';
  11722. }
  11723. function isObject(arg) {
  11724. return typeof arg === 'object' && arg !== null;
  11725. }
  11726. function isUndefined(arg) {
  11727. return arg === void 0;
  11728. }
  11729. },{}],44:[function(require,module,exports){
  11730. // shim for using process in browser
  11731. var process = module.exports = {};
  11732. var queue = [];
  11733. var draining = false;
  11734. var currentQueue;
  11735. var queueIndex = -1;
  11736. function cleanUpNextTick() {
  11737. draining = false;
  11738. if (currentQueue.length) {
  11739. queue = currentQueue.concat(queue);
  11740. } else {
  11741. queueIndex = -1;
  11742. }
  11743. if (queue.length) {
  11744. drainQueue();
  11745. }
  11746. }
  11747. function drainQueue() {
  11748. if (draining) {
  11749. return;
  11750. }
  11751. var timeout = setTimeout(cleanUpNextTick);
  11752. draining = true;
  11753. var len = queue.length;
  11754. while(len) {
  11755. currentQueue = queue;
  11756. queue = [];
  11757. while (++queueIndex < len) {
  11758. if (currentQueue) {
  11759. currentQueue[queueIndex].run();
  11760. }
  11761. }
  11762. queueIndex = -1;
  11763. len = queue.length;
  11764. }
  11765. currentQueue = null;
  11766. draining = false;
  11767. clearTimeout(timeout);
  11768. }
  11769. process.nextTick = function (fun) {
  11770. var args = new Array(arguments.length - 1);
  11771. if (arguments.length > 1) {
  11772. for (var i = 1; i < arguments.length; i++) {
  11773. args[i - 1] = arguments[i];
  11774. }
  11775. }
  11776. queue.push(new Item(fun, args));
  11777. if (queue.length === 1 && !draining) {
  11778. setTimeout(drainQueue, 0);
  11779. }
  11780. };
  11781. // v8 likes predictible objects
  11782. function Item(fun, array) {
  11783. this.fun = fun;
  11784. this.array = array;
  11785. }
  11786. Item.prototype.run = function () {
  11787. this.fun.apply(null, this.array);
  11788. };
  11789. process.title = 'browser';
  11790. process.browser = true;
  11791. process.env = {};
  11792. process.argv = [];
  11793. process.version = ''; // empty string to avoid regexp issues
  11794. process.versions = {};
  11795. function noop() {}
  11796. process.on = noop;
  11797. process.addListener = noop;
  11798. process.once = noop;
  11799. process.off = noop;
  11800. process.removeListener = noop;
  11801. process.removeAllListeners = noop;
  11802. process.emit = noop;
  11803. process.binding = function (name) {
  11804. throw new Error('process.binding is not supported');
  11805. };
  11806. process.cwd = function () { return '/' };
  11807. process.chdir = function (dir) {
  11808. throw new Error('process.chdir is not supported');
  11809. };
  11810. process.umask = function() { return 0; };
  11811. },{}],45:[function(require,module,exports){
  11812. (function (process,global){
  11813. /*!
  11814. * @overview es6-promise - a tiny implementation of Promises/A+.
  11815. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11816. * @license Licensed under MIT license
  11817. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  11818. * @version 3.0.2
  11819. */
  11820. (function() {
  11821. "use strict";
  11822. function lib$es6$promise$utils$$objectOrFunction(x) {
  11823. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  11824. }
  11825. function lib$es6$promise$utils$$isFunction(x) {
  11826. return typeof x === 'function';
  11827. }
  11828. function lib$es6$promise$utils$$isMaybeThenable(x) {
  11829. return typeof x === 'object' && x !== null;
  11830. }
  11831. var lib$es6$promise$utils$$_isArray;
  11832. if (!Array.isArray) {
  11833. lib$es6$promise$utils$$_isArray = function (x) {
  11834. return Object.prototype.toString.call(x) === '[object Array]';
  11835. };
  11836. } else {
  11837. lib$es6$promise$utils$$_isArray = Array.isArray;
  11838. }
  11839. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  11840. var lib$es6$promise$asap$$len = 0;
  11841. var lib$es6$promise$asap$$toString = {}.toString;
  11842. var lib$es6$promise$asap$$vertxNext;
  11843. var lib$es6$promise$asap$$customSchedulerFn;
  11844. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  11845. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  11846. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  11847. lib$es6$promise$asap$$len += 2;
  11848. if (lib$es6$promise$asap$$len === 2) {
  11849. // If len is 2, that means that we need to schedule an async flush.
  11850. // If additional callbacks are queued before the queue is flushed, they
  11851. // will be processed by this flush that we are scheduling.
  11852. if (lib$es6$promise$asap$$customSchedulerFn) {
  11853. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  11854. } else {
  11855. lib$es6$promise$asap$$scheduleFlush();
  11856. }
  11857. }
  11858. }
  11859. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  11860. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  11861. }
  11862. function lib$es6$promise$asap$$setAsap(asapFn) {
  11863. lib$es6$promise$asap$$asap = asapFn;
  11864. }
  11865. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  11866. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  11867. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  11868. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  11869. // test for web worker but not in IE10
  11870. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  11871. typeof importScripts !== 'undefined' &&
  11872. typeof MessageChannel !== 'undefined';
  11873. // node
  11874. function lib$es6$promise$asap$$useNextTick() {
  11875. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  11876. // see https://github.com/cujojs/when/issues/410 for details
  11877. return function() {
  11878. process.nextTick(lib$es6$promise$asap$$flush);
  11879. };
  11880. }
  11881. // vertx
  11882. function lib$es6$promise$asap$$useVertxTimer() {
  11883. return function() {
  11884. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  11885. };
  11886. }
  11887. function lib$es6$promise$asap$$useMutationObserver() {
  11888. var iterations = 0;
  11889. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  11890. var node = document.createTextNode('');
  11891. observer.observe(node, { characterData: true });
  11892. return function() {
  11893. node.data = (iterations = ++iterations % 2);
  11894. };
  11895. }
  11896. // web worker
  11897. function lib$es6$promise$asap$$useMessageChannel() {
  11898. var channel = new MessageChannel();
  11899. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  11900. return function () {
  11901. channel.port2.postMessage(0);
  11902. };
  11903. }
  11904. function lib$es6$promise$asap$$useSetTimeout() {
  11905. return function() {
  11906. setTimeout(lib$es6$promise$asap$$flush, 1);
  11907. };
  11908. }
  11909. var lib$es6$promise$asap$$queue = new Array(1000);
  11910. function lib$es6$promise$asap$$flush() {
  11911. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  11912. var callback = lib$es6$promise$asap$$queue[i];
  11913. var arg = lib$es6$promise$asap$$queue[i+1];
  11914. callback(arg);
  11915. lib$es6$promise$asap$$queue[i] = undefined;
  11916. lib$es6$promise$asap$$queue[i+1] = undefined;
  11917. }
  11918. lib$es6$promise$asap$$len = 0;
  11919. }
  11920. function lib$es6$promise$asap$$attemptVertx() {
  11921. try {
  11922. var r = require;
  11923. var vertx = r('vertx');
  11924. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  11925. return lib$es6$promise$asap$$useVertxTimer();
  11926. } catch(e) {
  11927. return lib$es6$promise$asap$$useSetTimeout();
  11928. }
  11929. }
  11930. var lib$es6$promise$asap$$scheduleFlush;
  11931. // Decide what async method to use to triggering processing of queued callbacks:
  11932. if (lib$es6$promise$asap$$isNode) {
  11933. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  11934. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  11935. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  11936. } else if (lib$es6$promise$asap$$isWorker) {
  11937. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  11938. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  11939. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  11940. } else {
  11941. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  11942. }
  11943. function lib$es6$promise$$internal$$noop() {}
  11944. var lib$es6$promise$$internal$$PENDING = void 0;
  11945. var lib$es6$promise$$internal$$FULFILLED = 1;
  11946. var lib$es6$promise$$internal$$REJECTED = 2;
  11947. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11948. function lib$es6$promise$$internal$$selfFulfillment() {
  11949. return new TypeError("You cannot resolve a promise with itself");
  11950. }
  11951. function lib$es6$promise$$internal$$cannotReturnOwn() {
  11952. return new TypeError('A promises callback cannot return that same promise.');
  11953. }
  11954. function lib$es6$promise$$internal$$getThen(promise) {
  11955. try {
  11956. return promise.then;
  11957. } catch(error) {
  11958. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  11959. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  11960. }
  11961. }
  11962. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  11963. try {
  11964. then.call(value, fulfillmentHandler, rejectionHandler);
  11965. } catch(e) {
  11966. return e;
  11967. }
  11968. }
  11969. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  11970. lib$es6$promise$asap$$asap(function(promise) {
  11971. var sealed = false;
  11972. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  11973. if (sealed) { return; }
  11974. sealed = true;
  11975. if (thenable !== value) {
  11976. lib$es6$promise$$internal$$resolve(promise, value);
  11977. } else {
  11978. lib$es6$promise$$internal$$fulfill(promise, value);
  11979. }
  11980. }, function(reason) {
  11981. if (sealed) { return; }
  11982. sealed = true;
  11983. lib$es6$promise$$internal$$reject(promise, reason);
  11984. }, 'Settle: ' + (promise._label || ' unknown promise'));
  11985. if (!sealed && error) {
  11986. sealed = true;
  11987. lib$es6$promise$$internal$$reject(promise, error);
  11988. }
  11989. }, promise);
  11990. }
  11991. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  11992. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  11993. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  11994. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  11995. lib$es6$promise$$internal$$reject(promise, thenable._result);
  11996. } else {
  11997. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  11998. lib$es6$promise$$internal$$resolve(promise, value);
  11999. }, function(reason) {
  12000. lib$es6$promise$$internal$$reject(promise, reason);
  12001. });
  12002. }
  12003. }
  12004. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12005. if (maybeThenable.constructor === promise.constructor) {
  12006. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12007. } else {
  12008. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12009. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12010. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12011. } else if (then === undefined) {
  12012. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12013. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12014. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12015. } else {
  12016. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12017. }
  12018. }
  12019. }
  12020. function lib$es6$promise$$internal$$resolve(promise, value) {
  12021. if (promise === value) {
  12022. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12023. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12024. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12025. } else {
  12026. lib$es6$promise$$internal$$fulfill(promise, value);
  12027. }
  12028. }
  12029. function lib$es6$promise$$internal$$publishRejection(promise) {
  12030. if (promise._onerror) {
  12031. promise._onerror(promise._result);
  12032. }
  12033. lib$es6$promise$$internal$$publish(promise);
  12034. }
  12035. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12036. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12037. promise._result = value;
  12038. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12039. if (promise._subscribers.length !== 0) {
  12040. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12041. }
  12042. }
  12043. function lib$es6$promise$$internal$$reject(promise, reason) {
  12044. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12045. promise._state = lib$es6$promise$$internal$$REJECTED;
  12046. promise._result = reason;
  12047. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12048. }
  12049. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12050. var subscribers = parent._subscribers;
  12051. var length = subscribers.length;
  12052. parent._onerror = null;
  12053. subscribers[length] = child;
  12054. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12055. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12056. if (length === 0 && parent._state) {
  12057. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12058. }
  12059. }
  12060. function lib$es6$promise$$internal$$publish(promise) {
  12061. var subscribers = promise._subscribers;
  12062. var settled = promise._state;
  12063. if (subscribers.length === 0) { return; }
  12064. var child, callback, detail = promise._result;
  12065. for (var i = 0; i < subscribers.length; i += 3) {
  12066. child = subscribers[i];
  12067. callback = subscribers[i + settled];
  12068. if (child) {
  12069. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12070. } else {
  12071. callback(detail);
  12072. }
  12073. }
  12074. promise._subscribers.length = 0;
  12075. }
  12076. function lib$es6$promise$$internal$$ErrorObject() {
  12077. this.error = null;
  12078. }
  12079. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12080. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12081. try {
  12082. return callback(detail);
  12083. } catch(e) {
  12084. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12085. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12086. }
  12087. }
  12088. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12089. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12090. value, error, succeeded, failed;
  12091. if (hasCallback) {
  12092. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12093. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12094. failed = true;
  12095. error = value.error;
  12096. value = null;
  12097. } else {
  12098. succeeded = true;
  12099. }
  12100. if (promise === value) {
  12101. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12102. return;
  12103. }
  12104. } else {
  12105. value = detail;
  12106. succeeded = true;
  12107. }
  12108. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12109. // noop
  12110. } else if (hasCallback && succeeded) {
  12111. lib$es6$promise$$internal$$resolve(promise, value);
  12112. } else if (failed) {
  12113. lib$es6$promise$$internal$$reject(promise, error);
  12114. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12115. lib$es6$promise$$internal$$fulfill(promise, value);
  12116. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12117. lib$es6$promise$$internal$$reject(promise, value);
  12118. }
  12119. }
  12120. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12121. try {
  12122. resolver(function resolvePromise(value){
  12123. lib$es6$promise$$internal$$resolve(promise, value);
  12124. }, function rejectPromise(reason) {
  12125. lib$es6$promise$$internal$$reject(promise, reason);
  12126. });
  12127. } catch(e) {
  12128. lib$es6$promise$$internal$$reject(promise, e);
  12129. }
  12130. }
  12131. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12132. var enumerator = this;
  12133. enumerator._instanceConstructor = Constructor;
  12134. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12135. if (enumerator._validateInput(input)) {
  12136. enumerator._input = input;
  12137. enumerator.length = input.length;
  12138. enumerator._remaining = input.length;
  12139. enumerator._init();
  12140. if (enumerator.length === 0) {
  12141. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12142. } else {
  12143. enumerator.length = enumerator.length || 0;
  12144. enumerator._enumerate();
  12145. if (enumerator._remaining === 0) {
  12146. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12147. }
  12148. }
  12149. } else {
  12150. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12151. }
  12152. }
  12153. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12154. return lib$es6$promise$utils$$isArray(input);
  12155. };
  12156. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12157. return new Error('Array Methods must be provided an Array');
  12158. };
  12159. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12160. this._result = new Array(this.length);
  12161. };
  12162. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12163. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12164. var enumerator = this;
  12165. var length = enumerator.length;
  12166. var promise = enumerator.promise;
  12167. var input = enumerator._input;
  12168. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12169. enumerator._eachEntry(input[i], i);
  12170. }
  12171. };
  12172. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12173. var enumerator = this;
  12174. var c = enumerator._instanceConstructor;
  12175. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12176. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12177. entry._onerror = null;
  12178. enumerator._settledAt(entry._state, i, entry._result);
  12179. } else {
  12180. enumerator._willSettleAt(c.resolve(entry), i);
  12181. }
  12182. } else {
  12183. enumerator._remaining--;
  12184. enumerator._result[i] = entry;
  12185. }
  12186. };
  12187. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12188. var enumerator = this;
  12189. var promise = enumerator.promise;
  12190. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12191. enumerator._remaining--;
  12192. if (state === lib$es6$promise$$internal$$REJECTED) {
  12193. lib$es6$promise$$internal$$reject(promise, value);
  12194. } else {
  12195. enumerator._result[i] = value;
  12196. }
  12197. }
  12198. if (enumerator._remaining === 0) {
  12199. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12200. }
  12201. };
  12202. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12203. var enumerator = this;
  12204. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12205. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12206. }, function(reason) {
  12207. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12208. });
  12209. };
  12210. function lib$es6$promise$promise$all$$all(entries) {
  12211. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12212. }
  12213. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12214. function lib$es6$promise$promise$race$$race(entries) {
  12215. /*jshint validthis:true */
  12216. var Constructor = this;
  12217. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12218. if (!lib$es6$promise$utils$$isArray(entries)) {
  12219. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12220. return promise;
  12221. }
  12222. var length = entries.length;
  12223. function onFulfillment(value) {
  12224. lib$es6$promise$$internal$$resolve(promise, value);
  12225. }
  12226. function onRejection(reason) {
  12227. lib$es6$promise$$internal$$reject(promise, reason);
  12228. }
  12229. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12230. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12231. }
  12232. return promise;
  12233. }
  12234. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12235. function lib$es6$promise$promise$resolve$$resolve(object) {
  12236. /*jshint validthis:true */
  12237. var Constructor = this;
  12238. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12239. return object;
  12240. }
  12241. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12242. lib$es6$promise$$internal$$resolve(promise, object);
  12243. return promise;
  12244. }
  12245. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12246. function lib$es6$promise$promise$reject$$reject(reason) {
  12247. /*jshint validthis:true */
  12248. var Constructor = this;
  12249. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12250. lib$es6$promise$$internal$$reject(promise, reason);
  12251. return promise;
  12252. }
  12253. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12254. var lib$es6$promise$promise$$counter = 0;
  12255. function lib$es6$promise$promise$$needsResolver() {
  12256. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12257. }
  12258. function lib$es6$promise$promise$$needsNew() {
  12259. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12260. }
  12261. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12262. /**
  12263. Promise objects represent the eventual result of an asynchronous operation. The
  12264. primary way of interacting with a promise is through its `then` method, which
  12265. registers callbacks to receive either a promise's eventual value or the reason
  12266. why the promise cannot be fulfilled.
  12267. Terminology
  12268. -----------
  12269. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12270. - `thenable` is an object or function that defines a `then` method.
  12271. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12272. - `exception` is a value that is thrown using the throw statement.
  12273. - `reason` is a value that indicates why a promise was rejected.
  12274. - `settled` the final resting state of a promise, fulfilled or rejected.
  12275. A promise can be in one of three states: pending, fulfilled, or rejected.
  12276. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12277. state. Promises that are rejected have a rejection reason and are in the
  12278. rejected state. A fulfillment value is never a thenable.
  12279. Promises can also be said to *resolve* a value. If this value is also a
  12280. promise, then the original promise's settled state will match the value's
  12281. settled state. So a promise that *resolves* a promise that rejects will
  12282. itself reject, and a promise that *resolves* a promise that fulfills will
  12283. itself fulfill.
  12284. Basic Usage:
  12285. ------------
  12286. ```js
  12287. var promise = new Promise(function(resolve, reject) {
  12288. // on success
  12289. resolve(value);
  12290. // on failure
  12291. reject(reason);
  12292. });
  12293. promise.then(function(value) {
  12294. // on fulfillment
  12295. }, function(reason) {
  12296. // on rejection
  12297. });
  12298. ```
  12299. Advanced Usage:
  12300. ---------------
  12301. Promises shine when abstracting away asynchronous interactions such as
  12302. `XMLHttpRequest`s.
  12303. ```js
  12304. function getJSON(url) {
  12305. return new Promise(function(resolve, reject){
  12306. var xhr = new XMLHttpRequest();
  12307. xhr.open('GET', url);
  12308. xhr.onreadystatechange = handler;
  12309. xhr.responseType = 'json';
  12310. xhr.setRequestHeader('Accept', 'application/json');
  12311. xhr.send();
  12312. function handler() {
  12313. if (this.readyState === this.DONE) {
  12314. if (this.status === 200) {
  12315. resolve(this.response);
  12316. } else {
  12317. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12318. }
  12319. }
  12320. };
  12321. });
  12322. }
  12323. getJSON('/posts.json').then(function(json) {
  12324. // on fulfillment
  12325. }, function(reason) {
  12326. // on rejection
  12327. });
  12328. ```
  12329. Unlike callbacks, promises are great composable primitives.
  12330. ```js
  12331. Promise.all([
  12332. getJSON('/posts'),
  12333. getJSON('/comments')
  12334. ]).then(function(values){
  12335. values[0] // => postsJSON
  12336. values[1] // => commentsJSON
  12337. return values;
  12338. });
  12339. ```
  12340. @class Promise
  12341. @param {function} resolver
  12342. Useful for tooling.
  12343. @constructor
  12344. */
  12345. function lib$es6$promise$promise$$Promise(resolver) {
  12346. this._id = lib$es6$promise$promise$$counter++;
  12347. this._state = undefined;
  12348. this._result = undefined;
  12349. this._subscribers = [];
  12350. if (lib$es6$promise$$internal$$noop !== resolver) {
  12351. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12352. lib$es6$promise$promise$$needsResolver();
  12353. }
  12354. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12355. lib$es6$promise$promise$$needsNew();
  12356. }
  12357. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12358. }
  12359. }
  12360. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12361. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12362. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12363. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12364. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12365. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12366. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12367. lib$es6$promise$promise$$Promise.prototype = {
  12368. constructor: lib$es6$promise$promise$$Promise,
  12369. /**
  12370. The primary way of interacting with a promise is through its `then` method,
  12371. which registers callbacks to receive either a promise's eventual value or the
  12372. reason why the promise cannot be fulfilled.
  12373. ```js
  12374. findUser().then(function(user){
  12375. // user is available
  12376. }, function(reason){
  12377. // user is unavailable, and you are given the reason why
  12378. });
  12379. ```
  12380. Chaining
  12381. --------
  12382. The return value of `then` is itself a promise. This second, 'downstream'
  12383. promise is resolved with the return value of the first promise's fulfillment
  12384. or rejection handler, or rejected if the handler throws an exception.
  12385. ```js
  12386. findUser().then(function (user) {
  12387. return user.name;
  12388. }, function (reason) {
  12389. return 'default name';
  12390. }).then(function (userName) {
  12391. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12392. // will be `'default name'`
  12393. });
  12394. findUser().then(function (user) {
  12395. throw new Error('Found user, but still unhappy');
  12396. }, function (reason) {
  12397. throw new Error('`findUser` rejected and we're unhappy');
  12398. }).then(function (value) {
  12399. // never reached
  12400. }, function (reason) {
  12401. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12402. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12403. });
  12404. ```
  12405. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12406. ```js
  12407. findUser().then(function (user) {
  12408. throw new PedagogicalException('Upstream error');
  12409. }).then(function (value) {
  12410. // never reached
  12411. }).then(function (value) {
  12412. // never reached
  12413. }, function (reason) {
  12414. // The `PedgagocialException` is propagated all the way down to here
  12415. });
  12416. ```
  12417. Assimilation
  12418. ------------
  12419. Sometimes the value you want to propagate to a downstream promise can only be
  12420. retrieved asynchronously. This can be achieved by returning a promise in the
  12421. fulfillment or rejection handler. The downstream promise will then be pending
  12422. until the returned promise is settled. This is called *assimilation*.
  12423. ```js
  12424. findUser().then(function (user) {
  12425. return findCommentsByAuthor(user);
  12426. }).then(function (comments) {
  12427. // The user's comments are now available
  12428. });
  12429. ```
  12430. If the assimliated promise rejects, then the downstream promise will also reject.
  12431. ```js
  12432. findUser().then(function (user) {
  12433. return findCommentsByAuthor(user);
  12434. }).then(function (comments) {
  12435. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12436. }, function (reason) {
  12437. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12438. });
  12439. ```
  12440. Simple Example
  12441. --------------
  12442. Synchronous Example
  12443. ```javascript
  12444. var result;
  12445. try {
  12446. result = findResult();
  12447. // success
  12448. } catch(reason) {
  12449. // failure
  12450. }
  12451. ```
  12452. Errback Example
  12453. ```js
  12454. findResult(function(result, err){
  12455. if (err) {
  12456. // failure
  12457. } else {
  12458. // success
  12459. }
  12460. });
  12461. ```
  12462. Promise Example;
  12463. ```javascript
  12464. findResult().then(function(result){
  12465. // success
  12466. }, function(reason){
  12467. // failure
  12468. });
  12469. ```
  12470. Advanced Example
  12471. --------------
  12472. Synchronous Example
  12473. ```javascript
  12474. var author, books;
  12475. try {
  12476. author = findAuthor();
  12477. books = findBooksByAuthor(author);
  12478. // success
  12479. } catch(reason) {
  12480. // failure
  12481. }
  12482. ```
  12483. Errback Example
  12484. ```js
  12485. function foundBooks(books) {
  12486. }
  12487. function failure(reason) {
  12488. }
  12489. findAuthor(function(author, err){
  12490. if (err) {
  12491. failure(err);
  12492. // failure
  12493. } else {
  12494. try {
  12495. findBoooksByAuthor(author, function(books, err) {
  12496. if (err) {
  12497. failure(err);
  12498. } else {
  12499. try {
  12500. foundBooks(books);
  12501. } catch(reason) {
  12502. failure(reason);
  12503. }
  12504. }
  12505. });
  12506. } catch(error) {
  12507. failure(err);
  12508. }
  12509. // success
  12510. }
  12511. });
  12512. ```
  12513. Promise Example;
  12514. ```javascript
  12515. findAuthor().
  12516. then(findBooksByAuthor).
  12517. then(function(books){
  12518. // found books
  12519. }).catch(function(reason){
  12520. // something went wrong
  12521. });
  12522. ```
  12523. @method then
  12524. @param {Function} onFulfilled
  12525. @param {Function} onRejected
  12526. Useful for tooling.
  12527. @return {Promise}
  12528. */
  12529. then: function(onFulfillment, onRejection) {
  12530. var parent = this;
  12531. var state = parent._state;
  12532. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12533. return this;
  12534. }
  12535. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12536. var result = parent._result;
  12537. if (state) {
  12538. var callback = arguments[state - 1];
  12539. lib$es6$promise$asap$$asap(function(){
  12540. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12541. });
  12542. } else {
  12543. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12544. }
  12545. return child;
  12546. },
  12547. /**
  12548. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12549. as the catch block of a try/catch statement.
  12550. ```js
  12551. function findAuthor(){
  12552. throw new Error('couldn't find that author');
  12553. }
  12554. // synchronous
  12555. try {
  12556. findAuthor();
  12557. } catch(reason) {
  12558. // something went wrong
  12559. }
  12560. // async with promises
  12561. findAuthor().catch(function(reason){
  12562. // something went wrong
  12563. });
  12564. ```
  12565. @method catch
  12566. @param {Function} onRejection
  12567. Useful for tooling.
  12568. @return {Promise}
  12569. */
  12570. 'catch': function(onRejection) {
  12571. return this.then(null, onRejection);
  12572. }
  12573. };
  12574. function lib$es6$promise$polyfill$$polyfill() {
  12575. var local;
  12576. if (typeof global !== 'undefined') {
  12577. local = global;
  12578. } else if (typeof self !== 'undefined') {
  12579. local = self;
  12580. } else {
  12581. try {
  12582. local = Function('return this')();
  12583. } catch (e) {
  12584. throw new Error('polyfill failed because global object is unavailable in this environment');
  12585. }
  12586. }
  12587. var P = local.Promise;
  12588. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12589. return;
  12590. }
  12591. local.Promise = lib$es6$promise$promise$$default;
  12592. }
  12593. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12594. var lib$es6$promise$umd$$ES6Promise = {
  12595. 'Promise': lib$es6$promise$promise$$default,
  12596. 'polyfill': lib$es6$promise$polyfill$$default
  12597. };
  12598. /* global define:true module:true window: true */
  12599. if (typeof define === 'function' && define['amd']) {
  12600. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12601. } else if (typeof module !== 'undefined' && module['exports']) {
  12602. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12603. } else if (typeof this !== 'undefined') {
  12604. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12605. }
  12606. lib$es6$promise$polyfill$$default();
  12607. }).call(this);
  12608. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12609. },{"_process":44}],46:[function(require,module,exports){
  12610. /* Copyright @ 2015 Atlassian Pty Ltd
  12611. *
  12612. * Licensed under the Apache License, Version 2.0 (the "License");
  12613. * you may not use this file except in compliance with the License.
  12614. * You may obtain a copy of the License at
  12615. *
  12616. * http://www.apache.org/licenses/LICENSE-2.0
  12617. *
  12618. * Unless required by applicable law or agreed to in writing, software
  12619. * distributed under the License is distributed on an "AS IS" BASIS,
  12620. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12621. * See the License for the specific language governing permissions and
  12622. * limitations under the License.
  12623. */
  12624. /**
  12625. * Ordered log levels.
  12626. */
  12627. var levels = {
  12628. "trace": 0,
  12629. "debug": 1,
  12630. "info": 2,
  12631. "log": 3,
  12632. "warn": 4,
  12633. "error": 5
  12634. };
  12635. /**
  12636. * Parses Error's object stack trace and extracts information about the last
  12637. * caller before the log method was called.
  12638. * @returns JS object with info about the caller - method name, file location,
  12639. * line and column.
  12640. */
  12641. function getCallerInfo() {
  12642. var callerInfo = {
  12643. methodName: "",
  12644. fileLocation: "",
  12645. line: null,
  12646. column: null
  12647. };
  12648. //gets the part of the stack without the logger wrappers
  12649. var error = new Error();
  12650. var stack = error.stack? error.stack.split("\n") : [];
  12651. if(!stack || stack.length < 1) {
  12652. return callerInfo;
  12653. }
  12654. var m = null;
  12655. if(stack[3]) {
  12656. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  12657. }
  12658. if(!m || m.length <= 4) {
  12659. //Firefox && Safari
  12660. if(stack[2].indexOf("log@") === 0){
  12661. //Safari
  12662. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  12663. } else {
  12664. //Firefox
  12665. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  12666. }
  12667. return callerInfo;
  12668. }
  12669. callerInfo.methodName = m[1];
  12670. callerInfo.fileLocation = m[2];
  12671. callerInfo.line = m[3];
  12672. callerInfo.column = m[4];
  12673. return callerInfo;
  12674. }
  12675. /**
  12676. * Logs messages using the transports and level from the logger.
  12677. * @param logger a logger instance.
  12678. * @param level the log level of the message. See the levels variable.
  12679. * @param arguments array with arguments that will be logged.
  12680. */
  12681. function log() {
  12682. var logger = arguments[0], level = arguments[1],
  12683. args = Array.prototype.slice.call(arguments, 2);
  12684. if(levels[level] <= logger.level) {
  12685. return;
  12686. }
  12687. var callerInfo = getCallerInfo();
  12688. for(var i = 0; i < logger.transports.length; i++) {
  12689. var t = logger.transports[i];
  12690. var l = t[level];
  12691. if(l && typeof(l) === "function") {
  12692. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12693. .apply(t, args);
  12694. }
  12695. }
  12696. }
  12697. /**
  12698. *
  12699. * Constructs new logger object.
  12700. * @param level the logging level for the new logger
  12701. * @param id optional identifier for the logger instance.
  12702. * @param transports optional list of handlers(objects) for the logs.
  12703. * The handlers must support - log, warn, error, debug, info, trace.
  12704. * @param format optional (NOT implemented) string.
  12705. */
  12706. function Logger(level, id, transports, format) {
  12707. this.id = id;
  12708. this.format = format;
  12709. if(!this.transports) {
  12710. this.transports = [];
  12711. this.transports.push(Logger.consoleTransport);
  12712. }
  12713. this.level = levels[level];
  12714. var methods = Object.keys(levels);
  12715. for(var i = 0; i < methods.length; i++){
  12716. this[methods[i]] =
  12717. log.bind(null, this, methods[i]);
  12718. }
  12719. }
  12720. /**
  12721. * Sets the log level for the logger.
  12722. * @param level the new log level.
  12723. */
  12724. Logger.prototype.setLevel = function (level) {
  12725. this.level = levels[level];
  12726. };
  12727. module.exports = Logger;
  12728. /**
  12729. * The default transport - console
  12730. */
  12731. Logger.consoleTransport = console;
  12732. /**
  12733. * Enum for the supported log levels.
  12734. */
  12735. Logger.levels = {
  12736. TRACE: "trace",
  12737. DEBUG: "debug",
  12738. INFO: "info",
  12739. LOG: "log",
  12740. WARN: "warn",
  12741. ERROR: "error"
  12742. };
  12743. },{}],47:[function(require,module,exports){
  12744. /* Copyright @ 2015 Atlassian Pty Ltd
  12745. *
  12746. * Licensed under the Apache License, Version 2.0 (the "License");
  12747. * you may not use this file except in compliance with the License.
  12748. * You may obtain a copy of the License at
  12749. *
  12750. * http://www.apache.org/licenses/LICENSE-2.0
  12751. *
  12752. * Unless required by applicable law or agreed to in writing, software
  12753. * distributed under the License is distributed on an "AS IS" BASIS,
  12754. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12755. * See the License for the specific language governing permissions and
  12756. * limitations under the License.
  12757. */
  12758. var Logger = require("./Logger");
  12759. /**
  12760. * Map with the created loggers with ID.
  12761. */
  12762. var idLoggers = {};
  12763. /**
  12764. * Array with the loggers without id.
  12765. */
  12766. var loggers = [];
  12767. /**
  12768. * Log level for the lbrary.
  12769. */
  12770. var curLevel = Logger.levels.TRACE;
  12771. module.exports = {
  12772. /**
  12773. * Creates new logger.
  12774. * @arguments the same as Logger constructor
  12775. */
  12776. getLogger: function(id, transports, format) {
  12777. var logger = new Logger(curLevel, id, transports, format);
  12778. if(id) {
  12779. idLoggers[id] = idLoggers[id] || [];
  12780. idLoggers[id].push(logger);
  12781. } else {
  12782. loggers.push(logger);
  12783. }
  12784. return logger;
  12785. },
  12786. /**
  12787. * Changes the log level for the existing loggers by id.
  12788. * @param level the new log level.
  12789. * @param id if specified the level will be changed only for loggers with the
  12790. * same id. Otherwise the operation will affect all loggers that don't
  12791. * have id.
  12792. */
  12793. setLogLevelById: function(level, id) {
  12794. var l = id? (idLoggers[id] || []) : loggers;
  12795. for(var i = 0; i < l.length; i++) {
  12796. l[i].setLevel(level);
  12797. }
  12798. },
  12799. /**
  12800. * Changes the log level for all existing loggers.
  12801. * @param level the new log level.
  12802. */
  12803. setLogLevel: function (level) {
  12804. curLevel = level;
  12805. var i = 0;
  12806. for(; i < loggers.length; i++) {
  12807. loggers[i].setLevel(level);
  12808. }
  12809. for(var id in idLoggers) {
  12810. var l = idLoggers[id] || [];
  12811. for(i = 0; i < l.length; i++) {
  12812. l[i].setLevel(level);
  12813. }
  12814. }
  12815. },
  12816. /**
  12817. * The supported log levels.
  12818. */
  12819. levels: Logger.levels
  12820. };
  12821. },{"./Logger":46}],48:[function(require,module,exports){
  12822. // Top level file is just a mixin of submodules & constants
  12823. 'use strict';
  12824. var assign = require('./lib/utils/common').assign;
  12825. var deflate = require('./lib/deflate');
  12826. var inflate = require('./lib/inflate');
  12827. var constants = require('./lib/zlib/constants');
  12828. var pako = {};
  12829. assign(pako, deflate, inflate, constants);
  12830. module.exports = pako;
  12831. },{"./lib/deflate":49,"./lib/inflate":50,"./lib/utils/common":51,"./lib/zlib/constants":54}],49:[function(require,module,exports){
  12832. 'use strict';
  12833. var zlib_deflate = require('./zlib/deflate.js');
  12834. var utils = require('./utils/common');
  12835. var strings = require('./utils/strings');
  12836. var msg = require('./zlib/messages');
  12837. var zstream = require('./zlib/zstream');
  12838. var toString = Object.prototype.toString;
  12839. /* Public constants ==========================================================*/
  12840. /* ===========================================================================*/
  12841. var Z_NO_FLUSH = 0;
  12842. var Z_FINISH = 4;
  12843. var Z_OK = 0;
  12844. var Z_STREAM_END = 1;
  12845. var Z_SYNC_FLUSH = 2;
  12846. var Z_DEFAULT_COMPRESSION = -1;
  12847. var Z_DEFAULT_STRATEGY = 0;
  12848. var Z_DEFLATED = 8;
  12849. /* ===========================================================================*/
  12850. /**
  12851. * class Deflate
  12852. *
  12853. * Generic JS-style wrapper for zlib calls. If you don't need
  12854. * streaming behaviour - use more simple functions: [[deflate]],
  12855. * [[deflateRaw]] and [[gzip]].
  12856. **/
  12857. /* internal
  12858. * Deflate.chunks -> Array
  12859. *
  12860. * Chunks of output data, if [[Deflate#onData]] not overriden.
  12861. **/
  12862. /**
  12863. * Deflate.result -> Uint8Array|Array
  12864. *
  12865. * Compressed result, generated by default [[Deflate#onData]]
  12866. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  12867. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  12868. * push a chunk with explicit flush (call [[Deflate#push]] with
  12869. * `Z_SYNC_FLUSH` param).
  12870. **/
  12871. /**
  12872. * Deflate.err -> Number
  12873. *
  12874. * Error code after deflate finished. 0 (Z_OK) on success.
  12875. * You will not need it in real life, because deflate errors
  12876. * are possible only on wrong options or bad `onData` / `onEnd`
  12877. * custom handlers.
  12878. **/
  12879. /**
  12880. * Deflate.msg -> String
  12881. *
  12882. * Error message, if [[Deflate.err]] != 0
  12883. **/
  12884. /**
  12885. * new Deflate(options)
  12886. * - options (Object): zlib deflate options.
  12887. *
  12888. * Creates new deflator instance with specified params. Throws exception
  12889. * on bad params. Supported options:
  12890. *
  12891. * - `level`
  12892. * - `windowBits`
  12893. * - `memLevel`
  12894. * - `strategy`
  12895. *
  12896. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12897. * for more information on these.
  12898. *
  12899. * Additional options, for internal needs:
  12900. *
  12901. * - `chunkSize` - size of generated data chunks (16K by default)
  12902. * - `raw` (Boolean) - do raw deflate
  12903. * - `gzip` (Boolean) - create gzip wrapper
  12904. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12905. * (each char code [0..255])
  12906. * - `header` (Object) - custom header for gzip
  12907. * - `text` (Boolean) - true if compressed data believed to be text
  12908. * - `time` (Number) - modification time, unix timestamp
  12909. * - `os` (Number) - operation system code
  12910. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12911. * - `name` (String) - file name (binary string)
  12912. * - `comment` (String) - comment (binary string)
  12913. * - `hcrc` (Boolean) - true if header crc should be added
  12914. *
  12915. * ##### Example:
  12916. *
  12917. * ```javascript
  12918. * var pako = require('pako')
  12919. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12920. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12921. *
  12922. * var deflate = new pako.Deflate({ level: 3});
  12923. *
  12924. * deflate.push(chunk1, false);
  12925. * deflate.push(chunk2, true); // true -> last chunk
  12926. *
  12927. * if (deflate.err) { throw new Error(deflate.err); }
  12928. *
  12929. * console.log(deflate.result);
  12930. * ```
  12931. **/
  12932. var Deflate = function(options) {
  12933. this.options = utils.assign({
  12934. level: Z_DEFAULT_COMPRESSION,
  12935. method: Z_DEFLATED,
  12936. chunkSize: 16384,
  12937. windowBits: 15,
  12938. memLevel: 8,
  12939. strategy: Z_DEFAULT_STRATEGY,
  12940. to: ''
  12941. }, options || {});
  12942. var opt = this.options;
  12943. if (opt.raw && (opt.windowBits > 0)) {
  12944. opt.windowBits = -opt.windowBits;
  12945. }
  12946. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12947. opt.windowBits += 16;
  12948. }
  12949. this.err = 0; // error code, if happens (0 = Z_OK)
  12950. this.msg = ''; // error message
  12951. this.ended = false; // used to avoid multiple onEnd() calls
  12952. this.chunks = []; // chunks of compressed data
  12953. this.strm = new zstream();
  12954. this.strm.avail_out = 0;
  12955. var status = zlib_deflate.deflateInit2(
  12956. this.strm,
  12957. opt.level,
  12958. opt.method,
  12959. opt.windowBits,
  12960. opt.memLevel,
  12961. opt.strategy
  12962. );
  12963. if (status !== Z_OK) {
  12964. throw new Error(msg[status]);
  12965. }
  12966. if (opt.header) {
  12967. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12968. }
  12969. };
  12970. /**
  12971. * Deflate#push(data[, mode]) -> Boolean
  12972. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12973. * converted to utf8 byte sequence.
  12974. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12975. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12976. *
  12977. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12978. * new compressed chunks. Returns `true` on success. The last data block must have
  12979. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12980. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12981. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12982. *
  12983. * On fail call [[Deflate#onEnd]] with error code and return false.
  12984. *
  12985. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12986. * array format is detected automatically). Also, don't skip last param and always
  12987. * use the same type in your code (boolean or number). That will improve JS speed.
  12988. *
  12989. * For regular `Array`-s make sure all elements are [0..255].
  12990. *
  12991. * ##### Example
  12992. *
  12993. * ```javascript
  12994. * push(chunk, false); // push one of data chunks
  12995. * ...
  12996. * push(chunk, true); // push last chunk
  12997. * ```
  12998. **/
  12999. Deflate.prototype.push = function(data, mode) {
  13000. var strm = this.strm;
  13001. var chunkSize = this.options.chunkSize;
  13002. var status, _mode;
  13003. if (this.ended) { return false; }
  13004. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13005. // Convert data if needed
  13006. if (typeof data === 'string') {
  13007. // If we need to compress text, change encoding to utf8.
  13008. strm.input = strings.string2buf(data);
  13009. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13010. strm.input = new Uint8Array(data);
  13011. } else {
  13012. strm.input = data;
  13013. }
  13014. strm.next_in = 0;
  13015. strm.avail_in = strm.input.length;
  13016. do {
  13017. if (strm.avail_out === 0) {
  13018. strm.output = new utils.Buf8(chunkSize);
  13019. strm.next_out = 0;
  13020. strm.avail_out = chunkSize;
  13021. }
  13022. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13023. if (status !== Z_STREAM_END && status !== Z_OK) {
  13024. this.onEnd(status);
  13025. this.ended = true;
  13026. return false;
  13027. }
  13028. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13029. if (this.options.to === 'string') {
  13030. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13031. } else {
  13032. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13033. }
  13034. }
  13035. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13036. // Finalize on the last chunk.
  13037. if (_mode === Z_FINISH) {
  13038. status = zlib_deflate.deflateEnd(this.strm);
  13039. this.onEnd(status);
  13040. this.ended = true;
  13041. return status === Z_OK;
  13042. }
  13043. // callback interim results if Z_SYNC_FLUSH.
  13044. if (_mode === Z_SYNC_FLUSH) {
  13045. this.onEnd(Z_OK);
  13046. strm.avail_out = 0;
  13047. return true;
  13048. }
  13049. return true;
  13050. };
  13051. /**
  13052. * Deflate#onData(chunk) -> Void
  13053. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13054. * on js engine support. When string output requested, each chunk
  13055. * will be string.
  13056. *
  13057. * By default, stores data blocks in `chunks[]` property and glue
  13058. * those in `onEnd`. Override this handler, if you need another behaviour.
  13059. **/
  13060. Deflate.prototype.onData = function(chunk) {
  13061. this.chunks.push(chunk);
  13062. };
  13063. /**
  13064. * Deflate#onEnd(status) -> Void
  13065. * - status (Number): deflate status. 0 (Z_OK) on success,
  13066. * other if not.
  13067. *
  13068. * Called once after you tell deflate that the input stream is
  13069. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13070. * or if an error happened. By default - join collected chunks,
  13071. * free memory and fill `results` / `err` properties.
  13072. **/
  13073. Deflate.prototype.onEnd = function(status) {
  13074. // On success - join
  13075. if (status === Z_OK) {
  13076. if (this.options.to === 'string') {
  13077. this.result = this.chunks.join('');
  13078. } else {
  13079. this.result = utils.flattenChunks(this.chunks);
  13080. }
  13081. }
  13082. this.chunks = [];
  13083. this.err = status;
  13084. this.msg = this.strm.msg;
  13085. };
  13086. /**
  13087. * deflate(data[, options]) -> Uint8Array|Array|String
  13088. * - data (Uint8Array|Array|String): input data to compress.
  13089. * - options (Object): zlib deflate options.
  13090. *
  13091. * Compress `data` with deflate alrorythm and `options`.
  13092. *
  13093. * Supported options are:
  13094. *
  13095. * - level
  13096. * - windowBits
  13097. * - memLevel
  13098. * - strategy
  13099. *
  13100. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13101. * for more information on these.
  13102. *
  13103. * Sugar (options):
  13104. *
  13105. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13106. * negative windowBits implicitly.
  13107. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13108. * (each char code [0..255])
  13109. *
  13110. * ##### Example:
  13111. *
  13112. * ```javascript
  13113. * var pako = require('pako')
  13114. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13115. *
  13116. * console.log(pako.deflate(data));
  13117. * ```
  13118. **/
  13119. function deflate(input, options) {
  13120. var deflator = new Deflate(options);
  13121. deflator.push(input, true);
  13122. // That will never happens, if you don't cheat with options :)
  13123. if (deflator.err) { throw deflator.msg; }
  13124. return deflator.result;
  13125. }
  13126. /**
  13127. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13128. * - data (Uint8Array|Array|String): input data to compress.
  13129. * - options (Object): zlib deflate options.
  13130. *
  13131. * The same as [[deflate]], but creates raw data, without wrapper
  13132. * (header and adler32 crc).
  13133. **/
  13134. function deflateRaw(input, options) {
  13135. options = options || {};
  13136. options.raw = true;
  13137. return deflate(input, options);
  13138. }
  13139. /**
  13140. * gzip(data[, options]) -> Uint8Array|Array|String
  13141. * - data (Uint8Array|Array|String): input data to compress.
  13142. * - options (Object): zlib deflate options.
  13143. *
  13144. * The same as [[deflate]], but create gzip wrapper instead of
  13145. * deflate one.
  13146. **/
  13147. function gzip(input, options) {
  13148. options = options || {};
  13149. options.gzip = true;
  13150. return deflate(input, options);
  13151. }
  13152. exports.Deflate = Deflate;
  13153. exports.deflate = deflate;
  13154. exports.deflateRaw = deflateRaw;
  13155. exports.gzip = gzip;
  13156. },{"./utils/common":51,"./utils/strings":52,"./zlib/deflate.js":56,"./zlib/messages":61,"./zlib/zstream":63}],50:[function(require,module,exports){
  13157. 'use strict';
  13158. var zlib_inflate = require('./zlib/inflate.js');
  13159. var utils = require('./utils/common');
  13160. var strings = require('./utils/strings');
  13161. var c = require('./zlib/constants');
  13162. var msg = require('./zlib/messages');
  13163. var zstream = require('./zlib/zstream');
  13164. var gzheader = require('./zlib/gzheader');
  13165. var toString = Object.prototype.toString;
  13166. /**
  13167. * class Inflate
  13168. *
  13169. * Generic JS-style wrapper for zlib calls. If you don't need
  13170. * streaming behaviour - use more simple functions: [[inflate]]
  13171. * and [[inflateRaw]].
  13172. **/
  13173. /* internal
  13174. * inflate.chunks -> Array
  13175. *
  13176. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13177. **/
  13178. /**
  13179. * Inflate.result -> Uint8Array|Array|String
  13180. *
  13181. * Uncompressed result, generated by default [[Inflate#onData]]
  13182. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13183. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13184. * push a chunk with explicit flush (call [[Inflate#push]] with
  13185. * `Z_SYNC_FLUSH` param).
  13186. **/
  13187. /**
  13188. * Inflate.err -> Number
  13189. *
  13190. * Error code after inflate finished. 0 (Z_OK) on success.
  13191. * Should be checked if broken data possible.
  13192. **/
  13193. /**
  13194. * Inflate.msg -> String
  13195. *
  13196. * Error message, if [[Inflate.err]] != 0
  13197. **/
  13198. /**
  13199. * new Inflate(options)
  13200. * - options (Object): zlib inflate options.
  13201. *
  13202. * Creates new inflator instance with specified params. Throws exception
  13203. * on bad params. Supported options:
  13204. *
  13205. * - `windowBits`
  13206. *
  13207. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13208. * for more information on these.
  13209. *
  13210. * Additional options, for internal needs:
  13211. *
  13212. * - `chunkSize` - size of generated data chunks (16K by default)
  13213. * - `raw` (Boolean) - do raw inflate
  13214. * - `to` (String) - if equal to 'string', then result will be converted
  13215. * from utf8 to utf16 (javascript) string. When string output requested,
  13216. * chunk length can differ from `chunkSize`, depending on content.
  13217. *
  13218. * By default, when no options set, autodetect deflate/gzip data format via
  13219. * wrapper header.
  13220. *
  13221. * ##### Example:
  13222. *
  13223. * ```javascript
  13224. * var pako = require('pako')
  13225. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13226. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13227. *
  13228. * var inflate = new pako.Inflate({ level: 3});
  13229. *
  13230. * inflate.push(chunk1, false);
  13231. * inflate.push(chunk2, true); // true -> last chunk
  13232. *
  13233. * if (inflate.err) { throw new Error(inflate.err); }
  13234. *
  13235. * console.log(inflate.result);
  13236. * ```
  13237. **/
  13238. var Inflate = function(options) {
  13239. this.options = utils.assign({
  13240. chunkSize: 16384,
  13241. windowBits: 0,
  13242. to: ''
  13243. }, options || {});
  13244. var opt = this.options;
  13245. // Force window size for `raw` data, if not set directly,
  13246. // because we have no header for autodetect.
  13247. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13248. opt.windowBits = -opt.windowBits;
  13249. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13250. }
  13251. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13252. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13253. !(options && options.windowBits)) {
  13254. opt.windowBits += 32;
  13255. }
  13256. // Gzip header has no info about windows size, we can do autodetect only
  13257. // for deflate. So, if window size not set, force it to max when gzip possible
  13258. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13259. // bit 3 (16) -> gzipped data
  13260. // bit 4 (32) -> autodetect gzip/deflate
  13261. if ((opt.windowBits & 15) === 0) {
  13262. opt.windowBits |= 15;
  13263. }
  13264. }
  13265. this.err = 0; // error code, if happens (0 = Z_OK)
  13266. this.msg = ''; // error message
  13267. this.ended = false; // used to avoid multiple onEnd() calls
  13268. this.chunks = []; // chunks of compressed data
  13269. this.strm = new zstream();
  13270. this.strm.avail_out = 0;
  13271. var status = zlib_inflate.inflateInit2(
  13272. this.strm,
  13273. opt.windowBits
  13274. );
  13275. if (status !== c.Z_OK) {
  13276. throw new Error(msg[status]);
  13277. }
  13278. this.header = new gzheader();
  13279. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13280. };
  13281. /**
  13282. * Inflate#push(data[, mode]) -> Boolean
  13283. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13284. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13285. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13286. *
  13287. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13288. * new output chunks. Returns `true` on success. The last data block must have
  13289. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13290. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13291. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13292. *
  13293. * On fail call [[Inflate#onEnd]] with error code and return false.
  13294. *
  13295. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13296. * format is detected automatically). Also, don't skip last param and always
  13297. * use the same type in your code (boolean or number). That will improve JS speed.
  13298. *
  13299. * For regular `Array`-s make sure all elements are [0..255].
  13300. *
  13301. * ##### Example
  13302. *
  13303. * ```javascript
  13304. * push(chunk, false); // push one of data chunks
  13305. * ...
  13306. * push(chunk, true); // push last chunk
  13307. * ```
  13308. **/
  13309. Inflate.prototype.push = function(data, mode) {
  13310. var strm = this.strm;
  13311. var chunkSize = this.options.chunkSize;
  13312. var status, _mode;
  13313. var next_out_utf8, tail, utf8str;
  13314. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13315. // when we check that all output data was flushed.
  13316. var allowBufError = false;
  13317. if (this.ended) { return false; }
  13318. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13319. // Convert data if needed
  13320. if (typeof data === 'string') {
  13321. // Only binary strings can be decompressed on practice
  13322. strm.input = strings.binstring2buf(data);
  13323. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13324. strm.input = new Uint8Array(data);
  13325. } else {
  13326. strm.input = data;
  13327. }
  13328. strm.next_in = 0;
  13329. strm.avail_in = strm.input.length;
  13330. do {
  13331. if (strm.avail_out === 0) {
  13332. strm.output = new utils.Buf8(chunkSize);
  13333. strm.next_out = 0;
  13334. strm.avail_out = chunkSize;
  13335. }
  13336. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13337. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13338. status = c.Z_OK;
  13339. allowBufError = false;
  13340. }
  13341. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13342. this.onEnd(status);
  13343. this.ended = true;
  13344. return false;
  13345. }
  13346. if (strm.next_out) {
  13347. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13348. if (this.options.to === 'string') {
  13349. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13350. tail = strm.next_out - next_out_utf8;
  13351. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13352. // move tail
  13353. strm.next_out = tail;
  13354. strm.avail_out = chunkSize - tail;
  13355. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13356. this.onData(utf8str);
  13357. } else {
  13358. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13359. }
  13360. }
  13361. }
  13362. // When no more input data, we should check that internal inflate buffers
  13363. // are flushed. The only way to do it when avail_out = 0 - run one more
  13364. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13365. // Here we set flag to process this error properly.
  13366. //
  13367. // NOTE. Deflate does not return error in this case and does not needs such
  13368. // logic.
  13369. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13370. allowBufError = true;
  13371. }
  13372. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13373. if (status === c.Z_STREAM_END) {
  13374. _mode = c.Z_FINISH;
  13375. }
  13376. // Finalize on the last chunk.
  13377. if (_mode === c.Z_FINISH) {
  13378. status = zlib_inflate.inflateEnd(this.strm);
  13379. this.onEnd(status);
  13380. this.ended = true;
  13381. return status === c.Z_OK;
  13382. }
  13383. // callback interim results if Z_SYNC_FLUSH.
  13384. if (_mode === c.Z_SYNC_FLUSH) {
  13385. this.onEnd(c.Z_OK);
  13386. strm.avail_out = 0;
  13387. return true;
  13388. }
  13389. return true;
  13390. };
  13391. /**
  13392. * Inflate#onData(chunk) -> Void
  13393. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13394. * on js engine support. When string output requested, each chunk
  13395. * will be string.
  13396. *
  13397. * By default, stores data blocks in `chunks[]` property and glue
  13398. * those in `onEnd`. Override this handler, if you need another behaviour.
  13399. **/
  13400. Inflate.prototype.onData = function(chunk) {
  13401. this.chunks.push(chunk);
  13402. };
  13403. /**
  13404. * Inflate#onEnd(status) -> Void
  13405. * - status (Number): inflate status. 0 (Z_OK) on success,
  13406. * other if not.
  13407. *
  13408. * Called either after you tell inflate that the input stream is
  13409. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13410. * or if an error happened. By default - join collected chunks,
  13411. * free memory and fill `results` / `err` properties.
  13412. **/
  13413. Inflate.prototype.onEnd = function(status) {
  13414. // On success - join
  13415. if (status === c.Z_OK) {
  13416. if (this.options.to === 'string') {
  13417. // Glue & convert here, until we teach pako to send
  13418. // utf8 alligned strings to onData
  13419. this.result = this.chunks.join('');
  13420. } else {
  13421. this.result = utils.flattenChunks(this.chunks);
  13422. }
  13423. }
  13424. this.chunks = [];
  13425. this.err = status;
  13426. this.msg = this.strm.msg;
  13427. };
  13428. /**
  13429. * inflate(data[, options]) -> Uint8Array|Array|String
  13430. * - data (Uint8Array|Array|String): input data to decompress.
  13431. * - options (Object): zlib inflate options.
  13432. *
  13433. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13434. * format via wrapper header by default. That's why we don't provide
  13435. * separate `ungzip` method.
  13436. *
  13437. * Supported options are:
  13438. *
  13439. * - windowBits
  13440. *
  13441. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13442. * for more information.
  13443. *
  13444. * Sugar (options):
  13445. *
  13446. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13447. * negative windowBits implicitly.
  13448. * - `to` (String) - if equal to 'string', then result will be converted
  13449. * from utf8 to utf16 (javascript) string. When string output requested,
  13450. * chunk length can differ from `chunkSize`, depending on content.
  13451. *
  13452. *
  13453. * ##### Example:
  13454. *
  13455. * ```javascript
  13456. * var pako = require('pako')
  13457. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13458. * , output;
  13459. *
  13460. * try {
  13461. * output = pako.inflate(input);
  13462. * } catch (err)
  13463. * console.log(err);
  13464. * }
  13465. * ```
  13466. **/
  13467. function inflate(input, options) {
  13468. var inflator = new Inflate(options);
  13469. inflator.push(input, true);
  13470. // That will never happens, if you don't cheat with options :)
  13471. if (inflator.err) { throw inflator.msg; }
  13472. return inflator.result;
  13473. }
  13474. /**
  13475. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13476. * - data (Uint8Array|Array|String): input data to decompress.
  13477. * - options (Object): zlib inflate options.
  13478. *
  13479. * The same as [[inflate]], but creates raw data, without wrapper
  13480. * (header and adler32 crc).
  13481. **/
  13482. function inflateRaw(input, options) {
  13483. options = options || {};
  13484. options.raw = true;
  13485. return inflate(input, options);
  13486. }
  13487. /**
  13488. * ungzip(data[, options]) -> Uint8Array|Array|String
  13489. * - data (Uint8Array|Array|String): input data to decompress.
  13490. * - options (Object): zlib inflate options.
  13491. *
  13492. * Just shortcut to [[inflate]], because it autodetects format
  13493. * by header.content. Done for convenience.
  13494. **/
  13495. exports.Inflate = Inflate;
  13496. exports.inflate = inflate;
  13497. exports.inflateRaw = inflateRaw;
  13498. exports.ungzip = inflate;
  13499. },{"./utils/common":51,"./utils/strings":52,"./zlib/constants":54,"./zlib/gzheader":57,"./zlib/inflate.js":59,"./zlib/messages":61,"./zlib/zstream":63}],51:[function(require,module,exports){
  13500. 'use strict';
  13501. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13502. (typeof Uint16Array !== 'undefined') &&
  13503. (typeof Int32Array !== 'undefined');
  13504. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13505. var sources = Array.prototype.slice.call(arguments, 1);
  13506. while (sources.length) {
  13507. var source = sources.shift();
  13508. if (!source) { continue; }
  13509. if (typeof source !== 'object') {
  13510. throw new TypeError(source + 'must be non-object');
  13511. }
  13512. for (var p in source) {
  13513. if (source.hasOwnProperty(p)) {
  13514. obj[p] = source[p];
  13515. }
  13516. }
  13517. }
  13518. return obj;
  13519. };
  13520. // reduce buffer size, avoiding mem copy
  13521. exports.shrinkBuf = function (buf, size) {
  13522. if (buf.length === size) { return buf; }
  13523. if (buf.subarray) { return buf.subarray(0, size); }
  13524. buf.length = size;
  13525. return buf;
  13526. };
  13527. var fnTyped = {
  13528. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13529. if (src.subarray && dest.subarray) {
  13530. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13531. return;
  13532. }
  13533. // Fallback to ordinary array
  13534. for (var i=0; i<len; i++) {
  13535. dest[dest_offs + i] = src[src_offs + i];
  13536. }
  13537. },
  13538. // Join array of chunks to single array.
  13539. flattenChunks: function(chunks) {
  13540. var i, l, len, pos, chunk, result;
  13541. // calculate data length
  13542. len = 0;
  13543. for (i=0, l=chunks.length; i<l; i++) {
  13544. len += chunks[i].length;
  13545. }
  13546. // join chunks
  13547. result = new Uint8Array(len);
  13548. pos = 0;
  13549. for (i=0, l=chunks.length; i<l; i++) {
  13550. chunk = chunks[i];
  13551. result.set(chunk, pos);
  13552. pos += chunk.length;
  13553. }
  13554. return result;
  13555. }
  13556. };
  13557. var fnUntyped = {
  13558. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13559. for (var i=0; i<len; i++) {
  13560. dest[dest_offs + i] = src[src_offs + i];
  13561. }
  13562. },
  13563. // Join array of chunks to single array.
  13564. flattenChunks: function(chunks) {
  13565. return [].concat.apply([], chunks);
  13566. }
  13567. };
  13568. // Enable/Disable typed arrays use, for testing
  13569. //
  13570. exports.setTyped = function (on) {
  13571. if (on) {
  13572. exports.Buf8 = Uint8Array;
  13573. exports.Buf16 = Uint16Array;
  13574. exports.Buf32 = Int32Array;
  13575. exports.assign(exports, fnTyped);
  13576. } else {
  13577. exports.Buf8 = Array;
  13578. exports.Buf16 = Array;
  13579. exports.Buf32 = Array;
  13580. exports.assign(exports, fnUntyped);
  13581. }
  13582. };
  13583. exports.setTyped(TYPED_OK);
  13584. },{}],52:[function(require,module,exports){
  13585. // String encode/decode helpers
  13586. 'use strict';
  13587. var utils = require('./common');
  13588. // Quick check if we can use fast array to bin string conversion
  13589. //
  13590. // - apply(Array) can fail on Android 2.2
  13591. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13592. //
  13593. var STR_APPLY_OK = true;
  13594. var STR_APPLY_UIA_OK = true;
  13595. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13596. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13597. // Table with utf8 lengths (calculated by first byte of sequence)
  13598. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13599. // because max possible codepoint is 0x10ffff
  13600. var _utf8len = new utils.Buf8(256);
  13601. for (var q=0; q<256; q++) {
  13602. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13603. }
  13604. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13605. // convert string to array (typed, when possible)
  13606. exports.string2buf = function (str) {
  13607. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13608. // count binary size
  13609. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13610. c = str.charCodeAt(m_pos);
  13611. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13612. c2 = str.charCodeAt(m_pos+1);
  13613. if ((c2 & 0xfc00) === 0xdc00) {
  13614. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13615. m_pos++;
  13616. }
  13617. }
  13618. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13619. }
  13620. // allocate buffer
  13621. buf = new utils.Buf8(buf_len);
  13622. // convert
  13623. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13624. c = str.charCodeAt(m_pos);
  13625. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13626. c2 = str.charCodeAt(m_pos+1);
  13627. if ((c2 & 0xfc00) === 0xdc00) {
  13628. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13629. m_pos++;
  13630. }
  13631. }
  13632. if (c < 0x80) {
  13633. /* one byte */
  13634. buf[i++] = c;
  13635. } else if (c < 0x800) {
  13636. /* two bytes */
  13637. buf[i++] = 0xC0 | (c >>> 6);
  13638. buf[i++] = 0x80 | (c & 0x3f);
  13639. } else if (c < 0x10000) {
  13640. /* three bytes */
  13641. buf[i++] = 0xE0 | (c >>> 12);
  13642. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13643. buf[i++] = 0x80 | (c & 0x3f);
  13644. } else {
  13645. /* four bytes */
  13646. buf[i++] = 0xf0 | (c >>> 18);
  13647. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13648. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13649. buf[i++] = 0x80 | (c & 0x3f);
  13650. }
  13651. }
  13652. return buf;
  13653. };
  13654. // Helper (used in 2 places)
  13655. function buf2binstring(buf, len) {
  13656. // use fallback for big arrays to avoid stack overflow
  13657. if (len < 65537) {
  13658. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13659. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13660. }
  13661. }
  13662. var result = '';
  13663. for (var i=0; i < len; i++) {
  13664. result += String.fromCharCode(buf[i]);
  13665. }
  13666. return result;
  13667. }
  13668. // Convert byte array to binary string
  13669. exports.buf2binstring = function(buf) {
  13670. return buf2binstring(buf, buf.length);
  13671. };
  13672. // Convert binary string (typed, when possible)
  13673. exports.binstring2buf = function(str) {
  13674. var buf = new utils.Buf8(str.length);
  13675. for (var i=0, len=buf.length; i < len; i++) {
  13676. buf[i] = str.charCodeAt(i);
  13677. }
  13678. return buf;
  13679. };
  13680. // convert array to string
  13681. exports.buf2string = function (buf, max) {
  13682. var i, out, c, c_len;
  13683. var len = max || buf.length;
  13684. // Reserve max possible length (2 words per char)
  13685. // NB: by unknown reasons, Array is significantly faster for
  13686. // String.fromCharCode.apply than Uint16Array.
  13687. var utf16buf = new Array(len*2);
  13688. for (out=0, i=0; i<len;) {
  13689. c = buf[i++];
  13690. // quick process ascii
  13691. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13692. c_len = _utf8len[c];
  13693. // skip 5 & 6 byte codes
  13694. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13695. // apply mask on first byte
  13696. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13697. // join the rest
  13698. while (c_len > 1 && i < len) {
  13699. c = (c << 6) | (buf[i++] & 0x3f);
  13700. c_len--;
  13701. }
  13702. // terminated by end of string?
  13703. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13704. if (c < 0x10000) {
  13705. utf16buf[out++] = c;
  13706. } else {
  13707. c -= 0x10000;
  13708. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13709. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13710. }
  13711. }
  13712. return buf2binstring(utf16buf, out);
  13713. };
  13714. // Calculate max possible position in utf8 buffer,
  13715. // that will not break sequence. If that's not possible
  13716. // - (very small limits) return max size as is.
  13717. //
  13718. // buf[] - utf8 bytes array
  13719. // max - length limit (mandatory);
  13720. exports.utf8border = function(buf, max) {
  13721. var pos;
  13722. max = max || buf.length;
  13723. if (max > buf.length) { max = buf.length; }
  13724. // go back from last position, until start of sequence found
  13725. pos = max-1;
  13726. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13727. // Fuckup - very small and broken sequence,
  13728. // return max, because we should return something anyway.
  13729. if (pos < 0) { return max; }
  13730. // If we came to start of buffer - that means vuffer is too small,
  13731. // return max too.
  13732. if (pos === 0) { return max; }
  13733. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13734. };
  13735. },{"./common":51}],53:[function(require,module,exports){
  13736. 'use strict';
  13737. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13738. // It doesn't worth to make additional optimizationa as in original.
  13739. // Small size is preferable.
  13740. function adler32(adler, buf, len, pos) {
  13741. var s1 = (adler & 0xffff) |0,
  13742. s2 = ((adler >>> 16) & 0xffff) |0,
  13743. n = 0;
  13744. while (len !== 0) {
  13745. // Set limit ~ twice less than 5552, to keep
  13746. // s2 in 31-bits, because we force signed ints.
  13747. // in other case %= will fail.
  13748. n = len > 2000 ? 2000 : len;
  13749. len -= n;
  13750. do {
  13751. s1 = (s1 + buf[pos++]) |0;
  13752. s2 = (s2 + s1) |0;
  13753. } while (--n);
  13754. s1 %= 65521;
  13755. s2 %= 65521;
  13756. }
  13757. return (s1 | (s2 << 16)) |0;
  13758. }
  13759. module.exports = adler32;
  13760. },{}],54:[function(require,module,exports){
  13761. module.exports = {
  13762. /* Allowed flush values; see deflate() and inflate() below for details */
  13763. Z_NO_FLUSH: 0,
  13764. Z_PARTIAL_FLUSH: 1,
  13765. Z_SYNC_FLUSH: 2,
  13766. Z_FULL_FLUSH: 3,
  13767. Z_FINISH: 4,
  13768. Z_BLOCK: 5,
  13769. Z_TREES: 6,
  13770. /* Return codes for the compression/decompression functions. Negative values
  13771. * are errors, positive values are used for special but normal events.
  13772. */
  13773. Z_OK: 0,
  13774. Z_STREAM_END: 1,
  13775. Z_NEED_DICT: 2,
  13776. Z_ERRNO: -1,
  13777. Z_STREAM_ERROR: -2,
  13778. Z_DATA_ERROR: -3,
  13779. //Z_MEM_ERROR: -4,
  13780. Z_BUF_ERROR: -5,
  13781. //Z_VERSION_ERROR: -6,
  13782. /* compression levels */
  13783. Z_NO_COMPRESSION: 0,
  13784. Z_BEST_SPEED: 1,
  13785. Z_BEST_COMPRESSION: 9,
  13786. Z_DEFAULT_COMPRESSION: -1,
  13787. Z_FILTERED: 1,
  13788. Z_HUFFMAN_ONLY: 2,
  13789. Z_RLE: 3,
  13790. Z_FIXED: 4,
  13791. Z_DEFAULT_STRATEGY: 0,
  13792. /* Possible values of the data_type field (though see inflate()) */
  13793. Z_BINARY: 0,
  13794. Z_TEXT: 1,
  13795. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13796. Z_UNKNOWN: 2,
  13797. /* The deflate compression method */
  13798. Z_DEFLATED: 8
  13799. //Z_NULL: null // Use -1 or null inline, depending on var type
  13800. };
  13801. },{}],55:[function(require,module,exports){
  13802. 'use strict';
  13803. // Note: we can't get significant speed boost here.
  13804. // So write code to minimize size - no pregenerated tables
  13805. // and array tools dependencies.
  13806. // Use ordinary array, since untyped makes no boost here
  13807. function makeTable() {
  13808. var c, table = [];
  13809. for (var n =0; n < 256; n++) {
  13810. c = n;
  13811. for (var k =0; k < 8; k++) {
  13812. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13813. }
  13814. table[n] = c;
  13815. }
  13816. return table;
  13817. }
  13818. // Create table on load. Just 255 signed longs. Not a problem.
  13819. var crcTable = makeTable();
  13820. function crc32(crc, buf, len, pos) {
  13821. var t = crcTable,
  13822. end = pos + len;
  13823. crc = crc ^ (-1);
  13824. for (var i = pos; i < end; i++) {
  13825. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13826. }
  13827. return (crc ^ (-1)); // >>> 0;
  13828. }
  13829. module.exports = crc32;
  13830. },{}],56:[function(require,module,exports){
  13831. 'use strict';
  13832. var utils = require('../utils/common');
  13833. var trees = require('./trees');
  13834. var adler32 = require('./adler32');
  13835. var crc32 = require('./crc32');
  13836. var msg = require('./messages');
  13837. /* Public constants ==========================================================*/
  13838. /* ===========================================================================*/
  13839. /* Allowed flush values; see deflate() and inflate() below for details */
  13840. var Z_NO_FLUSH = 0;
  13841. var Z_PARTIAL_FLUSH = 1;
  13842. //var Z_SYNC_FLUSH = 2;
  13843. var Z_FULL_FLUSH = 3;
  13844. var Z_FINISH = 4;
  13845. var Z_BLOCK = 5;
  13846. //var Z_TREES = 6;
  13847. /* Return codes for the compression/decompression functions. Negative values
  13848. * are errors, positive values are used for special but normal events.
  13849. */
  13850. var Z_OK = 0;
  13851. var Z_STREAM_END = 1;
  13852. //var Z_NEED_DICT = 2;
  13853. //var Z_ERRNO = -1;
  13854. var Z_STREAM_ERROR = -2;
  13855. var Z_DATA_ERROR = -3;
  13856. //var Z_MEM_ERROR = -4;
  13857. var Z_BUF_ERROR = -5;
  13858. //var Z_VERSION_ERROR = -6;
  13859. /* compression levels */
  13860. //var Z_NO_COMPRESSION = 0;
  13861. //var Z_BEST_SPEED = 1;
  13862. //var Z_BEST_COMPRESSION = 9;
  13863. var Z_DEFAULT_COMPRESSION = -1;
  13864. var Z_FILTERED = 1;
  13865. var Z_HUFFMAN_ONLY = 2;
  13866. var Z_RLE = 3;
  13867. var Z_FIXED = 4;
  13868. var Z_DEFAULT_STRATEGY = 0;
  13869. /* Possible values of the data_type field (though see inflate()) */
  13870. //var Z_BINARY = 0;
  13871. //var Z_TEXT = 1;
  13872. //var Z_ASCII = 1; // = Z_TEXT
  13873. var Z_UNKNOWN = 2;
  13874. /* The deflate compression method */
  13875. var Z_DEFLATED = 8;
  13876. /*============================================================================*/
  13877. var MAX_MEM_LEVEL = 9;
  13878. /* Maximum value for memLevel in deflateInit2 */
  13879. var MAX_WBITS = 15;
  13880. /* 32K LZ77 window */
  13881. var DEF_MEM_LEVEL = 8;
  13882. var LENGTH_CODES = 29;
  13883. /* number of length codes, not counting the special END_BLOCK code */
  13884. var LITERALS = 256;
  13885. /* number of literal bytes 0..255 */
  13886. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13887. /* number of Literal or Length codes, including the END_BLOCK code */
  13888. var D_CODES = 30;
  13889. /* number of distance codes */
  13890. var BL_CODES = 19;
  13891. /* number of codes used to transfer the bit lengths */
  13892. var HEAP_SIZE = 2*L_CODES + 1;
  13893. /* maximum heap size */
  13894. var MAX_BITS = 15;
  13895. /* All codes must not exceed MAX_BITS bits */
  13896. var MIN_MATCH = 3;
  13897. var MAX_MATCH = 258;
  13898. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13899. var PRESET_DICT = 0x20;
  13900. var INIT_STATE = 42;
  13901. var EXTRA_STATE = 69;
  13902. var NAME_STATE = 73;
  13903. var COMMENT_STATE = 91;
  13904. var HCRC_STATE = 103;
  13905. var BUSY_STATE = 113;
  13906. var FINISH_STATE = 666;
  13907. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13908. var BS_BLOCK_DONE = 2; /* block flush performed */
  13909. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13910. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13911. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13912. function err(strm, errorCode) {
  13913. strm.msg = msg[errorCode];
  13914. return errorCode;
  13915. }
  13916. function rank(f) {
  13917. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13918. }
  13919. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13920. /* =========================================================================
  13921. * Flush as much pending output as possible. All deflate() output goes
  13922. * through this function so some applications may wish to modify it
  13923. * to avoid allocating a large strm->output buffer and copying into it.
  13924. * (See also read_buf()).
  13925. */
  13926. function flush_pending(strm) {
  13927. var s = strm.state;
  13928. //_tr_flush_bits(s);
  13929. var len = s.pending;
  13930. if (len > strm.avail_out) {
  13931. len = strm.avail_out;
  13932. }
  13933. if (len === 0) { return; }
  13934. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13935. strm.next_out += len;
  13936. s.pending_out += len;
  13937. strm.total_out += len;
  13938. strm.avail_out -= len;
  13939. s.pending -= len;
  13940. if (s.pending === 0) {
  13941. s.pending_out = 0;
  13942. }
  13943. }
  13944. function flush_block_only (s, last) {
  13945. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13946. s.block_start = s.strstart;
  13947. flush_pending(s.strm);
  13948. }
  13949. function put_byte(s, b) {
  13950. s.pending_buf[s.pending++] = b;
  13951. }
  13952. /* =========================================================================
  13953. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13954. * IN assertion: the stream state is correct and there is enough room in
  13955. * pending_buf.
  13956. */
  13957. function putShortMSB(s, b) {
  13958. // put_byte(s, (Byte)(b >> 8));
  13959. // put_byte(s, (Byte)(b & 0xff));
  13960. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13961. s.pending_buf[s.pending++] = b & 0xff;
  13962. }
  13963. /* ===========================================================================
  13964. * Read a new buffer from the current input stream, update the adler32
  13965. * and total number of bytes read. All deflate() input goes through
  13966. * this function so some applications may wish to modify it to avoid
  13967. * allocating a large strm->input buffer and copying from it.
  13968. * (See also flush_pending()).
  13969. */
  13970. function read_buf(strm, buf, start, size) {
  13971. var len = strm.avail_in;
  13972. if (len > size) { len = size; }
  13973. if (len === 0) { return 0; }
  13974. strm.avail_in -= len;
  13975. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13976. if (strm.state.wrap === 1) {
  13977. strm.adler = adler32(strm.adler, buf, len, start);
  13978. }
  13979. else if (strm.state.wrap === 2) {
  13980. strm.adler = crc32(strm.adler, buf, len, start);
  13981. }
  13982. strm.next_in += len;
  13983. strm.total_in += len;
  13984. return len;
  13985. }
  13986. /* ===========================================================================
  13987. * Set match_start to the longest match starting at the given string and
  13988. * return its length. Matches shorter or equal to prev_length are discarded,
  13989. * in which case the result is equal to prev_length and match_start is
  13990. * garbage.
  13991. * IN assertions: cur_match is the head of the hash chain for the current
  13992. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13993. * OUT assertion: the match length is not greater than s->lookahead.
  13994. */
  13995. function longest_match(s, cur_match) {
  13996. var chain_length = s.max_chain_length; /* max hash chain length */
  13997. var scan = s.strstart; /* current string */
  13998. var match; /* matched string */
  13999. var len; /* length of current match */
  14000. var best_len = s.prev_length; /* best match length so far */
  14001. var nice_match = s.nice_match; /* stop if match long enough */
  14002. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14003. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14004. var _win = s.window; // shortcut
  14005. var wmask = s.w_mask;
  14006. var prev = s.prev;
  14007. /* Stop when cur_match becomes <= limit. To simplify the code,
  14008. * we prevent matches with the string of window index 0.
  14009. */
  14010. var strend = s.strstart + MAX_MATCH;
  14011. var scan_end1 = _win[scan + best_len - 1];
  14012. var scan_end = _win[scan + best_len];
  14013. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14014. * It is easy to get rid of this optimization if necessary.
  14015. */
  14016. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14017. /* Do not waste too much time if we already have a good match: */
  14018. if (s.prev_length >= s.good_match) {
  14019. chain_length >>= 2;
  14020. }
  14021. /* Do not look for matches beyond the end of the input. This is necessary
  14022. * to make deflate deterministic.
  14023. */
  14024. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14025. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14026. do {
  14027. // Assert(cur_match < s->strstart, "no future");
  14028. match = cur_match;
  14029. /* Skip to next match if the match length cannot increase
  14030. * or if the match length is less than 2. Note that the checks below
  14031. * for insufficient lookahead only occur occasionally for performance
  14032. * reasons. Therefore uninitialized memory will be accessed, and
  14033. * conditional jumps will be made that depend on those values.
  14034. * However the length of the match is limited to the lookahead, so
  14035. * the output of deflate is not affected by the uninitialized values.
  14036. */
  14037. if (_win[match + best_len] !== scan_end ||
  14038. _win[match + best_len - 1] !== scan_end1 ||
  14039. _win[match] !== _win[scan] ||
  14040. _win[++match] !== _win[scan + 1]) {
  14041. continue;
  14042. }
  14043. /* The check at best_len-1 can be removed because it will be made
  14044. * again later. (This heuristic is not always a win.)
  14045. * It is not necessary to compare scan[2] and match[2] since they
  14046. * are always equal when the other bytes match, given that
  14047. * the hash keys are equal and that HASH_BITS >= 8.
  14048. */
  14049. scan += 2;
  14050. match++;
  14051. // Assert(*scan == *match, "match[2]?");
  14052. /* We check for insufficient lookahead only every 8th comparison;
  14053. * the 256th check will be made at strstart+258.
  14054. */
  14055. do {
  14056. /*jshint noempty:false*/
  14057. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14058. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14059. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14060. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14061. scan < strend);
  14062. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14063. len = MAX_MATCH - (strend - scan);
  14064. scan = strend - MAX_MATCH;
  14065. if (len > best_len) {
  14066. s.match_start = cur_match;
  14067. best_len = len;
  14068. if (len >= nice_match) {
  14069. break;
  14070. }
  14071. scan_end1 = _win[scan + best_len - 1];
  14072. scan_end = _win[scan + best_len];
  14073. }
  14074. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14075. if (best_len <= s.lookahead) {
  14076. return best_len;
  14077. }
  14078. return s.lookahead;
  14079. }
  14080. /* ===========================================================================
  14081. * Fill the window when the lookahead becomes insufficient.
  14082. * Updates strstart and lookahead.
  14083. *
  14084. * IN assertion: lookahead < MIN_LOOKAHEAD
  14085. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14086. * At least one byte has been read, or avail_in == 0; reads are
  14087. * performed for at least two bytes (required for the zip translate_eol
  14088. * option -- not supported here).
  14089. */
  14090. function fill_window(s) {
  14091. var _w_size = s.w_size;
  14092. var p, n, m, more, str;
  14093. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14094. do {
  14095. more = s.window_size - s.lookahead - s.strstart;
  14096. // JS ints have 32 bit, block below not needed
  14097. /* Deal with !@#$% 64K limit: */
  14098. //if (sizeof(int) <= 2) {
  14099. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14100. // more = wsize;
  14101. //
  14102. // } else if (more == (unsigned)(-1)) {
  14103. // /* Very unlikely, but possible on 16 bit machine if
  14104. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14105. // */
  14106. // more--;
  14107. // }
  14108. //}
  14109. /* If the window is almost full and there is insufficient lookahead,
  14110. * move the upper half to the lower one to make room in the upper half.
  14111. */
  14112. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14113. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14114. s.match_start -= _w_size;
  14115. s.strstart -= _w_size;
  14116. /* we now have strstart >= MAX_DIST */
  14117. s.block_start -= _w_size;
  14118. /* Slide the hash table (could be avoided with 32 bit values
  14119. at the expense of memory usage). We slide even when level == 0
  14120. to keep the hash table consistent if we switch back to level > 0
  14121. later. (Using level 0 permanently is not an optimal usage of
  14122. zlib, so we don't care about this pathological case.)
  14123. */
  14124. n = s.hash_size;
  14125. p = n;
  14126. do {
  14127. m = s.head[--p];
  14128. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14129. } while (--n);
  14130. n = _w_size;
  14131. p = n;
  14132. do {
  14133. m = s.prev[--p];
  14134. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14135. /* If n is not on any hash chain, prev[n] is garbage but
  14136. * its value will never be used.
  14137. */
  14138. } while (--n);
  14139. more += _w_size;
  14140. }
  14141. if (s.strm.avail_in === 0) {
  14142. break;
  14143. }
  14144. /* If there was no sliding:
  14145. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14146. * more == window_size - lookahead - strstart
  14147. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14148. * => more >= window_size - 2*WSIZE + 2
  14149. * In the BIG_MEM or MMAP case (not yet supported),
  14150. * window_size == input_size + MIN_LOOKAHEAD &&
  14151. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14152. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14153. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14154. */
  14155. //Assert(more >= 2, "more < 2");
  14156. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14157. s.lookahead += n;
  14158. /* Initialize the hash value now that we have some input: */
  14159. if (s.lookahead + s.insert >= MIN_MATCH) {
  14160. str = s.strstart - s.insert;
  14161. s.ins_h = s.window[str];
  14162. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14163. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14164. //#if MIN_MATCH != 3
  14165. // Call update_hash() MIN_MATCH-3 more times
  14166. //#endif
  14167. while (s.insert) {
  14168. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14169. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14170. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14171. s.head[s.ins_h] = str;
  14172. str++;
  14173. s.insert--;
  14174. if (s.lookahead + s.insert < MIN_MATCH) {
  14175. break;
  14176. }
  14177. }
  14178. }
  14179. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14180. * but this is not important since only literal bytes will be emitted.
  14181. */
  14182. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14183. /* If the WIN_INIT bytes after the end of the current data have never been
  14184. * written, then zero those bytes in order to avoid memory check reports of
  14185. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14186. * the longest match routines. Update the high water mark for the next
  14187. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14188. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14189. */
  14190. // if (s.high_water < s.window_size) {
  14191. // var curr = s.strstart + s.lookahead;
  14192. // var init = 0;
  14193. //
  14194. // if (s.high_water < curr) {
  14195. // /* Previous high water mark below current data -- zero WIN_INIT
  14196. // * bytes or up to end of window, whichever is less.
  14197. // */
  14198. // init = s.window_size - curr;
  14199. // if (init > WIN_INIT)
  14200. // init = WIN_INIT;
  14201. // zmemzero(s->window + curr, (unsigned)init);
  14202. // s->high_water = curr + init;
  14203. // }
  14204. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14205. // /* High water mark at or above current data, but below current data
  14206. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14207. // * to end of window, whichever is less.
  14208. // */
  14209. // init = (ulg)curr + WIN_INIT - s->high_water;
  14210. // if (init > s->window_size - s->high_water)
  14211. // init = s->window_size - s->high_water;
  14212. // zmemzero(s->window + s->high_water, (unsigned)init);
  14213. // s->high_water += init;
  14214. // }
  14215. // }
  14216. //
  14217. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14218. // "not enough room for search");
  14219. }
  14220. /* ===========================================================================
  14221. * Copy without compression as much as possible from the input stream, return
  14222. * the current block state.
  14223. * This function does not insert new strings in the dictionary since
  14224. * uncompressible data is probably not useful. This function is used
  14225. * only for the level=0 compression option.
  14226. * NOTE: this function should be optimized to avoid extra copying from
  14227. * window to pending_buf.
  14228. */
  14229. function deflate_stored(s, flush) {
  14230. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14231. * to pending_buf_size, and each stored block has a 5 byte header:
  14232. */
  14233. var max_block_size = 0xffff;
  14234. if (max_block_size > s.pending_buf_size - 5) {
  14235. max_block_size = s.pending_buf_size - 5;
  14236. }
  14237. /* Copy as much as possible from input to output: */
  14238. for (;;) {
  14239. /* Fill the window as much as possible: */
  14240. if (s.lookahead <= 1) {
  14241. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14242. // s->block_start >= (long)s->w_size, "slide too late");
  14243. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14244. // s.block_start >= s.w_size)) {
  14245. // throw new Error("slide too late");
  14246. // }
  14247. fill_window(s);
  14248. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14249. return BS_NEED_MORE;
  14250. }
  14251. if (s.lookahead === 0) {
  14252. break;
  14253. }
  14254. /* flush the current block */
  14255. }
  14256. //Assert(s->block_start >= 0L, "block gone");
  14257. // if (s.block_start < 0) throw new Error("block gone");
  14258. s.strstart += s.lookahead;
  14259. s.lookahead = 0;
  14260. /* Emit a stored block if pending_buf will be full: */
  14261. var max_start = s.block_start + max_block_size;
  14262. if (s.strstart === 0 || s.strstart >= max_start) {
  14263. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14264. s.lookahead = s.strstart - max_start;
  14265. s.strstart = max_start;
  14266. /*** FLUSH_BLOCK(s, 0); ***/
  14267. flush_block_only(s, false);
  14268. if (s.strm.avail_out === 0) {
  14269. return BS_NEED_MORE;
  14270. }
  14271. /***/
  14272. }
  14273. /* Flush if we may have to slide, otherwise block_start may become
  14274. * negative and the data will be gone:
  14275. */
  14276. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14277. /*** FLUSH_BLOCK(s, 0); ***/
  14278. flush_block_only(s, false);
  14279. if (s.strm.avail_out === 0) {
  14280. return BS_NEED_MORE;
  14281. }
  14282. /***/
  14283. }
  14284. }
  14285. s.insert = 0;
  14286. if (flush === Z_FINISH) {
  14287. /*** FLUSH_BLOCK(s, 1); ***/
  14288. flush_block_only(s, true);
  14289. if (s.strm.avail_out === 0) {
  14290. return BS_FINISH_STARTED;
  14291. }
  14292. /***/
  14293. return BS_FINISH_DONE;
  14294. }
  14295. if (s.strstart > s.block_start) {
  14296. /*** FLUSH_BLOCK(s, 0); ***/
  14297. flush_block_only(s, false);
  14298. if (s.strm.avail_out === 0) {
  14299. return BS_NEED_MORE;
  14300. }
  14301. /***/
  14302. }
  14303. return BS_NEED_MORE;
  14304. }
  14305. /* ===========================================================================
  14306. * Compress as much as possible from the input stream, return the current
  14307. * block state.
  14308. * This function does not perform lazy evaluation of matches and inserts
  14309. * new strings in the dictionary only for unmatched strings or for short
  14310. * matches. It is used only for the fast compression options.
  14311. */
  14312. function deflate_fast(s, flush) {
  14313. var hash_head; /* head of the hash chain */
  14314. var bflush; /* set if current block must be flushed */
  14315. for (;;) {
  14316. /* Make sure that we always have enough lookahead, except
  14317. * at the end of the input file. We need MAX_MATCH bytes
  14318. * for the next match, plus MIN_MATCH bytes to insert the
  14319. * string following the next match.
  14320. */
  14321. if (s.lookahead < MIN_LOOKAHEAD) {
  14322. fill_window(s);
  14323. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14324. return BS_NEED_MORE;
  14325. }
  14326. if (s.lookahead === 0) {
  14327. break; /* flush the current block */
  14328. }
  14329. }
  14330. /* Insert the string window[strstart .. strstart+2] in the
  14331. * dictionary, and set hash_head to the head of the hash chain:
  14332. */
  14333. hash_head = 0/*NIL*/;
  14334. if (s.lookahead >= MIN_MATCH) {
  14335. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14336. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14337. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14338. s.head[s.ins_h] = s.strstart;
  14339. /***/
  14340. }
  14341. /* Find the longest match, discarding those <= prev_length.
  14342. * At this point we have always match_length < MIN_MATCH
  14343. */
  14344. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14345. /* To simplify the code, we prevent matches with the string
  14346. * of window index 0 (in particular we have to avoid a match
  14347. * of the string with itself at the start of the input file).
  14348. */
  14349. s.match_length = longest_match(s, hash_head);
  14350. /* longest_match() sets match_start */
  14351. }
  14352. if (s.match_length >= MIN_MATCH) {
  14353. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14354. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14355. s.match_length - MIN_MATCH, bflush); ***/
  14356. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14357. s.lookahead -= s.match_length;
  14358. /* Insert new strings in the hash table only if the match length
  14359. * is not too large. This saves time but degrades compression.
  14360. */
  14361. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14362. s.match_length--; /* string at strstart already in table */
  14363. do {
  14364. s.strstart++;
  14365. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14366. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14367. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14368. s.head[s.ins_h] = s.strstart;
  14369. /***/
  14370. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14371. * always MIN_MATCH bytes ahead.
  14372. */
  14373. } while (--s.match_length !== 0);
  14374. s.strstart++;
  14375. } else
  14376. {
  14377. s.strstart += s.match_length;
  14378. s.match_length = 0;
  14379. s.ins_h = s.window[s.strstart];
  14380. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14381. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14382. //#if MIN_MATCH != 3
  14383. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14384. //#endif
  14385. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14386. * matter since it will be recomputed at next deflate call.
  14387. */
  14388. }
  14389. } else {
  14390. /* No match, output a literal byte */
  14391. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14392. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14393. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14394. s.lookahead--;
  14395. s.strstart++;
  14396. }
  14397. if (bflush) {
  14398. /*** FLUSH_BLOCK(s, 0); ***/
  14399. flush_block_only(s, false);
  14400. if (s.strm.avail_out === 0) {
  14401. return BS_NEED_MORE;
  14402. }
  14403. /***/
  14404. }
  14405. }
  14406. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14407. if (flush === Z_FINISH) {
  14408. /*** FLUSH_BLOCK(s, 1); ***/
  14409. flush_block_only(s, true);
  14410. if (s.strm.avail_out === 0) {
  14411. return BS_FINISH_STARTED;
  14412. }
  14413. /***/
  14414. return BS_FINISH_DONE;
  14415. }
  14416. if (s.last_lit) {
  14417. /*** FLUSH_BLOCK(s, 0); ***/
  14418. flush_block_only(s, false);
  14419. if (s.strm.avail_out === 0) {
  14420. return BS_NEED_MORE;
  14421. }
  14422. /***/
  14423. }
  14424. return BS_BLOCK_DONE;
  14425. }
  14426. /* ===========================================================================
  14427. * Same as above, but achieves better compression. We use a lazy
  14428. * evaluation for matches: a match is finally adopted only if there is
  14429. * no better match at the next window position.
  14430. */
  14431. function deflate_slow(s, flush) {
  14432. var hash_head; /* head of hash chain */
  14433. var bflush; /* set if current block must be flushed */
  14434. var max_insert;
  14435. /* Process the input block. */
  14436. for (;;) {
  14437. /* Make sure that we always have enough lookahead, except
  14438. * at the end of the input file. We need MAX_MATCH bytes
  14439. * for the next match, plus MIN_MATCH bytes to insert the
  14440. * string following the next match.
  14441. */
  14442. if (s.lookahead < MIN_LOOKAHEAD) {
  14443. fill_window(s);
  14444. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14445. return BS_NEED_MORE;
  14446. }
  14447. if (s.lookahead === 0) { break; } /* flush the current block */
  14448. }
  14449. /* Insert the string window[strstart .. strstart+2] in the
  14450. * dictionary, and set hash_head to the head of the hash chain:
  14451. */
  14452. hash_head = 0/*NIL*/;
  14453. if (s.lookahead >= MIN_MATCH) {
  14454. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14455. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14456. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14457. s.head[s.ins_h] = s.strstart;
  14458. /***/
  14459. }
  14460. /* Find the longest match, discarding those <= prev_length.
  14461. */
  14462. s.prev_length = s.match_length;
  14463. s.prev_match = s.match_start;
  14464. s.match_length = MIN_MATCH-1;
  14465. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14466. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14467. /* To simplify the code, we prevent matches with the string
  14468. * of window index 0 (in particular we have to avoid a match
  14469. * of the string with itself at the start of the input file).
  14470. */
  14471. s.match_length = longest_match(s, hash_head);
  14472. /* longest_match() sets match_start */
  14473. if (s.match_length <= 5 &&
  14474. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14475. /* If prev_match is also MIN_MATCH, match_start is garbage
  14476. * but we will ignore the current match anyway.
  14477. */
  14478. s.match_length = MIN_MATCH-1;
  14479. }
  14480. }
  14481. /* If there was a match at the previous step and the current
  14482. * match is not better, output the previous match:
  14483. */
  14484. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14485. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14486. /* Do not insert strings in hash table beyond this. */
  14487. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14488. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14489. s.prev_length - MIN_MATCH, bflush);***/
  14490. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14491. /* Insert in hash table all strings up to the end of the match.
  14492. * strstart-1 and strstart are already inserted. If there is not
  14493. * enough lookahead, the last two strings are not inserted in
  14494. * the hash table.
  14495. */
  14496. s.lookahead -= s.prev_length-1;
  14497. s.prev_length -= 2;
  14498. do {
  14499. if (++s.strstart <= max_insert) {
  14500. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14501. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14502. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14503. s.head[s.ins_h] = s.strstart;
  14504. /***/
  14505. }
  14506. } while (--s.prev_length !== 0);
  14507. s.match_available = 0;
  14508. s.match_length = MIN_MATCH-1;
  14509. s.strstart++;
  14510. if (bflush) {
  14511. /*** FLUSH_BLOCK(s, 0); ***/
  14512. flush_block_only(s, false);
  14513. if (s.strm.avail_out === 0) {
  14514. return BS_NEED_MORE;
  14515. }
  14516. /***/
  14517. }
  14518. } else if (s.match_available) {
  14519. /* If there was no match at the previous position, output a
  14520. * single literal. If there was a match but the current match
  14521. * is longer, truncate the previous match to a single literal.
  14522. */
  14523. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14524. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14525. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14526. if (bflush) {
  14527. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14528. flush_block_only(s, false);
  14529. /***/
  14530. }
  14531. s.strstart++;
  14532. s.lookahead--;
  14533. if (s.strm.avail_out === 0) {
  14534. return BS_NEED_MORE;
  14535. }
  14536. } else {
  14537. /* There is no previous match to compare with, wait for
  14538. * the next step to decide.
  14539. */
  14540. s.match_available = 1;
  14541. s.strstart++;
  14542. s.lookahead--;
  14543. }
  14544. }
  14545. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14546. if (s.match_available) {
  14547. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14548. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14549. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14550. s.match_available = 0;
  14551. }
  14552. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14553. if (flush === Z_FINISH) {
  14554. /*** FLUSH_BLOCK(s, 1); ***/
  14555. flush_block_only(s, true);
  14556. if (s.strm.avail_out === 0) {
  14557. return BS_FINISH_STARTED;
  14558. }
  14559. /***/
  14560. return BS_FINISH_DONE;
  14561. }
  14562. if (s.last_lit) {
  14563. /*** FLUSH_BLOCK(s, 0); ***/
  14564. flush_block_only(s, false);
  14565. if (s.strm.avail_out === 0) {
  14566. return BS_NEED_MORE;
  14567. }
  14568. /***/
  14569. }
  14570. return BS_BLOCK_DONE;
  14571. }
  14572. /* ===========================================================================
  14573. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14574. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14575. * deflate switches away from Z_RLE.)
  14576. */
  14577. function deflate_rle(s, flush) {
  14578. var bflush; /* set if current block must be flushed */
  14579. var prev; /* byte at distance one to match */
  14580. var scan, strend; /* scan goes up to strend for length of run */
  14581. var _win = s.window;
  14582. for (;;) {
  14583. /* Make sure that we always have enough lookahead, except
  14584. * at the end of the input file. We need MAX_MATCH bytes
  14585. * for the longest run, plus one for the unrolled loop.
  14586. */
  14587. if (s.lookahead <= MAX_MATCH) {
  14588. fill_window(s);
  14589. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14590. return BS_NEED_MORE;
  14591. }
  14592. if (s.lookahead === 0) { break; } /* flush the current block */
  14593. }
  14594. /* See how many times the previous byte repeats */
  14595. s.match_length = 0;
  14596. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14597. scan = s.strstart - 1;
  14598. prev = _win[scan];
  14599. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14600. strend = s.strstart + MAX_MATCH;
  14601. do {
  14602. /*jshint noempty:false*/
  14603. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14604. prev === _win[++scan] && prev === _win[++scan] &&
  14605. prev === _win[++scan] && prev === _win[++scan] &&
  14606. prev === _win[++scan] && prev === _win[++scan] &&
  14607. scan < strend);
  14608. s.match_length = MAX_MATCH - (strend - scan);
  14609. if (s.match_length > s.lookahead) {
  14610. s.match_length = s.lookahead;
  14611. }
  14612. }
  14613. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14614. }
  14615. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14616. if (s.match_length >= MIN_MATCH) {
  14617. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14618. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14619. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14620. s.lookahead -= s.match_length;
  14621. s.strstart += s.match_length;
  14622. s.match_length = 0;
  14623. } else {
  14624. /* No match, output a literal byte */
  14625. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14626. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14627. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14628. s.lookahead--;
  14629. s.strstart++;
  14630. }
  14631. if (bflush) {
  14632. /*** FLUSH_BLOCK(s, 0); ***/
  14633. flush_block_only(s, false);
  14634. if (s.strm.avail_out === 0) {
  14635. return BS_NEED_MORE;
  14636. }
  14637. /***/
  14638. }
  14639. }
  14640. s.insert = 0;
  14641. if (flush === Z_FINISH) {
  14642. /*** FLUSH_BLOCK(s, 1); ***/
  14643. flush_block_only(s, true);
  14644. if (s.strm.avail_out === 0) {
  14645. return BS_FINISH_STARTED;
  14646. }
  14647. /***/
  14648. return BS_FINISH_DONE;
  14649. }
  14650. if (s.last_lit) {
  14651. /*** FLUSH_BLOCK(s, 0); ***/
  14652. flush_block_only(s, false);
  14653. if (s.strm.avail_out === 0) {
  14654. return BS_NEED_MORE;
  14655. }
  14656. /***/
  14657. }
  14658. return BS_BLOCK_DONE;
  14659. }
  14660. /* ===========================================================================
  14661. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14662. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14663. */
  14664. function deflate_huff(s, flush) {
  14665. var bflush; /* set if current block must be flushed */
  14666. for (;;) {
  14667. /* Make sure that we have a literal to write. */
  14668. if (s.lookahead === 0) {
  14669. fill_window(s);
  14670. if (s.lookahead === 0) {
  14671. if (flush === Z_NO_FLUSH) {
  14672. return BS_NEED_MORE;
  14673. }
  14674. break; /* flush the current block */
  14675. }
  14676. }
  14677. /* Output a literal byte */
  14678. s.match_length = 0;
  14679. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14680. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14681. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14682. s.lookahead--;
  14683. s.strstart++;
  14684. if (bflush) {
  14685. /*** FLUSH_BLOCK(s, 0); ***/
  14686. flush_block_only(s, false);
  14687. if (s.strm.avail_out === 0) {
  14688. return BS_NEED_MORE;
  14689. }
  14690. /***/
  14691. }
  14692. }
  14693. s.insert = 0;
  14694. if (flush === Z_FINISH) {
  14695. /*** FLUSH_BLOCK(s, 1); ***/
  14696. flush_block_only(s, true);
  14697. if (s.strm.avail_out === 0) {
  14698. return BS_FINISH_STARTED;
  14699. }
  14700. /***/
  14701. return BS_FINISH_DONE;
  14702. }
  14703. if (s.last_lit) {
  14704. /*** FLUSH_BLOCK(s, 0); ***/
  14705. flush_block_only(s, false);
  14706. if (s.strm.avail_out === 0) {
  14707. return BS_NEED_MORE;
  14708. }
  14709. /***/
  14710. }
  14711. return BS_BLOCK_DONE;
  14712. }
  14713. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14714. * the desired pack level (0..9). The values given below have been tuned to
  14715. * exclude worst case performance for pathological files. Better values may be
  14716. * found for specific files.
  14717. */
  14718. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14719. this.good_length = good_length;
  14720. this.max_lazy = max_lazy;
  14721. this.nice_length = nice_length;
  14722. this.max_chain = max_chain;
  14723. this.func = func;
  14724. };
  14725. var configuration_table;
  14726. configuration_table = [
  14727. /* good lazy nice chain */
  14728. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14729. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14730. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14731. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14732. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14733. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14734. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14735. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14736. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14737. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14738. ];
  14739. /* ===========================================================================
  14740. * Initialize the "longest match" routines for a new zlib stream
  14741. */
  14742. function lm_init(s) {
  14743. s.window_size = 2 * s.w_size;
  14744. /*** CLEAR_HASH(s); ***/
  14745. zero(s.head); // Fill with NIL (= 0);
  14746. /* Set the default configuration parameters:
  14747. */
  14748. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14749. s.good_match = configuration_table[s.level].good_length;
  14750. s.nice_match = configuration_table[s.level].nice_length;
  14751. s.max_chain_length = configuration_table[s.level].max_chain;
  14752. s.strstart = 0;
  14753. s.block_start = 0;
  14754. s.lookahead = 0;
  14755. s.insert = 0;
  14756. s.match_length = s.prev_length = MIN_MATCH - 1;
  14757. s.match_available = 0;
  14758. s.ins_h = 0;
  14759. }
  14760. function DeflateState() {
  14761. this.strm = null; /* pointer back to this zlib stream */
  14762. this.status = 0; /* as the name implies */
  14763. this.pending_buf = null; /* output still pending */
  14764. this.pending_buf_size = 0; /* size of pending_buf */
  14765. this.pending_out = 0; /* next pending byte to output to the stream */
  14766. this.pending = 0; /* nb of bytes in the pending buffer */
  14767. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14768. this.gzhead = null; /* gzip header information to write */
  14769. this.gzindex = 0; /* where in extra, name, or comment */
  14770. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14771. this.last_flush = -1; /* value of flush param for previous deflate call */
  14772. this.w_size = 0; /* LZ77 window size (32K by default) */
  14773. this.w_bits = 0; /* log2(w_size) (8..16) */
  14774. this.w_mask = 0; /* w_size - 1 */
  14775. this.window = null;
  14776. /* Sliding window. Input bytes are read into the second half of the window,
  14777. * and move to the first half later to keep a dictionary of at least wSize
  14778. * bytes. With this organization, matches are limited to a distance of
  14779. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14780. * performed with a length multiple of the block size.
  14781. */
  14782. this.window_size = 0;
  14783. /* Actual size of window: 2*wSize, except when the user input buffer
  14784. * is directly used as sliding window.
  14785. */
  14786. this.prev = null;
  14787. /* Link to older string with same hash index. To limit the size of this
  14788. * array to 64K, this link is maintained only for the last 32K strings.
  14789. * An index in this array is thus a window index modulo 32K.
  14790. */
  14791. this.head = null; /* Heads of the hash chains or NIL. */
  14792. this.ins_h = 0; /* hash index of string to be inserted */
  14793. this.hash_size = 0; /* number of elements in hash table */
  14794. this.hash_bits = 0; /* log2(hash_size) */
  14795. this.hash_mask = 0; /* hash_size-1 */
  14796. this.hash_shift = 0;
  14797. /* Number of bits by which ins_h must be shifted at each input
  14798. * step. It must be such that after MIN_MATCH steps, the oldest
  14799. * byte no longer takes part in the hash key, that is:
  14800. * hash_shift * MIN_MATCH >= hash_bits
  14801. */
  14802. this.block_start = 0;
  14803. /* Window position at the beginning of the current output block. Gets
  14804. * negative when the window is moved backwards.
  14805. */
  14806. this.match_length = 0; /* length of best match */
  14807. this.prev_match = 0; /* previous match */
  14808. this.match_available = 0; /* set if previous match exists */
  14809. this.strstart = 0; /* start of string to insert */
  14810. this.match_start = 0; /* start of matching string */
  14811. this.lookahead = 0; /* number of valid bytes ahead in window */
  14812. this.prev_length = 0;
  14813. /* Length of the best match at previous step. Matches not greater than this
  14814. * are discarded. This is used in the lazy match evaluation.
  14815. */
  14816. this.max_chain_length = 0;
  14817. /* To speed up deflation, hash chains are never searched beyond this
  14818. * length. A higher limit improves compression ratio but degrades the
  14819. * speed.
  14820. */
  14821. this.max_lazy_match = 0;
  14822. /* Attempt to find a better match only when the current match is strictly
  14823. * smaller than this value. This mechanism is used only for compression
  14824. * levels >= 4.
  14825. */
  14826. // That's alias to max_lazy_match, don't use directly
  14827. //this.max_insert_length = 0;
  14828. /* Insert new strings in the hash table only if the match length is not
  14829. * greater than this length. This saves time but degrades compression.
  14830. * max_insert_length is used only for compression levels <= 3.
  14831. */
  14832. this.level = 0; /* compression level (1..9) */
  14833. this.strategy = 0; /* favor or force Huffman coding*/
  14834. this.good_match = 0;
  14835. /* Use a faster search when the previous match is longer than this */
  14836. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14837. /* used by trees.c: */
  14838. /* Didn't use ct_data typedef below to suppress compiler warning */
  14839. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  14840. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  14841. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  14842. // Use flat array of DOUBLE size, with interleaved fata,
  14843. // because JS does not support effective
  14844. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  14845. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  14846. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  14847. zero(this.dyn_ltree);
  14848. zero(this.dyn_dtree);
  14849. zero(this.bl_tree);
  14850. this.l_desc = null; /* desc. for literal tree */
  14851. this.d_desc = null; /* desc. for distance tree */
  14852. this.bl_desc = null; /* desc. for bit length tree */
  14853. //ush bl_count[MAX_BITS+1];
  14854. this.bl_count = new utils.Buf16(MAX_BITS+1);
  14855. /* number of codes at each bit length for an optimal tree */
  14856. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  14857. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  14858. zero(this.heap);
  14859. this.heap_len = 0; /* number of elements in the heap */
  14860. this.heap_max = 0; /* element of largest frequency */
  14861. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  14862. * The same heap array is used to build all trees.
  14863. */
  14864. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  14865. zero(this.depth);
  14866. /* Depth of each subtree used as tie breaker for trees of equal frequency
  14867. */
  14868. this.l_buf = 0; /* buffer index for literals or lengths */
  14869. this.lit_bufsize = 0;
  14870. /* Size of match buffer for literals/lengths. There are 4 reasons for
  14871. * limiting lit_bufsize to 64K:
  14872. * - frequencies can be kept in 16 bit counters
  14873. * - if compression is not successful for the first block, all input
  14874. * data is still in the window so we can still emit a stored block even
  14875. * when input comes from standard input. (This can also be done for
  14876. * all blocks if lit_bufsize is not greater than 32K.)
  14877. * - if compression is not successful for a file smaller than 64K, we can
  14878. * even emit a stored file instead of a stored block (saving 5 bytes).
  14879. * This is applicable only for zip (not gzip or zlib).
  14880. * - creating new Huffman trees less frequently may not provide fast
  14881. * adaptation to changes in the input data statistics. (Take for
  14882. * example a binary file with poorly compressible code followed by
  14883. * a highly compressible string table.) Smaller buffer sizes give
  14884. * fast adaptation but have of course the overhead of transmitting
  14885. * trees more frequently.
  14886. * - I can't count above 4
  14887. */
  14888. this.last_lit = 0; /* running index in l_buf */
  14889. this.d_buf = 0;
  14890. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14891. * the same number of elements. To use different lengths, an extra flag
  14892. * array would be necessary.
  14893. */
  14894. this.opt_len = 0; /* bit length of current block with optimal trees */
  14895. this.static_len = 0; /* bit length of current block with static trees */
  14896. this.matches = 0; /* number of string matches in current block */
  14897. this.insert = 0; /* bytes at end of window left to insert */
  14898. this.bi_buf = 0;
  14899. /* Output buffer. bits are inserted starting at the bottom (least
  14900. * significant bits).
  14901. */
  14902. this.bi_valid = 0;
  14903. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14904. * are always zero.
  14905. */
  14906. // Used for window memory init. We safely ignore it for JS. That makes
  14907. // sense only for pointers and memory check tools.
  14908. //this.high_water = 0;
  14909. /* High water mark offset in window for initialized bytes -- bytes above
  14910. * this are set to zero in order to avoid memory check warnings when
  14911. * longest match routines access bytes past the input. This is then
  14912. * updated to the new high water mark.
  14913. */
  14914. }
  14915. function deflateResetKeep(strm) {
  14916. var s;
  14917. if (!strm || !strm.state) {
  14918. return err(strm, Z_STREAM_ERROR);
  14919. }
  14920. strm.total_in = strm.total_out = 0;
  14921. strm.data_type = Z_UNKNOWN;
  14922. s = strm.state;
  14923. s.pending = 0;
  14924. s.pending_out = 0;
  14925. if (s.wrap < 0) {
  14926. s.wrap = -s.wrap;
  14927. /* was made negative by deflate(..., Z_FINISH); */
  14928. }
  14929. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14930. strm.adler = (s.wrap === 2) ?
  14931. 0 // crc32(0, Z_NULL, 0)
  14932. :
  14933. 1; // adler32(0, Z_NULL, 0)
  14934. s.last_flush = Z_NO_FLUSH;
  14935. trees._tr_init(s);
  14936. return Z_OK;
  14937. }
  14938. function deflateReset(strm) {
  14939. var ret = deflateResetKeep(strm);
  14940. if (ret === Z_OK) {
  14941. lm_init(strm.state);
  14942. }
  14943. return ret;
  14944. }
  14945. function deflateSetHeader(strm, head) {
  14946. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14947. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14948. strm.state.gzhead = head;
  14949. return Z_OK;
  14950. }
  14951. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14952. if (!strm) { // === Z_NULL
  14953. return Z_STREAM_ERROR;
  14954. }
  14955. var wrap = 1;
  14956. if (level === Z_DEFAULT_COMPRESSION) {
  14957. level = 6;
  14958. }
  14959. if (windowBits < 0) { /* suppress zlib wrapper */
  14960. wrap = 0;
  14961. windowBits = -windowBits;
  14962. }
  14963. else if (windowBits > 15) {
  14964. wrap = 2; /* write gzip wrapper instead */
  14965. windowBits -= 16;
  14966. }
  14967. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14968. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14969. strategy < 0 || strategy > Z_FIXED) {
  14970. return err(strm, Z_STREAM_ERROR);
  14971. }
  14972. if (windowBits === 8) {
  14973. windowBits = 9;
  14974. }
  14975. /* until 256-byte window bug fixed */
  14976. var s = new DeflateState();
  14977. strm.state = s;
  14978. s.strm = strm;
  14979. s.wrap = wrap;
  14980. s.gzhead = null;
  14981. s.w_bits = windowBits;
  14982. s.w_size = 1 << s.w_bits;
  14983. s.w_mask = s.w_size - 1;
  14984. s.hash_bits = memLevel + 7;
  14985. s.hash_size = 1 << s.hash_bits;
  14986. s.hash_mask = s.hash_size - 1;
  14987. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14988. s.window = new utils.Buf8(s.w_size * 2);
  14989. s.head = new utils.Buf16(s.hash_size);
  14990. s.prev = new utils.Buf16(s.w_size);
  14991. // Don't need mem init magic for JS.
  14992. //s.high_water = 0; /* nothing written to s->window yet */
  14993. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14994. s.pending_buf_size = s.lit_bufsize * 4;
  14995. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14996. s.d_buf = s.lit_bufsize >> 1;
  14997. s.l_buf = (1 + 2) * s.lit_bufsize;
  14998. s.level = level;
  14999. s.strategy = strategy;
  15000. s.method = method;
  15001. return deflateReset(strm);
  15002. }
  15003. function deflateInit(strm, level) {
  15004. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15005. }
  15006. function deflate(strm, flush) {
  15007. var old_flush, s;
  15008. var beg, val; // for gzip header write only
  15009. if (!strm || !strm.state ||
  15010. flush > Z_BLOCK || flush < 0) {
  15011. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15012. }
  15013. s = strm.state;
  15014. if (!strm.output ||
  15015. (!strm.input && strm.avail_in !== 0) ||
  15016. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15017. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15018. }
  15019. s.strm = strm; /* just in case */
  15020. old_flush = s.last_flush;
  15021. s.last_flush = flush;
  15022. /* Write the header */
  15023. if (s.status === INIT_STATE) {
  15024. if (s.wrap === 2) { // GZIP header
  15025. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15026. put_byte(s, 31);
  15027. put_byte(s, 139);
  15028. put_byte(s, 8);
  15029. if (!s.gzhead) { // s->gzhead == Z_NULL
  15030. put_byte(s, 0);
  15031. put_byte(s, 0);
  15032. put_byte(s, 0);
  15033. put_byte(s, 0);
  15034. put_byte(s, 0);
  15035. put_byte(s, s.level === 9 ? 2 :
  15036. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15037. 4 : 0));
  15038. put_byte(s, OS_CODE);
  15039. s.status = BUSY_STATE;
  15040. }
  15041. else {
  15042. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15043. (s.gzhead.hcrc ? 2 : 0) +
  15044. (!s.gzhead.extra ? 0 : 4) +
  15045. (!s.gzhead.name ? 0 : 8) +
  15046. (!s.gzhead.comment ? 0 : 16)
  15047. );
  15048. put_byte(s, s.gzhead.time & 0xff);
  15049. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15050. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15051. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15052. put_byte(s, s.level === 9 ? 2 :
  15053. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15054. 4 : 0));
  15055. put_byte(s, s.gzhead.os & 0xff);
  15056. if (s.gzhead.extra && s.gzhead.extra.length) {
  15057. put_byte(s, s.gzhead.extra.length & 0xff);
  15058. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15059. }
  15060. if (s.gzhead.hcrc) {
  15061. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15062. }
  15063. s.gzindex = 0;
  15064. s.status = EXTRA_STATE;
  15065. }
  15066. }
  15067. else // DEFLATE header
  15068. {
  15069. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15070. var level_flags = -1;
  15071. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15072. level_flags = 0;
  15073. } else if (s.level < 6) {
  15074. level_flags = 1;
  15075. } else if (s.level === 6) {
  15076. level_flags = 2;
  15077. } else {
  15078. level_flags = 3;
  15079. }
  15080. header |= (level_flags << 6);
  15081. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15082. header += 31 - (header % 31);
  15083. s.status = BUSY_STATE;
  15084. putShortMSB(s, header);
  15085. /* Save the adler32 of the preset dictionary: */
  15086. if (s.strstart !== 0) {
  15087. putShortMSB(s, strm.adler >>> 16);
  15088. putShortMSB(s, strm.adler & 0xffff);
  15089. }
  15090. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15091. }
  15092. }
  15093. //#ifdef GZIP
  15094. if (s.status === EXTRA_STATE) {
  15095. if (s.gzhead.extra/* != Z_NULL*/) {
  15096. beg = s.pending; /* start of bytes to update crc */
  15097. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15098. if (s.pending === s.pending_buf_size) {
  15099. if (s.gzhead.hcrc && s.pending > beg) {
  15100. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15101. }
  15102. flush_pending(strm);
  15103. beg = s.pending;
  15104. if (s.pending === s.pending_buf_size) {
  15105. break;
  15106. }
  15107. }
  15108. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15109. s.gzindex++;
  15110. }
  15111. if (s.gzhead.hcrc && s.pending > beg) {
  15112. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15113. }
  15114. if (s.gzindex === s.gzhead.extra.length) {
  15115. s.gzindex = 0;
  15116. s.status = NAME_STATE;
  15117. }
  15118. }
  15119. else {
  15120. s.status = NAME_STATE;
  15121. }
  15122. }
  15123. if (s.status === NAME_STATE) {
  15124. if (s.gzhead.name/* != Z_NULL*/) {
  15125. beg = s.pending; /* start of bytes to update crc */
  15126. //int val;
  15127. do {
  15128. if (s.pending === s.pending_buf_size) {
  15129. if (s.gzhead.hcrc && s.pending > beg) {
  15130. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15131. }
  15132. flush_pending(strm);
  15133. beg = s.pending;
  15134. if (s.pending === s.pending_buf_size) {
  15135. val = 1;
  15136. break;
  15137. }
  15138. }
  15139. // JS specific: little magic to add zero terminator to end of string
  15140. if (s.gzindex < s.gzhead.name.length) {
  15141. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15142. } else {
  15143. val = 0;
  15144. }
  15145. put_byte(s, val);
  15146. } while (val !== 0);
  15147. if (s.gzhead.hcrc && s.pending > beg) {
  15148. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15149. }
  15150. if (val === 0) {
  15151. s.gzindex = 0;
  15152. s.status = COMMENT_STATE;
  15153. }
  15154. }
  15155. else {
  15156. s.status = COMMENT_STATE;
  15157. }
  15158. }
  15159. if (s.status === COMMENT_STATE) {
  15160. if (s.gzhead.comment/* != Z_NULL*/) {
  15161. beg = s.pending; /* start of bytes to update crc */
  15162. //int val;
  15163. do {
  15164. if (s.pending === s.pending_buf_size) {
  15165. if (s.gzhead.hcrc && s.pending > beg) {
  15166. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15167. }
  15168. flush_pending(strm);
  15169. beg = s.pending;
  15170. if (s.pending === s.pending_buf_size) {
  15171. val = 1;
  15172. break;
  15173. }
  15174. }
  15175. // JS specific: little magic to add zero terminator to end of string
  15176. if (s.gzindex < s.gzhead.comment.length) {
  15177. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15178. } else {
  15179. val = 0;
  15180. }
  15181. put_byte(s, val);
  15182. } while (val !== 0);
  15183. if (s.gzhead.hcrc && s.pending > beg) {
  15184. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15185. }
  15186. if (val === 0) {
  15187. s.status = HCRC_STATE;
  15188. }
  15189. }
  15190. else {
  15191. s.status = HCRC_STATE;
  15192. }
  15193. }
  15194. if (s.status === HCRC_STATE) {
  15195. if (s.gzhead.hcrc) {
  15196. if (s.pending + 2 > s.pending_buf_size) {
  15197. flush_pending(strm);
  15198. }
  15199. if (s.pending + 2 <= s.pending_buf_size) {
  15200. put_byte(s, strm.adler & 0xff);
  15201. put_byte(s, (strm.adler >> 8) & 0xff);
  15202. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15203. s.status = BUSY_STATE;
  15204. }
  15205. }
  15206. else {
  15207. s.status = BUSY_STATE;
  15208. }
  15209. }
  15210. //#endif
  15211. /* Flush as much pending output as possible */
  15212. if (s.pending !== 0) {
  15213. flush_pending(strm);
  15214. if (strm.avail_out === 0) {
  15215. /* Since avail_out is 0, deflate will be called again with
  15216. * more output space, but possibly with both pending and
  15217. * avail_in equal to zero. There won't be anything to do,
  15218. * but this is not an error situation so make sure we
  15219. * return OK instead of BUF_ERROR at next call of deflate:
  15220. */
  15221. s.last_flush = -1;
  15222. return Z_OK;
  15223. }
  15224. /* Make sure there is something to do and avoid duplicate consecutive
  15225. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15226. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15227. */
  15228. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15229. flush !== Z_FINISH) {
  15230. return err(strm, Z_BUF_ERROR);
  15231. }
  15232. /* User must not provide more input after the first FINISH: */
  15233. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15234. return err(strm, Z_BUF_ERROR);
  15235. }
  15236. /* Start a new block or continue the current one.
  15237. */
  15238. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15239. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15240. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15241. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15242. configuration_table[s.level].func(s, flush));
  15243. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15244. s.status = FINISH_STATE;
  15245. }
  15246. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15247. if (strm.avail_out === 0) {
  15248. s.last_flush = -1;
  15249. /* avoid BUF_ERROR next call, see above */
  15250. }
  15251. return Z_OK;
  15252. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15253. * of deflate should use the same flush parameter to make sure
  15254. * that the flush is complete. So we don't have to output an
  15255. * empty block here, this will be done at next call. This also
  15256. * ensures that for a very small output buffer, we emit at most
  15257. * one empty block.
  15258. */
  15259. }
  15260. if (bstate === BS_BLOCK_DONE) {
  15261. if (flush === Z_PARTIAL_FLUSH) {
  15262. trees._tr_align(s);
  15263. }
  15264. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15265. trees._tr_stored_block(s, 0, 0, false);
  15266. /* For a full flush, this empty block will be recognized
  15267. * as a special marker by inflate_sync().
  15268. */
  15269. if (flush === Z_FULL_FLUSH) {
  15270. /*** CLEAR_HASH(s); ***/ /* forget history */
  15271. zero(s.head); // Fill with NIL (= 0);
  15272. if (s.lookahead === 0) {
  15273. s.strstart = 0;
  15274. s.block_start = 0;
  15275. s.insert = 0;
  15276. }
  15277. }
  15278. }
  15279. flush_pending(strm);
  15280. if (strm.avail_out === 0) {
  15281. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15282. return Z_OK;
  15283. }
  15284. }
  15285. }
  15286. //Assert(strm->avail_out > 0, "bug2");
  15287. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15288. if (flush !== Z_FINISH) { return Z_OK; }
  15289. if (s.wrap <= 0) { return Z_STREAM_END; }
  15290. /* Write the trailer */
  15291. if (s.wrap === 2) {
  15292. put_byte(s, strm.adler & 0xff);
  15293. put_byte(s, (strm.adler >> 8) & 0xff);
  15294. put_byte(s, (strm.adler >> 16) & 0xff);
  15295. put_byte(s, (strm.adler >> 24) & 0xff);
  15296. put_byte(s, strm.total_in & 0xff);
  15297. put_byte(s, (strm.total_in >> 8) & 0xff);
  15298. put_byte(s, (strm.total_in >> 16) & 0xff);
  15299. put_byte(s, (strm.total_in >> 24) & 0xff);
  15300. }
  15301. else
  15302. {
  15303. putShortMSB(s, strm.adler >>> 16);
  15304. putShortMSB(s, strm.adler & 0xffff);
  15305. }
  15306. flush_pending(strm);
  15307. /* If avail_out is zero, the application will call deflate again
  15308. * to flush the rest.
  15309. */
  15310. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15311. /* write the trailer only once! */
  15312. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15313. }
  15314. function deflateEnd(strm) {
  15315. var status;
  15316. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15317. return Z_STREAM_ERROR;
  15318. }
  15319. status = strm.state.status;
  15320. if (status !== INIT_STATE &&
  15321. status !== EXTRA_STATE &&
  15322. status !== NAME_STATE &&
  15323. status !== COMMENT_STATE &&
  15324. status !== HCRC_STATE &&
  15325. status !== BUSY_STATE &&
  15326. status !== FINISH_STATE
  15327. ) {
  15328. return err(strm, Z_STREAM_ERROR);
  15329. }
  15330. strm.state = null;
  15331. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15332. }
  15333. /* =========================================================================
  15334. * Copy the source state to the destination state
  15335. */
  15336. //function deflateCopy(dest, source) {
  15337. //
  15338. //}
  15339. exports.deflateInit = deflateInit;
  15340. exports.deflateInit2 = deflateInit2;
  15341. exports.deflateReset = deflateReset;
  15342. exports.deflateResetKeep = deflateResetKeep;
  15343. exports.deflateSetHeader = deflateSetHeader;
  15344. exports.deflate = deflate;
  15345. exports.deflateEnd = deflateEnd;
  15346. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15347. /* Not implemented
  15348. exports.deflateBound = deflateBound;
  15349. exports.deflateCopy = deflateCopy;
  15350. exports.deflateSetDictionary = deflateSetDictionary;
  15351. exports.deflateParams = deflateParams;
  15352. exports.deflatePending = deflatePending;
  15353. exports.deflatePrime = deflatePrime;
  15354. exports.deflateTune = deflateTune;
  15355. */
  15356. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./messages":61,"./trees":62}],57:[function(require,module,exports){
  15357. 'use strict';
  15358. function GZheader() {
  15359. /* true if compressed data believed to be text */
  15360. this.text = 0;
  15361. /* modification time */
  15362. this.time = 0;
  15363. /* extra flags (not used when writing a gzip file) */
  15364. this.xflags = 0;
  15365. /* operating system */
  15366. this.os = 0;
  15367. /* pointer to extra field or Z_NULL if none */
  15368. this.extra = null;
  15369. /* extra field length (valid if extra != Z_NULL) */
  15370. this.extra_len = 0; // Actually, we don't need it in JS,
  15371. // but leave for few code modifications
  15372. //
  15373. // Setup limits is not necessary because in js we should not preallocate memory
  15374. // for inflate use constant limit in 65536 bytes
  15375. //
  15376. /* space at extra (only when reading header) */
  15377. // this.extra_max = 0;
  15378. /* pointer to zero-terminated file name or Z_NULL */
  15379. this.name = '';
  15380. /* space at name (only when reading header) */
  15381. // this.name_max = 0;
  15382. /* pointer to zero-terminated comment or Z_NULL */
  15383. this.comment = '';
  15384. /* space at comment (only when reading header) */
  15385. // this.comm_max = 0;
  15386. /* true if there was or will be a header crc */
  15387. this.hcrc = 0;
  15388. /* true when done reading gzip header (not used when writing a gzip file) */
  15389. this.done = false;
  15390. }
  15391. module.exports = GZheader;
  15392. },{}],58:[function(require,module,exports){
  15393. 'use strict';
  15394. // See state defs from inflate.js
  15395. var BAD = 30; /* got a data error -- remain here until reset */
  15396. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15397. /*
  15398. Decode literal, length, and distance codes and write out the resulting
  15399. literal and match bytes until either not enough input or output is
  15400. available, an end-of-block is encountered, or a data error is encountered.
  15401. When large enough input and output buffers are supplied to inflate(), for
  15402. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15403. inflate execution time is spent in this routine.
  15404. Entry assumptions:
  15405. state.mode === LEN
  15406. strm.avail_in >= 6
  15407. strm.avail_out >= 258
  15408. start >= strm.avail_out
  15409. state.bits < 8
  15410. On return, state.mode is one of:
  15411. LEN -- ran out of enough output space or enough available input
  15412. TYPE -- reached end of block code, inflate() to interpret next block
  15413. BAD -- error in block data
  15414. Notes:
  15415. - The maximum input bits used by a length/distance pair is 15 bits for the
  15416. length code, 5 bits for the length extra, 15 bits for the distance code,
  15417. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15418. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15419. checking for available input while decoding.
  15420. - The maximum bytes that a single length/distance pair can output is 258
  15421. bytes, which is the maximum length that can be coded. inflate_fast()
  15422. requires strm.avail_out >= 258 for each loop to avoid checking for
  15423. output space.
  15424. */
  15425. module.exports = function inflate_fast(strm, start) {
  15426. var state;
  15427. var _in; /* local strm.input */
  15428. var last; /* have enough input while in < last */
  15429. var _out; /* local strm.output */
  15430. var beg; /* inflate()'s initial strm.output */
  15431. var end; /* while out < end, enough space available */
  15432. //#ifdef INFLATE_STRICT
  15433. var dmax; /* maximum distance from zlib header */
  15434. //#endif
  15435. var wsize; /* window size or zero if not using window */
  15436. var whave; /* valid bytes in the window */
  15437. var wnext; /* window write index */
  15438. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15439. var s_window; /* allocated sliding window, if wsize != 0 */
  15440. var hold; /* local strm.hold */
  15441. var bits; /* local strm.bits */
  15442. var lcode; /* local strm.lencode */
  15443. var dcode; /* local strm.distcode */
  15444. var lmask; /* mask for first level of length codes */
  15445. var dmask; /* mask for first level of distance codes */
  15446. var here; /* retrieved table entry */
  15447. var op; /* code bits, operation, extra bits, or */
  15448. /* window position, window bytes to copy */
  15449. var len; /* match length, unused bytes */
  15450. var dist; /* match distance */
  15451. var from; /* where to copy match from */
  15452. var from_source;
  15453. var input, output; // JS specific, because we have no pointers
  15454. /* copy state to local variables */
  15455. state = strm.state;
  15456. //here = state.here;
  15457. _in = strm.next_in;
  15458. input = strm.input;
  15459. last = _in + (strm.avail_in - 5);
  15460. _out = strm.next_out;
  15461. output = strm.output;
  15462. beg = _out - (start - strm.avail_out);
  15463. end = _out + (strm.avail_out - 257);
  15464. //#ifdef INFLATE_STRICT
  15465. dmax = state.dmax;
  15466. //#endif
  15467. wsize = state.wsize;
  15468. whave = state.whave;
  15469. wnext = state.wnext;
  15470. s_window = state.window;
  15471. hold = state.hold;
  15472. bits = state.bits;
  15473. lcode = state.lencode;
  15474. dcode = state.distcode;
  15475. lmask = (1 << state.lenbits) - 1;
  15476. dmask = (1 << state.distbits) - 1;
  15477. /* decode literals and length/distances until end-of-block or not enough
  15478. input data or output space */
  15479. top:
  15480. do {
  15481. if (bits < 15) {
  15482. hold += input[_in++] << bits;
  15483. bits += 8;
  15484. hold += input[_in++] << bits;
  15485. bits += 8;
  15486. }
  15487. here = lcode[hold & lmask];
  15488. dolen:
  15489. for (;;) { // Goto emulation
  15490. op = here >>> 24/*here.bits*/;
  15491. hold >>>= op;
  15492. bits -= op;
  15493. op = (here >>> 16) & 0xff/*here.op*/;
  15494. if (op === 0) { /* literal */
  15495. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15496. // "inflate: literal '%c'\n" :
  15497. // "inflate: literal 0x%02x\n", here.val));
  15498. output[_out++] = here & 0xffff/*here.val*/;
  15499. }
  15500. else if (op & 16) { /* length base */
  15501. len = here & 0xffff/*here.val*/;
  15502. op &= 15; /* number of extra bits */
  15503. if (op) {
  15504. if (bits < op) {
  15505. hold += input[_in++] << bits;
  15506. bits += 8;
  15507. }
  15508. len += hold & ((1 << op) - 1);
  15509. hold >>>= op;
  15510. bits -= op;
  15511. }
  15512. //Tracevv((stderr, "inflate: length %u\n", len));
  15513. if (bits < 15) {
  15514. hold += input[_in++] << bits;
  15515. bits += 8;
  15516. hold += input[_in++] << bits;
  15517. bits += 8;
  15518. }
  15519. here = dcode[hold & dmask];
  15520. dodist:
  15521. for (;;) { // goto emulation
  15522. op = here >>> 24/*here.bits*/;
  15523. hold >>>= op;
  15524. bits -= op;
  15525. op = (here >>> 16) & 0xff/*here.op*/;
  15526. if (op & 16) { /* distance base */
  15527. dist = here & 0xffff/*here.val*/;
  15528. op &= 15; /* number of extra bits */
  15529. if (bits < op) {
  15530. hold += input[_in++] << bits;
  15531. bits += 8;
  15532. if (bits < op) {
  15533. hold += input[_in++] << bits;
  15534. bits += 8;
  15535. }
  15536. }
  15537. dist += hold & ((1 << op) - 1);
  15538. //#ifdef INFLATE_STRICT
  15539. if (dist > dmax) {
  15540. strm.msg = 'invalid distance too far back';
  15541. state.mode = BAD;
  15542. break top;
  15543. }
  15544. //#endif
  15545. hold >>>= op;
  15546. bits -= op;
  15547. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15548. op = _out - beg; /* max distance in output */
  15549. if (dist > op) { /* see if copy from window */
  15550. op = dist - op; /* distance back in window */
  15551. if (op > whave) {
  15552. if (state.sane) {
  15553. strm.msg = 'invalid distance too far back';
  15554. state.mode = BAD;
  15555. break top;
  15556. }
  15557. // (!) This block is disabled in zlib defailts,
  15558. // don't enable it for binary compatibility
  15559. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15560. // if (len <= op - whave) {
  15561. // do {
  15562. // output[_out++] = 0;
  15563. // } while (--len);
  15564. // continue top;
  15565. // }
  15566. // len -= op - whave;
  15567. // do {
  15568. // output[_out++] = 0;
  15569. // } while (--op > whave);
  15570. // if (op === 0) {
  15571. // from = _out - dist;
  15572. // do {
  15573. // output[_out++] = output[from++];
  15574. // } while (--len);
  15575. // continue top;
  15576. // }
  15577. //#endif
  15578. }
  15579. from = 0; // window index
  15580. from_source = s_window;
  15581. if (wnext === 0) { /* very common case */
  15582. from += wsize - op;
  15583. if (op < len) { /* some from window */
  15584. len -= op;
  15585. do {
  15586. output[_out++] = s_window[from++];
  15587. } while (--op);
  15588. from = _out - dist; /* rest from output */
  15589. from_source = output;
  15590. }
  15591. }
  15592. else if (wnext < op) { /* wrap around window */
  15593. from += wsize + wnext - op;
  15594. op -= wnext;
  15595. if (op < len) { /* some from end of window */
  15596. len -= op;
  15597. do {
  15598. output[_out++] = s_window[from++];
  15599. } while (--op);
  15600. from = 0;
  15601. if (wnext < len) { /* some from start of window */
  15602. op = wnext;
  15603. len -= op;
  15604. do {
  15605. output[_out++] = s_window[from++];
  15606. } while (--op);
  15607. from = _out - dist; /* rest from output */
  15608. from_source = output;
  15609. }
  15610. }
  15611. }
  15612. else { /* contiguous in window */
  15613. from += wnext - op;
  15614. if (op < len) { /* some from window */
  15615. len -= op;
  15616. do {
  15617. output[_out++] = s_window[from++];
  15618. } while (--op);
  15619. from = _out - dist; /* rest from output */
  15620. from_source = output;
  15621. }
  15622. }
  15623. while (len > 2) {
  15624. output[_out++] = from_source[from++];
  15625. output[_out++] = from_source[from++];
  15626. output[_out++] = from_source[from++];
  15627. len -= 3;
  15628. }
  15629. if (len) {
  15630. output[_out++] = from_source[from++];
  15631. if (len > 1) {
  15632. output[_out++] = from_source[from++];
  15633. }
  15634. }
  15635. }
  15636. else {
  15637. from = _out - dist; /* copy direct from output */
  15638. do { /* minimum length is three */
  15639. output[_out++] = output[from++];
  15640. output[_out++] = output[from++];
  15641. output[_out++] = output[from++];
  15642. len -= 3;
  15643. } while (len > 2);
  15644. if (len) {
  15645. output[_out++] = output[from++];
  15646. if (len > 1) {
  15647. output[_out++] = output[from++];
  15648. }
  15649. }
  15650. }
  15651. }
  15652. else if ((op & 64) === 0) { /* 2nd level distance code */
  15653. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15654. continue dodist;
  15655. }
  15656. else {
  15657. strm.msg = 'invalid distance code';
  15658. state.mode = BAD;
  15659. break top;
  15660. }
  15661. break; // need to emulate goto via "continue"
  15662. }
  15663. }
  15664. else if ((op & 64) === 0) { /* 2nd level length code */
  15665. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15666. continue dolen;
  15667. }
  15668. else if (op & 32) { /* end-of-block */
  15669. //Tracevv((stderr, "inflate: end of block\n"));
  15670. state.mode = TYPE;
  15671. break top;
  15672. }
  15673. else {
  15674. strm.msg = 'invalid literal/length code';
  15675. state.mode = BAD;
  15676. break top;
  15677. }
  15678. break; // need to emulate goto via "continue"
  15679. }
  15680. } while (_in < last && _out < end);
  15681. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15682. len = bits >> 3;
  15683. _in -= len;
  15684. bits -= len << 3;
  15685. hold &= (1 << bits) - 1;
  15686. /* update state and return */
  15687. strm.next_in = _in;
  15688. strm.next_out = _out;
  15689. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15690. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15691. state.hold = hold;
  15692. state.bits = bits;
  15693. return;
  15694. };
  15695. },{}],59:[function(require,module,exports){
  15696. 'use strict';
  15697. var utils = require('../utils/common');
  15698. var adler32 = require('./adler32');
  15699. var crc32 = require('./crc32');
  15700. var inflate_fast = require('./inffast');
  15701. var inflate_table = require('./inftrees');
  15702. var CODES = 0;
  15703. var LENS = 1;
  15704. var DISTS = 2;
  15705. /* Public constants ==========================================================*/
  15706. /* ===========================================================================*/
  15707. /* Allowed flush values; see deflate() and inflate() below for details */
  15708. //var Z_NO_FLUSH = 0;
  15709. //var Z_PARTIAL_FLUSH = 1;
  15710. //var Z_SYNC_FLUSH = 2;
  15711. //var Z_FULL_FLUSH = 3;
  15712. var Z_FINISH = 4;
  15713. var Z_BLOCK = 5;
  15714. var Z_TREES = 6;
  15715. /* Return codes for the compression/decompression functions. Negative values
  15716. * are errors, positive values are used for special but normal events.
  15717. */
  15718. var Z_OK = 0;
  15719. var Z_STREAM_END = 1;
  15720. var Z_NEED_DICT = 2;
  15721. //var Z_ERRNO = -1;
  15722. var Z_STREAM_ERROR = -2;
  15723. var Z_DATA_ERROR = -3;
  15724. var Z_MEM_ERROR = -4;
  15725. var Z_BUF_ERROR = -5;
  15726. //var Z_VERSION_ERROR = -6;
  15727. /* The deflate compression method */
  15728. var Z_DEFLATED = 8;
  15729. /* STATES ====================================================================*/
  15730. /* ===========================================================================*/
  15731. var HEAD = 1; /* i: waiting for magic header */
  15732. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15733. var TIME = 3; /* i: waiting for modification time (gzip) */
  15734. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15735. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15736. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15737. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15738. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15739. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15740. var DICTID = 10; /* i: waiting for dictionary check value */
  15741. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15742. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15743. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15744. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15745. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15746. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15747. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15748. var LENLENS = 18; /* i: waiting for code length code lengths */
  15749. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15750. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15751. var LEN = 21; /* i: waiting for length/lit/eob code */
  15752. var LENEXT = 22; /* i: waiting for length extra bits */
  15753. var DIST = 23; /* i: waiting for distance code */
  15754. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15755. var MATCH = 25; /* o: waiting for output space to copy string */
  15756. var LIT = 26; /* o: waiting for output space to write literal */
  15757. var CHECK = 27; /* i: waiting for 32-bit check value */
  15758. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15759. var DONE = 29; /* finished check, done -- remain here until reset */
  15760. var BAD = 30; /* got a data error -- remain here until reset */
  15761. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15762. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15763. /* ===========================================================================*/
  15764. var ENOUGH_LENS = 852;
  15765. var ENOUGH_DISTS = 592;
  15766. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15767. var MAX_WBITS = 15;
  15768. /* 32K LZ77 window */
  15769. var DEF_WBITS = MAX_WBITS;
  15770. function ZSWAP32(q) {
  15771. return (((q >>> 24) & 0xff) +
  15772. ((q >>> 8) & 0xff00) +
  15773. ((q & 0xff00) << 8) +
  15774. ((q & 0xff) << 24));
  15775. }
  15776. function InflateState() {
  15777. this.mode = 0; /* current inflate mode */
  15778. this.last = false; /* true if processing last block */
  15779. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15780. this.havedict = false; /* true if dictionary provided */
  15781. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15782. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15783. this.check = 0; /* protected copy of check value */
  15784. this.total = 0; /* protected copy of output count */
  15785. // TODO: may be {}
  15786. this.head = null; /* where to save gzip header information */
  15787. /* sliding window */
  15788. this.wbits = 0; /* log base 2 of requested window size */
  15789. this.wsize = 0; /* window size or zero if not using window */
  15790. this.whave = 0; /* valid bytes in the window */
  15791. this.wnext = 0; /* window write index */
  15792. this.window = null; /* allocated sliding window, if needed */
  15793. /* bit accumulator */
  15794. this.hold = 0; /* input bit accumulator */
  15795. this.bits = 0; /* number of bits in "in" */
  15796. /* for string and stored block copying */
  15797. this.length = 0; /* literal or length of data to copy */
  15798. this.offset = 0; /* distance back to copy string from */
  15799. /* for table and code decoding */
  15800. this.extra = 0; /* extra bits needed */
  15801. /* fixed and dynamic code tables */
  15802. this.lencode = null; /* starting table for length/literal codes */
  15803. this.distcode = null; /* starting table for distance codes */
  15804. this.lenbits = 0; /* index bits for lencode */
  15805. this.distbits = 0; /* index bits for distcode */
  15806. /* dynamic table building */
  15807. this.ncode = 0; /* number of code length code lengths */
  15808. this.nlen = 0; /* number of length code lengths */
  15809. this.ndist = 0; /* number of distance code lengths */
  15810. this.have = 0; /* number of code lengths in lens[] */
  15811. this.next = null; /* next available space in codes[] */
  15812. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15813. this.work = new utils.Buf16(288); /* work area for code table building */
  15814. /*
  15815. because we don't have pointers in js, we use lencode and distcode directly
  15816. as buffers so we don't need codes
  15817. */
  15818. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15819. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15820. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15821. this.sane = 0; /* if false, allow invalid distance too far */
  15822. this.back = 0; /* bits back of last unprocessed length/lit */
  15823. this.was = 0; /* initial length of match */
  15824. }
  15825. function inflateResetKeep(strm) {
  15826. var state;
  15827. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15828. state = strm.state;
  15829. strm.total_in = strm.total_out = state.total = 0;
  15830. strm.msg = ''; /*Z_NULL*/
  15831. if (state.wrap) { /* to support ill-conceived Java test suite */
  15832. strm.adler = state.wrap & 1;
  15833. }
  15834. state.mode = HEAD;
  15835. state.last = 0;
  15836. state.havedict = 0;
  15837. state.dmax = 32768;
  15838. state.head = null/*Z_NULL*/;
  15839. state.hold = 0;
  15840. state.bits = 0;
  15841. //state.lencode = state.distcode = state.next = state.codes;
  15842. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  15843. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  15844. state.sane = 1;
  15845. state.back = -1;
  15846. //Tracev((stderr, "inflate: reset\n"));
  15847. return Z_OK;
  15848. }
  15849. function inflateReset(strm) {
  15850. var state;
  15851. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15852. state = strm.state;
  15853. state.wsize = 0;
  15854. state.whave = 0;
  15855. state.wnext = 0;
  15856. return inflateResetKeep(strm);
  15857. }
  15858. function inflateReset2(strm, windowBits) {
  15859. var wrap;
  15860. var state;
  15861. /* get the state */
  15862. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15863. state = strm.state;
  15864. /* extract wrap request from windowBits parameter */
  15865. if (windowBits < 0) {
  15866. wrap = 0;
  15867. windowBits = -windowBits;
  15868. }
  15869. else {
  15870. wrap = (windowBits >> 4) + 1;
  15871. if (windowBits < 48) {
  15872. windowBits &= 15;
  15873. }
  15874. }
  15875. /* set number of window bits, free window if different */
  15876. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  15877. return Z_STREAM_ERROR;
  15878. }
  15879. if (state.window !== null && state.wbits !== windowBits) {
  15880. state.window = null;
  15881. }
  15882. /* update state and reset the rest of it */
  15883. state.wrap = wrap;
  15884. state.wbits = windowBits;
  15885. return inflateReset(strm);
  15886. }
  15887. function inflateInit2(strm, windowBits) {
  15888. var ret;
  15889. var state;
  15890. if (!strm) { return Z_STREAM_ERROR; }
  15891. //strm.msg = Z_NULL; /* in case we return an error */
  15892. state = new InflateState();
  15893. //if (state === Z_NULL) return Z_MEM_ERROR;
  15894. //Tracev((stderr, "inflate: allocated\n"));
  15895. strm.state = state;
  15896. state.window = null/*Z_NULL*/;
  15897. ret = inflateReset2(strm, windowBits);
  15898. if (ret !== Z_OK) {
  15899. strm.state = null/*Z_NULL*/;
  15900. }
  15901. return ret;
  15902. }
  15903. function inflateInit(strm) {
  15904. return inflateInit2(strm, DEF_WBITS);
  15905. }
  15906. /*
  15907. Return state with length and distance decoding tables and index sizes set to
  15908. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15909. If BUILDFIXED is defined, then instead this routine builds the tables the
  15910. first time it's called, and returns those tables the first time and
  15911. thereafter. This reduces the size of the code by about 2K bytes, in
  15912. exchange for a little execution time. However, BUILDFIXED should not be
  15913. used for threaded applications, since the rewriting of the tables and virgin
  15914. may not be thread-safe.
  15915. */
  15916. var virgin = true;
  15917. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15918. function fixedtables(state) {
  15919. /* build fixed huffman tables if first call (may not be thread safe) */
  15920. if (virgin) {
  15921. var sym;
  15922. lenfix = new utils.Buf32(512);
  15923. distfix = new utils.Buf32(32);
  15924. /* literal/length table */
  15925. sym = 0;
  15926. while (sym < 144) { state.lens[sym++] = 8; }
  15927. while (sym < 256) { state.lens[sym++] = 9; }
  15928. while (sym < 280) { state.lens[sym++] = 7; }
  15929. while (sym < 288) { state.lens[sym++] = 8; }
  15930. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  15931. /* distance table */
  15932. sym = 0;
  15933. while (sym < 32) { state.lens[sym++] = 5; }
  15934. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  15935. /* do this just once */
  15936. virgin = false;
  15937. }
  15938. state.lencode = lenfix;
  15939. state.lenbits = 9;
  15940. state.distcode = distfix;
  15941. state.distbits = 5;
  15942. }
  15943. /*
  15944. Update the window with the last wsize (normally 32K) bytes written before
  15945. returning. If window does not exist yet, create it. This is only called
  15946. when a window is already in use, or when output has been written during this
  15947. inflate call, but the end of the deflate stream has not been reached yet.
  15948. It is also called to create a window for dictionary data when a dictionary
  15949. is loaded.
  15950. Providing output buffers larger than 32K to inflate() should provide a speed
  15951. advantage, since only the last 32K of output is copied to the sliding window
  15952. upon return from inflate(), and since all distances after the first 32K of
  15953. output will fall in the output data, making match copies simpler and faster.
  15954. The advantage may be dependent on the size of the processor's data caches.
  15955. */
  15956. function updatewindow(strm, src, end, copy) {
  15957. var dist;
  15958. var state = strm.state;
  15959. /* if it hasn't been done already, allocate space for the window */
  15960. if (state.window === null) {
  15961. state.wsize = 1 << state.wbits;
  15962. state.wnext = 0;
  15963. state.whave = 0;
  15964. state.window = new utils.Buf8(state.wsize);
  15965. }
  15966. /* copy state->wsize or less output bytes into the circular window */
  15967. if (copy >= state.wsize) {
  15968. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  15969. state.wnext = 0;
  15970. state.whave = state.wsize;
  15971. }
  15972. else {
  15973. dist = state.wsize - state.wnext;
  15974. if (dist > copy) {
  15975. dist = copy;
  15976. }
  15977. //zmemcpy(state->window + state->wnext, end - copy, dist);
  15978. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  15979. copy -= dist;
  15980. if (copy) {
  15981. //zmemcpy(state->window, end - copy, copy);
  15982. utils.arraySet(state.window,src, end - copy, copy, 0);
  15983. state.wnext = copy;
  15984. state.whave = state.wsize;
  15985. }
  15986. else {
  15987. state.wnext += dist;
  15988. if (state.wnext === state.wsize) { state.wnext = 0; }
  15989. if (state.whave < state.wsize) { state.whave += dist; }
  15990. }
  15991. }
  15992. return 0;
  15993. }
  15994. function inflate(strm, flush) {
  15995. var state;
  15996. var input, output; // input/output buffers
  15997. var next; /* next input INDEX */
  15998. var put; /* next output INDEX */
  15999. var have, left; /* available input and output */
  16000. var hold; /* bit buffer */
  16001. var bits; /* bits in bit buffer */
  16002. var _in, _out; /* save starting available input and output */
  16003. var copy; /* number of stored or match bytes to copy */
  16004. var from; /* where to copy match bytes from */
  16005. var from_source;
  16006. var here = 0; /* current decoding table entry */
  16007. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16008. //var last; /* parent table entry */
  16009. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16010. var len; /* length to copy for repeats, bits to drop */
  16011. var ret; /* return code */
  16012. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16013. var opts;
  16014. var n; // temporary var for NEED_BITS
  16015. var order = /* permutation of code lengths */
  16016. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16017. if (!strm || !strm.state || !strm.output ||
  16018. (!strm.input && strm.avail_in !== 0)) {
  16019. return Z_STREAM_ERROR;
  16020. }
  16021. state = strm.state;
  16022. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16023. //--- LOAD() ---
  16024. put = strm.next_out;
  16025. output = strm.output;
  16026. left = strm.avail_out;
  16027. next = strm.next_in;
  16028. input = strm.input;
  16029. have = strm.avail_in;
  16030. hold = state.hold;
  16031. bits = state.bits;
  16032. //---
  16033. _in = have;
  16034. _out = left;
  16035. ret = Z_OK;
  16036. inf_leave: // goto emulation
  16037. for (;;) {
  16038. switch (state.mode) {
  16039. case HEAD:
  16040. if (state.wrap === 0) {
  16041. state.mode = TYPEDO;
  16042. break;
  16043. }
  16044. //=== NEEDBITS(16);
  16045. while (bits < 16) {
  16046. if (have === 0) { break inf_leave; }
  16047. have--;
  16048. hold += input[next++] << bits;
  16049. bits += 8;
  16050. }
  16051. //===//
  16052. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16053. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16054. //=== CRC2(state.check, hold);
  16055. hbuf[0] = hold & 0xff;
  16056. hbuf[1] = (hold >>> 8) & 0xff;
  16057. state.check = crc32(state.check, hbuf, 2, 0);
  16058. //===//
  16059. //=== INITBITS();
  16060. hold = 0;
  16061. bits = 0;
  16062. //===//
  16063. state.mode = FLAGS;
  16064. break;
  16065. }
  16066. state.flags = 0; /* expect zlib header */
  16067. if (state.head) {
  16068. state.head.done = false;
  16069. }
  16070. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16071. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16072. strm.msg = 'incorrect header check';
  16073. state.mode = BAD;
  16074. break;
  16075. }
  16076. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16077. strm.msg = 'unknown compression method';
  16078. state.mode = BAD;
  16079. break;
  16080. }
  16081. //--- DROPBITS(4) ---//
  16082. hold >>>= 4;
  16083. bits -= 4;
  16084. //---//
  16085. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16086. if (state.wbits === 0) {
  16087. state.wbits = len;
  16088. }
  16089. else if (len > state.wbits) {
  16090. strm.msg = 'invalid window size';
  16091. state.mode = BAD;
  16092. break;
  16093. }
  16094. state.dmax = 1 << len;
  16095. //Tracev((stderr, "inflate: zlib header ok\n"));
  16096. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16097. state.mode = hold & 0x200 ? DICTID : TYPE;
  16098. //=== INITBITS();
  16099. hold = 0;
  16100. bits = 0;
  16101. //===//
  16102. break;
  16103. case FLAGS:
  16104. //=== NEEDBITS(16); */
  16105. while (bits < 16) {
  16106. if (have === 0) { break inf_leave; }
  16107. have--;
  16108. hold += input[next++] << bits;
  16109. bits += 8;
  16110. }
  16111. //===//
  16112. state.flags = hold;
  16113. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16114. strm.msg = 'unknown compression method';
  16115. state.mode = BAD;
  16116. break;
  16117. }
  16118. if (state.flags & 0xe000) {
  16119. strm.msg = 'unknown header flags set';
  16120. state.mode = BAD;
  16121. break;
  16122. }
  16123. if (state.head) {
  16124. state.head.text = ((hold >> 8) & 1);
  16125. }
  16126. if (state.flags & 0x0200) {
  16127. //=== CRC2(state.check, hold);
  16128. hbuf[0] = hold & 0xff;
  16129. hbuf[1] = (hold >>> 8) & 0xff;
  16130. state.check = crc32(state.check, hbuf, 2, 0);
  16131. //===//
  16132. }
  16133. //=== INITBITS();
  16134. hold = 0;
  16135. bits = 0;
  16136. //===//
  16137. state.mode = TIME;
  16138. /* falls through */
  16139. case TIME:
  16140. //=== NEEDBITS(32); */
  16141. while (bits < 32) {
  16142. if (have === 0) { break inf_leave; }
  16143. have--;
  16144. hold += input[next++] << bits;
  16145. bits += 8;
  16146. }
  16147. //===//
  16148. if (state.head) {
  16149. state.head.time = hold;
  16150. }
  16151. if (state.flags & 0x0200) {
  16152. //=== CRC4(state.check, hold)
  16153. hbuf[0] = hold & 0xff;
  16154. hbuf[1] = (hold >>> 8) & 0xff;
  16155. hbuf[2] = (hold >>> 16) & 0xff;
  16156. hbuf[3] = (hold >>> 24) & 0xff;
  16157. state.check = crc32(state.check, hbuf, 4, 0);
  16158. //===
  16159. }
  16160. //=== INITBITS();
  16161. hold = 0;
  16162. bits = 0;
  16163. //===//
  16164. state.mode = OS;
  16165. /* falls through */
  16166. case OS:
  16167. //=== NEEDBITS(16); */
  16168. while (bits < 16) {
  16169. if (have === 0) { break inf_leave; }
  16170. have--;
  16171. hold += input[next++] << bits;
  16172. bits += 8;
  16173. }
  16174. //===//
  16175. if (state.head) {
  16176. state.head.xflags = (hold & 0xff);
  16177. state.head.os = (hold >> 8);
  16178. }
  16179. if (state.flags & 0x0200) {
  16180. //=== CRC2(state.check, hold);
  16181. hbuf[0] = hold & 0xff;
  16182. hbuf[1] = (hold >>> 8) & 0xff;
  16183. state.check = crc32(state.check, hbuf, 2, 0);
  16184. //===//
  16185. }
  16186. //=== INITBITS();
  16187. hold = 0;
  16188. bits = 0;
  16189. //===//
  16190. state.mode = EXLEN;
  16191. /* falls through */
  16192. case EXLEN:
  16193. if (state.flags & 0x0400) {
  16194. //=== NEEDBITS(16); */
  16195. while (bits < 16) {
  16196. if (have === 0) { break inf_leave; }
  16197. have--;
  16198. hold += input[next++] << bits;
  16199. bits += 8;
  16200. }
  16201. //===//
  16202. state.length = hold;
  16203. if (state.head) {
  16204. state.head.extra_len = hold;
  16205. }
  16206. if (state.flags & 0x0200) {
  16207. //=== CRC2(state.check, hold);
  16208. hbuf[0] = hold & 0xff;
  16209. hbuf[1] = (hold >>> 8) & 0xff;
  16210. state.check = crc32(state.check, hbuf, 2, 0);
  16211. //===//
  16212. }
  16213. //=== INITBITS();
  16214. hold = 0;
  16215. bits = 0;
  16216. //===//
  16217. }
  16218. else if (state.head) {
  16219. state.head.extra = null/*Z_NULL*/;
  16220. }
  16221. state.mode = EXTRA;
  16222. /* falls through */
  16223. case EXTRA:
  16224. if (state.flags & 0x0400) {
  16225. copy = state.length;
  16226. if (copy > have) { copy = have; }
  16227. if (copy) {
  16228. if (state.head) {
  16229. len = state.head.extra_len - state.length;
  16230. if (!state.head.extra) {
  16231. // Use untyped array for more conveniend processing later
  16232. state.head.extra = new Array(state.head.extra_len);
  16233. }
  16234. utils.arraySet(
  16235. state.head.extra,
  16236. input,
  16237. next,
  16238. // extra field is limited to 65536 bytes
  16239. // - no need for additional size check
  16240. copy,
  16241. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16242. len
  16243. );
  16244. //zmemcpy(state.head.extra + len, next,
  16245. // len + copy > state.head.extra_max ?
  16246. // state.head.extra_max - len : copy);
  16247. }
  16248. if (state.flags & 0x0200) {
  16249. state.check = crc32(state.check, input, copy, next);
  16250. }
  16251. have -= copy;
  16252. next += copy;
  16253. state.length -= copy;
  16254. }
  16255. if (state.length) { break inf_leave; }
  16256. }
  16257. state.length = 0;
  16258. state.mode = NAME;
  16259. /* falls through */
  16260. case NAME:
  16261. if (state.flags & 0x0800) {
  16262. if (have === 0) { break inf_leave; }
  16263. copy = 0;
  16264. do {
  16265. // TODO: 2 or 1 bytes?
  16266. len = input[next + copy++];
  16267. /* use constant limit because in js we should not preallocate memory */
  16268. if (state.head && len &&
  16269. (state.length < 65536 /*state.head.name_max*/)) {
  16270. state.head.name += String.fromCharCode(len);
  16271. }
  16272. } while (len && copy < have);
  16273. if (state.flags & 0x0200) {
  16274. state.check = crc32(state.check, input, copy, next);
  16275. }
  16276. have -= copy;
  16277. next += copy;
  16278. if (len) { break inf_leave; }
  16279. }
  16280. else if (state.head) {
  16281. state.head.name = null;
  16282. }
  16283. state.length = 0;
  16284. state.mode = COMMENT;
  16285. /* falls through */
  16286. case COMMENT:
  16287. if (state.flags & 0x1000) {
  16288. if (have === 0) { break inf_leave; }
  16289. copy = 0;
  16290. do {
  16291. len = input[next + copy++];
  16292. /* use constant limit because in js we should not preallocate memory */
  16293. if (state.head && len &&
  16294. (state.length < 65536 /*state.head.comm_max*/)) {
  16295. state.head.comment += String.fromCharCode(len);
  16296. }
  16297. } while (len && copy < have);
  16298. if (state.flags & 0x0200) {
  16299. state.check = crc32(state.check, input, copy, next);
  16300. }
  16301. have -= copy;
  16302. next += copy;
  16303. if (len) { break inf_leave; }
  16304. }
  16305. else if (state.head) {
  16306. state.head.comment = null;
  16307. }
  16308. state.mode = HCRC;
  16309. /* falls through */
  16310. case HCRC:
  16311. if (state.flags & 0x0200) {
  16312. //=== NEEDBITS(16); */
  16313. while (bits < 16) {
  16314. if (have === 0) { break inf_leave; }
  16315. have--;
  16316. hold += input[next++] << bits;
  16317. bits += 8;
  16318. }
  16319. //===//
  16320. if (hold !== (state.check & 0xffff)) {
  16321. strm.msg = 'header crc mismatch';
  16322. state.mode = BAD;
  16323. break;
  16324. }
  16325. //=== INITBITS();
  16326. hold = 0;
  16327. bits = 0;
  16328. //===//
  16329. }
  16330. if (state.head) {
  16331. state.head.hcrc = ((state.flags >> 9) & 1);
  16332. state.head.done = true;
  16333. }
  16334. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16335. state.mode = TYPE;
  16336. break;
  16337. case DICTID:
  16338. //=== NEEDBITS(32); */
  16339. while (bits < 32) {
  16340. if (have === 0) { break inf_leave; }
  16341. have--;
  16342. hold += input[next++] << bits;
  16343. bits += 8;
  16344. }
  16345. //===//
  16346. strm.adler = state.check = ZSWAP32(hold);
  16347. //=== INITBITS();
  16348. hold = 0;
  16349. bits = 0;
  16350. //===//
  16351. state.mode = DICT;
  16352. /* falls through */
  16353. case DICT:
  16354. if (state.havedict === 0) {
  16355. //--- RESTORE() ---
  16356. strm.next_out = put;
  16357. strm.avail_out = left;
  16358. strm.next_in = next;
  16359. strm.avail_in = have;
  16360. state.hold = hold;
  16361. state.bits = bits;
  16362. //---
  16363. return Z_NEED_DICT;
  16364. }
  16365. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16366. state.mode = TYPE;
  16367. /* falls through */
  16368. case TYPE:
  16369. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16370. /* falls through */
  16371. case TYPEDO:
  16372. if (state.last) {
  16373. //--- BYTEBITS() ---//
  16374. hold >>>= bits & 7;
  16375. bits -= bits & 7;
  16376. //---//
  16377. state.mode = CHECK;
  16378. break;
  16379. }
  16380. //=== NEEDBITS(3); */
  16381. while (bits < 3) {
  16382. if (have === 0) { break inf_leave; }
  16383. have--;
  16384. hold += input[next++] << bits;
  16385. bits += 8;
  16386. }
  16387. //===//
  16388. state.last = (hold & 0x01)/*BITS(1)*/;
  16389. //--- DROPBITS(1) ---//
  16390. hold >>>= 1;
  16391. bits -= 1;
  16392. //---//
  16393. switch ((hold & 0x03)/*BITS(2)*/) {
  16394. case 0: /* stored block */
  16395. //Tracev((stderr, "inflate: stored block%s\n",
  16396. // state.last ? " (last)" : ""));
  16397. state.mode = STORED;
  16398. break;
  16399. case 1: /* fixed block */
  16400. fixedtables(state);
  16401. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16402. // state.last ? " (last)" : ""));
  16403. state.mode = LEN_; /* decode codes */
  16404. if (flush === Z_TREES) {
  16405. //--- DROPBITS(2) ---//
  16406. hold >>>= 2;
  16407. bits -= 2;
  16408. //---//
  16409. break inf_leave;
  16410. }
  16411. break;
  16412. case 2: /* dynamic block */
  16413. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16414. // state.last ? " (last)" : ""));
  16415. state.mode = TABLE;
  16416. break;
  16417. case 3:
  16418. strm.msg = 'invalid block type';
  16419. state.mode = BAD;
  16420. }
  16421. //--- DROPBITS(2) ---//
  16422. hold >>>= 2;
  16423. bits -= 2;
  16424. //---//
  16425. break;
  16426. case STORED:
  16427. //--- BYTEBITS() ---// /* go to byte boundary */
  16428. hold >>>= bits & 7;
  16429. bits -= bits & 7;
  16430. //---//
  16431. //=== NEEDBITS(32); */
  16432. while (bits < 32) {
  16433. if (have === 0) { break inf_leave; }
  16434. have--;
  16435. hold += input[next++] << bits;
  16436. bits += 8;
  16437. }
  16438. //===//
  16439. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16440. strm.msg = 'invalid stored block lengths';
  16441. state.mode = BAD;
  16442. break;
  16443. }
  16444. state.length = hold & 0xffff;
  16445. //Tracev((stderr, "inflate: stored length %u\n",
  16446. // state.length));
  16447. //=== INITBITS();
  16448. hold = 0;
  16449. bits = 0;
  16450. //===//
  16451. state.mode = COPY_;
  16452. if (flush === Z_TREES) { break inf_leave; }
  16453. /* falls through */
  16454. case COPY_:
  16455. state.mode = COPY;
  16456. /* falls through */
  16457. case COPY:
  16458. copy = state.length;
  16459. if (copy) {
  16460. if (copy > have) { copy = have; }
  16461. if (copy > left) { copy = left; }
  16462. if (copy === 0) { break inf_leave; }
  16463. //--- zmemcpy(put, next, copy); ---
  16464. utils.arraySet(output, input, next, copy, put);
  16465. //---//
  16466. have -= copy;
  16467. next += copy;
  16468. left -= copy;
  16469. put += copy;
  16470. state.length -= copy;
  16471. break;
  16472. }
  16473. //Tracev((stderr, "inflate: stored end\n"));
  16474. state.mode = TYPE;
  16475. break;
  16476. case TABLE:
  16477. //=== NEEDBITS(14); */
  16478. while (bits < 14) {
  16479. if (have === 0) { break inf_leave; }
  16480. have--;
  16481. hold += input[next++] << bits;
  16482. bits += 8;
  16483. }
  16484. //===//
  16485. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16486. //--- DROPBITS(5) ---//
  16487. hold >>>= 5;
  16488. bits -= 5;
  16489. //---//
  16490. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16491. //--- DROPBITS(5) ---//
  16492. hold >>>= 5;
  16493. bits -= 5;
  16494. //---//
  16495. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16496. //--- DROPBITS(4) ---//
  16497. hold >>>= 4;
  16498. bits -= 4;
  16499. //---//
  16500. //#ifndef PKZIP_BUG_WORKAROUND
  16501. if (state.nlen > 286 || state.ndist > 30) {
  16502. strm.msg = 'too many length or distance symbols';
  16503. state.mode = BAD;
  16504. break;
  16505. }
  16506. //#endif
  16507. //Tracev((stderr, "inflate: table sizes ok\n"));
  16508. state.have = 0;
  16509. state.mode = LENLENS;
  16510. /* falls through */
  16511. case LENLENS:
  16512. while (state.have < state.ncode) {
  16513. //=== NEEDBITS(3);
  16514. while (bits < 3) {
  16515. if (have === 0) { break inf_leave; }
  16516. have--;
  16517. hold += input[next++] << bits;
  16518. bits += 8;
  16519. }
  16520. //===//
  16521. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16522. //--- DROPBITS(3) ---//
  16523. hold >>>= 3;
  16524. bits -= 3;
  16525. //---//
  16526. }
  16527. while (state.have < 19) {
  16528. state.lens[order[state.have++]] = 0;
  16529. }
  16530. // We have separate tables & no pointers. 2 commented lines below not needed.
  16531. //state.next = state.codes;
  16532. //state.lencode = state.next;
  16533. // Switch to use dynamic table
  16534. state.lencode = state.lendyn;
  16535. state.lenbits = 7;
  16536. opts = {bits: state.lenbits};
  16537. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16538. state.lenbits = opts.bits;
  16539. if (ret) {
  16540. strm.msg = 'invalid code lengths set';
  16541. state.mode = BAD;
  16542. break;
  16543. }
  16544. //Tracev((stderr, "inflate: code lengths ok\n"));
  16545. state.have = 0;
  16546. state.mode = CODELENS;
  16547. /* falls through */
  16548. case CODELENS:
  16549. while (state.have < state.nlen + state.ndist) {
  16550. for (;;) {
  16551. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16552. here_bits = here >>> 24;
  16553. here_op = (here >>> 16) & 0xff;
  16554. here_val = here & 0xffff;
  16555. if ((here_bits) <= bits) { break; }
  16556. //--- PULLBYTE() ---//
  16557. if (have === 0) { break inf_leave; }
  16558. have--;
  16559. hold += input[next++] << bits;
  16560. bits += 8;
  16561. //---//
  16562. }
  16563. if (here_val < 16) {
  16564. //--- DROPBITS(here.bits) ---//
  16565. hold >>>= here_bits;
  16566. bits -= here_bits;
  16567. //---//
  16568. state.lens[state.have++] = here_val;
  16569. }
  16570. else {
  16571. if (here_val === 16) {
  16572. //=== NEEDBITS(here.bits + 2);
  16573. n = here_bits + 2;
  16574. while (bits < n) {
  16575. if (have === 0) { break inf_leave; }
  16576. have--;
  16577. hold += input[next++] << bits;
  16578. bits += 8;
  16579. }
  16580. //===//
  16581. //--- DROPBITS(here.bits) ---//
  16582. hold >>>= here_bits;
  16583. bits -= here_bits;
  16584. //---//
  16585. if (state.have === 0) {
  16586. strm.msg = 'invalid bit length repeat';
  16587. state.mode = BAD;
  16588. break;
  16589. }
  16590. len = state.lens[state.have - 1];
  16591. copy = 3 + (hold & 0x03);//BITS(2);
  16592. //--- DROPBITS(2) ---//
  16593. hold >>>= 2;
  16594. bits -= 2;
  16595. //---//
  16596. }
  16597. else if (here_val === 17) {
  16598. //=== NEEDBITS(here.bits + 3);
  16599. n = here_bits + 3;
  16600. while (bits < n) {
  16601. if (have === 0) { break inf_leave; }
  16602. have--;
  16603. hold += input[next++] << bits;
  16604. bits += 8;
  16605. }
  16606. //===//
  16607. //--- DROPBITS(here.bits) ---//
  16608. hold >>>= here_bits;
  16609. bits -= here_bits;
  16610. //---//
  16611. len = 0;
  16612. copy = 3 + (hold & 0x07);//BITS(3);
  16613. //--- DROPBITS(3) ---//
  16614. hold >>>= 3;
  16615. bits -= 3;
  16616. //---//
  16617. }
  16618. else {
  16619. //=== NEEDBITS(here.bits + 7);
  16620. n = here_bits + 7;
  16621. while (bits < n) {
  16622. if (have === 0) { break inf_leave; }
  16623. have--;
  16624. hold += input[next++] << bits;
  16625. bits += 8;
  16626. }
  16627. //===//
  16628. //--- DROPBITS(here.bits) ---//
  16629. hold >>>= here_bits;
  16630. bits -= here_bits;
  16631. //---//
  16632. len = 0;
  16633. copy = 11 + (hold & 0x7f);//BITS(7);
  16634. //--- DROPBITS(7) ---//
  16635. hold >>>= 7;
  16636. bits -= 7;
  16637. //---//
  16638. }
  16639. if (state.have + copy > state.nlen + state.ndist) {
  16640. strm.msg = 'invalid bit length repeat';
  16641. state.mode = BAD;
  16642. break;
  16643. }
  16644. while (copy--) {
  16645. state.lens[state.have++] = len;
  16646. }
  16647. }
  16648. }
  16649. /* handle error breaks in while */
  16650. if (state.mode === BAD) { break; }
  16651. /* check for end-of-block code (better have one) */
  16652. if (state.lens[256] === 0) {
  16653. strm.msg = 'invalid code -- missing end-of-block';
  16654. state.mode = BAD;
  16655. break;
  16656. }
  16657. /* build code tables -- note: do not change the lenbits or distbits
  16658. values here (9 and 6) without reading the comments in inftrees.h
  16659. concerning the ENOUGH constants, which depend on those values */
  16660. state.lenbits = 9;
  16661. opts = {bits: state.lenbits};
  16662. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16663. // We have separate tables & no pointers. 2 commented lines below not needed.
  16664. // state.next_index = opts.table_index;
  16665. state.lenbits = opts.bits;
  16666. // state.lencode = state.next;
  16667. if (ret) {
  16668. strm.msg = 'invalid literal/lengths set';
  16669. state.mode = BAD;
  16670. break;
  16671. }
  16672. state.distbits = 6;
  16673. //state.distcode.copy(state.codes);
  16674. // Switch to use dynamic table
  16675. state.distcode = state.distdyn;
  16676. opts = {bits: state.distbits};
  16677. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16678. // We have separate tables & no pointers. 2 commented lines below not needed.
  16679. // state.next_index = opts.table_index;
  16680. state.distbits = opts.bits;
  16681. // state.distcode = state.next;
  16682. if (ret) {
  16683. strm.msg = 'invalid distances set';
  16684. state.mode = BAD;
  16685. break;
  16686. }
  16687. //Tracev((stderr, 'inflate: codes ok\n'));
  16688. state.mode = LEN_;
  16689. if (flush === Z_TREES) { break inf_leave; }
  16690. /* falls through */
  16691. case LEN_:
  16692. state.mode = LEN;
  16693. /* falls through */
  16694. case LEN:
  16695. if (have >= 6 && left >= 258) {
  16696. //--- RESTORE() ---
  16697. strm.next_out = put;
  16698. strm.avail_out = left;
  16699. strm.next_in = next;
  16700. strm.avail_in = have;
  16701. state.hold = hold;
  16702. state.bits = bits;
  16703. //---
  16704. inflate_fast(strm, _out);
  16705. //--- LOAD() ---
  16706. put = strm.next_out;
  16707. output = strm.output;
  16708. left = strm.avail_out;
  16709. next = strm.next_in;
  16710. input = strm.input;
  16711. have = strm.avail_in;
  16712. hold = state.hold;
  16713. bits = state.bits;
  16714. //---
  16715. if (state.mode === TYPE) {
  16716. state.back = -1;
  16717. }
  16718. break;
  16719. }
  16720. state.back = 0;
  16721. for (;;) {
  16722. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16723. here_bits = here >>> 24;
  16724. here_op = (here >>> 16) & 0xff;
  16725. here_val = here & 0xffff;
  16726. if (here_bits <= bits) { break; }
  16727. //--- PULLBYTE() ---//
  16728. if (have === 0) { break inf_leave; }
  16729. have--;
  16730. hold += input[next++] << bits;
  16731. bits += 8;
  16732. //---//
  16733. }
  16734. if (here_op && (here_op & 0xf0) === 0) {
  16735. last_bits = here_bits;
  16736. last_op = here_op;
  16737. last_val = here_val;
  16738. for (;;) {
  16739. here = state.lencode[last_val +
  16740. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16741. here_bits = here >>> 24;
  16742. here_op = (here >>> 16) & 0xff;
  16743. here_val = here & 0xffff;
  16744. if ((last_bits + here_bits) <= bits) { break; }
  16745. //--- PULLBYTE() ---//
  16746. if (have === 0) { break inf_leave; }
  16747. have--;
  16748. hold += input[next++] << bits;
  16749. bits += 8;
  16750. //---//
  16751. }
  16752. //--- DROPBITS(last.bits) ---//
  16753. hold >>>= last_bits;
  16754. bits -= last_bits;
  16755. //---//
  16756. state.back += last_bits;
  16757. }
  16758. //--- DROPBITS(here.bits) ---//
  16759. hold >>>= here_bits;
  16760. bits -= here_bits;
  16761. //---//
  16762. state.back += here_bits;
  16763. state.length = here_val;
  16764. if (here_op === 0) {
  16765. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16766. // "inflate: literal '%c'\n" :
  16767. // "inflate: literal 0x%02x\n", here.val));
  16768. state.mode = LIT;
  16769. break;
  16770. }
  16771. if (here_op & 32) {
  16772. //Tracevv((stderr, "inflate: end of block\n"));
  16773. state.back = -1;
  16774. state.mode = TYPE;
  16775. break;
  16776. }
  16777. if (here_op & 64) {
  16778. strm.msg = 'invalid literal/length code';
  16779. state.mode = BAD;
  16780. break;
  16781. }
  16782. state.extra = here_op & 15;
  16783. state.mode = LENEXT;
  16784. /* falls through */
  16785. case LENEXT:
  16786. if (state.extra) {
  16787. //=== NEEDBITS(state.extra);
  16788. n = state.extra;
  16789. while (bits < n) {
  16790. if (have === 0) { break inf_leave; }
  16791. have--;
  16792. hold += input[next++] << bits;
  16793. bits += 8;
  16794. }
  16795. //===//
  16796. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16797. //--- DROPBITS(state.extra) ---//
  16798. hold >>>= state.extra;
  16799. bits -= state.extra;
  16800. //---//
  16801. state.back += state.extra;
  16802. }
  16803. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16804. state.was = state.length;
  16805. state.mode = DIST;
  16806. /* falls through */
  16807. case DIST:
  16808. for (;;) {
  16809. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16810. here_bits = here >>> 24;
  16811. here_op = (here >>> 16) & 0xff;
  16812. here_val = here & 0xffff;
  16813. if ((here_bits) <= bits) { break; }
  16814. //--- PULLBYTE() ---//
  16815. if (have === 0) { break inf_leave; }
  16816. have--;
  16817. hold += input[next++] << bits;
  16818. bits += 8;
  16819. //---//
  16820. }
  16821. if ((here_op & 0xf0) === 0) {
  16822. last_bits = here_bits;
  16823. last_op = here_op;
  16824. last_val = here_val;
  16825. for (;;) {
  16826. here = state.distcode[last_val +
  16827. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16828. here_bits = here >>> 24;
  16829. here_op = (here >>> 16) & 0xff;
  16830. here_val = here & 0xffff;
  16831. if ((last_bits + here_bits) <= bits) { break; }
  16832. //--- PULLBYTE() ---//
  16833. if (have === 0) { break inf_leave; }
  16834. have--;
  16835. hold += input[next++] << bits;
  16836. bits += 8;
  16837. //---//
  16838. }
  16839. //--- DROPBITS(last.bits) ---//
  16840. hold >>>= last_bits;
  16841. bits -= last_bits;
  16842. //---//
  16843. state.back += last_bits;
  16844. }
  16845. //--- DROPBITS(here.bits) ---//
  16846. hold >>>= here_bits;
  16847. bits -= here_bits;
  16848. //---//
  16849. state.back += here_bits;
  16850. if (here_op & 64) {
  16851. strm.msg = 'invalid distance code';
  16852. state.mode = BAD;
  16853. break;
  16854. }
  16855. state.offset = here_val;
  16856. state.extra = (here_op) & 15;
  16857. state.mode = DISTEXT;
  16858. /* falls through */
  16859. case DISTEXT:
  16860. if (state.extra) {
  16861. //=== NEEDBITS(state.extra);
  16862. n = state.extra;
  16863. while (bits < n) {
  16864. if (have === 0) { break inf_leave; }
  16865. have--;
  16866. hold += input[next++] << bits;
  16867. bits += 8;
  16868. }
  16869. //===//
  16870. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16871. //--- DROPBITS(state.extra) ---//
  16872. hold >>>= state.extra;
  16873. bits -= state.extra;
  16874. //---//
  16875. state.back += state.extra;
  16876. }
  16877. //#ifdef INFLATE_STRICT
  16878. if (state.offset > state.dmax) {
  16879. strm.msg = 'invalid distance too far back';
  16880. state.mode = BAD;
  16881. break;
  16882. }
  16883. //#endif
  16884. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  16885. state.mode = MATCH;
  16886. /* falls through */
  16887. case MATCH:
  16888. if (left === 0) { break inf_leave; }
  16889. copy = _out - left;
  16890. if (state.offset > copy) { /* copy from window */
  16891. copy = state.offset - copy;
  16892. if (copy > state.whave) {
  16893. if (state.sane) {
  16894. strm.msg = 'invalid distance too far back';
  16895. state.mode = BAD;
  16896. break;
  16897. }
  16898. // (!) This block is disabled in zlib defailts,
  16899. // don't enable it for binary compatibility
  16900. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16901. // Trace((stderr, "inflate.c too far\n"));
  16902. // copy -= state.whave;
  16903. // if (copy > state.length) { copy = state.length; }
  16904. // if (copy > left) { copy = left; }
  16905. // left -= copy;
  16906. // state.length -= copy;
  16907. // do {
  16908. // output[put++] = 0;
  16909. // } while (--copy);
  16910. // if (state.length === 0) { state.mode = LEN; }
  16911. // break;
  16912. //#endif
  16913. }
  16914. if (copy > state.wnext) {
  16915. copy -= state.wnext;
  16916. from = state.wsize - copy;
  16917. }
  16918. else {
  16919. from = state.wnext - copy;
  16920. }
  16921. if (copy > state.length) { copy = state.length; }
  16922. from_source = state.window;
  16923. }
  16924. else { /* copy from output */
  16925. from_source = output;
  16926. from = put - state.offset;
  16927. copy = state.length;
  16928. }
  16929. if (copy > left) { copy = left; }
  16930. left -= copy;
  16931. state.length -= copy;
  16932. do {
  16933. output[put++] = from_source[from++];
  16934. } while (--copy);
  16935. if (state.length === 0) { state.mode = LEN; }
  16936. break;
  16937. case LIT:
  16938. if (left === 0) { break inf_leave; }
  16939. output[put++] = state.length;
  16940. left--;
  16941. state.mode = LEN;
  16942. break;
  16943. case CHECK:
  16944. if (state.wrap) {
  16945. //=== NEEDBITS(32);
  16946. while (bits < 32) {
  16947. if (have === 0) { break inf_leave; }
  16948. have--;
  16949. // Use '|' insdead of '+' to make sure that result is signed
  16950. hold |= input[next++] << bits;
  16951. bits += 8;
  16952. }
  16953. //===//
  16954. _out -= left;
  16955. strm.total_out += _out;
  16956. state.total += _out;
  16957. if (_out) {
  16958. strm.adler = state.check =
  16959. /*UPDATE(state.check, put - _out, _out);*/
  16960. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  16961. }
  16962. _out = left;
  16963. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  16964. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  16965. strm.msg = 'incorrect data check';
  16966. state.mode = BAD;
  16967. break;
  16968. }
  16969. //=== INITBITS();
  16970. hold = 0;
  16971. bits = 0;
  16972. //===//
  16973. //Tracev((stderr, "inflate: check matches trailer\n"));
  16974. }
  16975. state.mode = LENGTH;
  16976. /* falls through */
  16977. case LENGTH:
  16978. if (state.wrap && state.flags) {
  16979. //=== NEEDBITS(32);
  16980. while (bits < 32) {
  16981. if (have === 0) { break inf_leave; }
  16982. have--;
  16983. hold += input[next++] << bits;
  16984. bits += 8;
  16985. }
  16986. //===//
  16987. if (hold !== (state.total & 0xffffffff)) {
  16988. strm.msg = 'incorrect length check';
  16989. state.mode = BAD;
  16990. break;
  16991. }
  16992. //=== INITBITS();
  16993. hold = 0;
  16994. bits = 0;
  16995. //===//
  16996. //Tracev((stderr, "inflate: length matches trailer\n"));
  16997. }
  16998. state.mode = DONE;
  16999. /* falls through */
  17000. case DONE:
  17001. ret = Z_STREAM_END;
  17002. break inf_leave;
  17003. case BAD:
  17004. ret = Z_DATA_ERROR;
  17005. break inf_leave;
  17006. case MEM:
  17007. return Z_MEM_ERROR;
  17008. case SYNC:
  17009. /* falls through */
  17010. default:
  17011. return Z_STREAM_ERROR;
  17012. }
  17013. }
  17014. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17015. /*
  17016. Return from inflate(), updating the total counts and the check value.
  17017. If there was no progress during the inflate() call, return a buffer
  17018. error. Call updatewindow() to create and/or update the window state.
  17019. Note: a memory error from inflate() is non-recoverable.
  17020. */
  17021. //--- RESTORE() ---
  17022. strm.next_out = put;
  17023. strm.avail_out = left;
  17024. strm.next_in = next;
  17025. strm.avail_in = have;
  17026. state.hold = hold;
  17027. state.bits = bits;
  17028. //---
  17029. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17030. (state.mode < CHECK || flush !== Z_FINISH))) {
  17031. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17032. state.mode = MEM;
  17033. return Z_MEM_ERROR;
  17034. }
  17035. }
  17036. _in -= strm.avail_in;
  17037. _out -= strm.avail_out;
  17038. strm.total_in += _in;
  17039. strm.total_out += _out;
  17040. state.total += _out;
  17041. if (state.wrap && _out) {
  17042. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17043. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17044. }
  17045. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17046. (state.mode === TYPE ? 128 : 0) +
  17047. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17048. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17049. ret = Z_BUF_ERROR;
  17050. }
  17051. return ret;
  17052. }
  17053. function inflateEnd(strm) {
  17054. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17055. return Z_STREAM_ERROR;
  17056. }
  17057. var state = strm.state;
  17058. if (state.window) {
  17059. state.window = null;
  17060. }
  17061. strm.state = null;
  17062. return Z_OK;
  17063. }
  17064. function inflateGetHeader(strm, head) {
  17065. var state;
  17066. /* check state */
  17067. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17068. state = strm.state;
  17069. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17070. /* save header structure */
  17071. state.head = head;
  17072. head.done = false;
  17073. return Z_OK;
  17074. }
  17075. exports.inflateReset = inflateReset;
  17076. exports.inflateReset2 = inflateReset2;
  17077. exports.inflateResetKeep = inflateResetKeep;
  17078. exports.inflateInit = inflateInit;
  17079. exports.inflateInit2 = inflateInit2;
  17080. exports.inflate = inflate;
  17081. exports.inflateEnd = inflateEnd;
  17082. exports.inflateGetHeader = inflateGetHeader;
  17083. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17084. /* Not implemented
  17085. exports.inflateCopy = inflateCopy;
  17086. exports.inflateGetDictionary = inflateGetDictionary;
  17087. exports.inflateMark = inflateMark;
  17088. exports.inflatePrime = inflatePrime;
  17089. exports.inflateSetDictionary = inflateSetDictionary;
  17090. exports.inflateSync = inflateSync;
  17091. exports.inflateSyncPoint = inflateSyncPoint;
  17092. exports.inflateUndermine = inflateUndermine;
  17093. */
  17094. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./inffast":58,"./inftrees":60}],60:[function(require,module,exports){
  17095. 'use strict';
  17096. var utils = require('../utils/common');
  17097. var MAXBITS = 15;
  17098. var ENOUGH_LENS = 852;
  17099. var ENOUGH_DISTS = 592;
  17100. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17101. var CODES = 0;
  17102. var LENS = 1;
  17103. var DISTS = 2;
  17104. var lbase = [ /* Length codes 257..285 base */
  17105. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17106. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17107. ];
  17108. var lext = [ /* Length codes 257..285 extra */
  17109. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17110. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17111. ];
  17112. var dbase = [ /* Distance codes 0..29 base */
  17113. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17114. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17115. 8193, 12289, 16385, 24577, 0, 0
  17116. ];
  17117. var dext = [ /* Distance codes 0..29 extra */
  17118. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17119. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17120. 28, 28, 29, 29, 64, 64
  17121. ];
  17122. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17123. {
  17124. var bits = opts.bits;
  17125. //here = opts.here; /* table entry for duplication */
  17126. var len = 0; /* a code's length in bits */
  17127. var sym = 0; /* index of code symbols */
  17128. var min = 0, max = 0; /* minimum and maximum code lengths */
  17129. var root = 0; /* number of index bits for root table */
  17130. var curr = 0; /* number of index bits for current table */
  17131. var drop = 0; /* code bits to drop for sub-table */
  17132. var left = 0; /* number of prefix codes available */
  17133. var used = 0; /* code entries in table used */
  17134. var huff = 0; /* Huffman code */
  17135. var incr; /* for incrementing code, index */
  17136. var fill; /* index for replicating entries */
  17137. var low; /* low bits for current root entry */
  17138. var mask; /* mask for low root bits */
  17139. var next; /* next available space in table */
  17140. var base = null; /* base value table to use */
  17141. var base_index = 0;
  17142. // var shoextra; /* extra bits table to use */
  17143. var end; /* use base and extra for symbol > end */
  17144. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17145. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17146. var extra = null;
  17147. var extra_index = 0;
  17148. var here_bits, here_op, here_val;
  17149. /*
  17150. Process a set of code lengths to create a canonical Huffman code. The
  17151. code lengths are lens[0..codes-1]. Each length corresponds to the
  17152. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17153. symbols by length from short to long, and retaining the symbol order
  17154. for codes with equal lengths. Then the code starts with all zero bits
  17155. for the first code of the shortest length, and the codes are integer
  17156. increments for the same length, and zeros are appended as the length
  17157. increases. For the deflate format, these bits are stored backwards
  17158. from their more natural integer increment ordering, and so when the
  17159. decoding tables are built in the large loop below, the integer codes
  17160. are incremented backwards.
  17161. This routine assumes, but does not check, that all of the entries in
  17162. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17163. 1..MAXBITS is interpreted as that code length. zero means that that
  17164. symbol does not occur in this code.
  17165. The codes are sorted by computing a count of codes for each length,
  17166. creating from that a table of starting indices for each length in the
  17167. sorted table, and then entering the symbols in order in the sorted
  17168. table. The sorted table is work[], with that space being provided by
  17169. the caller.
  17170. The length counts are used for other purposes as well, i.e. finding
  17171. the minimum and maximum length codes, determining if there are any
  17172. codes at all, checking for a valid set of lengths, and looking ahead
  17173. at length counts to determine sub-table sizes when building the
  17174. decoding tables.
  17175. */
  17176. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17177. for (len = 0; len <= MAXBITS; len++) {
  17178. count[len] = 0;
  17179. }
  17180. for (sym = 0; sym < codes; sym++) {
  17181. count[lens[lens_index + sym]]++;
  17182. }
  17183. /* bound code lengths, force root to be within code lengths */
  17184. root = bits;
  17185. for (max = MAXBITS; max >= 1; max--) {
  17186. if (count[max] !== 0) { break; }
  17187. }
  17188. if (root > max) {
  17189. root = max;
  17190. }
  17191. if (max === 0) { /* no symbols to code at all */
  17192. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17193. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17194. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17195. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17196. //table.op[opts.table_index] = 64;
  17197. //table.bits[opts.table_index] = 1;
  17198. //table.val[opts.table_index++] = 0;
  17199. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17200. opts.bits = 1;
  17201. return 0; /* no symbols, but wait for decoding to report error */
  17202. }
  17203. for (min = 1; min < max; min++) {
  17204. if (count[min] !== 0) { break; }
  17205. }
  17206. if (root < min) {
  17207. root = min;
  17208. }
  17209. /* check for an over-subscribed or incomplete set of lengths */
  17210. left = 1;
  17211. for (len = 1; len <= MAXBITS; len++) {
  17212. left <<= 1;
  17213. left -= count[len];
  17214. if (left < 0) {
  17215. return -1;
  17216. } /* over-subscribed */
  17217. }
  17218. if (left > 0 && (type === CODES || max !== 1)) {
  17219. return -1; /* incomplete set */
  17220. }
  17221. /* generate offsets into symbol table for each length for sorting */
  17222. offs[1] = 0;
  17223. for (len = 1; len < MAXBITS; len++) {
  17224. offs[len + 1] = offs[len] + count[len];
  17225. }
  17226. /* sort symbols by length, by symbol order within each length */
  17227. for (sym = 0; sym < codes; sym++) {
  17228. if (lens[lens_index + sym] !== 0) {
  17229. work[offs[lens[lens_index + sym]]++] = sym;
  17230. }
  17231. }
  17232. /*
  17233. Create and fill in decoding tables. In this loop, the table being
  17234. filled is at next and has curr index bits. The code being used is huff
  17235. with length len. That code is converted to an index by dropping drop
  17236. bits off of the bottom. For codes where len is less than drop + curr,
  17237. those top drop + curr - len bits are incremented through all values to
  17238. fill the table with replicated entries.
  17239. root is the number of index bits for the root table. When len exceeds
  17240. root, sub-tables are created pointed to by the root entry with an index
  17241. of the low root bits of huff. This is saved in low to check for when a
  17242. new sub-table should be started. drop is zero when the root table is
  17243. being filled, and drop is root when sub-tables are being filled.
  17244. When a new sub-table is needed, it is necessary to look ahead in the
  17245. code lengths to determine what size sub-table is needed. The length
  17246. counts are used for this, and so count[] is decremented as codes are
  17247. entered in the tables.
  17248. used keeps track of how many table entries have been allocated from the
  17249. provided *table space. It is checked for LENS and DIST tables against
  17250. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17251. the initial root table size constants. See the comments in inftrees.h
  17252. for more information.
  17253. sym increments through all symbols, and the loop terminates when
  17254. all codes of length max, i.e. all codes, have been processed. This
  17255. routine permits incomplete codes, so another loop after this one fills
  17256. in the rest of the decoding tables with invalid code markers.
  17257. */
  17258. /* set up for code type */
  17259. // poor man optimization - use if-else instead of switch,
  17260. // to avoid deopts in old v8
  17261. if (type === CODES) {
  17262. base = extra = work; /* dummy value--not used */
  17263. end = 19;
  17264. } else if (type === LENS) {
  17265. base = lbase;
  17266. base_index -= 257;
  17267. extra = lext;
  17268. extra_index -= 257;
  17269. end = 256;
  17270. } else { /* DISTS */
  17271. base = dbase;
  17272. extra = dext;
  17273. end = -1;
  17274. }
  17275. /* initialize opts for loop */
  17276. huff = 0; /* starting code */
  17277. sym = 0; /* starting code symbol */
  17278. len = min; /* starting code length */
  17279. next = table_index; /* current table to fill in */
  17280. curr = root; /* current table index bits */
  17281. drop = 0; /* current bits to drop from code for index */
  17282. low = -1; /* trigger new sub-table when len > root */
  17283. used = 1 << root; /* use root table entries */
  17284. mask = used - 1; /* mask for comparing low */
  17285. /* check available table space */
  17286. if ((type === LENS && used > ENOUGH_LENS) ||
  17287. (type === DISTS && used > ENOUGH_DISTS)) {
  17288. return 1;
  17289. }
  17290. var i=0;
  17291. /* process all codes and make table entries */
  17292. for (;;) {
  17293. i++;
  17294. /* create table entry */
  17295. here_bits = len - drop;
  17296. if (work[sym] < end) {
  17297. here_op = 0;
  17298. here_val = work[sym];
  17299. }
  17300. else if (work[sym] > end) {
  17301. here_op = extra[extra_index + work[sym]];
  17302. here_val = base[base_index + work[sym]];
  17303. }
  17304. else {
  17305. here_op = 32 + 64; /* end of block */
  17306. here_val = 0;
  17307. }
  17308. /* replicate for those indices with low len bits equal to huff */
  17309. incr = 1 << (len - drop);
  17310. fill = 1 << curr;
  17311. min = fill; /* save offset to next table */
  17312. do {
  17313. fill -= incr;
  17314. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17315. } while (fill !== 0);
  17316. /* backwards increment the len-bit code huff */
  17317. incr = 1 << (len - 1);
  17318. while (huff & incr) {
  17319. incr >>= 1;
  17320. }
  17321. if (incr !== 0) {
  17322. huff &= incr - 1;
  17323. huff += incr;
  17324. } else {
  17325. huff = 0;
  17326. }
  17327. /* go to next symbol, update count, len */
  17328. sym++;
  17329. if (--count[len] === 0) {
  17330. if (len === max) { break; }
  17331. len = lens[lens_index + work[sym]];
  17332. }
  17333. /* create new sub-table if needed */
  17334. if (len > root && (huff & mask) !== low) {
  17335. /* if first time, transition to sub-tables */
  17336. if (drop === 0) {
  17337. drop = root;
  17338. }
  17339. /* increment past last table */
  17340. next += min; /* here min is 1 << curr */
  17341. /* determine length of next table */
  17342. curr = len - drop;
  17343. left = 1 << curr;
  17344. while (curr + drop < max) {
  17345. left -= count[curr + drop];
  17346. if (left <= 0) { break; }
  17347. curr++;
  17348. left <<= 1;
  17349. }
  17350. /* check for enough space */
  17351. used += 1 << curr;
  17352. if ((type === LENS && used > ENOUGH_LENS) ||
  17353. (type === DISTS && used > ENOUGH_DISTS)) {
  17354. return 1;
  17355. }
  17356. /* point entry in root table to sub-table */
  17357. low = huff & mask;
  17358. /*table.op[low] = curr;
  17359. table.bits[low] = root;
  17360. table.val[low] = next - opts.table_index;*/
  17361. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17362. }
  17363. }
  17364. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17365. at most one remaining entry, since if the code is incomplete, the
  17366. maximum code length that was allowed to get this far is one bit) */
  17367. if (huff !== 0) {
  17368. //table.op[next + huff] = 64; /* invalid code marker */
  17369. //table.bits[next + huff] = len - drop;
  17370. //table.val[next + huff] = 0;
  17371. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17372. }
  17373. /* set return parameters */
  17374. //opts.table_index += used;
  17375. opts.bits = root;
  17376. return 0;
  17377. };
  17378. },{"../utils/common":51}],61:[function(require,module,exports){
  17379. 'use strict';
  17380. module.exports = {
  17381. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17382. '1': 'stream end', /* Z_STREAM_END 1 */
  17383. '0': '', /* Z_OK 0 */
  17384. '-1': 'file error', /* Z_ERRNO (-1) */
  17385. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17386. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17387. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17388. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17389. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17390. };
  17391. },{}],62:[function(require,module,exports){
  17392. 'use strict';
  17393. var utils = require('../utils/common');
  17394. /* Public constants ==========================================================*/
  17395. /* ===========================================================================*/
  17396. //var Z_FILTERED = 1;
  17397. //var Z_HUFFMAN_ONLY = 2;
  17398. //var Z_RLE = 3;
  17399. var Z_FIXED = 4;
  17400. //var Z_DEFAULT_STRATEGY = 0;
  17401. /* Possible values of the data_type field (though see inflate()) */
  17402. var Z_BINARY = 0;
  17403. var Z_TEXT = 1;
  17404. //var Z_ASCII = 1; // = Z_TEXT
  17405. var Z_UNKNOWN = 2;
  17406. /*============================================================================*/
  17407. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17408. // From zutil.h
  17409. var STORED_BLOCK = 0;
  17410. var STATIC_TREES = 1;
  17411. var DYN_TREES = 2;
  17412. /* The three kinds of block type */
  17413. var MIN_MATCH = 3;
  17414. var MAX_MATCH = 258;
  17415. /* The minimum and maximum match lengths */
  17416. // From deflate.h
  17417. /* ===========================================================================
  17418. * Internal compression state.
  17419. */
  17420. var LENGTH_CODES = 29;
  17421. /* number of length codes, not counting the special END_BLOCK code */
  17422. var LITERALS = 256;
  17423. /* number of literal bytes 0..255 */
  17424. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17425. /* number of Literal or Length codes, including the END_BLOCK code */
  17426. var D_CODES = 30;
  17427. /* number of distance codes */
  17428. var BL_CODES = 19;
  17429. /* number of codes used to transfer the bit lengths */
  17430. var HEAP_SIZE = 2*L_CODES + 1;
  17431. /* maximum heap size */
  17432. var MAX_BITS = 15;
  17433. /* All codes must not exceed MAX_BITS bits */
  17434. var Buf_size = 16;
  17435. /* size of bit buffer in bi_buf */
  17436. /* ===========================================================================
  17437. * Constants
  17438. */
  17439. var MAX_BL_BITS = 7;
  17440. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17441. var END_BLOCK = 256;
  17442. /* end of block literal code */
  17443. var REP_3_6 = 16;
  17444. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17445. var REPZ_3_10 = 17;
  17446. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17447. var REPZ_11_138 = 18;
  17448. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17449. var extra_lbits = /* extra bits for each length code */
  17450. [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];
  17451. var extra_dbits = /* extra bits for each distance code */
  17452. [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];
  17453. var extra_blbits = /* extra bits for each bit length code */
  17454. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17455. var bl_order =
  17456. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17457. /* The lengths of the bit length codes are sent in order of decreasing
  17458. * probability, to avoid transmitting the lengths for unused bit length codes.
  17459. */
  17460. /* ===========================================================================
  17461. * Local data. These are initialized only once.
  17462. */
  17463. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17464. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17465. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17466. var static_ltree = new Array((L_CODES+2) * 2);
  17467. zero(static_ltree);
  17468. /* The static literal tree. Since the bit lengths are imposed, there is no
  17469. * need for the L_CODES extra codes used during heap construction. However
  17470. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17471. * below).
  17472. */
  17473. var static_dtree = new Array(D_CODES * 2);
  17474. zero(static_dtree);
  17475. /* The static distance tree. (Actually a trivial tree since all codes use
  17476. * 5 bits.)
  17477. */
  17478. var _dist_code = new Array(DIST_CODE_LEN);
  17479. zero(_dist_code);
  17480. /* Distance codes. The first 256 values correspond to the distances
  17481. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17482. * the 15 bit distances.
  17483. */
  17484. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17485. zero(_length_code);
  17486. /* length code for each normalized match length (0 == MIN_MATCH) */
  17487. var base_length = new Array(LENGTH_CODES);
  17488. zero(base_length);
  17489. /* First normalized length for each code (0 = MIN_MATCH) */
  17490. var base_dist = new Array(D_CODES);
  17491. zero(base_dist);
  17492. /* First normalized distance for each code (0 = distance of 1) */
  17493. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17494. this.static_tree = static_tree; /* static tree or NULL */
  17495. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17496. this.extra_base = extra_base; /* base index for extra_bits */
  17497. this.elems = elems; /* max number of elements in the tree */
  17498. this.max_length = max_length; /* max bit length for the codes */
  17499. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17500. this.has_stree = static_tree && static_tree.length;
  17501. };
  17502. var static_l_desc;
  17503. var static_d_desc;
  17504. var static_bl_desc;
  17505. var TreeDesc = function(dyn_tree, stat_desc) {
  17506. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17507. this.max_code = 0; /* largest code with non zero frequency */
  17508. this.stat_desc = stat_desc; /* the corresponding static tree */
  17509. };
  17510. function d_code(dist) {
  17511. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17512. }
  17513. /* ===========================================================================
  17514. * Output a short LSB first on the stream.
  17515. * IN assertion: there is enough room in pendingBuf.
  17516. */
  17517. function put_short (s, w) {
  17518. // put_byte(s, (uch)((w) & 0xff));
  17519. // put_byte(s, (uch)((ush)(w) >> 8));
  17520. s.pending_buf[s.pending++] = (w) & 0xff;
  17521. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17522. }
  17523. /* ===========================================================================
  17524. * Send a value on a given number of bits.
  17525. * IN assertion: length <= 16 and value fits in length bits.
  17526. */
  17527. function send_bits(s, value, length) {
  17528. if (s.bi_valid > (Buf_size - length)) {
  17529. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17530. put_short(s, s.bi_buf);
  17531. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17532. s.bi_valid += length - Buf_size;
  17533. } else {
  17534. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17535. s.bi_valid += length;
  17536. }
  17537. }
  17538. function send_code(s, c, tree) {
  17539. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17540. }
  17541. /* ===========================================================================
  17542. * Reverse the first len bits of a code, using straightforward code (a faster
  17543. * method would use a table)
  17544. * IN assertion: 1 <= len <= 15
  17545. */
  17546. function bi_reverse(code, len) {
  17547. var res = 0;
  17548. do {
  17549. res |= code & 1;
  17550. code >>>= 1;
  17551. res <<= 1;
  17552. } while (--len > 0);
  17553. return res >>> 1;
  17554. }
  17555. /* ===========================================================================
  17556. * Flush the bit buffer, keeping at most 7 bits in it.
  17557. */
  17558. function bi_flush(s) {
  17559. if (s.bi_valid === 16) {
  17560. put_short(s, s.bi_buf);
  17561. s.bi_buf = 0;
  17562. s.bi_valid = 0;
  17563. } else if (s.bi_valid >= 8) {
  17564. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17565. s.bi_buf >>= 8;
  17566. s.bi_valid -= 8;
  17567. }
  17568. }
  17569. /* ===========================================================================
  17570. * Compute the optimal bit lengths for a tree and update the total bit length
  17571. * for the current block.
  17572. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17573. * above are the tree nodes sorted by increasing frequency.
  17574. * OUT assertions: the field len is set to the optimal bit length, the
  17575. * array bl_count contains the frequencies for each bit length.
  17576. * The length opt_len is updated; static_len is also updated if stree is
  17577. * not null.
  17578. */
  17579. function gen_bitlen(s, desc)
  17580. // deflate_state *s;
  17581. // tree_desc *desc; /* the tree descriptor */
  17582. {
  17583. var tree = desc.dyn_tree;
  17584. var max_code = desc.max_code;
  17585. var stree = desc.stat_desc.static_tree;
  17586. var has_stree = desc.stat_desc.has_stree;
  17587. var extra = desc.stat_desc.extra_bits;
  17588. var base = desc.stat_desc.extra_base;
  17589. var max_length = desc.stat_desc.max_length;
  17590. var h; /* heap index */
  17591. var n, m; /* iterate over the tree elements */
  17592. var bits; /* bit length */
  17593. var xbits; /* extra bits */
  17594. var f; /* frequency */
  17595. var overflow = 0; /* number of elements with bit length too large */
  17596. for (bits = 0; bits <= MAX_BITS; bits++) {
  17597. s.bl_count[bits] = 0;
  17598. }
  17599. /* In a first pass, compute the optimal bit lengths (which may
  17600. * overflow in the case of the bit length tree).
  17601. */
  17602. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17603. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17604. n = s.heap[h];
  17605. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17606. if (bits > max_length) {
  17607. bits = max_length;
  17608. overflow++;
  17609. }
  17610. tree[n*2 + 1]/*.Len*/ = bits;
  17611. /* We overwrite tree[n].Dad which is no longer needed */
  17612. if (n > max_code) { continue; } /* not a leaf node */
  17613. s.bl_count[bits]++;
  17614. xbits = 0;
  17615. if (n >= base) {
  17616. xbits = extra[n-base];
  17617. }
  17618. f = tree[n * 2]/*.Freq*/;
  17619. s.opt_len += f * (bits + xbits);
  17620. if (has_stree) {
  17621. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  17622. }
  17623. }
  17624. if (overflow === 0) { return; }
  17625. // Trace((stderr,"\nbit length overflow\n"));
  17626. /* This happens for example on obj2 and pic of the Calgary corpus */
  17627. /* Find the first bit length which could increase: */
  17628. do {
  17629. bits = max_length-1;
  17630. while (s.bl_count[bits] === 0) { bits--; }
  17631. s.bl_count[bits]--; /* move one leaf down the tree */
  17632. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  17633. s.bl_count[max_length]--;
  17634. /* The brother of the overflow item also moves one step up,
  17635. * but this does not affect bl_count[max_length]
  17636. */
  17637. overflow -= 2;
  17638. } while (overflow > 0);
  17639. /* Now recompute all bit lengths, scanning in increasing frequency.
  17640. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17641. * lengths instead of fixing only the wrong ones. This idea is taken
  17642. * from 'ar' written by Haruhiko Okumura.)
  17643. */
  17644. for (bits = max_length; bits !== 0; bits--) {
  17645. n = s.bl_count[bits];
  17646. while (n !== 0) {
  17647. m = s.heap[--h];
  17648. if (m > max_code) { continue; }
  17649. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  17650. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17651. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  17652. tree[m*2 + 1]/*.Len*/ = bits;
  17653. }
  17654. n--;
  17655. }
  17656. }
  17657. }
  17658. /* ===========================================================================
  17659. * Generate the codes for a given tree and bit counts (which need not be
  17660. * optimal).
  17661. * IN assertion: the array bl_count contains the bit length statistics for
  17662. * the given tree and the field len is set for all tree elements.
  17663. * OUT assertion: the field code is set for all tree elements of non
  17664. * zero code length.
  17665. */
  17666. function gen_codes(tree, max_code, bl_count)
  17667. // ct_data *tree; /* the tree to decorate */
  17668. // int max_code; /* largest code with non zero frequency */
  17669. // ushf *bl_count; /* number of codes at each bit length */
  17670. {
  17671. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17672. var code = 0; /* running code value */
  17673. var bits; /* bit index */
  17674. var n; /* code index */
  17675. /* The distribution counts are first used to generate the code values
  17676. * without bit reversal.
  17677. */
  17678. for (bits = 1; bits <= MAX_BITS; bits++) {
  17679. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17680. }
  17681. /* Check that the bit counts in bl_count are consistent. The last code
  17682. * must be all ones.
  17683. */
  17684. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17685. // "inconsistent bit counts");
  17686. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17687. for (n = 0; n <= max_code; n++) {
  17688. var len = tree[n*2 + 1]/*.Len*/;
  17689. if (len === 0) { continue; }
  17690. /* Now reverse the bits */
  17691. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17692. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17693. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17694. }
  17695. }
  17696. /* ===========================================================================
  17697. * Initialize the various 'constant' tables.
  17698. */
  17699. function tr_static_init() {
  17700. var n; /* iterates over tree elements */
  17701. var bits; /* bit counter */
  17702. var length; /* length value */
  17703. var code; /* code value */
  17704. var dist; /* distance index */
  17705. var bl_count = new Array(MAX_BITS+1);
  17706. /* number of codes at each bit length for an optimal tree */
  17707. // do check in _tr_init()
  17708. //if (static_init_done) return;
  17709. /* For some embedded targets, global variables are not initialized: */
  17710. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17711. static_l_desc.static_tree = static_ltree;
  17712. static_l_desc.extra_bits = extra_lbits;
  17713. static_d_desc.static_tree = static_dtree;
  17714. static_d_desc.extra_bits = extra_dbits;
  17715. static_bl_desc.extra_bits = extra_blbits;
  17716. #endif*/
  17717. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17718. length = 0;
  17719. for (code = 0; code < LENGTH_CODES-1; code++) {
  17720. base_length[code] = length;
  17721. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17722. _length_code[length++] = code;
  17723. }
  17724. }
  17725. //Assert (length == 256, "tr_static_init: length != 256");
  17726. /* Note that the length 255 (match length 258) can be represented
  17727. * in two different ways: code 284 + 5 bits or code 285, so we
  17728. * overwrite length_code[255] to use the best encoding:
  17729. */
  17730. _length_code[length-1] = code;
  17731. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17732. dist = 0;
  17733. for (code = 0 ; code < 16; code++) {
  17734. base_dist[code] = dist;
  17735. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17736. _dist_code[dist++] = code;
  17737. }
  17738. }
  17739. //Assert (dist == 256, "tr_static_init: dist != 256");
  17740. dist >>= 7; /* from now on, all distances are divided by 128 */
  17741. for (; code < D_CODES; code++) {
  17742. base_dist[code] = dist << 7;
  17743. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17744. _dist_code[256 + dist++] = code;
  17745. }
  17746. }
  17747. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17748. /* Construct the codes of the static literal tree */
  17749. for (bits = 0; bits <= MAX_BITS; bits++) {
  17750. bl_count[bits] = 0;
  17751. }
  17752. n = 0;
  17753. while (n <= 143) {
  17754. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17755. n++;
  17756. bl_count[8]++;
  17757. }
  17758. while (n <= 255) {
  17759. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17760. n++;
  17761. bl_count[9]++;
  17762. }
  17763. while (n <= 279) {
  17764. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17765. n++;
  17766. bl_count[7]++;
  17767. }
  17768. while (n <= 287) {
  17769. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17770. n++;
  17771. bl_count[8]++;
  17772. }
  17773. /* Codes 286 and 287 do not exist, but we must include them in the
  17774. * tree construction to get a canonical Huffman tree (longest code
  17775. * all ones)
  17776. */
  17777. gen_codes(static_ltree, L_CODES+1, bl_count);
  17778. /* The static distance tree is trivial: */
  17779. for (n = 0; n < D_CODES; n++) {
  17780. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17781. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17782. }
  17783. // Now data ready and we can init static trees
  17784. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17785. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17786. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17787. //static_init_done = true;
  17788. }
  17789. /* ===========================================================================
  17790. * Initialize a new block.
  17791. */
  17792. function init_block(s) {
  17793. var n; /* iterates over tree elements */
  17794. /* Initialize the trees. */
  17795. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17796. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17797. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17798. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17799. s.opt_len = s.static_len = 0;
  17800. s.last_lit = s.matches = 0;
  17801. }
  17802. /* ===========================================================================
  17803. * Flush the bit buffer and align the output on a byte boundary
  17804. */
  17805. function bi_windup(s)
  17806. {
  17807. if (s.bi_valid > 8) {
  17808. put_short(s, s.bi_buf);
  17809. } else if (s.bi_valid > 0) {
  17810. //put_byte(s, (Byte)s->bi_buf);
  17811. s.pending_buf[s.pending++] = s.bi_buf;
  17812. }
  17813. s.bi_buf = 0;
  17814. s.bi_valid = 0;
  17815. }
  17816. /* ===========================================================================
  17817. * Copy a stored block, storing first the length and its
  17818. * one's complement if requested.
  17819. */
  17820. function copy_block(s, buf, len, header)
  17821. //DeflateState *s;
  17822. //charf *buf; /* the input data */
  17823. //unsigned len; /* its length */
  17824. //int header; /* true if block header must be written */
  17825. {
  17826. bi_windup(s); /* align on byte boundary */
  17827. if (header) {
  17828. put_short(s, len);
  17829. put_short(s, ~len);
  17830. }
  17831. // while (len--) {
  17832. // put_byte(s, *buf++);
  17833. // }
  17834. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17835. s.pending += len;
  17836. }
  17837. /* ===========================================================================
  17838. * Compares to subtrees, using the tree depth as tie breaker when
  17839. * the subtrees have equal frequency. This minimizes the worst case length.
  17840. */
  17841. function smaller(tree, n, m, depth) {
  17842. var _n2 = n*2;
  17843. var _m2 = m*2;
  17844. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  17845. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  17846. }
  17847. /* ===========================================================================
  17848. * Restore the heap property by moving down the tree starting at node k,
  17849. * exchanging a node with the smallest of its two sons if necessary, stopping
  17850. * when the heap property is re-established (each father smaller than its
  17851. * two sons).
  17852. */
  17853. function pqdownheap(s, tree, k)
  17854. // deflate_state *s;
  17855. // ct_data *tree; /* the tree to restore */
  17856. // int k; /* node to move down */
  17857. {
  17858. var v = s.heap[k];
  17859. var j = k << 1; /* left son of k */
  17860. while (j <= s.heap_len) {
  17861. /* Set j to the smallest of the two sons: */
  17862. if (j < s.heap_len &&
  17863. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  17864. j++;
  17865. }
  17866. /* Exit if v is smaller than both sons */
  17867. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  17868. /* Exchange v with the smallest son */
  17869. s.heap[k] = s.heap[j];
  17870. k = j;
  17871. /* And continue down the tree, setting j to the left son of k */
  17872. j <<= 1;
  17873. }
  17874. s.heap[k] = v;
  17875. }
  17876. // inlined manually
  17877. // var SMALLEST = 1;
  17878. /* ===========================================================================
  17879. * Send the block data compressed using the given Huffman trees
  17880. */
  17881. function compress_block(s, ltree, dtree)
  17882. // deflate_state *s;
  17883. // const ct_data *ltree; /* literal tree */
  17884. // const ct_data *dtree; /* distance tree */
  17885. {
  17886. var dist; /* distance of matched string */
  17887. var lc; /* match length or unmatched char (if dist == 0) */
  17888. var lx = 0; /* running index in l_buf */
  17889. var code; /* the code to send */
  17890. var extra; /* number of extra bits to send */
  17891. if (s.last_lit !== 0) {
  17892. do {
  17893. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  17894. lc = s.pending_buf[s.l_buf + lx];
  17895. lx++;
  17896. if (dist === 0) {
  17897. send_code(s, lc, ltree); /* send a literal byte */
  17898. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  17899. } else {
  17900. /* Here, lc is the match length - MIN_MATCH */
  17901. code = _length_code[lc];
  17902. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  17903. extra = extra_lbits[code];
  17904. if (extra !== 0) {
  17905. lc -= base_length[code];
  17906. send_bits(s, lc, extra); /* send the extra length bits */
  17907. }
  17908. dist--; /* dist is now the match distance - 1 */
  17909. code = d_code(dist);
  17910. //Assert (code < D_CODES, "bad d_code");
  17911. send_code(s, code, dtree); /* send the distance code */
  17912. extra = extra_dbits[code];
  17913. if (extra !== 0) {
  17914. dist -= base_dist[code];
  17915. send_bits(s, dist, extra); /* send the extra distance bits */
  17916. }
  17917. } /* literal or match pair ? */
  17918. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  17919. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  17920. // "pendingBuf overflow");
  17921. } while (lx < s.last_lit);
  17922. }
  17923. send_code(s, END_BLOCK, ltree);
  17924. }
  17925. /* ===========================================================================
  17926. * Construct one Huffman tree and assigns the code bit strings and lengths.
  17927. * Update the total bit length for the current block.
  17928. * IN assertion: the field freq is set for all tree elements.
  17929. * OUT assertions: the fields len and code are set to the optimal bit length
  17930. * and corresponding code. The length opt_len is updated; static_len is
  17931. * also updated if stree is not null. The field max_code is set.
  17932. */
  17933. function build_tree(s, desc)
  17934. // deflate_state *s;
  17935. // tree_desc *desc; /* the tree descriptor */
  17936. {
  17937. var tree = desc.dyn_tree;
  17938. var stree = desc.stat_desc.static_tree;
  17939. var has_stree = desc.stat_desc.has_stree;
  17940. var elems = desc.stat_desc.elems;
  17941. var n, m; /* iterate over heap elements */
  17942. var max_code = -1; /* largest code with non zero frequency */
  17943. var node; /* new node being created */
  17944. /* Construct the initial heap, with least frequent element in
  17945. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17946. * heap[0] is not used.
  17947. */
  17948. s.heap_len = 0;
  17949. s.heap_max = HEAP_SIZE;
  17950. for (n = 0; n < elems; n++) {
  17951. if (tree[n * 2]/*.Freq*/ !== 0) {
  17952. s.heap[++s.heap_len] = max_code = n;
  17953. s.depth[n] = 0;
  17954. } else {
  17955. tree[n*2 + 1]/*.Len*/ = 0;
  17956. }
  17957. }
  17958. /* The pkzip format requires that at least one distance code exists,
  17959. * and that at least one bit should be sent even if there is only one
  17960. * possible code. So to avoid special checks later on we force at least
  17961. * two codes of non zero frequency.
  17962. */
  17963. while (s.heap_len < 2) {
  17964. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  17965. tree[node * 2]/*.Freq*/ = 1;
  17966. s.depth[node] = 0;
  17967. s.opt_len--;
  17968. if (has_stree) {
  17969. s.static_len -= stree[node*2 + 1]/*.Len*/;
  17970. }
  17971. /* node is 0 or 1 so it does not have extra bits */
  17972. }
  17973. desc.max_code = max_code;
  17974. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17975. * establish sub-heaps of increasing lengths:
  17976. */
  17977. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  17978. /* Construct the Huffman tree by repeatedly combining the least two
  17979. * frequent nodes.
  17980. */
  17981. node = elems; /* next internal node of the tree */
  17982. do {
  17983. //pqremove(s, tree, n); /* n = node of least frequency */
  17984. /*** pqremove ***/
  17985. n = s.heap[1/*SMALLEST*/];
  17986. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  17987. pqdownheap(s, tree, 1/*SMALLEST*/);
  17988. /***/
  17989. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  17990. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  17991. s.heap[--s.heap_max] = m;
  17992. /* Create a new node father of n and m */
  17993. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  17994. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  17995. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  17996. /* and insert the new node in the heap */
  17997. s.heap[1/*SMALLEST*/] = node++;
  17998. pqdownheap(s, tree, 1/*SMALLEST*/);
  17999. } while (s.heap_len >= 2);
  18000. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18001. /* At this point, the fields freq and dad are set. We can now
  18002. * generate the bit lengths.
  18003. */
  18004. gen_bitlen(s, desc);
  18005. /* The field len is now set, we can generate the bit codes */
  18006. gen_codes(tree, max_code, s.bl_count);
  18007. }
  18008. /* ===========================================================================
  18009. * Scan a literal or distance tree to determine the frequencies of the codes
  18010. * in the bit length tree.
  18011. */
  18012. function scan_tree(s, tree, max_code)
  18013. // deflate_state *s;
  18014. // ct_data *tree; /* the tree to be scanned */
  18015. // int max_code; /* and its largest code of non zero frequency */
  18016. {
  18017. var n; /* iterates over all tree elements */
  18018. var prevlen = -1; /* last emitted length */
  18019. var curlen; /* length of current code */
  18020. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18021. var count = 0; /* repeat count of the current code */
  18022. var max_count = 7; /* max repeat count */
  18023. var min_count = 4; /* min repeat count */
  18024. if (nextlen === 0) {
  18025. max_count = 138;
  18026. min_count = 3;
  18027. }
  18028. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18029. for (n = 0; n <= max_code; n++) {
  18030. curlen = nextlen;
  18031. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18032. if (++count < max_count && curlen === nextlen) {
  18033. continue;
  18034. } else if (count < min_count) {
  18035. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18036. } else if (curlen !== 0) {
  18037. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18038. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18039. } else if (count <= 10) {
  18040. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18041. } else {
  18042. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18043. }
  18044. count = 0;
  18045. prevlen = curlen;
  18046. if (nextlen === 0) {
  18047. max_count = 138;
  18048. min_count = 3;
  18049. } else if (curlen === nextlen) {
  18050. max_count = 6;
  18051. min_count = 3;
  18052. } else {
  18053. max_count = 7;
  18054. min_count = 4;
  18055. }
  18056. }
  18057. }
  18058. /* ===========================================================================
  18059. * Send a literal or distance tree in compressed form, using the codes in
  18060. * bl_tree.
  18061. */
  18062. function send_tree(s, tree, max_code)
  18063. // deflate_state *s;
  18064. // ct_data *tree; /* the tree to be scanned */
  18065. // int max_code; /* and its largest code of non zero frequency */
  18066. {
  18067. var n; /* iterates over all tree elements */
  18068. var prevlen = -1; /* last emitted length */
  18069. var curlen; /* length of current code */
  18070. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18071. var count = 0; /* repeat count of the current code */
  18072. var max_count = 7; /* max repeat count */
  18073. var min_count = 4; /* min repeat count */
  18074. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18075. if (nextlen === 0) {
  18076. max_count = 138;
  18077. min_count = 3;
  18078. }
  18079. for (n = 0; n <= max_code; n++) {
  18080. curlen = nextlen;
  18081. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18082. if (++count < max_count && curlen === nextlen) {
  18083. continue;
  18084. } else if (count < min_count) {
  18085. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18086. } else if (curlen !== 0) {
  18087. if (curlen !== prevlen) {
  18088. send_code(s, curlen, s.bl_tree);
  18089. count--;
  18090. }
  18091. //Assert(count >= 3 && count <= 6, " 3_6?");
  18092. send_code(s, REP_3_6, s.bl_tree);
  18093. send_bits(s, count-3, 2);
  18094. } else if (count <= 10) {
  18095. send_code(s, REPZ_3_10, s.bl_tree);
  18096. send_bits(s, count-3, 3);
  18097. } else {
  18098. send_code(s, REPZ_11_138, s.bl_tree);
  18099. send_bits(s, count-11, 7);
  18100. }
  18101. count = 0;
  18102. prevlen = curlen;
  18103. if (nextlen === 0) {
  18104. max_count = 138;
  18105. min_count = 3;
  18106. } else if (curlen === nextlen) {
  18107. max_count = 6;
  18108. min_count = 3;
  18109. } else {
  18110. max_count = 7;
  18111. min_count = 4;
  18112. }
  18113. }
  18114. }
  18115. /* ===========================================================================
  18116. * Construct the Huffman tree for the bit lengths and return the index in
  18117. * bl_order of the last bit length code to send.
  18118. */
  18119. function build_bl_tree(s) {
  18120. var max_blindex; /* index of last bit length code of non zero freq */
  18121. /* Determine the bit length frequencies for literal and distance trees */
  18122. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18123. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18124. /* Build the bit length tree: */
  18125. build_tree(s, s.bl_desc);
  18126. /* opt_len now includes the length of the tree representations, except
  18127. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18128. */
  18129. /* Determine the number of bit length codes to send. The pkzip format
  18130. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18131. * 3 but the actual value used is 4.)
  18132. */
  18133. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18134. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18135. break;
  18136. }
  18137. }
  18138. /* Update opt_len to include the bit length tree and counts */
  18139. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18140. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18141. // s->opt_len, s->static_len));
  18142. return max_blindex;
  18143. }
  18144. /* ===========================================================================
  18145. * Send the header for a block using dynamic Huffman trees: the counts, the
  18146. * lengths of the bit length codes, the literal tree and the distance tree.
  18147. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18148. */
  18149. function send_all_trees(s, lcodes, dcodes, blcodes)
  18150. // deflate_state *s;
  18151. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18152. {
  18153. var rank; /* index in bl_order */
  18154. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18155. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18156. // "too many codes");
  18157. //Tracev((stderr, "\nbl counts: "));
  18158. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18159. send_bits(s, dcodes-1, 5);
  18160. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18161. for (rank = 0; rank < blcodes; rank++) {
  18162. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18163. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18164. }
  18165. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18166. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18167. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18168. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18169. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18170. }
  18171. /* ===========================================================================
  18172. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18173. * - TEXT if the two conditions below are satisfied:
  18174. * a) There are no non-portable control characters belonging to the
  18175. * "black list" (0..6, 14..25, 28..31).
  18176. * b) There is at least one printable character belonging to the
  18177. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18178. * - BINARY otherwise.
  18179. * - The following partially-portable control characters form a
  18180. * "gray list" that is ignored in this detection algorithm:
  18181. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18182. * IN assertion: the fields Freq of dyn_ltree are set.
  18183. */
  18184. function detect_data_type(s) {
  18185. /* black_mask is the bit mask of black-listed bytes
  18186. * set bits 0..6, 14..25, and 28..31
  18187. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18188. */
  18189. var black_mask = 0xf3ffc07f;
  18190. var n;
  18191. /* Check for non-textual ("black-listed") bytes. */
  18192. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18193. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18194. return Z_BINARY;
  18195. }
  18196. }
  18197. /* Check for textual ("white-listed") bytes. */
  18198. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18199. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18200. return Z_TEXT;
  18201. }
  18202. for (n = 32; n < LITERALS; n++) {
  18203. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18204. return Z_TEXT;
  18205. }
  18206. }
  18207. /* There are no "black-listed" or "white-listed" bytes:
  18208. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18209. */
  18210. return Z_BINARY;
  18211. }
  18212. var static_init_done = false;
  18213. /* ===========================================================================
  18214. * Initialize the tree data structures for a new zlib stream.
  18215. */
  18216. function _tr_init(s)
  18217. {
  18218. if (!static_init_done) {
  18219. tr_static_init();
  18220. static_init_done = true;
  18221. }
  18222. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18223. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18224. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18225. s.bi_buf = 0;
  18226. s.bi_valid = 0;
  18227. /* Initialize the first block of the first file: */
  18228. init_block(s);
  18229. }
  18230. /* ===========================================================================
  18231. * Send a stored block
  18232. */
  18233. function _tr_stored_block(s, buf, stored_len, last)
  18234. //DeflateState *s;
  18235. //charf *buf; /* input block */
  18236. //ulg stored_len; /* length of input block */
  18237. //int last; /* one if this is the last block for a file */
  18238. {
  18239. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18240. copy_block(s, buf, stored_len, true); /* with header */
  18241. }
  18242. /* ===========================================================================
  18243. * Send one empty static block to give enough lookahead for inflate.
  18244. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18245. */
  18246. function _tr_align(s) {
  18247. send_bits(s, STATIC_TREES<<1, 3);
  18248. send_code(s, END_BLOCK, static_ltree);
  18249. bi_flush(s);
  18250. }
  18251. /* ===========================================================================
  18252. * Determine the best encoding for the current block: dynamic trees, static
  18253. * trees or store, and output the encoded block to the zip file.
  18254. */
  18255. function _tr_flush_block(s, buf, stored_len, last)
  18256. //DeflateState *s;
  18257. //charf *buf; /* input block, or NULL if too old */
  18258. //ulg stored_len; /* length of input block */
  18259. //int last; /* one if this is the last block for a file */
  18260. {
  18261. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18262. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18263. /* Build the Huffman trees unless a stored block is forced */
  18264. if (s.level > 0) {
  18265. /* Check if the file is binary or text */
  18266. if (s.strm.data_type === Z_UNKNOWN) {
  18267. s.strm.data_type = detect_data_type(s);
  18268. }
  18269. /* Construct the literal and distance trees */
  18270. build_tree(s, s.l_desc);
  18271. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18272. // s->static_len));
  18273. build_tree(s, s.d_desc);
  18274. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18275. // s->static_len));
  18276. /* At this point, opt_len and static_len are the total bit lengths of
  18277. * the compressed block data, excluding the tree representations.
  18278. */
  18279. /* Build the bit length tree for the above two trees, and get the index
  18280. * in bl_order of the last bit length code to send.
  18281. */
  18282. max_blindex = build_bl_tree(s);
  18283. /* Determine the best encoding. Compute the block lengths in bytes. */
  18284. opt_lenb = (s.opt_len+3+7) >>> 3;
  18285. static_lenb = (s.static_len+3+7) >>> 3;
  18286. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18287. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18288. // s->last_lit));
  18289. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18290. } else {
  18291. // Assert(buf != (char*)0, "lost buf");
  18292. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18293. }
  18294. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18295. /* 4: two words for the lengths */
  18296. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18297. * Otherwise we can't have processed more than WSIZE input bytes since
  18298. * the last block flush, because compression would have been
  18299. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18300. * transform a block into a stored block.
  18301. */
  18302. _tr_stored_block(s, buf, stored_len, last);
  18303. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18304. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18305. compress_block(s, static_ltree, static_dtree);
  18306. } else {
  18307. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18308. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18309. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18310. }
  18311. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18312. /* The above check is made mod 2^32, for files larger than 512 MB
  18313. * and uLong implemented on 32 bits.
  18314. */
  18315. init_block(s);
  18316. if (last) {
  18317. bi_windup(s);
  18318. }
  18319. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18320. // s->compressed_len-7*last));
  18321. }
  18322. /* ===========================================================================
  18323. * Save the match info and tally the frequency counts. Return true if
  18324. * the current block must be flushed.
  18325. */
  18326. function _tr_tally(s, dist, lc)
  18327. // deflate_state *s;
  18328. // unsigned dist; /* distance of matched string */
  18329. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18330. {
  18331. //var out_length, in_length, dcode;
  18332. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18333. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18334. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18335. s.last_lit++;
  18336. if (dist === 0) {
  18337. /* lc is the unmatched char */
  18338. s.dyn_ltree[lc*2]/*.Freq*/++;
  18339. } else {
  18340. s.matches++;
  18341. /* Here, lc is the match length - MIN_MATCH */
  18342. dist--; /* dist = match distance - 1 */
  18343. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18344. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18345. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18346. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18347. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18348. }
  18349. // (!) This block is disabled in zlib defailts,
  18350. // don't enable it for binary compatibility
  18351. //#ifdef TRUNCATE_BLOCK
  18352. // /* Try to guess if it is profitable to stop the current block here */
  18353. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18354. // /* Compute an upper bound for the compressed length */
  18355. // out_length = s.last_lit*8;
  18356. // in_length = s.strstart - s.block_start;
  18357. //
  18358. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18359. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18360. // }
  18361. // out_length >>>= 3;
  18362. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18363. // // s->last_lit, in_length, out_length,
  18364. // // 100L - out_length*100L/in_length));
  18365. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18366. // return true;
  18367. // }
  18368. // }
  18369. //#endif
  18370. return (s.last_lit === s.lit_bufsize-1);
  18371. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18372. * on 16 bit machines and because stored blocks are restricted to
  18373. * 64K-1 bytes.
  18374. */
  18375. }
  18376. exports._tr_init = _tr_init;
  18377. exports._tr_stored_block = _tr_stored_block;
  18378. exports._tr_flush_block = _tr_flush_block;
  18379. exports._tr_tally = _tr_tally;
  18380. exports._tr_align = _tr_align;
  18381. },{"../utils/common":51}],63:[function(require,module,exports){
  18382. 'use strict';
  18383. function ZStream() {
  18384. /* next input byte */
  18385. this.input = null; // JS specific, because we have no pointers
  18386. this.next_in = 0;
  18387. /* number of bytes available at input */
  18388. this.avail_in = 0;
  18389. /* total number of input bytes read so far */
  18390. this.total_in = 0;
  18391. /* next output byte should be put there */
  18392. this.output = null; // JS specific, because we have no pointers
  18393. this.next_out = 0;
  18394. /* remaining free space at output */
  18395. this.avail_out = 0;
  18396. /* total number of bytes output so far */
  18397. this.total_out = 0;
  18398. /* last error message, NULL if no error */
  18399. this.msg = ''/*Z_NULL*/;
  18400. /* not visible by applications */
  18401. this.state = null;
  18402. /* best guess about the data type: binary or text */
  18403. this.data_type = 2/*Z_UNKNOWN*/;
  18404. /* adler32 value of the uncompressed data */
  18405. this.adler = 0;
  18406. }
  18407. module.exports = ZStream;
  18408. },{}],64:[function(require,module,exports){
  18409. /* Copyright @ 2015 Atlassian Pty Ltd
  18410. *
  18411. * Licensed under the Apache License, Version 2.0 (the "License");
  18412. * you may not use this file except in compliance with the License.
  18413. * You may obtain a copy of the License at
  18414. *
  18415. * http://www.apache.org/licenses/LICENSE-2.0
  18416. *
  18417. * Unless required by applicable law or agreed to in writing, software
  18418. * distributed under the License is distributed on an "AS IS" BASIS,
  18419. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18420. * See the License for the specific language governing permissions and
  18421. * limitations under the License.
  18422. */
  18423. module.exports = function arrayEquals(array) {
  18424. // if the other array is a falsy value, return
  18425. if (!array)
  18426. return false;
  18427. // compare lengths - can save a lot of time
  18428. if (this.length != array.length)
  18429. return false;
  18430. for (var i = 0, l = this.length; i < l; i++) {
  18431. // Check if we have nested arrays
  18432. if (this[i] instanceof Array && array[i] instanceof Array) {
  18433. // recurse into the nested arrays
  18434. if (!arrayEquals.apply(this[i], [array[i]]))
  18435. return false;
  18436. } else if (this[i] != array[i]) {
  18437. // Warning - two different object instances will never be equal:
  18438. // {x:20} != {x:20}
  18439. return false;
  18440. }
  18441. }
  18442. return true;
  18443. };
  18444. },{}],65:[function(require,module,exports){
  18445. /* Copyright @ 2015 Atlassian Pty Ltd
  18446. *
  18447. * Licensed under the Apache License, Version 2.0 (the "License");
  18448. * you may not use this file except in compliance with the License.
  18449. * You may obtain a copy of the License at
  18450. *
  18451. * http://www.apache.org/licenses/LICENSE-2.0
  18452. *
  18453. * Unless required by applicable law or agreed to in writing, software
  18454. * distributed under the License is distributed on an "AS IS" BASIS,
  18455. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18456. * See the License for the specific language governing permissions and
  18457. * limitations under the License.
  18458. */
  18459. exports.Interop = require('./interop');
  18460. },{"./interop":66}],66:[function(require,module,exports){
  18461. /* Copyright @ 2015 Atlassian Pty Ltd
  18462. *
  18463. * Licensed under the Apache License, Version 2.0 (the "License");
  18464. * you may not use this file except in compliance with the License.
  18465. * You may obtain a copy of the License at
  18466. *
  18467. * http://www.apache.org/licenses/LICENSE-2.0
  18468. *
  18469. * Unless required by applicable law or agreed to in writing, software
  18470. * distributed under the License is distributed on an "AS IS" BASIS,
  18471. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18472. * See the License for the specific language governing permissions and
  18473. * limitations under the License.
  18474. */
  18475. /* global RTCSessionDescription */
  18476. /* jshint -W097 */
  18477. "use strict";
  18478. var transform = require('./transform');
  18479. var arrayEquals = require('./array-equals');
  18480. function Interop() {
  18481. /**
  18482. * This map holds the most recent Unified Plan offer/answer SDP that was
  18483. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18484. * the SDP string as values.
  18485. *
  18486. * @type {{}}
  18487. */
  18488. this.cache = {};
  18489. }
  18490. module.exports = Interop;
  18491. /**
  18492. * Returns the index of the first m-line with the given media type and with a
  18493. * direction which allows sending, in the last Unified Plan description with
  18494. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18495. * answer, or if none of its m-lines with the given type allow sending.
  18496. * @param type the media type ("audio" or "video").
  18497. * @returns {*}
  18498. */
  18499. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18500. if (!this.cache.answer) {
  18501. return null;
  18502. }
  18503. var session = transform.parse(this.cache.answer);
  18504. if (session && session.media && Array.isArray(session.media)){
  18505. for (var i = 0; i < session.media.length; i++) {
  18506. if (session.media[i].type == type &&
  18507. (!session.media[i].direction /* default to sendrecv */ ||
  18508. session.media[i].direction === 'sendrecv' ||
  18509. session.media[i].direction === 'sendonly')){
  18510. return i;
  18511. }
  18512. }
  18513. }
  18514. return null;
  18515. };
  18516. /**
  18517. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18518. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18519. * application.
  18520. *
  18521. * @param desc
  18522. * @returns {*}
  18523. */
  18524. Interop.prototype.toPlanB = function(desc) {
  18525. var self = this;
  18526. //#region Preliminary input validation.
  18527. if (typeof desc !== 'object' || desc === null ||
  18528. typeof desc.sdp !== 'string') {
  18529. console.warn('An empty description was passed as an argument.');
  18530. return desc;
  18531. }
  18532. // Objectify the SDP for easier manipulation.
  18533. var session = transform.parse(desc.sdp);
  18534. // If the SDP contains no media, there's nothing to transform.
  18535. if (typeof session.media === 'undefined' ||
  18536. !Array.isArray(session.media) || session.media.length === 0) {
  18537. console.warn('The description has no media.');
  18538. return desc;
  18539. }
  18540. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18541. // SDP has a video, an audio and a data "channel" at most.
  18542. if (session.media.length <= 3 && session.media.every(function(m) {
  18543. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18544. })) {
  18545. console.warn('This description does not look like Unified Plan.');
  18546. return desc;
  18547. }
  18548. //#endregion
  18549. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18550. var sdp = desc.sdp;
  18551. var rewrite = false;
  18552. for (var i = 0; i < session.media.length; i++) {
  18553. var uLine = session.media[i];
  18554. uLine.rtp.forEach(function(rtp) {
  18555. if (rtp.codec === 'NULL')
  18556. {
  18557. rewrite = true;
  18558. var offer = transform.parse(self.cache['offer']);
  18559. rtp.codec = offer.media[i].rtp[0].codec;
  18560. }
  18561. });
  18562. };
  18563. if (rewrite) {
  18564. sdp = transform.write(session);
  18565. }
  18566. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18567. // -> Unified Plan transformation.
  18568. this.cache[desc.type] = sdp;
  18569. //#region Convert from Unified Plan to Plan B.
  18570. // We rebuild the session.media array.
  18571. var media = session.media;
  18572. session.media = [];
  18573. // Associative array that maps channel types to channel objects for fast
  18574. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18575. // obj.
  18576. var type2bl = {};
  18577. // Used to build the group:BUNDLE value after the channels construction
  18578. // loop.
  18579. var types = [];
  18580. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18581. media.forEach(function(uLine) {
  18582. // rtcp-mux is required in the Plan B SDP.
  18583. if ((typeof uLine.rtcpMux !== 'string' ||
  18584. uLine.rtcpMux !== 'rtcp-mux') &&
  18585. uLine.direction !== 'inactive') {
  18586. throw new Error('Cannot convert to Plan B because m-lines ' +
  18587. 'without the rtcp-mux attribute were found.');
  18588. }
  18589. if (uLine.type === 'application') {
  18590. session.media.push(uLine);
  18591. types.push(uLine.mid);
  18592. return;
  18593. }
  18594. // If we don't have a channel for this uLine.type, then use this
  18595. // uLine as the channel basis.
  18596. if (typeof type2bl[uLine.type] === 'undefined') {
  18597. type2bl[uLine.type] = uLine;
  18598. }
  18599. // Add sources to the channel and handle a=msid.
  18600. if (typeof uLine.sources === 'object') {
  18601. Object.keys(uLine.sources).forEach(function(ssrc) {
  18602. if (typeof type2bl[uLine.type].sources !== 'object')
  18603. type2bl[uLine.type].sources = {};
  18604. // Assign the sources to the channel.
  18605. type2bl[uLine.type].sources[ssrc] =
  18606. uLine.sources[ssrc];
  18607. if (typeof uLine.msid !== 'undefined') {
  18608. // In Plan B the msid is an SSRC attribute. Also, we don't
  18609. // care about the obsolete label and mslabel attributes.
  18610. //
  18611. // Note that it is not guaranteed that the uLine will
  18612. // have an msid. recvonly channels in particular don't have
  18613. // one.
  18614. type2bl[uLine.type].sources[ssrc].msid =
  18615. uLine.msid;
  18616. }
  18617. // NOTE ssrcs in ssrc groups will share msids, as
  18618. // draft-uberti-rtcweb-plan-00 mandates.
  18619. });
  18620. }
  18621. // Add ssrc groups to the channel.
  18622. if (typeof uLine.ssrcGroups !== 'undefined' &&
  18623. Array.isArray(uLine.ssrcGroups)) {
  18624. // Create the ssrcGroups array, if it's not defined.
  18625. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  18626. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  18627. type2bl[uLine.type].ssrcGroups = [];
  18628. }
  18629. type2bl[uLine.type].ssrcGroups =
  18630. type2bl[uLine.type].ssrcGroups.concat(
  18631. uLine.ssrcGroups);
  18632. }
  18633. if (type2bl[uLine.type] === uLine) {
  18634. // Copy ICE related stuff from the principal media line.
  18635. uLine.candidates = media[0].candidates;
  18636. uLine.iceUfrag = media[0].iceUfrag;
  18637. uLine.icePwd = media[0].icePwd;
  18638. uLine.fingerprint = media[0].fingerprint;
  18639. // Plan B mids are in ['audio', 'video', 'data']
  18640. uLine.mid = uLine.type;
  18641. // Plan B doesn't support/need the bundle-only attribute.
  18642. delete uLine.bundleOnly;
  18643. // In Plan B the msid is an SSRC attribute.
  18644. delete uLine.msid;
  18645. // Used to build the group:BUNDLE value after this loop.
  18646. types.push(uLine.type);
  18647. // Add the channel to the new media array.
  18648. session.media.push(uLine);
  18649. }
  18650. });
  18651. // We regenerate the BUNDLE group with the new mids.
  18652. session.groups.some(function(group) {
  18653. if (group.type === 'BUNDLE') {
  18654. group.mids = types.join(' ');
  18655. return true;
  18656. }
  18657. });
  18658. // msid semantic
  18659. session.msidSemantic = {
  18660. semantic: 'WMS',
  18661. token: '*'
  18662. };
  18663. var resStr = transform.write(session);
  18664. return new RTCSessionDescription({
  18665. type: desc.type,
  18666. sdp: resStr
  18667. });
  18668. //#endregion
  18669. };
  18670. /**
  18671. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18672. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18673. * to FF.
  18674. *
  18675. * @param desc
  18676. * @returns {*}
  18677. */
  18678. Interop.prototype.toUnifiedPlan = function(desc) {
  18679. var self = this;
  18680. //#region Preliminary input validation.
  18681. if (typeof desc !== 'object' || desc === null ||
  18682. typeof desc.sdp !== 'string') {
  18683. console.warn('An empty description was passed as an argument.');
  18684. return desc;
  18685. }
  18686. var session = transform.parse(desc.sdp);
  18687. // If the SDP contains no media, there's nothing to transform.
  18688. if (typeof session.media === 'undefined' ||
  18689. !Array.isArray(session.media) || session.media.length === 0) {
  18690. console.warn('The description has no media.');
  18691. return desc;
  18692. }
  18693. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18694. // a video, an audio and a data "channel" at most.
  18695. if (session.media.length > 3 || !session.media.every(function(m) {
  18696. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18697. })) {
  18698. console.warn('This description does not look like Plan B.');
  18699. return desc;
  18700. }
  18701. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18702. var mids = [];
  18703. session.media.forEach(function(m) {
  18704. mids.push(m.mid);
  18705. });
  18706. var hasBundle = false;
  18707. if (typeof session.groups !== 'undefined' &&
  18708. Array.isArray(session.groups)) {
  18709. hasBundle = session.groups.every(function(g) {
  18710. return g.type !== 'BUNDLE' ||
  18711. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18712. });
  18713. }
  18714. if (!hasBundle) {
  18715. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18716. " are not bundled were found.");
  18717. }
  18718. //#endregion
  18719. //#region Convert from Plan B to Unified Plan.
  18720. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18721. // rebuild an equivalent Unified Plan offer/answer.
  18722. //
  18723. // For example, if this is a local answer (in Unified Plan style) that we
  18724. // convert to Plan B prior to handing it over to the application (the
  18725. // PeerConnection wrapper called us, for instance, after a successful
  18726. // createAnswer), we want to remember the m-line at which we've seen the
  18727. // (local) SSRC. That's because when the application wants to do call the
  18728. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18729. // Unified Plan), we need to know to which m-line to assign the (local)
  18730. // SSRC. We also need to know all the other m-lines that the original
  18731. // answer had and include them in the transformed answer as well.
  18732. //
  18733. // Another example is if this is a remote offer that we convert to Plan B
  18734. // prior to giving it to the application, we want to remember the mid at
  18735. // which we've seen the (remote) SSRC.
  18736. //
  18737. // In the iteration that follows, we use the cached Unified Plan (if it
  18738. // exists) to assign mids to ssrcs.
  18739. var cached;
  18740. if (typeof this.cache[desc.type] !== 'undefined') {
  18741. cached = transform.parse(this.cache[desc.type]);
  18742. }
  18743. var recvonlySsrcs = {
  18744. audio: {},
  18745. video: {}
  18746. };
  18747. // A helper map that sends mids to m-line objects. We use it later to
  18748. // rebuild the Unified Plan style session.media array.
  18749. var mid2ul = {};
  18750. session.media.forEach(function(bLine) {
  18751. if ((typeof bLine.rtcpMux !== 'string' ||
  18752. bLine.rtcpMux !== 'rtcp-mux') &&
  18753. bLine.direction !== 'inactive') {
  18754. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18755. "without the rtcp-mux attribute were found.");
  18756. }
  18757. if (bLine.type === 'application') {
  18758. mid2ul[bLine.mid] = bLine;
  18759. return;
  18760. }
  18761. // With rtcp-mux and bundle all the channels should have the same ICE
  18762. // stuff.
  18763. var sources = bLine.sources;
  18764. var ssrcGroups = bLine.ssrcGroups;
  18765. var candidates = bLine.candidates;
  18766. var iceUfrag = bLine.iceUfrag;
  18767. var icePwd = bLine.icePwd;
  18768. var fingerprint = bLine.fingerprint;
  18769. var port = bLine.port;
  18770. // We'll use the "bLine" object as a prototype for each new "mLine"
  18771. // that we create, but first we need to clean it up a bit.
  18772. delete bLine.sources;
  18773. delete bLine.ssrcGroups;
  18774. delete bLine.candidates;
  18775. delete bLine.iceUfrag;
  18776. delete bLine.icePwd;
  18777. delete bLine.fingerprint;
  18778. delete bLine.port;
  18779. delete bLine.mid;
  18780. // inverted ssrc group map
  18781. var ssrc2group = {};
  18782. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18783. ssrcGroups.forEach(function (ssrcGroup) {
  18784. // TODO(gp) find out how to receive simulcast with FF. For the
  18785. // time being, hide it.
  18786. if (ssrcGroup.semantics === 'SIM') {
  18787. return;
  18788. }
  18789. // XXX This might brake if an SSRC is in more than one group
  18790. // for some reason.
  18791. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18792. Array.isArray(ssrcGroup.ssrcs)) {
  18793. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18794. if (typeof ssrc2group[ssrc] === 'undefined') {
  18795. ssrc2group[ssrc] = [];
  18796. }
  18797. ssrc2group[ssrc].push(ssrcGroup);
  18798. });
  18799. }
  18800. });
  18801. }
  18802. // ssrc to m-line index.
  18803. var ssrc2ml = {};
  18804. if (typeof sources === 'object') {
  18805. // Explode the Plan B channel sources with one m-line per source.
  18806. Object.keys(sources).forEach(function(ssrc) {
  18807. // The (unified) m-line for this SSRC. We either create it from
  18808. // scratch or, if it's a grouped SSRC, we re-use a related
  18809. // mline. In other words, if the source is grouped with another
  18810. // source, put the two together in the same m-line.
  18811. var uLine;
  18812. // We assume here that we are the answerer in the O/A, so any
  18813. // offers which we translate come from the remote side, while
  18814. // answers are local. So the check below is to make that we
  18815. // handle receive-only SSRCs in a special way only if they come
  18816. // from the remote side.
  18817. if (desc.type==='offer') {
  18818. // We want to detect SSRCs which are used by a remote peer
  18819. // in an m-line with direction=recvonly (i.e. they are
  18820. // being used for RTCP only).
  18821. // This information would have gotten lost if the remote
  18822. // peer used Unified Plan and their local description was
  18823. // translated to Plan B. So we use the lack of an MSID
  18824. // attribute to deduce a "receive only" SSRC.
  18825. if (!sources[ssrc].msid) {
  18826. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  18827. // Receive-only SSRCs must not create new m-lines. We
  18828. // will assign them to an existing m-line later.
  18829. return;
  18830. }
  18831. }
  18832. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  18833. Array.isArray(ssrc2group[ssrc])) {
  18834. ssrc2group[ssrc].some(function (ssrcGroup) {
  18835. // ssrcGroup.ssrcs *is* an Array, no need to check
  18836. // again here.
  18837. return ssrcGroup.ssrcs.some(function (related) {
  18838. if (typeof ssrc2ml[related] === 'object') {
  18839. uLine = ssrc2ml[related];
  18840. return true;
  18841. }
  18842. });
  18843. });
  18844. }
  18845. if (typeof uLine === 'object') {
  18846. // the m-line already exists. Just add the source.
  18847. uLine.sources[ssrc] = sources[ssrc];
  18848. delete sources[ssrc].msid;
  18849. } else {
  18850. // Use the "bLine" as a prototype for the "uLine".
  18851. uLine = Object.create(bLine);
  18852. ssrc2ml[ssrc] = uLine;
  18853. if (typeof sources[ssrc].msid !== 'undefined') {
  18854. // Assign the msid of the source to the m-line. Note
  18855. // that it is not guaranteed that the source will have
  18856. // msid. In particular "recvonly" sources don't have an
  18857. // msid. Note that "recvonly" is a term only defined
  18858. // for m-lines.
  18859. uLine.msid = sources[ssrc].msid;
  18860. uLine.direction = 'sendrecv';
  18861. delete sources[ssrc].msid;
  18862. }
  18863. // We assign one SSRC per media line.
  18864. uLine.sources = {};
  18865. uLine.sources[ssrc] = sources[ssrc];
  18866. uLine.ssrcGroups = ssrc2group[ssrc];
  18867. // Use the cached Unified Plan SDP (if it exists) to assign
  18868. // SSRCs to mids.
  18869. if (typeof cached !== 'undefined' &&
  18870. typeof cached.media !== 'undefined' &&
  18871. Array.isArray(cached.media)) {
  18872. cached.media.forEach(function (m) {
  18873. if (typeof m.sources === 'object') {
  18874. Object.keys(m.sources).forEach(function (s) {
  18875. if (s === ssrc) {
  18876. uLine.mid = m.mid;
  18877. }
  18878. });
  18879. }
  18880. });
  18881. }
  18882. if (typeof uLine.mid === 'undefined') {
  18883. // If this is an SSRC that we see for the first time
  18884. // assign it a new mid. This is typically the case when
  18885. // this method is called to transform a remote
  18886. // description for the first time or when there is a
  18887. // new SSRC in the remote description because a new
  18888. // peer has joined the conference. Local SSRCs should
  18889. // have already been added to the map in the toPlanB
  18890. // method.
  18891. //
  18892. // Because FF generates answers in Unified Plan style,
  18893. // we MUST already have a cached answer with all the
  18894. // local SSRCs mapped to some m-line/mid.
  18895. if (desc.type === 'answer') {
  18896. throw new Error("An unmapped SSRC was found.");
  18897. }
  18898. uLine.mid = [bLine.type, '-', ssrc].join('');
  18899. }
  18900. // Include the candidates in the 1st media line.
  18901. uLine.candidates = candidates;
  18902. uLine.iceUfrag = iceUfrag;
  18903. uLine.icePwd = icePwd;
  18904. uLine.fingerprint = fingerprint;
  18905. uLine.port = port;
  18906. mid2ul[uLine.mid] = uLine;
  18907. }
  18908. });
  18909. }
  18910. });
  18911. // Rebuild the media array in the right order and add the missing mLines
  18912. // (missing from the Plan B SDP).
  18913. session.media = [];
  18914. mids = []; // reuse
  18915. if (desc.type === 'answer') {
  18916. // The media lines in the answer must match the media lines in the
  18917. // offer. The order is important too. Here we assume that Firefox is
  18918. // the answerer, so we merely have to use the reconstructed (unified)
  18919. // answer to update the cached (unified) answer accordingly.
  18920. //
  18921. // In the general case, one would have to use the cached (unified)
  18922. // offer to find the m-lines that are missing from the reconstructed
  18923. // answer, potentially grabbing them from the cached (unified) answer.
  18924. // One has to be careful with this approach because inactive m-lines do
  18925. // not always have an mid, making it tricky (impossible?) to find where
  18926. // exactly and which m-lines are missing from the reconstructed answer.
  18927. for (var i = 0; i < cached.media.length; i++) {
  18928. var uLine = cached.media[i];
  18929. if (typeof mid2ul[uLine.mid] === 'undefined') {
  18930. // The mid isn't in the reconstructed (unified) answer.
  18931. // This is either a (unified) m-line containing a remote
  18932. // track only, or a (unified) m-line containing a remote
  18933. // track and a local track that has been removed.
  18934. // In either case, it MUST exist in the cached
  18935. // (unified) answer.
  18936. //
  18937. // In case this is a removed local track, clean-up
  18938. // the (unified) m-line and make sure it's 'recvonly' or
  18939. // 'inactive'.
  18940. delete uLine.msid;
  18941. delete uLine.sources;
  18942. delete uLine.ssrcGroups;
  18943. if (!uLine.direction
  18944. || uLine.direction === 'sendrecv')
  18945. uLine.direction = 'recvonly';
  18946. else if (uLine.direction === 'sendonly')
  18947. uLine.direction = 'inactive';
  18948. } else {
  18949. // This is an (unified) m-line/channel that contains a local
  18950. // track (sendrecv or sendonly channel) or it's a unified
  18951. // recvonly m-line/channel. In either case, since we're
  18952. // going from PlanB -> Unified Plan this m-line MUST
  18953. // exist in the cached answer.
  18954. }
  18955. session.media.push(uLine);
  18956. if (typeof uLine.mid === 'string') {
  18957. // inactive lines don't/may not have an mid.
  18958. mids.push(uLine.mid);
  18959. }
  18960. }
  18961. } else {
  18962. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  18963. // under any circumstances. If we are no longer interested in sending a
  18964. // track, we just remove the msid and ssrc attributes and set it to
  18965. // either a=recvonly (as the reofferer, we must use recvonly if the
  18966. // other side was previously sending on the m-section, but we can also
  18967. // leave the possibility open if it wasn't previously in use), or
  18968. // a=inactive.
  18969. if (typeof cached !== 'undefined' &&
  18970. typeof cached.media !== 'undefined' &&
  18971. Array.isArray(cached.media)) {
  18972. cached.media.forEach(function(uLine) {
  18973. mids.push(uLine.mid);
  18974. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  18975. session.media.push(mid2ul[uLine.mid]);
  18976. } else {
  18977. delete uLine.msid;
  18978. delete uLine.sources;
  18979. delete uLine.ssrcGroups;
  18980. if (!uLine.direction
  18981. || uLine.direction === 'sendrecv')
  18982. uLine.direction = 'recvonly';
  18983. if (!uLine.direction
  18984. || uLine.direction === 'sendonly')
  18985. uLine.direction = 'inactive';
  18986. session.media.push(uLine);
  18987. }
  18988. });
  18989. }
  18990. // Add all the remaining (new) m-lines of the transformed SDP.
  18991. Object.keys(mid2ul).forEach(function(mid) {
  18992. if (mids.indexOf(mid) === -1) {
  18993. mids.push(mid);
  18994. if (mid2ul[mid].direction === 'recvonly') {
  18995. // This is a remote recvonly channel. Add its SSRC to the
  18996. // appropriate sendrecv or sendonly channel.
  18997. // TODO(gp) what if we don't have sendrecv/sendonly
  18998. // channel?
  18999. session.media.some(function (uLine) {
  19000. if ((uLine.direction === 'sendrecv' ||
  19001. uLine.direction === 'sendonly') &&
  19002. uLine.type === mid2ul[mid].type) {
  19003. // mid2ul[mid] shouldn't have any ssrc-groups
  19004. Object.keys(mid2ul[mid].sources).forEach(
  19005. function (ssrc) {
  19006. uLine.sources[ssrc] =
  19007. mid2ul[mid].sources[ssrc];
  19008. });
  19009. return true;
  19010. }
  19011. });
  19012. } else {
  19013. session.media.push(mid2ul[mid]);
  19014. }
  19015. }
  19016. });
  19017. }
  19018. // After we have constructed the Plan Unified m-lines we can figure out
  19019. // where (in which m-line) to place the 'recvonly SSRCs'.
  19020. // Note: we assume here that we are the answerer in the O/A, so any offers
  19021. // which we translate come from the remote side, while answers are local
  19022. // (and so our last local description is cached as an 'answer').
  19023. ["audio", "video"].forEach(function (type) {
  19024. if (!session || !session.media || !Array.isArray(session.media))
  19025. return;
  19026. var idx = null;
  19027. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19028. idx = self.getFirstSendingIndexFromAnswer(type);
  19029. if (idx === null){
  19030. // If this is the first offer we receive, we don't have a
  19031. // cached answer. Assume that we will be sending media using
  19032. // the first m-line for each media type.
  19033. for (var i = 0; i < session.media.length; i++) {
  19034. if (session.media[i].type === type) {
  19035. idx = i;
  19036. break;
  19037. }
  19038. }
  19039. }
  19040. }
  19041. if (idx && session.media.length > idx) {
  19042. var mLine = session.media[idx];
  19043. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19044. if (mLine.sources && mLine.sources[ssrc]) {
  19045. console.warn("Replacing an existing SSRC.");
  19046. }
  19047. if (!mLine.sources) {
  19048. mLine.sources = {};
  19049. }
  19050. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19051. });
  19052. }
  19053. });
  19054. // We regenerate the BUNDLE group (since we regenerated the mids)
  19055. session.groups.some(function(group) {
  19056. if (group.type === 'BUNDLE') {
  19057. group.mids = mids.join(' ');
  19058. return true;
  19059. }
  19060. });
  19061. // msid semantic
  19062. session.msidSemantic = {
  19063. semantic: 'WMS',
  19064. token: '*'
  19065. };
  19066. var resStr = transform.write(session);
  19067. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19068. // function.
  19069. this.cache[desc.type] = resStr;
  19070. return new RTCSessionDescription({
  19071. type: desc.type,
  19072. sdp: resStr
  19073. });
  19074. //#endregion
  19075. };
  19076. },{"./array-equals":64,"./transform":67}],67:[function(require,module,exports){
  19077. /* Copyright @ 2015 Atlassian Pty Ltd
  19078. *
  19079. * Licensed under the Apache License, Version 2.0 (the "License");
  19080. * you may not use this file except in compliance with the License.
  19081. * You may obtain a copy of the License at
  19082. *
  19083. * http://www.apache.org/licenses/LICENSE-2.0
  19084. *
  19085. * Unless required by applicable law or agreed to in writing, software
  19086. * distributed under the License is distributed on an "AS IS" BASIS,
  19087. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19088. * See the License for the specific language governing permissions and
  19089. * limitations under the License.
  19090. */
  19091. var transform = require('sdp-transform');
  19092. exports.write = function(session, opts) {
  19093. if (typeof session !== 'undefined' &&
  19094. typeof session.media !== 'undefined' &&
  19095. Array.isArray(session.media)) {
  19096. session.media.forEach(function (mLine) {
  19097. // expand sources to ssrcs
  19098. if (typeof mLine.sources !== 'undefined' &&
  19099. Object.keys(mLine.sources).length !== 0) {
  19100. mLine.ssrcs = [];
  19101. Object.keys(mLine.sources).forEach(function (ssrc) {
  19102. var source = mLine.sources[ssrc];
  19103. Object.keys(source).forEach(function (attribute) {
  19104. mLine.ssrcs.push({
  19105. id: ssrc,
  19106. attribute: attribute,
  19107. value: source[attribute]
  19108. });
  19109. });
  19110. });
  19111. delete mLine.sources;
  19112. }
  19113. // join ssrcs in ssrc groups
  19114. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19115. Array.isArray(mLine.ssrcGroups)) {
  19116. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19117. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19118. Array.isArray(ssrcGroup.ssrcs)) {
  19119. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19120. }
  19121. });
  19122. }
  19123. });
  19124. }
  19125. // join group mids
  19126. if (typeof session !== 'undefined' &&
  19127. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19128. session.groups.forEach(function (g) {
  19129. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19130. g.mids = g.mids.join(' ');
  19131. }
  19132. });
  19133. }
  19134. return transform.write(session, opts);
  19135. };
  19136. exports.parse = function(sdp) {
  19137. var session = transform.parse(sdp);
  19138. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19139. Array.isArray(session.media)) {
  19140. session.media.forEach(function (mLine) {
  19141. // group sources attributes by ssrc
  19142. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19143. mLine.sources = {};
  19144. mLine.ssrcs.forEach(function (ssrc) {
  19145. if (!mLine.sources[ssrc.id])
  19146. mLine.sources[ssrc.id] = {};
  19147. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19148. });
  19149. delete mLine.ssrcs;
  19150. }
  19151. // split ssrcs in ssrc groups
  19152. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19153. Array.isArray(mLine.ssrcGroups)) {
  19154. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19155. if (typeof ssrcGroup.ssrcs === 'string') {
  19156. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19157. }
  19158. });
  19159. }
  19160. });
  19161. }
  19162. // split group mids
  19163. if (typeof session !== 'undefined' &&
  19164. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19165. session.groups.forEach(function (g) {
  19166. if (typeof g.mids === 'string') {
  19167. g.mids = g.mids.split(' ');
  19168. }
  19169. });
  19170. }
  19171. return session;
  19172. };
  19173. },{"sdp-transform":75}],68:[function(require,module,exports){
  19174. /* Copyright @ 2015 Atlassian Pty Ltd
  19175. *
  19176. * Licensed under the Apache License, Version 2.0 (the "License");
  19177. * you may not use this file except in compliance with the License.
  19178. * You may obtain a copy of the License at
  19179. *
  19180. * http://www.apache.org/licenses/LICENSE-2.0
  19181. *
  19182. * Unless required by applicable law or agreed to in writing, software
  19183. * distributed under the License is distributed on an "AS IS" BASIS,
  19184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19185. * See the License for the specific language governing permissions and
  19186. * limitations under the License.
  19187. */
  19188. var transform = require('sdp-transform');
  19189. var transformUtils = require('./transform-utils');
  19190. var parseSsrcs = transformUtils.parseSsrcs;
  19191. var writeSsrcs = transformUtils.writeSsrcs;
  19192. //region Constants
  19193. var DEFAULT_NUM_OF_LAYERS = 3;
  19194. //endregion
  19195. //region Ctor
  19196. function Simulcast(options) {
  19197. this.options = options ? options : {};
  19198. if (!this.options.numOfLayers) {
  19199. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  19200. }
  19201. this.layers = [];
  19202. }
  19203. //endregion
  19204. //region Stateless private utility functions
  19205. /**
  19206. * Returns a random integer between min (included) and max (excluded)
  19207. * Using Math.round() gives a non-uniform distribution!
  19208. * @returns {number}
  19209. */
  19210. function generateSSRC() {
  19211. var min = 0, max = 0xffffffff;
  19212. return Math.floor(Math.random() * (max - min)) + min;
  19213. };
  19214. function processVideo(session, action) {
  19215. if (session == null || !Array.isArray(session.media)) {
  19216. return;
  19217. }
  19218. session.media.forEach(function (mLine) {
  19219. if (mLine.type === 'video') {
  19220. action(mLine);
  19221. }
  19222. });
  19223. }
  19224. function validateDescription(desc)
  19225. {
  19226. return desc && desc != null
  19227. && desc.type && desc.type != ''
  19228. && desc.sdp && desc.sdp != '';
  19229. }
  19230. function explodeRemoteSimulcast(mLine) {
  19231. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19232. return;
  19233. }
  19234. var sources = parseSsrcs(mLine);
  19235. var order = [];
  19236. // Find the SIM group and explode its sources.
  19237. var j = mLine.ssrcGroups.length;
  19238. while (j--) {
  19239. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  19240. continue;
  19241. }
  19242. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  19243. for (var i = 0; i < simulcastSsrcs.length; i++) {
  19244. var ssrc = simulcastSsrcs[i];
  19245. order.push(ssrc);
  19246. var parts = sources[ssrc].msid.split(' ');
  19247. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  19248. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  19249. // Remove all the groups that this SSRC participates in.
  19250. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19251. if (relatedGroup.semantics === 'SIM') {
  19252. return;
  19253. }
  19254. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19255. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19256. return;
  19257. }
  19258. // Nuke all the related SSRCs.
  19259. relatedSsrcs.forEach(function (relatedSSRC) {
  19260. sources[relatedSSRC].msid = sources[ssrc].msid;
  19261. sources[relatedSSRC].cname = sources[ssrc].cname;
  19262. if (relatedSSRC !== ssrc) {
  19263. order.push(relatedSSRC);
  19264. }
  19265. });
  19266. // Schedule the related group for nuking.
  19267. })
  19268. }
  19269. mLine.ssrcs = writeSsrcs(sources, order);
  19270. mLine.ssrcGroups.splice(j, 1);
  19271. };
  19272. }
  19273. function implodeRemoteSimulcast(mLine) {
  19274. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19275. console.debug('Halt: There are no SSRC groups in the remote ' +
  19276. 'description.');
  19277. return;
  19278. }
  19279. var sources = parseSsrcs(mLine);
  19280. // Find the SIM group and nuke it.
  19281. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  19282. if (simulcastGroup.semantics !== 'SIM') {
  19283. return;
  19284. }
  19285. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  19286. // Schedule the SIM group for nuking.
  19287. simulcastGroup.nuke = true;
  19288. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  19289. // Nuke all the higher layer SSRCs.
  19290. for (var i = 1; i < simulcastSsrcs.length; i++) {
  19291. var ssrc = simulcastSsrcs[i];
  19292. delete sources[ssrc];
  19293. // Remove all the groups that this SSRC participates in.
  19294. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19295. if (relatedGroup.semantics === 'SIM') {
  19296. return;
  19297. }
  19298. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19299. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19300. return;
  19301. }
  19302. // Nuke all the related SSRCs.
  19303. relatedSsrcs.forEach(function (relatedSSRC) {
  19304. delete sources[relatedSSRC];
  19305. });
  19306. // Schedule the related group for nuking.
  19307. relatedGroup.nuke = true;
  19308. })
  19309. }
  19310. return;
  19311. });
  19312. mLine.ssrcs = writeSsrcs(sources);
  19313. // Nuke all the scheduled groups.
  19314. var i = mLine.ssrcGroups.length;
  19315. while (i--) {
  19316. if (mLine.ssrcGroups[i].nuke) {
  19317. mLine.ssrcGroups.splice(i, 1);
  19318. }
  19319. }
  19320. }
  19321. function removeGoogConference(mLine) {
  19322. if (!mLine || !Array.isArray(mLine.invalid)) {
  19323. return;
  19324. }
  19325. var i = mLine.invalid.length;
  19326. while (i--) {
  19327. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  19328. mLine.invalid.splice(i, 1);
  19329. }
  19330. }
  19331. }
  19332. function assertGoogConference(mLine) {
  19333. if (!mLine) {
  19334. return;
  19335. }
  19336. if (!Array.isArray(mLine.invalid)) {
  19337. mLine.invalid = [];
  19338. }
  19339. if (!mLine.invalid.some(
  19340. function (i) { return i.value === 'x-google-flag:conference' })) {
  19341. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19342. }
  19343. }
  19344. //endregion
  19345. //region "Private" functions
  19346. /**
  19347. *
  19348. * @param mLine
  19349. * @private
  19350. */
  19351. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19352. if (!mLine || mLine.type !== 'video') {
  19353. return;
  19354. }
  19355. var sources = parseSsrcs(mLine);
  19356. if (Object.keys(sources).length === 0) {
  19357. // no sources, disable simulcast.
  19358. if (this.layers.length !== 0) {
  19359. this.layers = [];
  19360. }
  19361. return;
  19362. }
  19363. // find the base layer (we'll reuse its msid and cname).
  19364. var baseLayerSSRC = Object.keys(sources)[0];
  19365. var baseLayer = sources[baseLayerSSRC];
  19366. // todo(gp) handle screen sharing.
  19367. // check if base CNAME has changed and reinitialise layers.
  19368. if (this.layers.length > 0
  19369. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  19370. this.layers = [];
  19371. }
  19372. // (re)initialise layers
  19373. if (this.layers.length < 1) {
  19374. // first push the base layer.
  19375. this.layers.push({
  19376. ssrc: baseLayerSSRC,
  19377. msid: baseLayer.msid,
  19378. cname: baseLayer.cname
  19379. });
  19380. var rtx = false; // RFC 4588
  19381. if (Array.isArray(mLine.rtp)) {
  19382. rtx = mLine.rtp.some(
  19383. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  19384. }
  19385. if (rtx) {
  19386. this.layers[0].rtx = generateSSRC();
  19387. }
  19388. // now push additional layers.
  19389. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  19390. var layer = { ssrc: generateSSRC() };
  19391. if (rtx) {
  19392. layer.rtx = generateSSRC();
  19393. }
  19394. this.layers.push(layer);
  19395. }
  19396. }
  19397. };
  19398. /**
  19399. *
  19400. * @param mLine
  19401. * @private
  19402. */
  19403. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  19404. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  19405. var sources = {};
  19406. var msid = this.layers[0].msid;
  19407. var cname = this.layers[0].cname;
  19408. var simulcastSsrcs = [];
  19409. var ssrcGroups = [];
  19410. for (var i = 0; i < this.layers.length; i++) {
  19411. var layer = this.layers[i];
  19412. sources[layer.ssrc] = { msid: msid, cname: cname };
  19413. simulcastSsrcs.push(layer.ssrc);
  19414. if (layer.rtx) {
  19415. sources[layer.rtx] = {
  19416. msid: msid,
  19417. cname: cname
  19418. }
  19419. ssrcGroups.push({
  19420. semantics: 'FID',
  19421. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  19422. });
  19423. }
  19424. }
  19425. ssrcGroups.push({
  19426. semantics: 'SIM',
  19427. ssrcs: simulcastSsrcs.join(' ')
  19428. });
  19429. mLine.ssrcGroups = ssrcGroups;
  19430. mLine.ssrcs = writeSsrcs(sources);
  19431. }
  19432. }
  19433. //endregion
  19434. //region "Public" functions
  19435. Simulcast.prototype.isSupported = function () {
  19436. return window.chrome;
  19437. // TODO this needs improvements. For example I doubt that Chrome in Android
  19438. // has simulcast support. Also, only recent versions of Chromium have native
  19439. // simulcast support.
  19440. }
  19441. /**
  19442. *
  19443. * @param desc
  19444. * @returns {RTCSessionDescription}
  19445. */
  19446. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  19447. if (!validateDescription(desc)) {
  19448. return desc;
  19449. }
  19450. var session = transform.parse(desc.sdp);
  19451. var self = this;
  19452. processVideo(session, function (mLine) {
  19453. // Handle simulcast reception.
  19454. if (self.options.explodeRemoteSimulcast) {
  19455. explodeRemoteSimulcast(mLine);
  19456. } else {
  19457. implodeRemoteSimulcast(mLine);
  19458. }
  19459. // If native simulcast is enabled, we must append the x-goog-conference
  19460. // attribute to the SDP.
  19461. if (self.layers.length < 1) {
  19462. removeGoogConference(mLine);
  19463. } else {
  19464. assertGoogConference(mLine);
  19465. }
  19466. });
  19467. return new RTCSessionDescription({
  19468. type: desc.type,
  19469. sdp: transform.write(session)
  19470. });
  19471. };
  19472. /**
  19473. *
  19474. * @param desc
  19475. * @returns {RTCSessionDescription}
  19476. */
  19477. Simulcast.prototype.mungeLocalDescription = function (desc) {
  19478. if (!validateDescription(desc) || !this.isSupported()) {
  19479. return desc;
  19480. }
  19481. var session = transform.parse(desc.sdp);
  19482. var self = this;
  19483. processVideo(session, function (mLine) {
  19484. // Initialize native simulcast layers, if not already done.
  19485. self._maybeInitializeLayers(mLine);
  19486. // Update the SDP with the simulcast layers.
  19487. self._restoreSimulcastView(mLine);
  19488. });
  19489. return new RTCSessionDescription({
  19490. type: desc.type,
  19491. sdp: transform.write(session)
  19492. });
  19493. };
  19494. //endregion
  19495. module.exports = Simulcast;
  19496. },{"./transform-utils":69,"sdp-transform":71}],69:[function(require,module,exports){
  19497. /* Copyright @ 2015 Atlassian Pty Ltd
  19498. *
  19499. * Licensed under the Apache License, Version 2.0 (the "License");
  19500. * you may not use this file except in compliance with the License.
  19501. * You may obtain a copy of the License at
  19502. *
  19503. * http://www.apache.org/licenses/LICENSE-2.0
  19504. *
  19505. * Unless required by applicable law or agreed to in writing, software
  19506. * distributed under the License is distributed on an "AS IS" BASIS,
  19507. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19508. * See the License for the specific language governing permissions and
  19509. * limitations under the License.
  19510. */
  19511. exports.writeSsrcs = function(sources, order) {
  19512. var ssrcs = [];
  19513. // expand sources to ssrcs
  19514. if (typeof sources !== 'undefined' &&
  19515. Object.keys(sources).length !== 0) {
  19516. if (Array.isArray(order)) {
  19517. for (var i = 0; i < order.length; i++) {
  19518. var ssrc = order[i];
  19519. var source = sources[ssrc];
  19520. Object.keys(source).forEach(function (attribute) {
  19521. ssrcs.push({
  19522. id: ssrc,
  19523. attribute: attribute,
  19524. value: source[attribute]
  19525. });
  19526. });
  19527. }
  19528. } else {
  19529. Object.keys(sources).forEach(function (ssrc) {
  19530. var source = sources[ssrc];
  19531. Object.keys(source).forEach(function (attribute) {
  19532. ssrcs.push({
  19533. id: ssrc,
  19534. attribute: attribute,
  19535. value: source[attribute]
  19536. });
  19537. });
  19538. });
  19539. }
  19540. }
  19541. return ssrcs;
  19542. };
  19543. exports.parseSsrcs = function (mLine) {
  19544. var sources = {};
  19545. // group sources attributes by ssrc.
  19546. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19547. mLine.ssrcs.forEach(function (ssrc) {
  19548. if (!sources[ssrc.id])
  19549. sources[ssrc.id] = {};
  19550. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19551. });
  19552. }
  19553. return sources;
  19554. };
  19555. },{}],70:[function(require,module,exports){
  19556. var grammar = module.exports = {
  19557. v: [{
  19558. name: 'version',
  19559. reg: /^(\d*)$/
  19560. }],
  19561. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19562. // NB: sessionId will be a String in most cases because it is huge
  19563. name: 'origin',
  19564. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19565. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19566. format: "%s %s %d %s IP%d %s"
  19567. }],
  19568. // default parsing of these only (though some of these feel outdated)
  19569. s: [{ name: 'name' }],
  19570. i: [{ name: 'description' }],
  19571. u: [{ name: 'uri' }],
  19572. e: [{ name: 'email' }],
  19573. p: [{ name: 'phone' }],
  19574. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19575. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19576. //k: [{}], // outdated thing ignored
  19577. t: [{ //t=0 0
  19578. name: 'timing',
  19579. reg: /^(\d*) (\d*)/,
  19580. names: ['start', 'stop'],
  19581. format: "%d %d"
  19582. }],
  19583. c: [{ //c=IN IP4 10.47.197.26
  19584. name: 'connection',
  19585. reg: /^IN IP(\d) (\S*)/,
  19586. names: ['version', 'ip'],
  19587. format: "IN IP%d %s"
  19588. }],
  19589. b: [{ //b=AS:4000
  19590. push: 'bandwidth',
  19591. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19592. names: ['type', 'limit'],
  19593. format: "%s:%s"
  19594. }],
  19595. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19596. // NB: special - pushes to session
  19597. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19598. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19599. names: ['type', 'port', 'protocol', 'payloads'],
  19600. format: "%s %d %s %s"
  19601. }],
  19602. a: [
  19603. { //a=rtpmap:110 opus/48000/2
  19604. push: 'rtp',
  19605. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19606. names: ['payload', 'codec', 'rate', 'encoding'],
  19607. format: function (o) {
  19608. return (o.encoding) ?
  19609. "rtpmap:%d %s/%s/%s":
  19610. "rtpmap:%d %s/%s";
  19611. }
  19612. },
  19613. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19614. push: 'fmtp',
  19615. reg: /^fmtp:(\d*) (\S*)/,
  19616. names: ['payload', 'config'],
  19617. format: "fmtp:%d %s"
  19618. },
  19619. { //a=control:streamid=0
  19620. name: 'control',
  19621. reg: /^control:(.*)/,
  19622. format: "control:%s"
  19623. },
  19624. { //a=rtcp:65179 IN IP4 193.84.77.194
  19625. name: 'rtcp',
  19626. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19627. names: ['port', 'netType', 'ipVer', 'address'],
  19628. format: function (o) {
  19629. return (o.address != null) ?
  19630. "rtcp:%d %s IP%d %s":
  19631. "rtcp:%d";
  19632. }
  19633. },
  19634. { //a=rtcp-fb:98 trr-int 100
  19635. push: 'rtcpFbTrrInt',
  19636. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19637. names: ['payload', 'value'],
  19638. format: "rtcp-fb:%d trr-int %d"
  19639. },
  19640. { //a=rtcp-fb:98 nack rpsi
  19641. push: 'rtcpFb',
  19642. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19643. names: ['payload', 'type', 'subtype'],
  19644. format: function (o) {
  19645. return (o.subtype != null) ?
  19646. "rtcp-fb:%s %s %s":
  19647. "rtcp-fb:%s %s";
  19648. }
  19649. },
  19650. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19651. //a=extmap:1/recvonly URI-gps-string
  19652. push: 'ext',
  19653. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19654. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19655. format: function (o) {
  19656. return (o.config != null) ?
  19657. "extmap:%s %s %s":
  19658. "extmap:%s %s";
  19659. }
  19660. },
  19661. {
  19662. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19663. push: 'crypto',
  19664. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19665. names: ['id', 'suite', 'config', 'sessionConfig'],
  19666. format: function (o) {
  19667. return (o.sessionConfig != null) ?
  19668. "crypto:%d %s %s %s":
  19669. "crypto:%d %s %s";
  19670. }
  19671. },
  19672. { //a=setup:actpass
  19673. name: 'setup',
  19674. reg: /^setup:(\w*)/,
  19675. format: "setup:%s"
  19676. },
  19677. { //a=mid:1
  19678. name: 'mid',
  19679. reg: /^mid:([^\s]*)/,
  19680. format: "mid:%s"
  19681. },
  19682. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19683. name: 'msid',
  19684. reg: /^msid:(.*)/,
  19685. format: "msid:%s"
  19686. },
  19687. { //a=ptime:20
  19688. name: 'ptime',
  19689. reg: /^ptime:(\d*)/,
  19690. format: "ptime:%d"
  19691. },
  19692. { //a=maxptime:60
  19693. name: 'maxptime',
  19694. reg: /^maxptime:(\d*)/,
  19695. format: "maxptime:%d"
  19696. },
  19697. { //a=sendrecv
  19698. name: 'direction',
  19699. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19700. },
  19701. { //a=ice-lite
  19702. name: 'icelite',
  19703. reg: /^(ice-lite)/
  19704. },
  19705. { //a=ice-ufrag:F7gI
  19706. name: 'iceUfrag',
  19707. reg: /^ice-ufrag:(\S*)/,
  19708. format: "ice-ufrag:%s"
  19709. },
  19710. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19711. name: 'icePwd',
  19712. reg: /^ice-pwd:(\S*)/,
  19713. format: "ice-pwd:%s"
  19714. },
  19715. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19716. name: 'fingerprint',
  19717. reg: /^fingerprint:(\S*) (\S*)/,
  19718. names: ['type', 'hash'],
  19719. format: "fingerprint:%s %s"
  19720. },
  19721. {
  19722. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19723. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19724. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19725. push:'candidates',
  19726. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19727. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19728. format: function (o) {
  19729. var str = "candidate:%s %d %s %d %s %d typ %s";
  19730. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19731. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19732. if (o.generation != null) {
  19733. str += " generation %d";
  19734. }
  19735. return str;
  19736. }
  19737. },
  19738. { //a=end-of-candidates (keep after the candidates line for readability)
  19739. name: 'endOfCandidates',
  19740. reg: /^(end-of-candidates)/
  19741. },
  19742. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19743. name: 'remoteCandidates',
  19744. reg: /^remote-candidates:(.*)/,
  19745. format: "remote-candidates:%s"
  19746. },
  19747. { //a=ice-options:google-ice
  19748. name: 'iceOptions',
  19749. reg: /^ice-options:(\S*)/,
  19750. format: "ice-options:%s"
  19751. },
  19752. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19753. push: "ssrcs",
  19754. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19755. names: ['id', 'attribute', 'value'],
  19756. format: "ssrc:%d %s:%s"
  19757. },
  19758. { //a=ssrc-group:FEC 1 2
  19759. push: "ssrcGroups",
  19760. reg: /^ssrc-group:(\w*) (.*)/,
  19761. names: ['semantics', 'ssrcs'],
  19762. format: "ssrc-group:%s %s"
  19763. },
  19764. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19765. name: "msidSemantic",
  19766. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19767. names: ['semantic', 'token'],
  19768. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19769. },
  19770. { //a=group:BUNDLE audio video
  19771. push: 'groups',
  19772. reg: /^group:(\w*) (.*)/,
  19773. names: ['type', 'mids'],
  19774. format: "group:%s %s"
  19775. },
  19776. { //a=rtcp-mux
  19777. name: 'rtcpMux',
  19778. reg: /^(rtcp-mux)/
  19779. },
  19780. { //a=rtcp-rsize
  19781. name: 'rtcpRsize',
  19782. reg: /^(rtcp-rsize)/
  19783. },
  19784. { // any a= that we don't understand is kepts verbatim on media.invalid
  19785. push: 'invalid',
  19786. names: ["value"]
  19787. }
  19788. ]
  19789. };
  19790. // set sensible defaults to avoid polluting the grammar with boring details
  19791. Object.keys(grammar).forEach(function (key) {
  19792. var objs = grammar[key];
  19793. objs.forEach(function (obj) {
  19794. if (!obj.reg) {
  19795. obj.reg = /(.*)/;
  19796. }
  19797. if (!obj.format) {
  19798. obj.format = "%s";
  19799. }
  19800. });
  19801. });
  19802. },{}],71:[function(require,module,exports){
  19803. var parser = require('./parser');
  19804. var writer = require('./writer');
  19805. exports.write = writer;
  19806. exports.parse = parser.parse;
  19807. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19808. exports.parsePayloads = parser.parsePayloads;
  19809. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19810. },{"./parser":72,"./writer":73}],72:[function(require,module,exports){
  19811. var toIntIfInt = function (v) {
  19812. return String(Number(v)) === v ? Number(v) : v;
  19813. };
  19814. var attachProperties = function (match, location, names, rawName) {
  19815. if (rawName && !names) {
  19816. location[rawName] = toIntIfInt(match[1]);
  19817. }
  19818. else {
  19819. for (var i = 0; i < names.length; i += 1) {
  19820. if (match[i+1] != null) {
  19821. location[names[i]] = toIntIfInt(match[i+1]);
  19822. }
  19823. }
  19824. }
  19825. };
  19826. var parseReg = function (obj, location, content) {
  19827. var needsBlank = obj.name && obj.names;
  19828. if (obj.push && !location[obj.push]) {
  19829. location[obj.push] = [];
  19830. }
  19831. else if (needsBlank && !location[obj.name]) {
  19832. location[obj.name] = {};
  19833. }
  19834. var keyLocation = obj.push ?
  19835. {} : // blank object that will be pushed
  19836. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19837. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19838. if (obj.push) {
  19839. location[obj.push].push(keyLocation);
  19840. }
  19841. };
  19842. var grammar = require('./grammar');
  19843. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19844. exports.parse = function (sdp) {
  19845. var session = {}
  19846. , media = []
  19847. , location = session; // points at where properties go under (one of the above)
  19848. // parse lines we understand
  19849. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19850. var type = l[0];
  19851. var content = l.slice(2);
  19852. if (type === 'm') {
  19853. media.push({rtp: [], fmtp: []});
  19854. location = media[media.length-1]; // point at latest media line
  19855. }
  19856. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19857. var obj = grammar[type][j];
  19858. if (obj.reg.test(content)) {
  19859. return parseReg(obj, location, content);
  19860. }
  19861. }
  19862. });
  19863. session.media = media; // link it up
  19864. return session;
  19865. };
  19866. var fmtpReducer = function (acc, expr) {
  19867. var s = expr.split('=');
  19868. if (s.length === 2) {
  19869. acc[s[0]] = toIntIfInt(s[1]);
  19870. }
  19871. return acc;
  19872. };
  19873. exports.parseFmtpConfig = function (str) {
  19874. return str.split(';').reduce(fmtpReducer, {});
  19875. };
  19876. exports.parsePayloads = function (str) {
  19877. return str.split(' ').map(Number);
  19878. };
  19879. exports.parseRemoteCandidates = function (str) {
  19880. var candidates = [];
  19881. var parts = str.split(' ').map(toIntIfInt);
  19882. for (var i = 0; i < parts.length; i += 3) {
  19883. candidates.push({
  19884. component: parts[i],
  19885. ip: parts[i + 1],
  19886. port: parts[i + 2]
  19887. });
  19888. }
  19889. return candidates;
  19890. };
  19891. },{"./grammar":70}],73:[function(require,module,exports){
  19892. var grammar = require('./grammar');
  19893. // customized util.format - discards excess arguments and can void middle ones
  19894. var formatRegExp = /%[sdv%]/g;
  19895. var format = function (formatStr) {
  19896. var i = 1;
  19897. var args = arguments;
  19898. var len = args.length;
  19899. return formatStr.replace(formatRegExp, function (x) {
  19900. if (i >= len) {
  19901. return x; // missing argument
  19902. }
  19903. var arg = args[i];
  19904. i += 1;
  19905. switch (x) {
  19906. case '%%':
  19907. return '%';
  19908. case '%s':
  19909. return String(arg);
  19910. case '%d':
  19911. return Number(arg);
  19912. case '%v':
  19913. return '';
  19914. }
  19915. });
  19916. // NB: we discard excess arguments - they are typically undefined from makeLine
  19917. };
  19918. var makeLine = function (type, obj, location) {
  19919. var str = obj.format instanceof Function ?
  19920. (obj.format(obj.push ? location : location[obj.name])) :
  19921. obj.format;
  19922. var args = [type + '=' + str];
  19923. if (obj.names) {
  19924. for (var i = 0; i < obj.names.length; i += 1) {
  19925. var n = obj.names[i];
  19926. if (obj.name) {
  19927. args.push(location[obj.name][n]);
  19928. }
  19929. else { // for mLine and push attributes
  19930. args.push(location[obj.names[i]]);
  19931. }
  19932. }
  19933. }
  19934. else {
  19935. args.push(location[obj.name]);
  19936. }
  19937. return format.apply(null, args);
  19938. };
  19939. // RFC specified order
  19940. // TODO: extend this with all the rest
  19941. var defaultOuterOrder = [
  19942. 'v', 'o', 's', 'i',
  19943. 'u', 'e', 'p', 'c',
  19944. 'b', 't', 'r', 'z', 'a'
  19945. ];
  19946. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19947. module.exports = function (session, opts) {
  19948. opts = opts || {};
  19949. // ensure certain properties exist
  19950. if (session.version == null) {
  19951. session.version = 0; // "v=0" must be there (only defined version atm)
  19952. }
  19953. if (session.name == null) {
  19954. session.name = " "; // "s= " must be there if no meaningful name set
  19955. }
  19956. session.media.forEach(function (mLine) {
  19957. if (mLine.payloads == null) {
  19958. mLine.payloads = "";
  19959. }
  19960. });
  19961. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19962. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19963. var sdp = [];
  19964. // loop through outerOrder for matching properties on session
  19965. outerOrder.forEach(function (type) {
  19966. grammar[type].forEach(function (obj) {
  19967. if (obj.name in session && session[obj.name] != null) {
  19968. sdp.push(makeLine(type, obj, session));
  19969. }
  19970. else if (obj.push in session && session[obj.push] != null) {
  19971. session[obj.push].forEach(function (el) {
  19972. sdp.push(makeLine(type, obj, el));
  19973. });
  19974. }
  19975. });
  19976. });
  19977. // then for each media line, follow the innerOrder
  19978. session.media.forEach(function (mLine) {
  19979. sdp.push(makeLine('m', grammar.m[0], mLine));
  19980. innerOrder.forEach(function (type) {
  19981. grammar[type].forEach(function (obj) {
  19982. if (obj.name in mLine && mLine[obj.name] != null) {
  19983. sdp.push(makeLine(type, obj, mLine));
  19984. }
  19985. else if (obj.push in mLine && mLine[obj.push] != null) {
  19986. mLine[obj.push].forEach(function (el) {
  19987. sdp.push(makeLine(type, obj, el));
  19988. });
  19989. }
  19990. });
  19991. });
  19992. });
  19993. return sdp.join('\r\n') + '\r\n';
  19994. };
  19995. },{"./grammar":70}],74:[function(require,module,exports){
  19996. var grammar = module.exports = {
  19997. v: [{
  19998. name: 'version',
  19999. reg: /^(\d*)$/
  20000. }],
  20001. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20002. // NB: sessionId will be a String in most cases because it is huge
  20003. name: 'origin',
  20004. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20005. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20006. format: "%s %s %d %s IP%d %s"
  20007. }],
  20008. // default parsing of these only (though some of these feel outdated)
  20009. s: [{ name: 'name' }],
  20010. i: [{ name: 'description' }],
  20011. u: [{ name: 'uri' }],
  20012. e: [{ name: 'email' }],
  20013. p: [{ name: 'phone' }],
  20014. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20015. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20016. //k: [{}], // outdated thing ignored
  20017. t: [{ //t=0 0
  20018. name: 'timing',
  20019. reg: /^(\d*) (\d*)/,
  20020. names: ['start', 'stop'],
  20021. format: "%d %d"
  20022. }],
  20023. c: [{ //c=IN IP4 10.47.197.26
  20024. name: 'connection',
  20025. reg: /^IN IP(\d) (\S*)/,
  20026. names: ['version', 'ip'],
  20027. format: "IN IP%d %s"
  20028. }],
  20029. b: [{ //b=AS:4000
  20030. push: 'bandwidth',
  20031. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20032. names: ['type', 'limit'],
  20033. format: "%s:%s"
  20034. }],
  20035. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20036. // NB: special - pushes to session
  20037. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20038. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20039. names: ['type', 'port', 'protocol', 'payloads'],
  20040. format: "%s %d %s %s"
  20041. }],
  20042. a: [
  20043. { //a=rtpmap:110 opus/48000/2
  20044. push: 'rtp',
  20045. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  20046. names: ['payload', 'codec', 'rate', 'encoding'],
  20047. format: function (o) {
  20048. return (o.encoding) ?
  20049. "rtpmap:%d %s/%s/%s":
  20050. "rtpmap:%d %s/%s";
  20051. }
  20052. },
  20053. {
  20054. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20055. //a=fmtp:111 minptime=10; useinbandfec=1
  20056. push: 'fmtp',
  20057. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20058. names: ['payload', 'config'],
  20059. format: "fmtp:%d %s"
  20060. },
  20061. { //a=control:streamid=0
  20062. name: 'control',
  20063. reg: /^control:(.*)/,
  20064. format: "control:%s"
  20065. },
  20066. { //a=rtcp:65179 IN IP4 193.84.77.194
  20067. name: 'rtcp',
  20068. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20069. names: ['port', 'netType', 'ipVer', 'address'],
  20070. format: function (o) {
  20071. return (o.address != null) ?
  20072. "rtcp:%d %s IP%d %s":
  20073. "rtcp:%d";
  20074. }
  20075. },
  20076. { //a=rtcp-fb:98 trr-int 100
  20077. push: 'rtcpFbTrrInt',
  20078. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20079. names: ['payload', 'value'],
  20080. format: "rtcp-fb:%d trr-int %d"
  20081. },
  20082. { //a=rtcp-fb:98 nack rpsi
  20083. push: 'rtcpFb',
  20084. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20085. names: ['payload', 'type', 'subtype'],
  20086. format: function (o) {
  20087. return (o.subtype != null) ?
  20088. "rtcp-fb:%s %s %s":
  20089. "rtcp-fb:%s %s";
  20090. }
  20091. },
  20092. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20093. //a=extmap:1/recvonly URI-gps-string
  20094. push: 'ext',
  20095. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20096. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20097. format: function (o) {
  20098. return (o.config != null) ?
  20099. "extmap:%s %s %s":
  20100. "extmap:%s %s";
  20101. }
  20102. },
  20103. {
  20104. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20105. push: 'crypto',
  20106. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20107. names: ['id', 'suite', 'config', 'sessionConfig'],
  20108. format: function (o) {
  20109. return (o.sessionConfig != null) ?
  20110. "crypto:%d %s %s %s":
  20111. "crypto:%d %s %s";
  20112. }
  20113. },
  20114. { //a=setup:actpass
  20115. name: 'setup',
  20116. reg: /^setup:(\w*)/,
  20117. format: "setup:%s"
  20118. },
  20119. { //a=mid:1
  20120. name: 'mid',
  20121. reg: /^mid:([^\s]*)/,
  20122. format: "mid:%s"
  20123. },
  20124. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20125. name: 'msid',
  20126. reg: /^msid:(.*)/,
  20127. format: "msid:%s"
  20128. },
  20129. { //a=ptime:20
  20130. name: 'ptime',
  20131. reg: /^ptime:(\d*)/,
  20132. format: "ptime:%d"
  20133. },
  20134. { //a=maxptime:60
  20135. name: 'maxptime',
  20136. reg: /^maxptime:(\d*)/,
  20137. format: "maxptime:%d"
  20138. },
  20139. { //a=sendrecv
  20140. name: 'direction',
  20141. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20142. },
  20143. { //a=ice-lite
  20144. name: 'icelite',
  20145. reg: /^(ice-lite)/
  20146. },
  20147. { //a=ice-ufrag:F7gI
  20148. name: 'iceUfrag',
  20149. reg: /^ice-ufrag:(\S*)/,
  20150. format: "ice-ufrag:%s"
  20151. },
  20152. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20153. name: 'icePwd',
  20154. reg: /^ice-pwd:(\S*)/,
  20155. format: "ice-pwd:%s"
  20156. },
  20157. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20158. name: 'fingerprint',
  20159. reg: /^fingerprint:(\S*) (\S*)/,
  20160. names: ['type', 'hash'],
  20161. format: "fingerprint:%s %s"
  20162. },
  20163. {
  20164. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20165. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20166. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20167. push:'candidates',
  20168. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  20169. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  20170. format: function (o) {
  20171. var str = "candidate:%s %d %s %d %s %d typ %s";
  20172. // NB: candidate has two optional chunks, so %void middle one if it's missing
  20173. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20174. if (o.generation != null) {
  20175. str += " generation %d";
  20176. }
  20177. return str;
  20178. }
  20179. },
  20180. { //a=end-of-candidates (keep after the candidates line for readability)
  20181. name: 'endOfCandidates',
  20182. reg: /^(end-of-candidates)/
  20183. },
  20184. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20185. name: 'remoteCandidates',
  20186. reg: /^remote-candidates:(.*)/,
  20187. format: "remote-candidates:%s"
  20188. },
  20189. { //a=ice-options:google-ice
  20190. name: 'iceOptions',
  20191. reg: /^ice-options:(\S*)/,
  20192. format: "ice-options:%s"
  20193. },
  20194. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20195. push: "ssrcs",
  20196. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20197. names: ['id', 'attribute', 'value'],
  20198. format: "ssrc:%d %s:%s"
  20199. },
  20200. { //a=ssrc-group:FEC 1 2
  20201. push: "ssrcGroups",
  20202. reg: /^ssrc-group:(\w*) (.*)/,
  20203. names: ['semantics', 'ssrcs'],
  20204. format: "ssrc-group:%s %s"
  20205. },
  20206. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20207. name: "msidSemantic",
  20208. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20209. names: ['semantic', 'token'],
  20210. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20211. },
  20212. { //a=group:BUNDLE audio video
  20213. push: 'groups',
  20214. reg: /^group:(\w*) (.*)/,
  20215. names: ['type', 'mids'],
  20216. format: "group:%s %s"
  20217. },
  20218. { //a=rtcp-mux
  20219. name: 'rtcpMux',
  20220. reg: /^(rtcp-mux)/
  20221. },
  20222. { //a=rtcp-rsize
  20223. name: 'rtcpRsize',
  20224. reg: /^(rtcp-rsize)/
  20225. },
  20226. { // any a= that we don't understand is kepts verbatim on media.invalid
  20227. push: 'invalid',
  20228. names: ["value"]
  20229. }
  20230. ]
  20231. };
  20232. // set sensible defaults to avoid polluting the grammar with boring details
  20233. Object.keys(grammar).forEach(function (key) {
  20234. var objs = grammar[key];
  20235. objs.forEach(function (obj) {
  20236. if (!obj.reg) {
  20237. obj.reg = /(.*)/;
  20238. }
  20239. if (!obj.format) {
  20240. obj.format = "%s";
  20241. }
  20242. });
  20243. });
  20244. },{}],75:[function(require,module,exports){
  20245. arguments[4][71][0].apply(exports,arguments)
  20246. },{"./parser":76,"./writer":77,"dup":71}],76:[function(require,module,exports){
  20247. var toIntIfInt = function (v) {
  20248. return String(Number(v)) === v ? Number(v) : v;
  20249. };
  20250. var attachProperties = function (match, location, names, rawName) {
  20251. if (rawName && !names) {
  20252. location[rawName] = toIntIfInt(match[1]);
  20253. }
  20254. else {
  20255. for (var i = 0; i < names.length; i += 1) {
  20256. if (match[i+1] != null) {
  20257. location[names[i]] = toIntIfInt(match[i+1]);
  20258. }
  20259. }
  20260. }
  20261. };
  20262. var parseReg = function (obj, location, content) {
  20263. var needsBlank = obj.name && obj.names;
  20264. if (obj.push && !location[obj.push]) {
  20265. location[obj.push] = [];
  20266. }
  20267. else if (needsBlank && !location[obj.name]) {
  20268. location[obj.name] = {};
  20269. }
  20270. var keyLocation = obj.push ?
  20271. {} : // blank object that will be pushed
  20272. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20273. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20274. if (obj.push) {
  20275. location[obj.push].push(keyLocation);
  20276. }
  20277. };
  20278. var grammar = require('./grammar');
  20279. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20280. exports.parse = function (sdp) {
  20281. var session = {}
  20282. , media = []
  20283. , location = session; // points at where properties go under (one of the above)
  20284. // parse lines we understand
  20285. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20286. var type = l[0];
  20287. var content = l.slice(2);
  20288. if (type === 'm') {
  20289. media.push({rtp: [], fmtp: []});
  20290. location = media[media.length-1]; // point at latest media line
  20291. }
  20292. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20293. var obj = grammar[type][j];
  20294. if (obj.reg.test(content)) {
  20295. return parseReg(obj, location, content);
  20296. }
  20297. }
  20298. });
  20299. session.media = media; // link it up
  20300. return session;
  20301. };
  20302. var fmtpReducer = function (acc, expr) {
  20303. var s = expr.split('=');
  20304. if (s.length === 2) {
  20305. acc[s[0]] = toIntIfInt(s[1]);
  20306. }
  20307. return acc;
  20308. };
  20309. exports.parseFmtpConfig = function (str) {
  20310. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  20311. };
  20312. exports.parsePayloads = function (str) {
  20313. return str.split(' ').map(Number);
  20314. };
  20315. exports.parseRemoteCandidates = function (str) {
  20316. var candidates = [];
  20317. var parts = str.split(' ').map(toIntIfInt);
  20318. for (var i = 0; i < parts.length; i += 3) {
  20319. candidates.push({
  20320. component: parts[i],
  20321. ip: parts[i + 1],
  20322. port: parts[i + 2]
  20323. });
  20324. }
  20325. return candidates;
  20326. };
  20327. },{"./grammar":74}],77:[function(require,module,exports){
  20328. arguments[4][73][0].apply(exports,arguments)
  20329. },{"./grammar":74,"dup":73}],78:[function(require,module,exports){
  20330. var MediaStreamType = {
  20331. VIDEO_TYPE: "Video",
  20332. AUDIO_TYPE: "Audio"
  20333. };
  20334. module.exports = MediaStreamType;
  20335. },{}],79:[function(require,module,exports){
  20336. var RTCEvents = {
  20337. RTC_READY: "rtc.ready",
  20338. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20339. LASTN_CHANGED: "rtc.lastn_changed",
  20340. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20341. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20342. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20343. };
  20344. module.exports = RTCEvents;
  20345. },{}],80:[function(require,module,exports){
  20346. var Resolutions = {
  20347. "1080": {
  20348. width: 1920,
  20349. height: 1080,
  20350. order: 7
  20351. },
  20352. "fullhd": {
  20353. width: 1920,
  20354. height: 1080,
  20355. order: 7
  20356. },
  20357. "720": {
  20358. width: 1280,
  20359. height: 720,
  20360. order: 6
  20361. },
  20362. "hd": {
  20363. width: 1280,
  20364. height: 720,
  20365. order: 6
  20366. },
  20367. "960": {
  20368. width: 960,
  20369. height: 720,
  20370. order: 5
  20371. },
  20372. "640": {
  20373. width: 640,
  20374. height: 480,
  20375. order: 4
  20376. },
  20377. "vga": {
  20378. width: 640,
  20379. height: 480,
  20380. order: 4
  20381. },
  20382. "360": {
  20383. width: 640,
  20384. height: 360,
  20385. order: 3
  20386. },
  20387. "320": {
  20388. width: 320,
  20389. height: 240,
  20390. order: 2
  20391. },
  20392. "180": {
  20393. width: 320,
  20394. height: 180,
  20395. order: 1
  20396. }
  20397. };
  20398. module.exports = Resolutions;
  20399. },{}],81:[function(require,module,exports){
  20400. var AuthenticationEvents = {
  20401. /**
  20402. * Event callback arguments:
  20403. * function(authenticationEnabled, userIdentity)
  20404. * authenticationEnabled - indicates whether authentication has been enabled
  20405. * in this session
  20406. * userIdentity - if user has been logged in then it contains user name. If
  20407. * contains 'null' or 'undefined' then user is not logged in.
  20408. */
  20409. IDENTITY_UPDATED: "authentication.identity_updated"
  20410. };
  20411. module.exports = AuthenticationEvents;
  20412. },{}],82:[function(require,module,exports){
  20413. var DesktopSharingEventTypes = {
  20414. INIT: "ds.init",
  20415. SWITCHING_DONE: "ds.switching_done",
  20416. NEW_STREAM_CREATED: "ds.new_stream_created",
  20417. /**
  20418. * An event which indicates that the jidesha extension for Firefox is
  20419. * needed to proceed with screen sharing, and that it is not installed.
  20420. */
  20421. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20422. };
  20423. module.exports = DesktopSharingEventTypes;
  20424. },{}],83:[function(require,module,exports){
  20425. module.exports = {
  20426. /**
  20427. * An event carrying connection statistics.
  20428. */
  20429. CONNECTION_STATS: "statistics.connectionstats",
  20430. /**
  20431. * FIXME: needs documentation.
  20432. */
  20433. AUDIO_LEVEL: "statistics.audioLevel",
  20434. /**
  20435. * FIXME: needs documentation.
  20436. */
  20437. STOP: "statistics.stop"
  20438. };
  20439. },{}],84:[function(require,module,exports){
  20440. var Constants = {
  20441. LOCAL_JID: 'local'
  20442. };
  20443. module.exports = Constants;
  20444. },{}],85:[function(require,module,exports){
  20445. var XMPPEvents = {
  20446. // Designates an event indicating that the connection to the XMPP server
  20447. // failed.
  20448. CONNECTION_FAILED: "xmpp.connection.failed",
  20449. // Designates an event indicating that the media (ICE) connection was
  20450. // interrupted. This should go to the RTC module.
  20451. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20452. // Designates an event indicating that the media (ICE) connection was
  20453. // restored. This should go to the RTC module.
  20454. CONNECTION_RESTORED: "xmpp.connection.restored",
  20455. // Designates an event indicating that an offer (e.g. Jingle
  20456. // session-initiate) was received.
  20457. CALL_INCOMING: "xmpp.callincoming.jingle",
  20458. // Designates an event indicating that we were kicked from the XMPP MUC.
  20459. KICKED: "xmpp.kicked",
  20460. // Designates an event indicating that the userID for a specific JID has
  20461. // changed.
  20462. // Note: currently this event fires every time we receive presence from
  20463. // someone (regardless of whether or not the "userID" changed).
  20464. USER_ID_CHANGED: "xmpp.user_id_changed",
  20465. // Designates an event indicating that we have joined the XMPP MUC.
  20466. MUC_JOINED: "xmpp.muc_joined",
  20467. // Designates an event indicating that a participant joined the XMPP MUC.
  20468. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20469. // Designates an event indicating that a participant left the XMPP MUC.
  20470. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20471. // Designates an event indicating that the MUC role of a participant has
  20472. // changed.
  20473. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20474. // Designates an event indicating that the XMPP MUC was destroyed.
  20475. MUC_DESTROYED: "xmpp.muc_destroyed",
  20476. // Designates an event indicating that the display name of a participant
  20477. // has changed.
  20478. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20479. // Designates an event indicating that we received statistics from a
  20480. // participant in the MUC.
  20481. REMOTE_STATS: "xmpp.remote_stats",
  20482. // Designates an event indicating that our role in the XMPP MUC has changed.
  20483. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20484. // Designates an event indicating that the subject of the XMPP MUC has
  20485. // changed.
  20486. SUBJECT_CHANGED: "xmpp.subject_changed",
  20487. // Designates an event indicating that an XMPP message in the MUC was
  20488. // received.
  20489. MESSAGE_RECEIVED: "xmpp.message_received",
  20490. // Designates an event indicating that we sent an XMPP message to the MUC.
  20491. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20492. // Designates an event indicating that the video type (e.g. 'camera' or
  20493. // 'screen') for a participant has changed.
  20494. // Note: currently this event fires every time we receive presence from
  20495. // someone (regardless of whether or not the "video type" changed).
  20496. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20497. // Designates an event indicating that a participant in the XMPP MUC has
  20498. // advertised that they have audio muted (or unmuted).
  20499. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20500. // Designates an event indicating that a participant in the XMPP MUC has
  20501. // advertised that they have video muted (or unmuted).
  20502. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20503. // Designates an event indicating that the focus has asked us to mute our
  20504. // audio.
  20505. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20506. // Designates an event indicating that a moderator in the room changed the
  20507. // "start muted" settings for the conference.
  20508. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20509. // Designates an event indicating that we should join the conference with
  20510. // audio and/or video muted.
  20511. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20512. // Designates an event indicating that a remote participant's available
  20513. // devices (whether he supports a audio and/or video) changed.
  20514. // Note: currently this event fires every time we receive presence from
  20515. // someone (regardless of whether or not the devices changed).
  20516. DEVICE_AVAILABLE: "xmpp.device_available",
  20517. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20518. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20519. PASSWORD_REQUIRED: "xmpp.password_required",
  20520. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20521. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20522. ETHERPAD: "xmpp.etherpad",
  20523. BRIDGE_DOWN: "xmpp.bridge_down",
  20524. PRESENCE_STATUS: "xmpp.presence_status",
  20525. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20526. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20527. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20528. // TODO: only used in a hack, should probably be removed.
  20529. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20530. // TODO: only used in a hack, should probably be removed.
  20531. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20532. // TODO: only used in a hack, should probably be removed.
  20533. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20534. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20535. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20536. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20537. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20538. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20539. // xmpp is connected and obtained user media
  20540. READY_TO_JOIN: 'xmpp.ready_to_join',
  20541. FOCUS_LEFT: "xmpp.focus_left",
  20542. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  20543. };
  20544. module.exports = XMPPEvents;
  20545. },{}]},{},[7])(7)
  20546. });