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

lib-jitsi-meet.js 768KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. /**
  18. * Creates a JitsiConference object with the given name and properties.
  19. * Note: this constructor is not a part of the public API (objects should be
  20. * created using JitsiConnection.createConference).
  21. * @param options.config properties / settings related to the conference that will be created.
  22. * @param options.name the name of the conference
  23. * @param options.connection the JitsiConnection object for this JitsiConference.
  24. * @constructor
  25. */
  26. function JitsiConference(options) {
  27. if(!options.name || options.name.toLowerCase() !== options.name) {
  28. logger.error("Invalid conference name (no conference name passed or it"
  29. + "contains invalid characters like capital letters)!");
  30. return;
  31. }
  32. this.options = options;
  33. this.connection = this.options.connection;
  34. this.xmpp = this.connection.xmpp;
  35. this.eventEmitter = new EventEmitter();
  36. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  37. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  38. this.rtc = new RTC(this.room, options);
  39. if(!RTC.options.disableAudioLevels)
  40. this.statistics = new Statistics();
  41. setupListeners(this);
  42. this.participants = {};
  43. this.lastActiveSpeaker = null;
  44. this.dtmfManager = null;
  45. this.somebodySupportsDTMF = false;
  46. this.authEnabled = false;
  47. this.authIdentity;
  48. }
  49. /**
  50. * Joins the conference.
  51. * @param password {string} the password
  52. */
  53. JitsiConference.prototype.join = function (password) {
  54. if(this.room)
  55. this.room.join(password);
  56. };
  57. /**
  58. * Check if joined to the conference.
  59. */
  60. JitsiConference.prototype.isJoined = function () {
  61. return this.room && this.room.joined;
  62. };
  63. /**
  64. * Leaves the conference.
  65. */
  66. JitsiConference.prototype.leave = function () {
  67. if(this.xmpp && this.room)
  68. this.xmpp.leaveRoom(this.room.roomjid);
  69. this.room = null;
  70. };
  71. /**
  72. * Returns name of this conference.
  73. */
  74. JitsiConference.prototype.getName = function () {
  75. return this.options.name;
  76. };
  77. /**
  78. * Check if authentication is enabled for this conference.
  79. */
  80. JitsiConference.prototype.isAuthEnabled = function () {
  81. return this.authEnabled;
  82. };
  83. /**
  84. * Check if user is logged in.
  85. */
  86. JitsiConference.prototype.isLoggedIn = function () {
  87. return !!this.authIdentity;
  88. };
  89. /**
  90. * Get authorized login.
  91. */
  92. JitsiConference.prototype.getAuthLogin = function () {
  93. return this.authIdentity;
  94. };
  95. /**
  96. * Check if external authentication is enabled for this conference.
  97. */
  98. JitsiConference.prototype.isExternalAuthEnabled = function () {
  99. return this.room && this.room.moderator.isExternalAuthEnabled();
  100. };
  101. /**
  102. * Get url for external authentication.
  103. * @param {boolean} [urlForPopup] if true then return url for login popup,
  104. * else url of login page.
  105. * @returns {Promise}
  106. */
  107. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  108. return new Promise(function (resolve, reject) {
  109. if (!this.isExternalAuthEnabled()) {
  110. reject();
  111. return;
  112. }
  113. if (urlForPopup) {
  114. this.room.moderator.getPopupLoginUrl(resolve, reject);
  115. } else {
  116. this.room.moderator.getLoginUrl(resolve, reject);
  117. }
  118. }.bind(this));
  119. };
  120. /**
  121. * Returns the local tracks.
  122. */
  123. JitsiConference.prototype.getLocalTracks = function () {
  124. if (this.rtc) {
  125. return this.rtc.localStreams;
  126. } else {
  127. return [];
  128. }
  129. };
  130. /**
  131. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  132. * in JitsiConferenceEvents.
  133. * @param eventId the event ID.
  134. * @param handler handler for the event.
  135. *
  136. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  137. */
  138. JitsiConference.prototype.on = function (eventId, handler) {
  139. if(this.eventEmitter)
  140. this.eventEmitter.on(eventId, handler);
  141. };
  142. /**
  143. * Removes event listener
  144. * @param eventId the event ID.
  145. * @param [handler] optional, the specific handler to unbind
  146. *
  147. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  148. */
  149. JitsiConference.prototype.off = function (eventId, handler) {
  150. if(this.eventEmitter)
  151. this.eventEmitter.removeListener(eventId, handler);
  152. };
  153. // Common aliases for event emitter
  154. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  155. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  156. /**
  157. * Receives notifications from another participants for commands / custom events
  158. * (send by sendPresenceCommand method).
  159. * @param command {String} the name of the command
  160. * @param handler {Function} handler for the command
  161. */
  162. JitsiConference.prototype.addCommandListener = function (command, handler) {
  163. if(this.room)
  164. this.room.addPresenceListener(command, handler);
  165. };
  166. /**
  167. * Removes command listener
  168. * @param command {String} the name of the command
  169. */
  170. JitsiConference.prototype.removeCommandListener = function (command) {
  171. if(this.room)
  172. this.room.removePresenceListener(command);
  173. };
  174. /**
  175. * Sends text message to the other participants in the conference
  176. * @param message the text message.
  177. */
  178. JitsiConference.prototype.sendTextMessage = function (message) {
  179. if(this.room)
  180. this.room.sendMessage(message);
  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. **/
  187. JitsiConference.prototype.sendCommand = function (name, values) {
  188. if(this.room) {
  189. this.room.addToPresence(name, values);
  190. this.room.sendPresence();
  191. }
  192. };
  193. /**
  194. * Send presence command one time.
  195. * @param name the name of the command.
  196. * @param values Object with keys and values that will be send.
  197. **/
  198. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  199. this.sendCommand(name, values);
  200. this.removeCommand(name);
  201. };
  202. /**
  203. * Send presence command.
  204. * @param name the name of the command.
  205. * @param values Object with keys and values that will be send.
  206. * @param persistent if false the command will be sent only one time
  207. **/
  208. JitsiConference.prototype.removeCommand = function (name) {
  209. if(this.room)
  210. this.room.removeFromPresence(name);
  211. };
  212. /**
  213. * Sets the display name for this conference.
  214. * @param name the display name to set
  215. */
  216. JitsiConference.prototype.setDisplayName = function(name) {
  217. if(this.room){
  218. // remove previously set nickname
  219. this.room.removeFromPresence("nick");
  220. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  221. this.room.sendPresence();
  222. }
  223. };
  224. /**
  225. * Adds JitsiLocalTrack object to the conference.
  226. * @param track the JitsiLocalTrack object.
  227. */
  228. JitsiConference.prototype.addTrack = function (track) {
  229. this.room.addStream(track.getOriginalStream(), function () {
  230. this.rtc.addLocalStream(track);
  231. var muteHandler = this._fireMuteChangeEvent.bind(this, track);
  232. var stopHandler = this.removeTrack.bind(this, track);
  233. var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  234. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  235. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  236. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  237. this.addEventListener(JitsiConferenceEvents.TRACK_REMOVED, function (someTrack) {
  238. if (someTrack !== track) {
  239. return;
  240. }
  241. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  242. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  243. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  244. });
  245. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  246. }.bind(this));
  247. };
  248. /**
  249. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  250. * @param audioLevel the audio level
  251. */
  252. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  253. this.eventEmitter.emit(
  254. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  255. this.myUserId(), audioLevel);
  256. };
  257. /**
  258. * Fires TRACK_MUTE_CHANGED change conference event.
  259. * @param track the JitsiTrack object related to the event.
  260. */
  261. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  262. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  263. };
  264. /**
  265. * Removes JitsiLocalTrack object to the conference.
  266. * @param track the JitsiLocalTrack object.
  267. */
  268. JitsiConference.prototype.removeTrack = function (track) {
  269. if(!this.room){
  270. if(this.rtc)
  271. this.rtc.removeLocalStream(track);
  272. return;
  273. }
  274. this.room.removeStream(track.getOriginalStream(), function(){
  275. this.rtc.removeLocalStream(track);
  276. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  277. }.bind(this));
  278. };
  279. /**
  280. * Get role of the local user.
  281. * @returns {string} user role: 'moderator' or 'none'
  282. */
  283. JitsiConference.prototype.getRole = function () {
  284. return this.room.role;
  285. };
  286. /**
  287. * Check if local user is moderator.
  288. * @returns {boolean} true if local user is moderator, false otherwise.
  289. */
  290. JitsiConference.prototype.isModerator = function () {
  291. return this.room.isModerator();
  292. };
  293. /**
  294. * Set password for the room.
  295. * @param {string} password new password for the room.
  296. * @returns {Promise}
  297. */
  298. JitsiConference.prototype.lock = function (password) {
  299. if (!this.isModerator()) {
  300. return Promise.reject();
  301. }
  302. var conference = this;
  303. return new Promise(function (resolve, reject) {
  304. conference.room.lockRoom(password || "", function () {
  305. resolve();
  306. }, function (err) {
  307. reject(err);
  308. }, function () {
  309. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  310. });
  311. });
  312. };
  313. /**
  314. * Remove password from the room.
  315. * @returns {Promise}
  316. */
  317. JitsiConference.prototype.unlock = function () {
  318. return this.lock();
  319. };
  320. /**
  321. * Elects the participant with the given id to be the selected participant or the speaker.
  322. * @param id the identifier of the participant
  323. */
  324. JitsiConference.prototype.selectParticipant = function(participantId) {
  325. if (this.rtc) {
  326. this.rtc.selectedEndpoint(participantId);
  327. }
  328. };
  329. /**
  330. *
  331. * @param id the identifier of the participant
  332. */
  333. JitsiConference.prototype.pinParticipant = function(participantId) {
  334. if (this.rtc) {
  335. this.rtc.pinEndpoint(participantId);
  336. }
  337. };
  338. /**
  339. * Returns the list of participants for this conference.
  340. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  341. */
  342. JitsiConference.prototype.getParticipants = function() {
  343. return Object.keys(this.participants).map(function (key) {
  344. return this.participants[key];
  345. }, this);
  346. };
  347. /**
  348. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  349. * undefined if there isn't one).
  350. * @param id the id of the participant.
  351. */
  352. JitsiConference.prototype.getParticipantById = function(id) {
  353. return this.participants[id];
  354. };
  355. /**
  356. * Kick participant from this conference.
  357. * @param {string} id id of the participant to kick
  358. */
  359. JitsiConference.prototype.kickParticipant = function (id) {
  360. var participant = this.getParticipantById(id);
  361. if (!participant) {
  362. return;
  363. }
  364. this.room.kick(participant.getJid());
  365. };
  366. /**
  367. * Kick participant from this conference.
  368. * @param {string} id id of the participant to kick
  369. */
  370. JitsiConference.prototype.muteParticipant = function (id) {
  371. var participant = this.getParticipantById(id);
  372. if (!participant) {
  373. return;
  374. }
  375. this.room.muteParticipant(participant.getJid(), true);
  376. };
  377. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  378. var id = Strophe.getResourceFromJid(jid);
  379. if (id === 'focus' || this.myUserId() === id) {
  380. return;
  381. }
  382. var participant = new JitsiParticipant(jid, this, nick);
  383. this.participants[id] = participant;
  384. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  385. this.xmpp.connection.disco.info(
  386. jid, "node", function(iq) {
  387. participant._supportsDTMF = $(iq).find(
  388. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  389. this.updateDTMFSupport();
  390. }.bind(this)
  391. );
  392. };
  393. JitsiConference.prototype.onMemberLeft = function (jid) {
  394. var id = Strophe.getResourceFromJid(jid);
  395. if (id === 'focus' || this.myUserId() === id) {
  396. return;
  397. }
  398. var participant = this.participants[id];
  399. delete this.participants[id];
  400. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  401. };
  402. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  403. var id = Strophe.getResourceFromJid(jid);
  404. var participant = this.getParticipantById(id);
  405. if (!participant) {
  406. return;
  407. }
  408. participant._role = role;
  409. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  410. };
  411. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  412. var id = Strophe.getResourceFromJid(jid);
  413. var participant = this.getParticipantById(id);
  414. if (!participant) {
  415. return;
  416. }
  417. participant._displayName = displayName;
  418. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  419. };
  420. JitsiConference.prototype.onTrackAdded = function (track) {
  421. var id = track.getParticipantId();
  422. var participant = this.getParticipantById(id);
  423. if (!participant) {
  424. return;
  425. }
  426. // add track to JitsiParticipant
  427. participant._tracks.push(track);
  428. var emitter = this.eventEmitter;
  429. track.addEventListener(
  430. JitsiTrackEvents.TRACK_STOPPED,
  431. function () {
  432. // remove track from JitsiParticipant
  433. var pos = participant._tracks.indexOf(track);
  434. if (pos > -1) {
  435. participant._tracks.splice(pos, 1);
  436. }
  437. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  438. }
  439. );
  440. track.addEventListener(
  441. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  442. function () {
  443. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  444. }
  445. );
  446. track.addEventListener(
  447. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  448. function (audioLevel) {
  449. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  450. }
  451. );
  452. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  453. };
  454. JitsiConference.prototype.updateDTMFSupport = function () {
  455. var somebodySupportsDTMF = false;
  456. var participants = this.getParticipants();
  457. // check if at least 1 participant supports DTMF
  458. for (var i = 0; i < participants.length; i += 1) {
  459. if (participants[i].supportsDTMF()) {
  460. somebodySupportsDTMF = true;
  461. break;
  462. }
  463. }
  464. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  465. this.somebodySupportsDTMF = somebodySupportsDTMF;
  466. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  467. }
  468. };
  469. /**
  470. * Allows to check if there is at least one user in the conference
  471. * that supports DTMF.
  472. * @returns {boolean} true if somebody supports DTMF, false otherwise
  473. */
  474. JitsiConference.prototype.isDTMFSupported = function () {
  475. return this.somebodySupportsDTMF;
  476. };
  477. /**
  478. * Returns the local user's ID
  479. * @return {string} local user's ID
  480. */
  481. JitsiConference.prototype.myUserId = function () {
  482. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  483. };
  484. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  485. if (!this.dtmfManager) {
  486. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  487. if (!connection) {
  488. logger.warn("cannot sendTones: no conneciton");
  489. return;
  490. }
  491. var tracks = this.getLocalTracks().filter(function (track) {
  492. return track.isAudioTrack();
  493. });
  494. if (!tracks.length) {
  495. logger.warn("cannot sendTones: no local audio stream");
  496. return;
  497. }
  498. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  499. }
  500. this.dtmfManager.sendTones(tones, duration, pause);
  501. };
  502. /**
  503. * Returns true if the recording is supproted and false if not.
  504. */
  505. JitsiConference.prototype.isRecordingSupported = function () {
  506. if(this.room)
  507. return this.room.isRecordingSupported();
  508. return false;
  509. };
  510. /**
  511. * Returns null if the recording is not supported, "on" if the recording started
  512. * and "off" if the recording is not started.
  513. */
  514. JitsiConference.prototype.getRecordingState = function () {
  515. if(this.room)
  516. return this.room.getRecordingState();
  517. return "off";
  518. }
  519. /**
  520. * Returns the url of the recorded video.
  521. */
  522. JitsiConference.prototype.getRecordingURL = function () {
  523. if(this.room)
  524. return this.room.getRecordingURL();
  525. return null;
  526. }
  527. /**
  528. * Starts/stops the recording
  529. */
  530. JitsiConference.prototype.toggleRecording = function (options) {
  531. if(this.room)
  532. return this.room.toggleRecording(options, function (status, error) {
  533. this.eventEmitter.emit(
  534. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  535. }.bind(this));
  536. this.eventEmitter.emit(
  537. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  538. new Error("The conference is not created yet!"));
  539. }
  540. /**
  541. * Returns true if the SIP calls are supported and false otherwise
  542. */
  543. JitsiConference.prototype.isSIPCallingSupported = function () {
  544. if(this.room)
  545. return this.room.isSIPCallingSupported();
  546. return false;
  547. }
  548. /**
  549. * Dials a number.
  550. * @param number the number
  551. */
  552. JitsiConference.prototype.dial = function (number) {
  553. if(this.room)
  554. return this.room.dial(number);
  555. return new Promise(function(resolve, reject){
  556. reject(new Error("The conference is not created yet!"))});
  557. }
  558. /**
  559. * Hangup an existing call
  560. */
  561. JitsiConference.prototype.hangup = function () {
  562. if(this.room)
  563. return this.room.hangup();
  564. return new Promise(function(resolve, reject){
  565. reject(new Error("The conference is not created yet!"))});
  566. }
  567. /**
  568. * Returns the phone number for joining the conference.
  569. */
  570. JitsiConference.prototype.getPhoneNumber = function () {
  571. if(this.room)
  572. return this.room.getPhoneNumber();
  573. return null;
  574. }
  575. /**
  576. * Returns the pin for joining the conference with phone.
  577. */
  578. JitsiConference.prototype.getPhonePin = function () {
  579. if(this.room)
  580. return this.room.getPhonePin();
  581. return null;
  582. }
  583. /**
  584. * Returns the connection state for the current room. Its ice connection state
  585. * for its session.
  586. */
  587. JitsiConference.prototype.getConnectionState = function () {
  588. if(this.room)
  589. return this.room.getConnectionState();
  590. return null;
  591. }
  592. /**
  593. * Setups the listeners needed for the conference.
  594. * @param conference the conference
  595. */
  596. function setupListeners(conference) {
  597. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  598. conference.rtc.onIncommingCall(event);
  599. if(conference.statistics)
  600. conference.statistics.startRemoteStats(event.peerconnection);
  601. });
  602. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  603. function (data, sid, thessrc) {
  604. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  605. if (track) {
  606. conference.onTrackAdded(track);
  607. }
  608. }
  609. );
  610. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  611. function (value) {
  612. conference.rtc.setAudioMute(value);
  613. }
  614. );
  615. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  616. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  617. });
  618. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  619. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  620. });
  621. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  622. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  623. });
  624. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  625. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  626. });
  627. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  628. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  629. });
  630. // FIXME
  631. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  632. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  633. // });
  634. conference.room.addListener(XMPPEvents.KICKED, function () {
  635. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  636. });
  637. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  638. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  639. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  640. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  641. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  642. });
  643. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  644. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  645. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  646. });
  647. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  648. function () {
  649. conference.eventEmitter.emit(
  650. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  651. });
  652. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  653. conference.eventEmitter.emit(
  654. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  655. });
  656. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  657. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  658. });
  659. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  660. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  661. });
  662. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  663. conference.authEnabled = authEnabled;
  664. conference.authIdentity = authIdentity;
  665. });
  666. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  667. var id = Strophe.getResourceFromJid(jid);
  668. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  669. });
  670. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  671. if(conference.lastActiveSpeaker !== id && conference.room) {
  672. conference.lastActiveSpeaker = id;
  673. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  674. }
  675. });
  676. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  677. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  678. });
  679. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  680. function (lastNEndpoints, endpointsEnteringLastN) {
  681. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  682. lastNEndpoints, endpointsEnteringLastN);
  683. });
  684. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  685. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  686. });
  687. if(conference.statistics) {
  688. //FIXME: Maybe remove event should not be associated with the conference.
  689. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  690. var userId = null;
  691. var jid = conference.room.getJidBySSRC(ssrc);
  692. if (!jid)
  693. return;
  694. conference.rtc.setAudioLevel(jid, level);
  695. });
  696. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  697. function () {
  698. conference.statistics.dispose();
  699. });
  700. // FIXME: Maybe we should move this.
  701. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  702. // conference.room.updateDeviceAvailability(devices);
  703. // });
  704. }
  705. }
  706. module.exports = JitsiConference;
  707. }).call(this,"/JitsiConference.js")
  708. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":80,"./service/authentication/AuthenticationEvents":83,"./service/xmpp/XMPPEvents":87,"events":44,"jitsi-meet-logger":48}],2:[function(require,module,exports){
  709. /**
  710. * Enumeration with the errors for the conference.
  711. * @type {{string: string}}
  712. */
  713. var JitsiConferenceErrors = {
  714. /**
  715. * Indicates that a password is required in order to join the conference.
  716. */
  717. PASSWORD_REQUIRED: "conference.passwordRequired",
  718. /**
  719. * Indicates that client must be authenticated to create the conference.
  720. */
  721. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  722. /**
  723. * Indicates that password cannot be set for this conference.
  724. */
  725. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  726. /**
  727. * Indicates that a connection error occurred when trying to join a
  728. * conference.
  729. */
  730. CONNECTION_ERROR: "conference.connectionError",
  731. /**
  732. * Indicates that the conference setup failed.
  733. */
  734. SETUP_FAILED: "conference.setup_failed",
  735. /**
  736. * Indicates that there is no available videobridge.
  737. */
  738. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  739. /**
  740. * Many more errors TBD here.
  741. */
  742. };
  743. module.exports = JitsiConferenceErrors;
  744. },{}],3:[function(require,module,exports){
  745. /**
  746. * Enumeration with the events for the conference.
  747. * @type {{string: string}}
  748. */
  749. var JitsiConferenceEvents = {
  750. /**
  751. * A new media track was added to the conference.
  752. */
  753. TRACK_ADDED: "conference.trackAdded",
  754. /**
  755. * The media track was removed from the conference.
  756. */
  757. TRACK_REMOVED: "conference.trackRemoved",
  758. /**
  759. * The active speaker was changed.
  760. */
  761. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  762. /**
  763. * A new user joinned the conference.
  764. */
  765. USER_JOINED: "conference.userJoined",
  766. /**
  767. * A user has left the conference.
  768. */
  769. USER_LEFT: "conference.userLeft",
  770. /**
  771. * User role changed.
  772. */
  773. USER_ROLE_CHANGED: "conference.roleChanged",
  774. /**
  775. * New text message was received.
  776. */
  777. MESSAGE_RECEIVED: "conference.messageReceived",
  778. /**
  779. * A user has changed it display name
  780. */
  781. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  782. /**
  783. * A participant avatar has changed.
  784. */
  785. AVATAR_CHANGED: "conference.avatarChanged",
  786. /**
  787. * New connection statistics are received.
  788. */
  789. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  790. /**
  791. * The Last N set is changed.
  792. */
  793. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  794. /**
  795. * You are included / excluded in somebody's last N set
  796. */
  797. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  798. /**
  799. * A media track ( attached to the conference) mute status was changed.
  800. */
  801. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  802. /**
  803. * Audio levels of a media track ( attached to the conference) was changed.
  804. */
  805. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  806. /**
  807. * Indicates that the connection to the conference has been interrupted
  808. * for some reason.
  809. */
  810. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  811. /**
  812. * Indicates that the connection to the conference has been restored.
  813. */
  814. CONNECTION_RESTORED: "conference.connectionRestored",
  815. /**
  816. * Indicates that conference failed.
  817. */
  818. CONFERENCE_FAILED: "conference.failed",
  819. /**
  820. * Indicates that conference has been joined.
  821. */
  822. CONFERENCE_JOINED: "conference.joined",
  823. /**
  824. * Indicates that conference has been left.
  825. */
  826. CONFERENCE_LEFT: "conference.left",
  827. /**
  828. * You are kicked from the conference.
  829. */
  830. KICKED: "conferenece.kicked",
  831. /**
  832. * Indicates that DTMF support changed.
  833. */
  834. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  835. /**
  836. * Indicates that recording state changed.
  837. */
  838. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  839. /**
  840. * Indicates that phone number changed.
  841. */
  842. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  843. };
  844. module.exports = JitsiConferenceEvents;
  845. },{}],4:[function(require,module,exports){
  846. var JitsiConference = require("./JitsiConference");
  847. var XMPP = require("./modules/xmpp/xmpp");
  848. /**
  849. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  850. * JitsiConference interface.
  851. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  852. * @param token the JWT token used to authenticate with the server(optional)
  853. * @param options Object with properties / settings related to connection with the server.
  854. * @constructor
  855. */
  856. function JitsiConnection(appID, token, options) {
  857. this.appID = appID;
  858. this.token = token;
  859. this.options = options;
  860. this.xmpp = new XMPP(options);
  861. this.conferences = {};
  862. }
  863. /**
  864. * Connect the client with the server.
  865. * @param options {object} connecting options (for example authentications parameters).
  866. */
  867. JitsiConnection.prototype.connect = function (options) {
  868. if(!options)
  869. options = {};
  870. this.xmpp.connect(options.id, options.password);
  871. }
  872. /**
  873. * Disconnect the client from the server.
  874. */
  875. JitsiConnection.prototype.disconnect = function () {
  876. this.xmpp.disconnect();
  877. }
  878. /**
  879. * This method allows renewal of the tokens if they are expiring.
  880. * @param token the new token.
  881. */
  882. JitsiConnection.prototype.setToken = function (token) {
  883. this.token = token;
  884. }
  885. /**
  886. * Creates and joins new conference.
  887. * @param name the name of the conference; if null - a generated name will be
  888. * provided from the api
  889. * @param options Object with properties / settings related to the conference
  890. * that will be created.
  891. * @returns {JitsiConference} returns the new conference object.
  892. */
  893. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  894. this.conferences[name] = new JitsiConference({name: name, config: options,
  895. connection: this});
  896. return this.conferences[name];
  897. }
  898. /**
  899. * Subscribes the passed listener to the event.
  900. * @param event {JitsiConnectionEvents} the connection event.
  901. * @param listener {Function} the function that will receive the event
  902. */
  903. JitsiConnection.prototype.addEventListener = function (event, listener) {
  904. this.xmpp.addListener(event, listener);
  905. }
  906. /**
  907. * Unsubscribes the passed handler.
  908. * @param event {JitsiConnectionEvents} the connection event.
  909. * @param listener {Function} the function that will receive the event
  910. */
  911. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  912. this.xmpp.removeListener(event, listener);
  913. }
  914. module.exports = JitsiConnection;
  915. },{"./JitsiConference":1,"./modules/xmpp/xmpp":42}],5:[function(require,module,exports){
  916. /**
  917. * Enumeration with the errors for the connection.
  918. * @type {{string: string}}
  919. */
  920. var JitsiConnectionErrors = {
  921. /**
  922. * Indicates that a password is required in order to join the conference.
  923. */
  924. PASSWORD_REQUIRED: "connection.passwordRequired",
  925. /**
  926. * Indicates that a connection error occurred when trying to join a
  927. * conference.
  928. */
  929. CONNECTION_ERROR: "connection.connectionError",
  930. /**
  931. * Not specified errors.
  932. */
  933. OTHER_ERROR: "connection.otherError"
  934. };
  935. module.exports = JitsiConnectionErrors;
  936. },{}],6:[function(require,module,exports){
  937. /**
  938. * Enumeration with the events for the connection.
  939. * @type {{string: string}}
  940. */
  941. var JitsiConnnectionEvents = {
  942. /**
  943. * Indicates that the connection has been failed for some reason.
  944. */
  945. CONNECTION_FAILED: "connection.connectionFailed",
  946. /**
  947. * Indicates that the connection has been established.
  948. */
  949. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  950. /**
  951. * Indicates that the connection has been disconnected.
  952. */
  953. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  954. /**
  955. * Indicates that the perfomed action cannot be executed because the
  956. * connection is not in the correct state(connected, disconnected, etc.)
  957. */
  958. WRONG_STATE: "connection.wrongState"
  959. };
  960. module.exports = JitsiConnnectionEvents;
  961. },{}],7:[function(require,module,exports){
  962. var JitsiConnection = require("./JitsiConnection");
  963. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  964. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  965. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  966. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  967. var JitsiTrackEvents = require("./JitsiTrackEvents");
  968. var JitsiTrackErrors = require("./JitsiTrackErrors");
  969. var Logger = require("jitsi-meet-logger");
  970. var RTC = require("./modules/RTC/RTC");
  971. var Statistics = require("./modules/statistics/statistics");
  972. /**
  973. * Namespace for the interface of Jitsi Meet Library.
  974. */
  975. var LibJitsiMeet = {
  976. JitsiConnection: JitsiConnection,
  977. events: {
  978. conference: JitsiConferenceEvents,
  979. connection: JitsiConnectionEvents,
  980. track: JitsiTrackEvents
  981. },
  982. errors: {
  983. conference: JitsiConferenceErrors,
  984. connection: JitsiConnectionErrors,
  985. track: JitsiTrackErrors
  986. },
  987. logLevels: Logger.levels,
  988. init: function (options) {
  989. return RTC.init(options || {});
  990. },
  991. /**
  992. * Returns whether the desktop sharing is enabled or not.
  993. * @returns {boolean}
  994. */
  995. isDesktopSharingEnabled: function () {
  996. return RTC.isDesktopSharingEnabled();
  997. },
  998. setLogLevel: function (level) {
  999. Logger.setLogLevel(level);
  1000. },
  1001. /**
  1002. * Creates the media tracks and returns them trough the callback.
  1003. * @param options Object with properties / settings specifying the tracks which should be created.
  1004. * should be created or some additional configurations about resolution for example.
  1005. * @param {Array} options.devices the devices that will be requested
  1006. * @param {string} options.resolution resolution constraints
  1007. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1008. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1009. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1010. * @param {string} options.cameraDeviceId
  1011. * @param {string} options.micDeviceId
  1012. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1013. * A promise that returns an array of created JitsiTracks if resolved,
  1014. * or a JitsiConferenceError if rejected.
  1015. */
  1016. createLocalTracks: function (options) {
  1017. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1018. function(tracks) {
  1019. if(!RTC.options.disableAudioLevels)
  1020. for(var i = 0; i < tracks.length; i++) {
  1021. var track = tracks[i];
  1022. var mStream = track.getOriginalStream();
  1023. if(track.getType() === "audio"){
  1024. Statistics.startLocalStats(mStream,
  1025. track.setAudioLevel.bind(track));
  1026. track.addEventListener(
  1027. JitsiTrackEvents.TRACK_STOPPED,
  1028. function(){
  1029. Statistics.stopLocalStats(mStream);
  1030. });
  1031. }
  1032. }
  1033. return tracks;
  1034. });
  1035. },
  1036. /**
  1037. * Checks if its possible to enumerate available cameras/micropones.
  1038. * @returns {boolean} true if available, false otherwise.
  1039. */
  1040. isDeviceListAvailable: function () {
  1041. return RTC.isDeviceListAvailable();
  1042. },
  1043. /**
  1044. * Returns true if changing the camera / microphone device is supported and
  1045. * false if not.
  1046. * @returns {boolean} true if available, false otherwise.
  1047. */
  1048. isDeviceChangeAvailable: function () {
  1049. return RTC.isDeviceChangeAvailable();
  1050. },
  1051. enumerateDevices: function (callback) {
  1052. RTC.enumerateDevices(callback);
  1053. }
  1054. };
  1055. require("es6-promise").polyfill()
  1056. //Setups the promise object.
  1057. window.Promise = window.Promise || require("es6-promise").Promise;
  1058. module.exports = LibJitsiMeet;
  1059. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"es6-promise":46,"jitsi-meet-logger":48}],8:[function(require,module,exports){
  1060. /* global Strophe */
  1061. /**
  1062. * Represents a participant in (a member of) a conference.
  1063. */
  1064. function JitsiParticipant(jid, conference, displayName){
  1065. this._jid = jid;
  1066. this._id = Strophe.getResourceFromJid(jid);
  1067. this._conference = conference;
  1068. this._displayName = displayName;
  1069. this._supportsDTMF = false;
  1070. this._tracks = [];
  1071. this._role = 'none';
  1072. }
  1073. /**
  1074. * @returns {JitsiConference} The conference that this participant belongs to.
  1075. */
  1076. JitsiParticipant.prototype.getConference = function() {
  1077. return this._conference;
  1078. };
  1079. /**
  1080. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1081. */
  1082. JitsiParticipant.prototype.getTracks = function() {
  1083. return this._tracks;
  1084. };
  1085. /**
  1086. * @returns {String} The ID of this participant.
  1087. */
  1088. JitsiParticipant.prototype.getId = function() {
  1089. return this._id;
  1090. };
  1091. /**
  1092. * @returns {String} The JID of this participant.
  1093. */
  1094. JitsiParticipant.prototype.getJid = function() {
  1095. return this._jid;
  1096. };
  1097. /**
  1098. * @returns {String} The human-readable display name of this participant.
  1099. */
  1100. JitsiParticipant.prototype.getDisplayName = function() {
  1101. return this._displayName;
  1102. };
  1103. /**
  1104. * @returns {Boolean} Whether this participant is a moderator or not.
  1105. */
  1106. JitsiParticipant.prototype.isModerator = function() {
  1107. return this._role === 'moderator';
  1108. };
  1109. // Gets a link to an etherpad instance advertised by the participant?
  1110. //JitsiParticipant.prototype.getEtherpad = function() {
  1111. //
  1112. //}
  1113. /*
  1114. * @returns {Boolean} Whether this participant has muted their audio.
  1115. */
  1116. JitsiParticipant.prototype.isAudioMuted = function() {
  1117. return this.getTracks().reduce(function (track, isAudioMuted) {
  1118. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1119. }, true);
  1120. };
  1121. /*
  1122. * @returns {Boolean} Whether this participant has muted their video.
  1123. */
  1124. JitsiParticipant.prototype.isVideoMuted = function() {
  1125. return this.getTracks().reduce(function (track, isVideoMuted) {
  1126. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1127. }, true);
  1128. };
  1129. /*
  1130. * @returns {???} The latest statistics reported by this participant
  1131. * (i.e. info used to populate the GSM bars)
  1132. * TODO: do we expose this or handle it internally?
  1133. */
  1134. JitsiParticipant.prototype.getLatestStats = function() {
  1135. };
  1136. /**
  1137. * @returns {String} The role of this participant.
  1138. */
  1139. JitsiParticipant.prototype.getRole = function() {
  1140. return this._role;
  1141. };
  1142. /*
  1143. * @returns {Boolean} Whether this participant is
  1144. * the conference focus (i.e. jicofo).
  1145. */
  1146. JitsiParticipant.prototype.isFocus = function() {
  1147. };
  1148. /*
  1149. * @returns {Boolean} Whether this participant is
  1150. * a conference recorder (i.e. jirecon).
  1151. */
  1152. JitsiParticipant.prototype.isRecorder = function() {
  1153. };
  1154. /*
  1155. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1156. */
  1157. JitsiParticipant.prototype.isSipGateway = function() {
  1158. };
  1159. /**
  1160. * @returns {Boolean} Whether this participant
  1161. * is currently sharing their screen.
  1162. */
  1163. JitsiParticipant.prototype.isScreenSharing = function() {
  1164. };
  1165. /**
  1166. * @returns {String} The user agent of this participant
  1167. * (i.e. browser userAgent string).
  1168. */
  1169. JitsiParticipant.prototype.getUserAgent = function() {
  1170. };
  1171. /**
  1172. * Kicks the participant from the conference (requires certain privileges).
  1173. */
  1174. JitsiParticipant.prototype.kick = function() {
  1175. };
  1176. /**
  1177. * Asks this participant to mute themselves.
  1178. */
  1179. JitsiParticipant.prototype.askToMute = function() {
  1180. };
  1181. JitsiParticipant.prototype.supportsDTMF = function () {
  1182. return this._supportsDTMF;
  1183. };
  1184. module.exports = JitsiParticipant;
  1185. },{}],9:[function(require,module,exports){
  1186. module.exports = {
  1187. /**
  1188. * Returns JitsiTrackErrors based on the error object passed by GUM
  1189. * @param error the error
  1190. * @param {Object} options the options object given to GUM.
  1191. */
  1192. parseError: function (error, options) {
  1193. options = options || {};
  1194. if (typeof error == "object" && error.constraintName && error.name
  1195. && (error.name == "ConstraintNotSatisfiedError" ||
  1196. error.name == "OverconstrainedError") &&
  1197. (error.constraintName == "minWidth" ||
  1198. error.constraintName == "maxWidth" ||
  1199. error.constraintName == "minHeight" ||
  1200. error.constraintName == "maxHeight") &&
  1201. options.devices.indexOf("video") !== -1) {
  1202. return this.UNSUPPORTED_RESOLUTION;
  1203. } else {
  1204. return this.GENERAL;
  1205. }
  1206. },
  1207. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1208. GENERAL: "gum.general"
  1209. };
  1210. },{}],10:[function(require,module,exports){
  1211. var JitsiTrackEvents = {
  1212. /**
  1213. * A media track mute status was changed.
  1214. */
  1215. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1216. /**
  1217. * Audio levels of a this track was changed.
  1218. */
  1219. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1220. /**
  1221. * The media track was removed to the conference.
  1222. */
  1223. TRACK_STOPPED: "track.stopped"
  1224. };
  1225. module.exports = JitsiTrackEvents;
  1226. },{}],11:[function(require,module,exports){
  1227. (function (__filename){
  1228. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1229. function JitsiDTMFManager (localAudio, peerConnection) {
  1230. var tracks = localAudio._getTracks();
  1231. if (!tracks.length) {
  1232. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1233. }
  1234. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1235. logger.debug("Initialized DTMFSender");
  1236. }
  1237. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1238. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1239. };
  1240. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1241. },{"jitsi-meet-logger":48}],12:[function(require,module,exports){
  1242. (function (__filename){
  1243. /* global config, APP, Strophe */
  1244. // cache datachannels to avoid garbage collection
  1245. // https://code.google.com/p/chromium/issues/detail?id=405545
  1246. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1247. var RTCEvents = require("../../service/RTC/RTCEvents");
  1248. /**
  1249. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1250. * @param peerConnection WebRTC peer connection instance.
  1251. */
  1252. function DataChannels(peerConnection, emitter) {
  1253. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1254. this.eventEmitter = emitter;
  1255. this._dataChannels = [];
  1256. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1257. // Although it's not a requirement to open separate channels from both bridge
  1258. // and peer as single channel can be used for sending and receiving data.
  1259. // So either channel opened by the bridge or the one opened here is enough
  1260. // for communication with the bridge.
  1261. /*var dataChannelOptions =
  1262. {
  1263. reliable: true
  1264. };
  1265. var dataChannel
  1266. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1267. // Can be used only when is in open state
  1268. dataChannel.onopen = function ()
  1269. {
  1270. dataChannel.send("My channel !!!");
  1271. };
  1272. dataChannel.onmessage = function (event)
  1273. {
  1274. var msgData = event.data;
  1275. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1276. };*/
  1277. };
  1278. /**
  1279. * Callback triggered by PeerConnection when new data channel is opened
  1280. * on the bridge.
  1281. * @param event the event info object.
  1282. */
  1283. DataChannels.prototype.onDataChannel = function (event) {
  1284. var dataChannel = event.channel;
  1285. var self = this;
  1286. dataChannel.onopen = function () {
  1287. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1288. // Code sample for sending string and/or binary data
  1289. // Sends String message to the bridge
  1290. //dataChannel.send("Hello bridge!");
  1291. // Sends 12 bytes binary message to the bridge
  1292. //dataChannel.send(new ArrayBuffer(12));
  1293. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1294. };
  1295. dataChannel.onerror = function (error) {
  1296. logger.error("Data Channel Error:", error, dataChannel);
  1297. };
  1298. dataChannel.onmessage = function (event) {
  1299. var data = event.data;
  1300. // JSON
  1301. var obj;
  1302. try {
  1303. obj = JSON.parse(data);
  1304. }
  1305. catch (e) {
  1306. logger.error(
  1307. "Failed to parse data channel message as JSON: ",
  1308. data,
  1309. dataChannel);
  1310. }
  1311. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1312. var colibriClass = obj.colibriClass;
  1313. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1314. // Endpoint ID from the Videobridge.
  1315. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1316. logger.info(
  1317. "Data channel new dominant speaker event: ",
  1318. dominantSpeakerEndpoint);
  1319. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1320. }
  1321. else if ("InLastNChangeEvent" === colibriClass) {
  1322. var oldValue = obj.oldValue;
  1323. var newValue = obj.newValue;
  1324. // Make sure that oldValue and newValue are of type boolean.
  1325. var type;
  1326. if ((type = typeof oldValue) !== 'boolean') {
  1327. if (type === 'string') {
  1328. oldValue = (oldValue == "true");
  1329. } else {
  1330. oldValue = new Boolean(oldValue).valueOf();
  1331. }
  1332. }
  1333. if ((type = typeof newValue) !== 'boolean') {
  1334. if (type === 'string') {
  1335. newValue = (newValue == "true");
  1336. } else {
  1337. newValue = new Boolean(newValue).valueOf();
  1338. }
  1339. }
  1340. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1341. }
  1342. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1343. // The new/latest list of last-n endpoint IDs.
  1344. var lastNEndpoints = obj.lastNEndpoints;
  1345. // The list of endpoint IDs which are entering the list of
  1346. // last-n at this time i.e. were not in the old list of last-n
  1347. // endpoint IDs.
  1348. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1349. logger.info(
  1350. "Data channel new last-n event: ",
  1351. lastNEndpoints, endpointsEnteringLastN, obj);
  1352. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1353. lastNEndpoints, endpointsEnteringLastN, obj);
  1354. }
  1355. else {
  1356. logger.debug("Data channel JSON-formatted message: ", obj);
  1357. // The received message appears to be appropriately formatted
  1358. // (i.e. is a JSON object which assigns a value to the mandatory
  1359. // property colibriClass) so don't just swallow it, expose it to
  1360. // public consumption.
  1361. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1362. }
  1363. }
  1364. };
  1365. dataChannel.onclose = function () {
  1366. logger.info("The Data Channel closed", dataChannel);
  1367. var idx = self._dataChannels.indexOf(dataChannel);
  1368. if (idx > -1)
  1369. self._dataChannels = self._dataChannels.splice(idx, 1);
  1370. };
  1371. this._dataChannels.push(dataChannel);
  1372. };
  1373. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1374. this._onXXXEndpointChanged("selected", userResource);
  1375. }
  1376. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1377. this._onXXXEndpointChanged("pinnned", userResource);
  1378. }
  1379. /**
  1380. * Notifies Videobridge about a change in the value of a specific
  1381. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1382. *
  1383. * @param xxx the name of the endpoint-related property whose value changed
  1384. * @param userResource the new value of the endpoint-related property after the
  1385. * change
  1386. */
  1387. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1388. // Derive the correct words from xxx such as selected and Selected, pinned
  1389. // and Pinned.
  1390. var head = xxx.charAt(0);
  1391. var tail = xxx.substring(1);
  1392. var lower = head.toLowerCase() + tail;
  1393. var upper = head.toUpperCase() + tail;
  1394. // Notify Videobridge about the specified endpoint change.
  1395. console.log(lower + ' endpoint changed: ', userResource);
  1396. this._some(function (dataChannel) {
  1397. if (dataChannel.readyState == 'open') {
  1398. console.log(
  1399. 'sending ' + lower
  1400. + ' endpoint changed notification to the bridge: ',
  1401. userResource);
  1402. var jsonObject = {};
  1403. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1404. jsonObject[lower + "Endpoint"]
  1405. = (userResource ? userResource : null);
  1406. dataChannel.send(JSON.stringify(jsonObject));
  1407. return true;
  1408. }
  1409. });
  1410. }
  1411. DataChannels.prototype._some = function (callback, thisArg) {
  1412. var dataChannels = this._dataChannels;
  1413. if (dataChannels && dataChannels.length !== 0) {
  1414. if (thisArg)
  1415. return dataChannels.some(callback, thisArg);
  1416. else
  1417. return dataChannels.some(callback);
  1418. } else {
  1419. return false;
  1420. }
  1421. }
  1422. module.exports = DataChannels;
  1423. }).call(this,"/modules/RTC/DataChannels.js")
  1424. },{"../../service/RTC/RTCEvents":80,"jitsi-meet-logger":48}],13:[function(require,module,exports){
  1425. var JitsiTrack = require("./JitsiTrack");
  1426. var RTCBrowserType = require("./RTCBrowserType");
  1427. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1428. var RTC = require("./RTCUtils");
  1429. /**
  1430. * Represents a single media track (either audio or video).
  1431. * @constructor
  1432. */
  1433. function JitsiLocalTrack(stream, videoType,
  1434. resolution)
  1435. {
  1436. this.videoType = videoType;
  1437. this.dontFireRemoveEvent = false;
  1438. this.resolution = resolution;
  1439. this.startMuted = false;
  1440. var self = this;
  1441. JitsiTrack.call(this, null, stream,
  1442. function () {
  1443. if(!this.dontFireRemoveEvent)
  1444. this.eventEmitter.emit(
  1445. JitsiTrackEvents.TRACK_STOPPED);
  1446. this.dontFireRemoveEvent = false;
  1447. }.bind(this));
  1448. }
  1449. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1450. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1451. /**
  1452. * Mutes / unmutes the track.
  1453. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1454. */
  1455. JitsiLocalTrack.prototype._setMute = function (mute) {
  1456. if(!this.rtc) {
  1457. this.startMuted = mute;
  1458. return;
  1459. }
  1460. var isAudio = this.type === JitsiTrack.AUDIO;
  1461. this.dontFireRemoveEvent = false;
  1462. if ((window.location.protocol != "https:") ||
  1463. (isAudio) || this.videoType === "desktop" ||
  1464. // FIXME FF does not support 'removeStream' method used to mute
  1465. RTCBrowserType.isFirefox()) {
  1466. var tracks = this._getTracks();
  1467. for (var idx = 0; idx < tracks.length; idx++) {
  1468. tracks[idx].enabled = !mute;
  1469. }
  1470. if(isAudio)
  1471. this.rtc.room.setAudioMute(mute);
  1472. else
  1473. this.rtc.room.setVideoMute(mute);
  1474. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1475. } else {
  1476. if (mute) {
  1477. this.dontFireRemoveEvent = true;
  1478. this.rtc.room.removeStream(this.stream, function () {});
  1479. RTC.stopMediaStream(this.stream);
  1480. if(isAudio)
  1481. this.rtc.room.setAudioMute(mute);
  1482. else
  1483. this.rtc.room.setVideoMute(mute);
  1484. this.stream = null;
  1485. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1486. //FIXME: Maybe here we should set the SRC for the containers to something
  1487. } else {
  1488. var self = this;
  1489. RTC.obtainAudioAndVideoPermissions({
  1490. devices: (isAudio ? ["audio"] : ["video"]),
  1491. resolution: self.resolution})
  1492. .then(function (streams) {
  1493. var stream = null;
  1494. for(var i = 0; i < streams.length; i++) {
  1495. stream = streams[i];
  1496. if(stream.type === self.type) {
  1497. self.stream = stream.stream;
  1498. self.videoType = stream.videoType;
  1499. break;
  1500. }
  1501. }
  1502. if(!stream)
  1503. return;
  1504. for(var i = 0; i < self.containers.length; i++)
  1505. {
  1506. RTC.attachMediaStream(self.containers[i], self.stream);
  1507. }
  1508. self.rtc.room.addStream(stream.stream,
  1509. function () {
  1510. if(isAudio)
  1511. self.rtc.room.setAudioMute(mute);
  1512. else
  1513. self.rtc.room.setVideoMute(mute);
  1514. self.eventEmitter.emit(
  1515. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1516. });
  1517. });
  1518. }
  1519. }
  1520. }
  1521. /**
  1522. * Stops sending the media track. And removes it from the HTML.
  1523. * NOTE: Works for local tracks only.
  1524. */
  1525. JitsiLocalTrack.prototype.stop = function () {
  1526. if(!this.stream)
  1527. return;
  1528. if(this.rtc)
  1529. this.rtc.room.removeStream(this.stream, function () {});
  1530. RTC.stopMediaStream(this.stream);
  1531. this.detach();
  1532. }
  1533. /**
  1534. * Returns <tt>true</tt> - if the stream is muted
  1535. * and <tt>false</tt> otherwise.
  1536. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1537. * and <tt>false</tt> otherwise.
  1538. */
  1539. JitsiLocalTrack.prototype.isMuted = function () {
  1540. if (!this.stream)
  1541. return true;
  1542. var tracks = [];
  1543. var isAudio = this.type === JitsiTrack.AUDIO;
  1544. if (isAudio) {
  1545. tracks = this.stream.getAudioTracks();
  1546. } else {
  1547. if (!this.isActive())
  1548. return true;
  1549. tracks = this.stream.getVideoTracks();
  1550. }
  1551. for (var idx = 0; idx < tracks.length; idx++) {
  1552. if(tracks[idx].enabled)
  1553. return false;
  1554. }
  1555. return true;
  1556. };
  1557. /**
  1558. * Private method. Updates rtc property of the track.
  1559. * @param rtc the rtc instance.
  1560. */
  1561. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1562. this.rtc = rtc;
  1563. };
  1564. /**
  1565. * Return true;
  1566. */
  1567. JitsiLocalTrack.prototype.isLocal = function () {
  1568. return true;
  1569. }
  1570. module.exports = JitsiLocalTrack;
  1571. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1572. var JitsiTrack = require("./JitsiTrack");
  1573. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1574. /**
  1575. * Represents a single media track (either audio or video).
  1576. * @param RTC the rtc instance.
  1577. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1578. * @param sid sid for the Media Stream
  1579. * @param ssrc ssrc for the Media Stream
  1580. * @param eventEmitter the event emitter
  1581. * @constructor
  1582. */
  1583. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1584. JitsiTrack.call(this, RTC, data.stream,
  1585. function () {
  1586. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1587. }.bind(this));
  1588. this.rtc = RTC;
  1589. this.sid = sid;
  1590. this.stream = data.stream;
  1591. this.peerjid = data.peerjid;
  1592. this.videoType = data.videoType;
  1593. this.ssrc = ssrc;
  1594. this.muted = false;
  1595. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1596. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1597. this.muted = true;
  1598. }
  1599. }
  1600. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1601. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1602. /**
  1603. * Sets current muted status and fires an events for the change.
  1604. * @param value the muted status.
  1605. */
  1606. JitsiRemoteTrack.prototype.setMute = function (value) {
  1607. this.stream.muted = value;
  1608. this.muted = value;
  1609. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1610. };
  1611. /**
  1612. * Returns the current muted status of the track.
  1613. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1614. */
  1615. JitsiRemoteTrack.prototype.isMuted = function () {
  1616. return this.muted;
  1617. };
  1618. /**
  1619. * Returns the participant id which owns the track.
  1620. * @returns {string} the id of the participants.
  1621. */
  1622. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1623. return Strophe.getResourceFromJid(this.peerjid);
  1624. };
  1625. /**
  1626. * Return false;
  1627. */
  1628. JitsiRemoteTrack.prototype.isLocal = function () {
  1629. return false;
  1630. };
  1631. delete JitsiRemoteTrack.prototype.stop;
  1632. delete JitsiRemoteTrack.prototype.start;
  1633. module.exports = JitsiRemoteTrack;
  1634. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1635. var RTCBrowserType = require("./RTCBrowserType");
  1636. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1637. var EventEmitter = require("events");
  1638. var RTC = require("./RTCUtils");
  1639. /**
  1640. * This implements 'onended' callback normally fired by WebRTC after the stream
  1641. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1642. * @param jitsiTrack our track object holding the original WebRTC stream object
  1643. * to which 'onended' handling will be added.
  1644. */
  1645. function implementOnEndedHandling(jitsiTrack) {
  1646. var stream = jitsiTrack.getOriginalStream();
  1647. var originalStop = stream.stop;
  1648. stream.stop = function () {
  1649. originalStop.apply(stream);
  1650. if (jitsiTrack.isActive()) {
  1651. stream.onended();
  1652. }
  1653. };
  1654. }
  1655. /**
  1656. * Adds onended/oninactive handler to a MediaStream.
  1657. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1658. * @param handler the handler
  1659. */
  1660. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1661. if(RTCBrowserType.isTemasysPluginUsed()) {
  1662. // themasys
  1663. //FIXME: Seems that not working properly.
  1664. if(mediaStream.onended) {
  1665. mediaStream.onended = handler;
  1666. } else if(mediaStream.addEventListener) {
  1667. mediaStream.addEventListener('ended', function () {
  1668. handler(mediaStream);
  1669. });
  1670. } else if(mediaStream.attachEvent) {
  1671. mediaStream.attachEvent('ended', function () {
  1672. handler(mediaStream);
  1673. });
  1674. }
  1675. }
  1676. else {
  1677. if(typeof mediaStream.active !== "undefined")
  1678. mediaStream.oninactive = handler;
  1679. else
  1680. mediaStream.onended = handler;
  1681. }
  1682. }
  1683. /**
  1684. * Represents a single media track (either audio or video).
  1685. * @constructor
  1686. * @param rtc the rtc instance
  1687. * @param stream the stream
  1688. * @param streamInactiveHandler the function that will handle
  1689. * onended/oninactive events of the stream.
  1690. */
  1691. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1692. {
  1693. /**
  1694. * Array with the HTML elements that are displaying the streams.
  1695. * @type {Array}
  1696. */
  1697. this.containers = [];
  1698. this.rtc = rtc;
  1699. this.stream = stream;
  1700. this.eventEmitter = new EventEmitter();
  1701. this.audioLevel = -1;
  1702. this.type = (this.stream.getVideoTracks().length > 0)?
  1703. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1704. if(this.type == "audio") {
  1705. this._getTracks = function () {
  1706. return this.stream.getAudioTracks();
  1707. }.bind(this);
  1708. } else {
  1709. this._getTracks = function () {
  1710. return this.stream.getVideoTracks();
  1711. }.bind(this);
  1712. }
  1713. if (RTCBrowserType.isFirefox() && this.stream) {
  1714. implementOnEndedHandling(this);
  1715. }
  1716. if(stream)
  1717. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1718. }
  1719. /**
  1720. * JitsiTrack video type.
  1721. * @type {string}
  1722. */
  1723. JitsiTrack.VIDEO = "video";
  1724. /**
  1725. * JitsiTrack audio type.
  1726. * @type {string}
  1727. */
  1728. JitsiTrack.AUDIO = "audio";
  1729. /**
  1730. * Returns the type (audio or video) of this track.
  1731. */
  1732. JitsiTrack.prototype.getType = function() {
  1733. return this.type;
  1734. };
  1735. /**
  1736. * Check if this is audiotrack.
  1737. */
  1738. JitsiTrack.prototype.isAudioTrack = function () {
  1739. return this.getType() === JitsiTrack.AUDIO;
  1740. };
  1741. /**
  1742. * Check if this is videotrack.
  1743. */
  1744. JitsiTrack.prototype.isVideoTrack = function () {
  1745. return this.getType() === JitsiTrack.VIDEO;
  1746. };
  1747. /**
  1748. * Returns the RTCMediaStream from the browser (?).
  1749. */
  1750. JitsiTrack.prototype.getOriginalStream = function() {
  1751. return this.stream;
  1752. }
  1753. /**
  1754. * Mutes the track.
  1755. */
  1756. JitsiTrack.prototype.mute = function () {
  1757. this._setMute(true);
  1758. }
  1759. /**
  1760. * Unmutes the stream.
  1761. */
  1762. JitsiTrack.prototype.unmute = function () {
  1763. this._setMute(false);
  1764. }
  1765. /**
  1766. * Attaches the MediaStream of this track to an HTML container (?).
  1767. * Adds the container to the list of containers that are displaying the track.
  1768. * @param container the HTML container
  1769. */
  1770. JitsiTrack.prototype.attach = function (container) {
  1771. if(this.stream)
  1772. require("./RTCUtils").attachMediaStream(container, this.stream);
  1773. this.containers.push(container);
  1774. }
  1775. /**
  1776. * Removes the track from the passed HTML container.
  1777. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1778. */
  1779. JitsiTrack.prototype.detach = function (container) {
  1780. for(var i = 0; i < this.containers.length; i++)
  1781. {
  1782. if(this.containers[i].is(container))
  1783. {
  1784. this.containers.splice(i,1);
  1785. }
  1786. if(!container)
  1787. {
  1788. this.containers[i].find(">video").remove();
  1789. }
  1790. }
  1791. if(container)
  1792. $(container).find(">video").remove();
  1793. }
  1794. /**
  1795. * Stops sending the media track. And removes it from the HTML.
  1796. * NOTE: Works for local tracks only.
  1797. */
  1798. JitsiTrack.prototype.stop = function () {
  1799. }
  1800. /**
  1801. * Returns true if this is a video track and the source of the video is a
  1802. * screen capture as opposed to a camera.
  1803. */
  1804. JitsiTrack.prototype.isScreenSharing = function(){
  1805. }
  1806. /**
  1807. * Returns id of the track.
  1808. * @returns {string} id of the track or null if this is fake track.
  1809. */
  1810. JitsiTrack.prototype._getId = function () {
  1811. var tracks = this.stream.getTracks();
  1812. if(!tracks || tracks.length === 0)
  1813. return null;
  1814. return tracks[0].id;
  1815. };
  1816. /**
  1817. * Returns id of the track.
  1818. * @returns {string} id of the track or null if this is fake track.
  1819. */
  1820. JitsiTrack.prototype.getId = function () {
  1821. return RTC.getStreamID(this.stream);
  1822. };
  1823. /**
  1824. * Checks whether the MediaStream is avtive/not ended.
  1825. * When there is no check for active we don't have information and so
  1826. * will return that stream is active (in case of FF).
  1827. * @returns {boolean} whether MediaStream is active.
  1828. */
  1829. JitsiTrack.prototype.isActive = function () {
  1830. if((typeof this.stream.active !== "undefined"))
  1831. return this.stream.active;
  1832. else
  1833. return true;
  1834. };
  1835. /**
  1836. * Attaches a handler for events(For example - "audio level changed".).
  1837. * All possible event are defined in JitsiTrackEvents.
  1838. * @param eventId the event ID.
  1839. * @param handler handler for the event.
  1840. */
  1841. JitsiTrack.prototype.on = function (eventId, handler) {
  1842. if(this.eventEmitter)
  1843. this.eventEmitter.on(eventId, handler);
  1844. }
  1845. /**
  1846. * Removes event listener
  1847. * @param eventId the event ID.
  1848. * @param [handler] optional, the specific handler to unbind
  1849. */
  1850. JitsiTrack.prototype.off = function (eventId, handler) {
  1851. if(this.eventEmitter)
  1852. this.eventEmitter.removeListener(eventId, handler);
  1853. }
  1854. // Common aliases for event emitter
  1855. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1856. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1857. /**
  1858. * Sets the audio level for the stream
  1859. * @param audioLevel the new audio level
  1860. */
  1861. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  1862. if(this.audioLevel !== audioLevel) {
  1863. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1864. audioLevel);
  1865. this.audioLevel = audioLevel;
  1866. }
  1867. }
  1868. module.exports = JitsiTrack;
  1869. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":44}],16:[function(require,module,exports){
  1870. /* global APP */
  1871. var EventEmitter = require("events");
  1872. var RTCBrowserType = require("./RTCBrowserType");
  1873. var RTCUtils = require("./RTCUtils.js");
  1874. var JitsiTrack = require("./JitsiTrack");
  1875. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1876. var DataChannels = require("./DataChannels");
  1877. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1878. var DesktopSharingEventTypes
  1879. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1880. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1881. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1882. function createLocalTracks(streams) {
  1883. var newStreams = []
  1884. for (var i = 0; i < streams.length; i++) {
  1885. var localStream = new JitsiLocalTrack(streams[i].stream,
  1886. streams[i].videoType, streams[i].resolution);
  1887. newStreams.push(localStream);
  1888. if (streams[i].isMuted === true)
  1889. localStream.setMute(true);
  1890. }
  1891. return newStreams;
  1892. }
  1893. function RTC(room, options) {
  1894. this.room = room;
  1895. this.localStreams = [];
  1896. //FIXME: we should start removing those streams.
  1897. //FIXME: We should support multiple streams per jid.
  1898. this.remoteStreams = {};
  1899. this.localAudio = null;
  1900. this.localVideo = null;
  1901. this.eventEmitter = new EventEmitter();
  1902. var self = this;
  1903. this.options = options || {};
  1904. room.addPresenceListener("videomuted", function (values, from) {
  1905. if(self.remoteStreams[from]) {
  1906. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1907. }
  1908. });
  1909. room.addPresenceListener("audiomuted", function (values, from) {
  1910. if(self.remoteStreams[from]) {
  1911. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1912. }
  1913. });
  1914. }
  1915. /**
  1916. * Creates the local MediaStreams.
  1917. * @param {Object} [options] optional parameters
  1918. * @param {Array} options.devices the devices that will be requested
  1919. * @param {string} options.resolution resolution constraints
  1920. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1921. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1922. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1923. * @param {string} options.cameraDeviceId
  1924. * @param {string} options.micDeviceId
  1925. * @returns {*} Promise object that will receive the new JitsiTracks
  1926. */
  1927. RTC.obtainAudioAndVideoPermissions = function (options) {
  1928. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1929. }
  1930. RTC.prototype.onIncommingCall = function(event) {
  1931. if(this.options.config.openSctp)
  1932. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1933. for(var i = 0; i < this.localStreams.length; i++)
  1934. if(this.localStreams[i])
  1935. {
  1936. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1937. }
  1938. }
  1939. RTC.prototype.selectedEndpoint = function (id) {
  1940. if(this.dataChannels)
  1941. this.dataChannels.handleSelectedEndpointEvent(id);
  1942. }
  1943. RTC.prototype.pinEndpoint = function (id) {
  1944. if(this.dataChannels)
  1945. this.dataChannels.handlePinnedEndpointEvent(id);
  1946. }
  1947. RTC.prototype.addListener = function (type, listener) {
  1948. this.eventEmitter.on(type, listener);
  1949. };
  1950. RTC.prototype.removeListener = function (eventType, listener) {
  1951. this.eventEmitter.removeListener(eventType, listener);
  1952. };
  1953. RTC.addListener = function (eventType, listener) {
  1954. RTCUtils.addListener(eventType, listener);
  1955. }
  1956. RTC.removeListener = function (eventType, listener) {
  1957. RTCUtils.removeListener(eventType, listener)
  1958. }
  1959. RTC.isRTCReady = function () {
  1960. return RTCUtils.isRTCReady();
  1961. }
  1962. RTC.init = function (options) {
  1963. this.options = options || {};
  1964. return RTCUtils.init(this.options);
  1965. }
  1966. RTC.getDeviceAvailability = function () {
  1967. return RTCUtils.getDeviceAvailability();
  1968. }
  1969. RTC.prototype.addLocalStream = function (stream) {
  1970. this.localStreams.push(stream);
  1971. stream._setRTC(this);
  1972. if (stream.type == "audio") {
  1973. this.localAudio = stream;
  1974. } else {
  1975. this.localVideo = stream;
  1976. }
  1977. };
  1978. /**
  1979. * Set mute for all local audio streams attached to the conference.
  1980. * @param value the mute value
  1981. */
  1982. RTC.prototype.setAudioMute = function (value) {
  1983. for(var i = 0; i < this.localStreams.length; i++) {
  1984. var stream = this.localStreams[i];
  1985. if(stream.getType() !== "audio") {
  1986. continue;
  1987. }
  1988. stream._setMute(value);
  1989. }
  1990. }
  1991. RTC.prototype.removeLocalStream = function (stream) {
  1992. for(var i = 0; i < this.localStreams.length; i++) {
  1993. if(this.localStreams[i].getOriginalStream() === stream) {
  1994. delete this.localStreams[i];
  1995. return;
  1996. }
  1997. }
  1998. };
  1999. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2000. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2001. if(!data.peerjid)
  2002. return;
  2003. var jid = Strophe.getResourceFromJid(data.peerjid);
  2004. if(!this.remoteStreams[jid]) {
  2005. this.remoteStreams[jid] = {};
  2006. }
  2007. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2008. return remoteStream;
  2009. };
  2010. RTC.getPCConstraints = function () {
  2011. return RTCUtils.pc_constraints;
  2012. };
  2013. RTC.attachMediaStream = function (elSelector, stream) {
  2014. RTCUtils.attachMediaStream(elSelector, stream);
  2015. };
  2016. RTC.getStreamID = function (stream) {
  2017. return RTCUtils.getStreamID(stream);
  2018. };
  2019. RTC.getVideoSrc = function (element) {
  2020. return RTCUtils.getVideoSrc(element);
  2021. };
  2022. /**
  2023. * Returns true if retrieving the the list of input devices is supported and
  2024. * false if not.
  2025. */
  2026. RTC.isDeviceListAvailable = function () {
  2027. return RTCUtils.isDeviceListAvailable();
  2028. };
  2029. /**
  2030. * Returns true if changing the camera / microphone device is supported and
  2031. * false if not.
  2032. */
  2033. RTC.isDeviceChangeAvailable = function () {
  2034. return RTCUtils.isDeviceChangeAvailable();
  2035. }
  2036. /**
  2037. * Allows to receive list of available cameras/microphones.
  2038. * @param {function} callback would receive array of devices as an argument
  2039. */
  2040. RTC.enumerateDevices = function (callback) {
  2041. RTCUtils.enumerateDevices(callback);
  2042. };
  2043. RTC.setVideoSrc = function (element, src) {
  2044. RTCUtils.setVideoSrc(element, src);
  2045. };
  2046. /**
  2047. * A method to handle stopping of the stream.
  2048. * One point to handle the differences in various implementations.
  2049. * @param mediaStream MediaStream object to stop.
  2050. */
  2051. RTC.stopMediaStream = function (mediaStream) {
  2052. RTCUtils.stopMediaStream(mediaStream);
  2053. };
  2054. /**
  2055. * Returns whether the desktop sharing is enabled or not.
  2056. * @returns {boolean}
  2057. */
  2058. RTC.isDesktopSharingEnabled = function () {
  2059. return RTCUtils.isDesktopSharingEnabled();
  2060. }
  2061. RTC.prototype.getVideoElementName = function () {
  2062. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2063. };
  2064. RTC.prototype.dispose = function() {
  2065. };
  2066. RTC.prototype.switchVideoStreams = function (newStream) {
  2067. this.localVideo.stream = newStream;
  2068. this.localStreams = [];
  2069. //in firefox we have only one stream object
  2070. if (this.localAudio.getOriginalStream() != newStream)
  2071. this.localStreams.push(this.localAudio);
  2072. this.localStreams.push(this.localVideo);
  2073. };
  2074. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2075. if(!jid)
  2076. return;
  2077. var resource = Strophe.getResourceFromJid(jid);
  2078. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2079. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2080. }
  2081. module.exports = RTC;
  2082. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/RTCEvents.js":80,"../../service/desktopsharing/DesktopSharingEventTypes":84,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":44}],17:[function(require,module,exports){
  2083. var currentBrowser;
  2084. var browserVersion;
  2085. var isAndroid;
  2086. var RTCBrowserType = {
  2087. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2088. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2089. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2090. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2091. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2092. getBrowserType: function () {
  2093. return currentBrowser;
  2094. },
  2095. isChrome: function () {
  2096. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2097. },
  2098. isOpera: function () {
  2099. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2100. },
  2101. isFirefox: function () {
  2102. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2103. },
  2104. isIExplorer: function () {
  2105. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2106. },
  2107. isSafari: function () {
  2108. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2109. },
  2110. isTemasysPluginUsed: function () {
  2111. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2112. },
  2113. getFirefoxVersion: function () {
  2114. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2115. },
  2116. getChromeVersion: function () {
  2117. return RTCBrowserType.isChrome() ? browserVersion : null;
  2118. },
  2119. usesPlanB: function() {
  2120. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2121. RTCBrowserType.isTemasysPluginUsed();
  2122. },
  2123. usesUnifiedPlan: function() {
  2124. return RTCBrowserType.isFirefox();
  2125. },
  2126. /**
  2127. * Whether the browser is running on an android device.
  2128. */
  2129. isAndroid: function() {
  2130. return isAndroid;
  2131. }
  2132. // Add version getters for other browsers when needed
  2133. };
  2134. // detectOpera() must be called before detectChrome() !!!
  2135. // otherwise Opera wil be detected as Chrome
  2136. function detectChrome() {
  2137. if (navigator.webkitGetUserMedia) {
  2138. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2139. var userAgent = navigator.userAgent.toLowerCase();
  2140. // We can assume that user agent is chrome, because it's
  2141. // enforced when 'ext' streaming method is set
  2142. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2143. console.log("This appears to be Chrome, ver: " + ver);
  2144. return ver;
  2145. }
  2146. return null;
  2147. }
  2148. function detectOpera() {
  2149. var userAgent = navigator.userAgent;
  2150. if (userAgent.match(/Opera|OPR/)) {
  2151. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2152. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2153. console.info("This appears to be Opera, ver: " + version);
  2154. return version;
  2155. }
  2156. return null;
  2157. }
  2158. function detectFirefox() {
  2159. if (navigator.mozGetUserMedia) {
  2160. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2161. var version = parseInt(
  2162. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2163. console.log('This appears to be Firefox, ver: ' + version);
  2164. return version;
  2165. }
  2166. return null;
  2167. }
  2168. function detectSafari() {
  2169. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2170. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2171. console.info("This appears to be Safari");
  2172. // FIXME detect Safari version when needed
  2173. return 1;
  2174. }
  2175. return null;
  2176. }
  2177. function detectIE() {
  2178. var version;
  2179. var ua = window.navigator.userAgent;
  2180. var msie = ua.indexOf('MSIE ');
  2181. if (msie > 0) {
  2182. // IE 10 or older => return version number
  2183. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2184. }
  2185. var trident = ua.indexOf('Trident/');
  2186. if (!version && trident > 0) {
  2187. // IE 11 => return version number
  2188. var rv = ua.indexOf('rv:');
  2189. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2190. }
  2191. var edge = ua.indexOf('Edge/');
  2192. if (!version && edge > 0) {
  2193. // IE 12 => return version number
  2194. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2195. }
  2196. if (version) {
  2197. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2198. console.info("This appears to be IExplorer, ver: " + version);
  2199. }
  2200. return version;
  2201. }
  2202. function detectBrowser() {
  2203. var version;
  2204. var detectors = [
  2205. detectOpera,
  2206. detectChrome,
  2207. detectFirefox,
  2208. detectIE,
  2209. detectSafari
  2210. ];
  2211. // Try all browser detectors
  2212. for (var i = 0; i < detectors.length; i++) {
  2213. version = detectors[i]();
  2214. if (version)
  2215. return version;
  2216. }
  2217. console.warn("Browser type defaults to Safari ver 1");
  2218. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2219. return 1;
  2220. }
  2221. browserVersion = detectBrowser();
  2222. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2223. module.exports = RTCBrowserType;
  2224. },{}],18:[function(require,module,exports){
  2225. (function (__filename){
  2226. /* global config, require, attachMediaStream, getUserMedia,
  2227. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2228. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2229. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2230. */
  2231. /* jshint -W101 */
  2232. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2233. var RTCBrowserType = require("./RTCBrowserType");
  2234. var Resolutions = require("../../service/RTC/Resolutions");
  2235. var RTCEvents = require("../../service/RTC/RTCEvents");
  2236. var AdapterJS = require("./adapter.screenshare");
  2237. var SDPUtil = require("../xmpp/SDPUtil");
  2238. var EventEmitter = require("events");
  2239. var screenObtainer = require("./ScreenObtainer");
  2240. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2241. var eventEmitter = new EventEmitter();
  2242. var devices = {
  2243. audio: true,
  2244. video: true
  2245. };
  2246. var rtcReady = false;
  2247. function setResolutionConstraints(constraints, resolution) {
  2248. var isAndroid = RTCBrowserType.isAndroid();
  2249. if (Resolutions[resolution]) {
  2250. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2251. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2252. }
  2253. else if (isAndroid) {
  2254. // FIXME can't remember if the purpose of this was to always request
  2255. // low resolution on Android ? if yes it should be moved up front
  2256. constraints.video.mandatory.minWidth = 320;
  2257. constraints.video.mandatory.minHeight = 240;
  2258. constraints.video.mandatory.maxFrameRate = 15;
  2259. }
  2260. if (constraints.video.mandatory.minWidth)
  2261. constraints.video.mandatory.maxWidth =
  2262. constraints.video.mandatory.minWidth;
  2263. if (constraints.video.mandatory.minHeight)
  2264. constraints.video.mandatory.maxHeight =
  2265. constraints.video.mandatory.minHeight;
  2266. }
  2267. /**
  2268. * @param {string[]} um required user media types
  2269. *
  2270. * @param {Object} [options={}] optional parameters
  2271. * @param {string} options.resolution
  2272. * @param {number} options.bandwidth
  2273. * @param {number} options.fps
  2274. * @param {string} options.desktopStream
  2275. * @param {string} options.cameraDeviceId
  2276. * @param {string} options.micDeviceId
  2277. * @param {bool} firefox_fake_device
  2278. */
  2279. function getConstraints(um, options) {
  2280. var constraints = {audio: false, video: false};
  2281. if (um.indexOf('video') >= 0) {
  2282. // same behaviour as true
  2283. constraints.video = { mandatory: {}, optional: [] };
  2284. if (options.cameraDeviceId) {
  2285. constraints.video.optional.push({
  2286. sourceId: options.cameraDeviceId
  2287. });
  2288. }
  2289. constraints.video.optional.push({ googLeakyBucket: true });
  2290. setResolutionConstraints(constraints, options.resolution);
  2291. }
  2292. if (um.indexOf('audio') >= 0) {
  2293. if (!RTCBrowserType.isFirefox()) {
  2294. // same behaviour as true
  2295. constraints.audio = { mandatory: {}, optional: []};
  2296. if (options.micDeviceId) {
  2297. constraints.audio.optional.push({
  2298. sourceId: options.micDeviceId
  2299. });
  2300. }
  2301. // if it is good enough for hangouts...
  2302. constraints.audio.optional.push(
  2303. {googEchoCancellation: true},
  2304. {googAutoGainControl: true},
  2305. {googNoiseSupression: true},
  2306. {googHighpassFilter: true},
  2307. {googNoisesuppression2: true},
  2308. {googEchoCancellation2: true},
  2309. {googAutoGainControl2: true}
  2310. );
  2311. } else {
  2312. if (options.micDeviceId) {
  2313. constraints.audio = {
  2314. mandatory: {},
  2315. optional: [{
  2316. sourceId: options.micDeviceId
  2317. }]};
  2318. } else {
  2319. constraints.audio = true;
  2320. }
  2321. }
  2322. }
  2323. if (um.indexOf('screen') >= 0) {
  2324. if (RTCBrowserType.isChrome()) {
  2325. constraints.video = {
  2326. mandatory: {
  2327. chromeMediaSource: "screen",
  2328. googLeakyBucket: true,
  2329. maxWidth: window.screen.width,
  2330. maxHeight: window.screen.height,
  2331. maxFrameRate: 3
  2332. },
  2333. optional: []
  2334. };
  2335. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2336. constraints.video = {
  2337. optional: [
  2338. {
  2339. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2340. }
  2341. ]
  2342. };
  2343. } else if (RTCBrowserType.isFirefox()) {
  2344. constraints.video = {
  2345. mozMediaSource: "window",
  2346. mediaSource: "window"
  2347. };
  2348. } else {
  2349. logger.error(
  2350. "'screen' WebRTC media source is supported only in Chrome" +
  2351. " and with Temasys plugin");
  2352. }
  2353. }
  2354. if (um.indexOf('desktop') >= 0) {
  2355. constraints.video = {
  2356. mandatory: {
  2357. chromeMediaSource: "desktop",
  2358. chromeMediaSourceId: options.desktopStream,
  2359. googLeakyBucket: true,
  2360. maxWidth: window.screen.width,
  2361. maxHeight: window.screen.height,
  2362. maxFrameRate: 3
  2363. },
  2364. optional: []
  2365. };
  2366. }
  2367. if (options.bandwidth) {
  2368. if (!constraints.video) {
  2369. //same behaviour as true
  2370. constraints.video = {mandatory: {}, optional: []};
  2371. }
  2372. constraints.video.optional.push({bandwidth: options.bandwidth});
  2373. }
  2374. if (options.fps) {
  2375. // for some cameras it might be necessary to request 30fps
  2376. // so they choose 30fps mjpg over 10fps yuy2
  2377. if (!constraints.video) {
  2378. // same behaviour as true;
  2379. constraints.video = {mandatory: {}, optional: []};
  2380. }
  2381. constraints.video.mandatory.minFrameRate = options.fps;
  2382. }
  2383. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2384. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2385. // this later can be a problem with some of the tests
  2386. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2387. {
  2388. // seems to be fixed now, removing this experimental fix, as having
  2389. // multiple audio tracks brake the tests
  2390. //constraints.audio = true;
  2391. constraints.fake = true;
  2392. }
  2393. return constraints;
  2394. }
  2395. function setAvailableDevices(um, available) {
  2396. if (um.indexOf("video") != -1) {
  2397. devices.video = available;
  2398. }
  2399. if (um.indexOf("audio") != -1) {
  2400. devices.audio = available;
  2401. }
  2402. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2403. }
  2404. // In case of IE we continue from 'onReady' callback
  2405. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2406. // once it is initialized.
  2407. function onReady (options, GUM) {
  2408. rtcReady = true;
  2409. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2410. screenObtainer.init(eventEmitter, options, GUM);
  2411. }
  2412. /**
  2413. * Apply function with arguments if function exists.
  2414. * Do nothing if function not provided.
  2415. * @param {function} [fn] function to apply
  2416. * @param {Array} [args=[]] arguments for function
  2417. */
  2418. function maybeApply(fn, args) {
  2419. if (fn) {
  2420. fn.apply(null, args || []);
  2421. }
  2422. }
  2423. var getUserMediaStatus = {
  2424. initialized: false,
  2425. callbacks: []
  2426. };
  2427. /**
  2428. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2429. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2430. * @param {Function} getUserMedia native function
  2431. * @returns {Function} wrapped function
  2432. */
  2433. function wrapGetUserMedia(getUserMedia) {
  2434. return function (constraints, successCallback, errorCallback) {
  2435. getUserMedia(constraints, function (stream) {
  2436. maybeApply(successCallback, [stream]);
  2437. if (!getUserMediaStatus.initialized) {
  2438. getUserMediaStatus.initialized = true;
  2439. getUserMediaStatus.callbacks.forEach(function (callback) {
  2440. callback();
  2441. });
  2442. getUserMediaStatus.callbacks.length = 0;
  2443. }
  2444. }, function (error) {
  2445. maybeApply(errorCallback, [error]);
  2446. });
  2447. };
  2448. }
  2449. /**
  2450. * Create stub device which equals to auto selected device.
  2451. * @param {string} kind if that should be `audio` or `video` device
  2452. * @returns {Object} stub device description in `enumerateDevices` format
  2453. */
  2454. function createAutoDeviceInfo(kind) {
  2455. return {
  2456. facing: null,
  2457. label: 'Auto',
  2458. kind: kind,
  2459. deviceId: '',
  2460. groupId: null
  2461. };
  2462. }
  2463. /**
  2464. * Execute function after getUserMedia was executed at least once.
  2465. * @param {Function} callback function to execute after getUserMedia
  2466. */
  2467. function afterUserMediaInitialized(callback) {
  2468. if (getUserMediaStatus.initialized) {
  2469. callback();
  2470. } else {
  2471. getUserMediaStatus.callbacks.push(callback);
  2472. }
  2473. }
  2474. /**
  2475. * Wrapper function which makes enumerateDevices to wait
  2476. * until someone executes getUserMedia first time.
  2477. * @param {Function} enumerateDevices native function
  2478. * @returns {Funtion} wrapped function
  2479. */
  2480. function wrapEnumerateDevices(enumerateDevices) {
  2481. return function (callback) {
  2482. // enumerate devices only after initial getUserMedia
  2483. afterUserMediaInitialized(function () {
  2484. enumerateDevices().then(function (devices) {
  2485. //add auto devices
  2486. devices.unshift(
  2487. createAutoDeviceInfo('audioinput'),
  2488. createAutoDeviceInfo('videoinput')
  2489. );
  2490. callback(devices);
  2491. }, function (err) {
  2492. console.error('cannot enumerate devices: ', err);
  2493. // return only auto devices
  2494. callback([createAutoDeviceInfo('audioInput'),
  2495. createAutoDeviceInfo('videoinput')]);
  2496. });
  2497. });
  2498. };
  2499. }
  2500. /**
  2501. * Use old MediaStreamTrack to get devices list and
  2502. * convert it to enumerateDevices format.
  2503. * @param {Function} callback function to call when received devices list.
  2504. */
  2505. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2506. MediaStreamTrack.getSources(function (sources) {
  2507. var devices = sources.map(function (source) {
  2508. var kind = (source.kind || '').toLowerCase();
  2509. return {
  2510. facing: source.facing || null,
  2511. label: source.label,
  2512. kind: kind ? kind + 'input': null,
  2513. deviceId: source.id,
  2514. groupId: source.groupId || null
  2515. };
  2516. });
  2517. //add auto devices
  2518. devices.unshift(
  2519. createAutoDeviceInfo('audioinput'),
  2520. createAutoDeviceInfo('videoinput')
  2521. );
  2522. callback(devices);
  2523. });
  2524. }
  2525. function obtainDevices(options) {
  2526. if(!options.devices || options.devices.length === 0) {
  2527. return options.successCallback(options.streams || {});
  2528. }
  2529. var device = options.devices.splice(0, 1);
  2530. options.deviceGUM[device](function (stream) {
  2531. options.streams = options.streams || {};
  2532. options.streams[device] = stream;
  2533. obtainDevices(options);
  2534. },
  2535. function (error) {
  2536. logger.error(
  2537. "failed to obtain " + device + " stream - stop", error);
  2538. options.errorCallback(JitsiTrackErrors.parseError(error));
  2539. });
  2540. }
  2541. /**
  2542. * Handles the newly created Media Streams.
  2543. * @param streams the new Media Streams
  2544. * @param resolution the resolution of the video streams
  2545. * @returns {*[]} object that describes the new streams
  2546. */
  2547. function handleLocalStream(streams, resolution) {
  2548. var audioStream, videoStream, desktopStream, res = [];
  2549. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2550. // an object with two properties: audioStream, videoStream.
  2551. if (window.webkitMediaStream) {
  2552. var audioVideo = streams.audioVideo;
  2553. if (audioVideo) {
  2554. var audioTracks = audioVideo.getAudioTracks();
  2555. if(audioTracks.length) {
  2556. audioStream = new webkitMediaStream();
  2557. for (var i = 0; i < audioTracks.length; i++) {
  2558. audioStream.addTrack(audioTracks[i]);
  2559. }
  2560. }
  2561. var videoTracks = audioVideo.getVideoTracks();
  2562. if(videoTracks.length) {
  2563. videoStream = new webkitMediaStream();
  2564. for (var j = 0; j < videoTracks.length; j++) {
  2565. videoStream.addTrack(videoTracks[j]);
  2566. }
  2567. }
  2568. }
  2569. if (streams && streams.desktopStream)
  2570. desktopStream = streams.desktopStream;
  2571. }
  2572. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2573. if (streams && streams.audio)
  2574. audioStream = streams.audio;
  2575. if (streams && streams.video)
  2576. videoStream = streams.video;
  2577. if(streams && streams.desktop)
  2578. desktopStream = streams.desktop;
  2579. }
  2580. if (desktopStream)
  2581. res.push({stream: desktopStream,
  2582. type: "video", videoType: "desktop"});
  2583. if(audioStream)
  2584. res.push({stream: audioStream, type: "audio", videoType: null});
  2585. if(videoStream)
  2586. res.push({stream: videoStream, type: "video", videoType: "camera",
  2587. resolution: resolution});
  2588. return res;
  2589. }
  2590. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2591. var RTCUtils = {
  2592. init: function (options) {
  2593. return new Promise(function(resolve, reject) {
  2594. if (RTCBrowserType.isFirefox()) {
  2595. var FFversion = RTCBrowserType.getFirefoxVersion();
  2596. if (FFversion < 40) {
  2597. logger.error(
  2598. "Firefox version too old: " + FFversion +
  2599. ". Required >= 40.");
  2600. reject(new Error("Firefox version too old: " + FFversion +
  2601. ". Required >= 40."));
  2602. return;
  2603. }
  2604. this.peerconnection = mozRTCPeerConnection;
  2605. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2606. this.enumerateDevices = wrapEnumerateDevices(
  2607. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2608. );
  2609. this.pc_constraints = {};
  2610. this.attachMediaStream = function (element, stream) {
  2611. // srcObject is being standardized and FF will eventually
  2612. // support that unprefixed. FF also supports the
  2613. // "element.src = URL.createObjectURL(...)" combo, but that
  2614. // will be deprecated in favour of srcObject.
  2615. //
  2616. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2617. // https://github.com/webrtc/samples/issues/302
  2618. if (!element[0])
  2619. return;
  2620. element[0].mozSrcObject = stream;
  2621. element[0].play();
  2622. };
  2623. this.getStreamID = function (stream) {
  2624. var id = stream.id;
  2625. if (!id) {
  2626. var tracks = stream.getVideoTracks();
  2627. if (!tracks || tracks.length === 0) {
  2628. tracks = stream.getAudioTracks();
  2629. }
  2630. id = tracks[0].id;
  2631. }
  2632. return SDPUtil.filter_special_chars(id);
  2633. };
  2634. this.getVideoSrc = function (element) {
  2635. if (!element)
  2636. return null;
  2637. return element.mozSrcObject;
  2638. };
  2639. this.setVideoSrc = function (element, src) {
  2640. if (element)
  2641. element.mozSrcObject = src;
  2642. };
  2643. RTCSessionDescription = mozRTCSessionDescription;
  2644. RTCIceCandidate = mozRTCIceCandidate;
  2645. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2646. this.peerconnection = webkitRTCPeerConnection;
  2647. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2648. if (navigator.mediaDevices) {
  2649. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2650. this.enumerateDevices = wrapEnumerateDevices(
  2651. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2652. );
  2653. } else {
  2654. this.getUserMedia = getUserMedia;
  2655. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2656. }
  2657. this.attachMediaStream = function (element, stream) {
  2658. element.attr('src', webkitURL.createObjectURL(stream));
  2659. };
  2660. this.getStreamID = function (stream) {
  2661. // streams from FF endpoints have the characters '{' and '}'
  2662. // that make jQuery choke.
  2663. return SDPUtil.filter_special_chars(stream.id);
  2664. };
  2665. this.getVideoSrc = function (element) {
  2666. if (!element)
  2667. return null;
  2668. return element.getAttribute("src");
  2669. };
  2670. this.setVideoSrc = function (element, src) {
  2671. if (element)
  2672. element.setAttribute("src", src);
  2673. };
  2674. // DTLS should now be enabled by default but..
  2675. this.pc_constraints = {'optional': [
  2676. {'DtlsSrtpKeyAgreement': 'true'}
  2677. ]};
  2678. if (options.useIPv6) {
  2679. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2680. this.pc_constraints.optional.push({googIPv6: true});
  2681. }
  2682. if (RTCBrowserType.isAndroid()) {
  2683. this.pc_constraints = {}; // disable DTLS on Android
  2684. }
  2685. if (!webkitMediaStream.prototype.getVideoTracks) {
  2686. webkitMediaStream.prototype.getVideoTracks = function () {
  2687. return this.videoTracks;
  2688. };
  2689. }
  2690. if (!webkitMediaStream.prototype.getAudioTracks) {
  2691. webkitMediaStream.prototype.getAudioTracks = function () {
  2692. return this.audioTracks;
  2693. };
  2694. }
  2695. }
  2696. // Detect IE/Safari
  2697. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2698. //AdapterJS.WebRTCPlugin.setLogLevel(
  2699. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2700. var self = this;
  2701. AdapterJS.webRTCReady(function (isPlugin) {
  2702. self.peerconnection = RTCPeerConnection;
  2703. self.getUserMedia = window.getUserMedia;
  2704. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2705. self.attachMediaStream = function (elSel, stream) {
  2706. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2707. return;
  2708. }
  2709. attachMediaStream(elSel[0], stream);
  2710. };
  2711. self.getStreamID = function (stream) {
  2712. var id = SDPUtil.filter_special_chars(stream.label);
  2713. return id;
  2714. };
  2715. self.getVideoSrc = function (element) {
  2716. if (!element) {
  2717. logger.warn("Attempt to get video SRC of null element");
  2718. return null;
  2719. }
  2720. var children = element.children;
  2721. for (var i = 0; i !== children.length; ++i) {
  2722. if (children[i].name === 'streamId') {
  2723. return children[i].value;
  2724. }
  2725. }
  2726. //logger.info(element.id + " SRC: " + src);
  2727. return null;
  2728. };
  2729. self.setVideoSrc = function (element, src) {
  2730. //logger.info("Set video src: ", element, src);
  2731. if (!src) {
  2732. logger.warn("Not attaching video stream, 'src' is null");
  2733. return;
  2734. }
  2735. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2736. var stream = AdapterJS.WebRTCPlugin.plugin
  2737. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2738. attachMediaStream(element, stream);
  2739. };
  2740. onReady(options, self.getUserMediaWithConstraints);
  2741. resolve();
  2742. });
  2743. } else {
  2744. try {
  2745. logger.error('Browser does not appear to be WebRTC-capable');
  2746. } catch (e) {
  2747. }
  2748. reject('Browser does not appear to be WebRTC-capable');
  2749. return;
  2750. }
  2751. // Call onReady() if Temasys plugin is not used
  2752. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2753. onReady(options, this.getUserMediaWithConstraints);
  2754. resolve();
  2755. }
  2756. }.bind(this));
  2757. },
  2758. /**
  2759. * @param {string[]} um required user media types
  2760. * @param {function} success_callback
  2761. * @param {Function} failure_callback
  2762. * @param {Object} [options] optional parameters
  2763. * @param {string} options.resolution
  2764. * @param {number} options.bandwidth
  2765. * @param {number} options.fps
  2766. * @param {string} options.desktopStream
  2767. * @param {string} options.cameraDeviceId
  2768. * @param {string} options.micDeviceId
  2769. **/
  2770. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2771. options = options || {};
  2772. var resolution = options.resolution;
  2773. var constraints = getConstraints(um, options);
  2774. logger.info("Get media constraints", constraints);
  2775. try {
  2776. this.getUserMedia(constraints,
  2777. function (stream) {
  2778. logger.log('onUserMediaSuccess');
  2779. setAvailableDevices(um, true);
  2780. success_callback(stream);
  2781. },
  2782. function (error) {
  2783. setAvailableDevices(um, false);
  2784. logger.warn('Failed to get access to local media. Error ',
  2785. error, constraints);
  2786. if (failure_callback) {
  2787. failure_callback(error, resolution);
  2788. }
  2789. });
  2790. } catch (e) {
  2791. logger.error('GUM failed: ', e);
  2792. if (failure_callback) {
  2793. failure_callback(e);
  2794. }
  2795. }
  2796. },
  2797. /**
  2798. * Creates the local MediaStreams.
  2799. * @param {Object} [options] optional parameters
  2800. * @param {Array} options.devices the devices that will be requested
  2801. * @param {string} options.resolution resolution constraints
  2802. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2803. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2804. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2805. * @param {string} options.cameraDeviceId
  2806. * @param {string} options.micDeviceId
  2807. * @returns {*} Promise object that will receive the new JitsiTracks
  2808. */
  2809. obtainAudioAndVideoPermissions: function (options) {
  2810. var self = this;
  2811. options = options || {};
  2812. return new Promise(function (resolve, reject) {
  2813. var successCallback = function (stream) {
  2814. resolve(handleLocalStream(stream, options.resolution));
  2815. };
  2816. options.devices = options.devices || ['audio', 'video'];
  2817. if(!screenObtainer.isSupported()
  2818. && options.devices.indexOf("desktop") !== -1){
  2819. reject(new Error("Desktop sharing is not supported!"));
  2820. }
  2821. if (RTCBrowserType.isFirefox() ||
  2822. RTCBrowserType.isTemasysPluginUsed()) {
  2823. var GUM = function (device, s, e) {
  2824. this.getUserMediaWithConstraints(device, s, e, options);
  2825. };
  2826. var deviceGUM = {
  2827. "audio": GUM.bind(self, ["audio"]),
  2828. "video": GUM.bind(self, ["video"]),
  2829. "desktop": screenObtainer.obtainStream.bind(screenObtainer)
  2830. };
  2831. // With FF/IE we can't split the stream into audio and video because FF
  2832. // doesn't support media stream constructors. So, we need to get the
  2833. // audio stream separately from the video stream using two distinct GUM
  2834. // calls. Not very user friendly :-( but we don't have many other
  2835. // options neither.
  2836. //
  2837. // Note that we pack those 2 streams in a single object and pass it to
  2838. // the successCallback method.
  2839. obtainDevices({
  2840. devices: options.devices,
  2841. streams: [],
  2842. successCallback: successCallback,
  2843. errorCallback: reject,
  2844. deviceGUM: deviceGUM
  2845. });
  2846. } else {
  2847. var hasDesktop = options.devices.indexOf('desktop') > -1;
  2848. if (hasDesktop) {
  2849. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2850. }
  2851. options.resolution = options.resolution || '360';
  2852. if(options.devices.length) {
  2853. this.getUserMediaWithConstraints(
  2854. options.devices,
  2855. function (stream) {
  2856. if(hasDesktop) {
  2857. screenObtainer.obtainStream(
  2858. function (desktopStream) {
  2859. successCallback({audioVideo: stream,
  2860. desktopStream: desktopStream});
  2861. }, function (error) {
  2862. reject(
  2863. JitsiTrackErrors.parseError(error));
  2864. });
  2865. } else {
  2866. successCallback({audioVideo: stream});
  2867. }
  2868. },
  2869. function (error) {
  2870. reject(JitsiTrackErrors.parseError(error));
  2871. },
  2872. options);
  2873. } else if (hasDesktop) {
  2874. screenObtainer.obtainStream(
  2875. function (stream) {
  2876. successCallback({desktopStream: stream});
  2877. }, function (error) {
  2878. reject(
  2879. JitsiTrackErrors.parseError(error));
  2880. });
  2881. }
  2882. }
  2883. }.bind(this));
  2884. },
  2885. addListener: function (eventType, listener) {
  2886. eventEmitter.on(eventType, listener);
  2887. },
  2888. removeListener: function (eventType, listener) {
  2889. eventEmitter.removeListener(eventType, listener);
  2890. },
  2891. getDeviceAvailability: function () {
  2892. return devices;
  2893. },
  2894. isRTCReady: function () {
  2895. return rtcReady;
  2896. },
  2897. /**
  2898. * Checks if its possible to enumerate available cameras/micropones.
  2899. * @returns {boolean} true if available, false otherwise.
  2900. */
  2901. isDeviceListAvailable: function () {
  2902. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2903. if (isEnumerateDevicesAvailable) {
  2904. return true;
  2905. }
  2906. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2907. },
  2908. /**
  2909. * Returns true if changing the camera / microphone device is supported and
  2910. * false if not.
  2911. */
  2912. isDeviceChangeAvailable: function () {
  2913. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2914. RTCBrowserType.isTemasysPluginUsed())
  2915. return true;
  2916. return false;
  2917. },
  2918. /**
  2919. * A method to handle stopping of the stream.
  2920. * One point to handle the differences in various implementations.
  2921. * @param mediaStream MediaStream object to stop.
  2922. */
  2923. stopMediaStream: function (mediaStream) {
  2924. mediaStream.getTracks().forEach(function (track) {
  2925. // stop() not supported with IE
  2926. if (track.stop) {
  2927. track.stop();
  2928. }
  2929. });
  2930. // leave stop for implementation still using it
  2931. if (mediaStream.stop) {
  2932. mediaStream.stop();
  2933. }
  2934. },
  2935. /**
  2936. * Returns whether the desktop sharing is enabled or not.
  2937. * @returns {boolean}
  2938. */
  2939. isDesktopSharingEnabled: function () {
  2940. return screenObtainer.isSupported();
  2941. }
  2942. };
  2943. module.exports = RTCUtils;
  2944. }).call(this,"/modules/RTC/RTCUtils.js")
  2945. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":80,"../../service/RTC/Resolutions":81,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":44,"jitsi-meet-logger":48}],19:[function(require,module,exports){
  2946. (function (__filename){
  2947. /* global chrome, $, alert */
  2948. /* jshint -W003 */
  2949. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2950. var RTCBrowserType = require("./RTCBrowserType");
  2951. var AdapterJS = require("./adapter.screenshare");
  2952. var DesktopSharingEventTypes
  2953. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2954. /**
  2955. * Indicates whether the Chrome desktop sharing extension is installed.
  2956. * @type {boolean}
  2957. */
  2958. var chromeExtInstalled = false;
  2959. /**
  2960. * Indicates whether an update of the Chrome desktop sharing extension is
  2961. * required.
  2962. * @type {boolean}
  2963. */
  2964. var chromeExtUpdateRequired = false;
  2965. /**
  2966. * Whether the jidesha extension for firefox is installed for the domain on
  2967. * which we are running. Null designates an unknown value.
  2968. * @type {null}
  2969. */
  2970. var firefoxExtInstalled = null;
  2971. /**
  2972. * If set to true, detection of an installed firefox extension will be started
  2973. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2974. * user tries to enable screen sharing).
  2975. */
  2976. var reDetectFirefoxExtension = false;
  2977. var GUM = null;
  2978. /**
  2979. * Handles obtaining a stream from a screen capture on different browsers.
  2980. */
  2981. var ScreenObtainer = {
  2982. /**
  2983. * The EventEmitter to use to emit events.
  2984. * @type {null}
  2985. */
  2986. eventEmitter: null,
  2987. obtainStream: null,
  2988. /**
  2989. * Initializes the function used to obtain a screen capture
  2990. * (this.obtainStream).
  2991. *
  2992. * If the browser is Chrome, it uses the value of
  2993. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2994. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2995. * use the "screen" media source (if the value is 'webrtc'),
  2996. * or disable screen capture (if the value is other).
  2997. * Note that for the "screen" media source to work the
  2998. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2999. */
  3000. init: function(eventEmitter, options, gum) {
  3001. this.eventEmitter = eventEmitter;
  3002. var obtainDesktopStream = null;
  3003. this.options = options = options || {};
  3004. GUM = gum;
  3005. if (RTCBrowserType.isFirefox())
  3006. initFirefoxExtensionDetection(options);
  3007. // TODO remove this, options.desktopSharing is deprecated.
  3008. var chromeMethod =
  3009. (options.desktopSharingChromeMethod || options.desktopSharing);
  3010. if (RTCBrowserType.isTemasysPluginUsed()) {
  3011. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3012. logger.info("Screensharing not supported by this plugin " +
  3013. "version");
  3014. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3015. logger.info(
  3016. "Screensharing not available with Temasys plugin on" +
  3017. " this site");
  3018. } else {
  3019. obtainDesktopStream = obtainWebRTCScreen;
  3020. logger.info("Using Temasys plugin for desktop sharing");
  3021. }
  3022. } else if (RTCBrowserType.isChrome()) {
  3023. if (chromeMethod == "ext") {
  3024. if (RTCBrowserType.getChromeVersion() >= 34) {
  3025. obtainDesktopStream =
  3026. this.obtainScreenFromExtension;
  3027. logger.info("Using Chrome extension for desktop sharing");
  3028. initChromeExtension(options);
  3029. } else {
  3030. logger.info("Chrome extension not supported until ver 34");
  3031. }
  3032. } else if (chromeMethod == "webrtc") {
  3033. obtainDesktopStream = obtainWebRTCScreen;
  3034. logger.info("Using Chrome WebRTC for desktop sharing");
  3035. }
  3036. } else if (RTCBrowserType.isFirefox()) {
  3037. if (options.desktopSharingFirefoxDisabled) {
  3038. obtainDesktopStream = null;
  3039. } else if (window.location.protocol === "http:"){
  3040. logger.log("Screen sharing is not supported over HTTP. " +
  3041. "Use of HTTPS is required.");
  3042. obtainDesktopStream = null;
  3043. } else {
  3044. obtainDesktopStream = this.obtainScreenOnFirefox;
  3045. }
  3046. }
  3047. if (!obtainDesktopStream) {
  3048. logger.info("Desktop sharing disabled");
  3049. }
  3050. this.obtainStream = obtainDesktopStream;
  3051. },
  3052. /**
  3053. * Checks whether obtaining a screen capture is supported in the current
  3054. * environment.
  3055. * @returns {boolean}
  3056. */
  3057. isSupported: function() {
  3058. return !!this.obtainStream;
  3059. },
  3060. /**
  3061. * Obtains a screen capture stream on Firefox.
  3062. * @param callback
  3063. * @param errorCallback
  3064. */
  3065. obtainScreenOnFirefox:
  3066. function (callback, errorCallback) {
  3067. var self = this;
  3068. var extensionRequired = false;
  3069. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3070. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3071. RTCBrowserType.getFirefoxVersion() <=
  3072. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3073. extensionRequired = true;
  3074. logger.log("Jidesha extension required on firefox version " +
  3075. RTCBrowserType.getFirefoxVersion());
  3076. }
  3077. if (!extensionRequired || firefoxExtInstalled === true) {
  3078. obtainWebRTCScreen(callback, errorCallback);
  3079. return;
  3080. }
  3081. if (reDetectFirefoxExtension) {
  3082. reDetectFirefoxExtension = false;
  3083. initFirefoxExtensionDetection(this.options);
  3084. }
  3085. // Give it some (more) time to initialize, and assume lack of
  3086. // extension if it hasn't.
  3087. if (firefoxExtInstalled === null) {
  3088. window.setTimeout(
  3089. function() {
  3090. if (firefoxExtInstalled === null)
  3091. firefoxExtInstalled = false;
  3092. self.obtainScreenOnFirefox(callback, errorCallback);
  3093. },
  3094. 300
  3095. );
  3096. logger.log("Waiting for detection of jidesha on firefox to " +
  3097. "finish.");
  3098. return;
  3099. }
  3100. // We need an extension and it isn't installed.
  3101. // Make sure we check for the extension when the user clicks again.
  3102. firefoxExtInstalled = null;
  3103. reDetectFirefoxExtension = true;
  3104. // Prompt the user to install the extension
  3105. this.eventEmitter.emit(
  3106. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  3107. this.options.desktopSharingFirefoxExtensionURL);
  3108. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3109. // stuck in 'switching' mode.
  3110. errorCallback('Firefox extension required.');
  3111. },
  3112. /**
  3113. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3114. * 'desktop' stream for returned stream token.
  3115. */
  3116. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3117. if (chromeExtInstalled) {
  3118. doGetStreamFromExtension(this.options, streamCallback,
  3119. failCallback);
  3120. } else {
  3121. if (chromeExtUpdateRequired) {
  3122. alert(
  3123. 'Jitsi Desktop Streamer requires update. ' +
  3124. 'Changes will take effect after next Chrome restart.');
  3125. }
  3126. chrome.webstore.install(
  3127. getWebStoreInstallUrl(this.options),
  3128. function (arg) {
  3129. logger.log("Extension installed successfully", arg);
  3130. chromeExtInstalled = true;
  3131. // We need to give a moment for the endpoint to become
  3132. // available
  3133. window.setTimeout(function () {
  3134. doGetStreamFromExtension(this.options, streamCallback,
  3135. failCallback);
  3136. }, 500);
  3137. },
  3138. function (arg) {
  3139. logger.log("Failed to install the extension", arg);
  3140. failCallback(arg);
  3141. }
  3142. );
  3143. }
  3144. }
  3145. };
  3146. /**
  3147. * Obtains a desktop stream using getUserMedia.
  3148. * For this to work on Chrome, the
  3149. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3150. *
  3151. * On firefox, the document's domain must be white-listed in the
  3152. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3153. * 'about:config'.
  3154. */
  3155. function obtainWebRTCScreen(streamCallback, failCallback) {
  3156. GUM(
  3157. ['screen'],
  3158. streamCallback,
  3159. failCallback
  3160. );
  3161. }
  3162. /**
  3163. * Constructs inline install URL for Chrome desktop streaming extension.
  3164. * The 'chromeExtensionId' must be defined in options parameter.
  3165. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3166. * @returns {string}
  3167. */
  3168. function getWebStoreInstallUrl(options)
  3169. {
  3170. //TODO remove chromeExtensionId (deprecated)
  3171. return "https://chrome.google.com/webstore/detail/" +
  3172. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3173. }
  3174. /**
  3175. * Checks whether an update of the Chrome extension is required.
  3176. * @param minVersion minimal required version
  3177. * @param extVersion current extension version
  3178. * @returns {boolean}
  3179. */
  3180. function isUpdateRequired(minVersion, extVersion) {
  3181. try {
  3182. var s1 = minVersion.split('.');
  3183. var s2 = extVersion.split('.');
  3184. var len = Math.max(s1.length, s2.length);
  3185. for (var i = 0; i < len; i++) {
  3186. var n1 = 0,
  3187. n2 = 0;
  3188. if (i < s1.length)
  3189. n1 = parseInt(s1[i]);
  3190. if (i < s2.length)
  3191. n2 = parseInt(s2[i]);
  3192. if (isNaN(n1) || isNaN(n2)) {
  3193. return true;
  3194. } else if (n1 !== n2) {
  3195. return n1 > n2;
  3196. }
  3197. }
  3198. // will happen if both versions have identical numbers in
  3199. // their components (even if one of them is longer, has more components)
  3200. return false;
  3201. }
  3202. catch (e) {
  3203. logger.error("Failed to parse extension version", e);
  3204. return true;
  3205. }
  3206. }
  3207. function checkChromeExtInstalled(callback, options) {
  3208. if (!chrome || !chrome.runtime) {
  3209. // No API, so no extension for sure
  3210. callback(false, false);
  3211. return;
  3212. }
  3213. chrome.runtime.sendMessage(
  3214. //TODO: remove chromeExtensionId (deprecated)
  3215. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3216. { getVersion: true },
  3217. function (response) {
  3218. if (!response || !response.version) {
  3219. // Communication failure - assume that no endpoint exists
  3220. logger.warn(
  3221. "Extension not installed?: ", chrome.runtime.lastError);
  3222. callback(false, false);
  3223. return;
  3224. }
  3225. // Check installed extension version
  3226. var extVersion = response.version;
  3227. logger.log('Extension version is: ' + extVersion);
  3228. //TODO: remove minChromeExtVersion (deprecated)
  3229. var updateRequired
  3230. = isUpdateRequired(
  3231. (options.desktopSharingChromeMinExtVersion ||
  3232. options.minChromeExtVersion),
  3233. extVersion);
  3234. callback(!updateRequired, updateRequired);
  3235. }
  3236. );
  3237. }
  3238. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3239. // Sends 'getStream' msg to the extension.
  3240. // Extension id must be defined in the config.
  3241. chrome.runtime.sendMessage(
  3242. //TODO: remove chromeExtensionId (deprecated)
  3243. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3244. {
  3245. getStream: true,
  3246. //TODO: remove desktopSharingSources (deprecated).
  3247. sources: (options.desktopSharingChromeSources ||
  3248. options.desktopSharingSources)
  3249. },
  3250. function (response) {
  3251. if (!response) {
  3252. failCallback(chrome.runtime.lastError);
  3253. return;
  3254. }
  3255. logger.log("Response from extension: " + response);
  3256. if (response.streamId) {
  3257. GUM(
  3258. ['desktop'],
  3259. function (stream) {
  3260. streamCallback(stream);
  3261. },
  3262. failCallback,
  3263. {desktopStream: response.streamId});
  3264. } else {
  3265. failCallback("Extension failed to get the stream");
  3266. }
  3267. }
  3268. );
  3269. }
  3270. /**
  3271. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3272. * config.js to support inline installs. Host site must be selected as main
  3273. * website of published extension.
  3274. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3275. */
  3276. function initInlineInstalls(options)
  3277. {
  3278. $("link[rel=chrome-webstore-item]").attr("href",
  3279. getWebStoreInstallUrl(options));
  3280. }
  3281. function initChromeExtension(options) {
  3282. // Initialize Chrome extension inline installs
  3283. initInlineInstalls(options);
  3284. // Check if extension is installed
  3285. checkChromeExtInstalled(function (installed, updateRequired) {
  3286. chromeExtInstalled = installed;
  3287. chromeExtUpdateRequired = updateRequired;
  3288. logger.info(
  3289. "Chrome extension installed: " + chromeExtInstalled +
  3290. " updateRequired: " + chromeExtUpdateRequired);
  3291. }, options);
  3292. }
  3293. /**
  3294. * Starts the detection of an installed jidesha extension for firefox.
  3295. * @param options supports "desktopSharingFirefoxDisabled",
  3296. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3297. */
  3298. function initFirefoxExtensionDetection(options) {
  3299. if (options.desktopSharingFirefoxDisabled) {
  3300. return;
  3301. }
  3302. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3303. return;
  3304. if (!options.desktopSharingFirefoxExtId) {
  3305. firefoxExtInstalled = false;
  3306. return;
  3307. }
  3308. var img = document.createElement('img');
  3309. img.onload = function(){
  3310. logger.log("Detected firefox screen sharing extension.");
  3311. firefoxExtInstalled = true;
  3312. };
  3313. img.onerror = function(){
  3314. logger.log("Detected lack of firefox screen sharing extension.");
  3315. firefoxExtInstalled = false;
  3316. };
  3317. // The jidesha extension exposes an empty image file under the url:
  3318. // "chrome://EXT_ID/content/DOMAIN.png"
  3319. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3320. // DOMAIN is a domain whitelisted by the extension.
  3321. var src = "chrome://" +
  3322. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3323. "/content/" + document.location.hostname + ".png";
  3324. img.setAttribute('src', src);
  3325. }
  3326. module.exports = ScreenObtainer;
  3327. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3328. },{"../../service/desktopsharing/DesktopSharingEventTypes":84,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":48}],20:[function(require,module,exports){
  3329. (function (__filename){
  3330. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3331. var console = require("jitsi-meet-logger").getLogger(__filename);
  3332. // Adapter's interface.
  3333. var AdapterJS = AdapterJS || {};
  3334. // Browserify compatibility
  3335. if(typeof exports !== 'undefined') {
  3336. module.exports = AdapterJS;
  3337. }
  3338. AdapterJS.options = AdapterJS.options || {};
  3339. // uncomment to get virtual webcams
  3340. // AdapterJS.options.getAllCams = true;
  3341. // uncomment to prevent the install prompt when the plugin in not yet installed
  3342. // AdapterJS.options.hidePluginInstallPrompt = true;
  3343. // AdapterJS version
  3344. AdapterJS.VERSION = '0.12.3';
  3345. // This function will be called when the WebRTC API is ready to be used
  3346. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3347. // the plugin
  3348. // You may Override this function to synchronise the start of your application
  3349. // with the WebRTC API being ready.
  3350. // If you decide not to override use this synchronisation, it may result in
  3351. // an extensive CPU usage on the plugin start (once per tab loaded)
  3352. // Params:
  3353. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3354. //
  3355. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3356. // The WebRTC API is ready.
  3357. // Override me and do whatever you want here
  3358. };
  3359. // Sets a callback function to be called when the WebRTC interface is ready.
  3360. // The first argument is the function to callback.\
  3361. // Throws an error if the first argument is not a function
  3362. AdapterJS.webRTCReady = function (callback) {
  3363. if (typeof callback !== 'function') {
  3364. throw new Error('Callback provided is not a function');
  3365. }
  3366. if (true === AdapterJS.onwebrtcreadyDone) {
  3367. // All WebRTC interfaces are ready, just call the callback
  3368. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3369. } else {
  3370. // will be triggered automatically when your browser/plugin is ready.
  3371. AdapterJS.onwebrtcready = callback;
  3372. }
  3373. };
  3374. // Plugin namespace
  3375. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3376. // The object to store plugin information
  3377. AdapterJS.WebRTCPlugin.pluginInfo = {
  3378. prefix : 'Tem',
  3379. plugName : 'TemWebRTCPlugin',
  3380. pluginId : 'plugin0',
  3381. type : 'application/x-temwebrtcplugin',
  3382. onload : '__TemWebRTCReady0',
  3383. portalLink : 'http://skylink.io/plugin/',
  3384. downloadLink : null, //set below
  3385. companyName: 'Temasys'
  3386. };
  3387. if(!!navigator.platform.match(/^Mac/i)) {
  3388. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3389. }
  3390. else if(!!navigator.platform.match(/^Win/i)) {
  3391. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3392. }
  3393. AdapterJS.WebRTCPlugin.TAGS = {
  3394. NONE : 'none',
  3395. AUDIO : 'audio',
  3396. VIDEO : 'video'
  3397. };
  3398. // Unique identifier of each opened page
  3399. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3400. // Use this whenever you want to call the plugin.
  3401. AdapterJS.WebRTCPlugin.plugin = null;
  3402. // Set log level for the plugin once it is ready.
  3403. // The different values are
  3404. // This is an asynchronous function that will run when the plugin is ready
  3405. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3406. // Defines webrtc's JS interface according to the plugin's implementation.
  3407. // Define plugin Browsers as WebRTC Interface.
  3408. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3409. // This function detects whether or not a plugin is installed.
  3410. // Checks if Not IE (firefox, for example), else if it's IE,
  3411. // we're running IE and do something. If not it is not supported.
  3412. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3413. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3414. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3415. // Inject the HTML DOM object element into the page.
  3416. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3417. // States of readiness that the plugin goes through when
  3418. // being injected and stated
  3419. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3420. NONE : 0, // no plugin use
  3421. INITIALIZING : 1, // Detected need for plugin
  3422. INJECTING : 2, // Injecting plugin
  3423. INJECTED: 3, // Plugin element injected but not usable yet
  3424. READY: 4 // Plugin ready to be used
  3425. };
  3426. // Current state of the plugin. You cannot use the plugin before this is
  3427. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3428. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3429. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3430. // Used to make sure AdapterJS.onwebrtcready is only called once
  3431. AdapterJS.onwebrtcreadyDone = false;
  3432. // Log levels for the plugin.
  3433. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3434. /*
  3435. Log outputs are prefixed in some cases.
  3436. INFO: Information reported by the plugin.
  3437. ERROR: Errors originating from within the plugin.
  3438. WEBRTC: Error originating from within the libWebRTC library
  3439. */
  3440. // From the least verbose to the most verbose
  3441. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3442. NONE : 'NONE',
  3443. ERROR : 'ERROR',
  3444. WARNING : 'WARNING',
  3445. INFO: 'INFO',
  3446. VERBOSE: 'VERBOSE',
  3447. SENSITIVE: 'SENSITIVE'
  3448. };
  3449. // Does a waiting check before proceeding to load the plugin.
  3450. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3451. // This methid will use an interval to wait for the plugin to be ready.
  3452. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3453. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3454. // This function will be called when plugin is ready. It sends necessary
  3455. // details to the plugin.
  3456. // The function will wait for the document to be ready and the set the
  3457. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3458. // indicating that it can start being requested.
  3459. // This function is not in the IE/Safari condition brackets so that
  3460. // TemPluginLoaded function might be called on Chrome/Firefox.
  3461. // This function is the only private function that is not encapsulated to
  3462. // allow the plugin method to be called.
  3463. __TemWebRTCReady0 = function () {
  3464. if (document.readyState === 'complete') {
  3465. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3466. AdapterJS.maybeThroughWebRTCReady();
  3467. } else {
  3468. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3469. if (document.readyState === 'complete') {
  3470. // TODO: update comments, we wait for the document to be ready
  3471. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3472. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3473. AdapterJS.maybeThroughWebRTCReady();
  3474. }
  3475. }, 100);
  3476. }
  3477. };
  3478. AdapterJS.maybeThroughWebRTCReady = function() {
  3479. if (!AdapterJS.onwebrtcreadyDone) {
  3480. AdapterJS.onwebrtcreadyDone = true;
  3481. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3482. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3483. }
  3484. }
  3485. };
  3486. // Text namespace
  3487. AdapterJS.TEXT = {
  3488. PLUGIN: {
  3489. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3490. 'to work on this browser.',
  3491. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3492. BUTTON: 'Install Now'
  3493. },
  3494. REFRESH: {
  3495. REQUIRE_REFRESH: 'Please refresh page',
  3496. BUTTON: 'Refresh Page'
  3497. }
  3498. };
  3499. // The result of ice connection states.
  3500. // - starting: Ice connection is starting.
  3501. // - checking: Ice connection is checking.
  3502. // - connected Ice connection is connected.
  3503. // - completed Ice connection is connected.
  3504. // - done Ice connection has been completed.
  3505. // - disconnected Ice connection has been disconnected.
  3506. // - failed Ice connection has failed.
  3507. // - closed Ice connection is closed.
  3508. AdapterJS._iceConnectionStates = {
  3509. starting : 'starting',
  3510. checking : 'checking',
  3511. connected : 'connected',
  3512. completed : 'connected',
  3513. done : 'completed',
  3514. disconnected : 'disconnected',
  3515. failed : 'failed',
  3516. closed : 'closed'
  3517. };
  3518. //The IceConnection states that has been fired for each peer.
  3519. AdapterJS._iceConnectionFiredStates = [];
  3520. // Check if WebRTC Interface is defined.
  3521. AdapterJS.isDefined = null;
  3522. // This function helps to retrieve the webrtc detected browser information.
  3523. // This sets:
  3524. // - webrtcDetectedBrowser: The browser agent name.
  3525. // - webrtcDetectedVersion: The browser version.
  3526. // - webrtcDetectedType: The types of webRTC support.
  3527. // - 'moz': Mozilla implementation of webRTC.
  3528. // - 'webkit': WebKit implementation of webRTC.
  3529. // - 'plugin': Using the plugin implementation.
  3530. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3531. var hasMatch, checkMatch = navigator.userAgent.match(
  3532. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3533. if (/trident/i.test(checkMatch[1])) {
  3534. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3535. webrtcDetectedBrowser = 'IE';
  3536. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3537. } else if (checkMatch[1] === 'Chrome') {
  3538. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3539. if (hasMatch !== null) {
  3540. webrtcDetectedBrowser = 'opera';
  3541. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3542. }
  3543. }
  3544. if (navigator.userAgent.indexOf('Safari')) {
  3545. if (typeof InstallTrigger !== 'undefined') {
  3546. webrtcDetectedBrowser = 'firefox';
  3547. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3548. webrtcDetectedBrowser = 'IE';
  3549. } else if (
  3550. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3551. webrtcDetectedBrowser = 'safari';
  3552. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3553. webrtcDetectedBrowser = 'opera';
  3554. } else if (!!window.chrome) {
  3555. webrtcDetectedBrowser = 'chrome';
  3556. }
  3557. }
  3558. if (!webrtcDetectedBrowser) {
  3559. webrtcDetectedVersion = checkMatch[1];
  3560. }
  3561. if (!webrtcDetectedVersion) {
  3562. try {
  3563. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3564. [navigator.appName, navigator.appVersion, '-?'];
  3565. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3566. checkMatch.splice(1, 1, hasMatch[1]);
  3567. }
  3568. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3569. } catch (error) { }
  3570. }
  3571. };
  3572. // To fix configuration as some browsers does not support
  3573. // the 'urls' attribute.
  3574. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3575. if (pcConfig === null) {
  3576. return;
  3577. }
  3578. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3579. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3580. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3581. delete pcConfig.iceServers[i].urls;
  3582. }
  3583. }
  3584. };
  3585. AdapterJS.addEvent = function(elem, evnt, func) {
  3586. if (elem.addEventListener) { // W3C DOM
  3587. elem.addEventListener(evnt, func, false);
  3588. } else if (elem.attachEvent) {// OLD IE DOM
  3589. elem.attachEvent('on'+evnt, func);
  3590. } else { // No much to do
  3591. elem[evnt] = func;
  3592. }
  3593. };
  3594. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3595. // only inject once the page is ready
  3596. if (document.readyState !== 'complete') {
  3597. return;
  3598. }
  3599. var w = window;
  3600. var i = document.createElement('iframe');
  3601. i.style.position = 'fixed';
  3602. i.style.top = '-41px';
  3603. i.style.left = 0;
  3604. i.style.right = 0;
  3605. i.style.width = '100%';
  3606. i.style.height = '40px';
  3607. i.style.backgroundColor = '#ffffe1';
  3608. i.style.border = 'none';
  3609. i.style.borderBottom = '1px solid #888888';
  3610. i.style.zIndex = '9999999';
  3611. if(typeof i.style.webkitTransition === 'string') {
  3612. i.style.webkitTransition = 'all .5s ease-out';
  3613. } else if(typeof i.style.transition === 'string') {
  3614. i.style.transition = 'all .5s ease-out';
  3615. }
  3616. document.body.appendChild(i);
  3617. c = (i.contentWindow) ? i.contentWindow :
  3618. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3619. c.document.open();
  3620. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3621. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3622. 'middle; cursor: default;">' + text + '</span>');
  3623. if(buttonText && buttonLink) {
  3624. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3625. c.document.close();
  3626. // On click on okay
  3627. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3628. if (!!displayRefreshBar) {
  3629. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3630. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3631. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3632. }
  3633. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3634. e.preventDefault();
  3635. try {
  3636. event.cancelBubble = true;
  3637. } catch(error) { }
  3638. var pluginInstallInterval = setInterval(function(){
  3639. if(! isIE) {
  3640. navigator.plugins.refresh(false);
  3641. }
  3642. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3643. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3644. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3645. function() { // plugin now installed
  3646. clearInterval(pluginInstallInterval);
  3647. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3648. },
  3649. function() {
  3650. // still no plugin detected, nothing to do
  3651. });
  3652. } , 500);
  3653. });
  3654. // On click on Cancel
  3655. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3656. w.document.body.removeChild(i);
  3657. });
  3658. } else {
  3659. c.document.close();
  3660. }
  3661. setTimeout(function() {
  3662. if(typeof i.style.webkitTransform === 'string') {
  3663. i.style.webkitTransform = 'translateY(40px)';
  3664. } else if(typeof i.style.transform === 'string') {
  3665. i.style.transform = 'translateY(40px)';
  3666. } else {
  3667. i.style.top = '0px';
  3668. }
  3669. }, 300);
  3670. };
  3671. // -----------------------------------------------------------
  3672. // Detected webrtc implementation. Types are:
  3673. // - 'moz': Mozilla implementation of webRTC.
  3674. // - 'webkit': WebKit implementation of webRTC.
  3675. // - 'plugin': Using the plugin implementation.
  3676. webrtcDetectedType = null;
  3677. // Detected webrtc datachannel support. Types are:
  3678. // - 'SCTP': SCTP datachannel support.
  3679. // - 'RTP': RTP datachannel support.
  3680. webrtcDetectedDCSupport = null;
  3681. // Set the settings for creating DataChannels, MediaStream for
  3682. // Cross-browser compability.
  3683. // - This is only for SCTP based support browsers.
  3684. // the 'urls' attribute.
  3685. checkMediaDataChannelSettings =
  3686. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3687. if (typeof callback !== 'function') {
  3688. return;
  3689. }
  3690. var beOfferer = true;
  3691. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3692. // Nightly version does not require MozDontOfferDataChannel for interop
  3693. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3694. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3695. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3696. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3697. // Resends an updated version of constraints for MozDataChannel to work
  3698. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3699. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3700. try {
  3701. delete constraints.mandatory.MozDontOfferDataChannel;
  3702. } catch (error) {
  3703. console.error('Failed deleting MozDontOfferDataChannel');
  3704. console.error(error);
  3705. }
  3706. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3707. constraints.mandatory.MozDontOfferDataChannel = true;
  3708. }
  3709. if (!isLocalFirefox) {
  3710. // temporary measure to remove Moz* constraints in non Firefox browsers
  3711. for (var prop in constraints.mandatory) {
  3712. if (constraints.mandatory.hasOwnProperty(prop)) {
  3713. if (prop.indexOf('Moz') !== -1) {
  3714. delete constraints.mandatory[prop];
  3715. }
  3716. }
  3717. }
  3718. }
  3719. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3720. // interopability of the media stream
  3721. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3722. beOfferer = false;
  3723. }
  3724. callback(beOfferer, constraints);
  3725. };
  3726. // Handles the differences for all browsers ice connection state output.
  3727. // - Tested outcomes are:
  3728. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3729. // - Chrome (answerer) : 'checking' > 'connected'
  3730. // - Firefox (offerer) : 'checking' > 'connected'
  3731. // - Firefox (answerer): 'checking' > 'connected'
  3732. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3733. if (typeof callback !== 'function') {
  3734. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3735. return;
  3736. }
  3737. peerId = (peerId) ? peerId : 'peer';
  3738. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3739. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3740. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3741. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3742. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3743. }
  3744. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3745. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3746. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3747. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3748. setTimeout(function () {
  3749. AdapterJS._iceConnectionFiredStates[peerId]
  3750. .push(AdapterJS._iceConnectionStates.done);
  3751. callback(AdapterJS._iceConnectionStates.done);
  3752. }, 1000);
  3753. }
  3754. callback(iceConnectionState);
  3755. }
  3756. return;
  3757. };
  3758. // Firefox:
  3759. // - Creates iceServer from the url for Firefox.
  3760. // - Create iceServer with stun url.
  3761. // - Create iceServer with turn url.
  3762. // - Ignore the transport parameter from TURN url for FF version <=27.
  3763. // - Return null for createIceServer if transport=tcp.
  3764. // - FF 27 and above supports transport parameters in TURN url,
  3765. // - So passing in the full url to create iceServer.
  3766. // Chrome:
  3767. // - Creates iceServer from the url for Chrome M33 and earlier.
  3768. // - Create iceServer with stun url.
  3769. // - Chrome M28 & above uses below TURN format.
  3770. // Plugin:
  3771. // - Creates Ice Server for Plugin Browsers
  3772. // - If Stun - Create iceServer with stun url.
  3773. // - Else - Create iceServer with turn url
  3774. // - This is a WebRTC Function
  3775. createIceServer = null;
  3776. // Firefox:
  3777. // - Creates IceServers for Firefox
  3778. // - Use .url for FireFox.
  3779. // - Multiple Urls support
  3780. // Chrome:
  3781. // - Creates iceServers from the urls for Chrome M34 and above.
  3782. // - .urls is supported since Chrome M34.
  3783. // - Multiple Urls support
  3784. // Plugin:
  3785. // - Creates Ice Servers for Plugin Browsers
  3786. // - Multiple Urls support
  3787. // - This is a WebRTC Function
  3788. createIceServers = null;
  3789. //------------------------------------------------------------
  3790. //The RTCPeerConnection object.
  3791. RTCPeerConnection = null;
  3792. // Creates RTCSessionDescription object for Plugin Browsers
  3793. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3794. RTCSessionDescription : null;
  3795. // Creates RTCIceCandidate object for Plugin Browsers
  3796. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3797. RTCIceCandidate : null;
  3798. // Get UserMedia (only difference is the prefix).
  3799. // Code from Adam Barth.
  3800. getUserMedia = null;
  3801. // Attach a media stream to an element.
  3802. attachMediaStream = null;
  3803. // Re-attach a media stream to an element.
  3804. reattachMediaStream = null;
  3805. // Detected browser agent name. Types are:
  3806. // - 'firefox': Firefox browser.
  3807. // - 'chrome': Chrome browser.
  3808. // - 'opera': Opera browser.
  3809. // - 'safari': Safari browser.
  3810. // - 'IE' - Internet Explorer browser.
  3811. webrtcDetectedBrowser = null;
  3812. // Detected browser version.
  3813. webrtcDetectedVersion = null;
  3814. // Check for browser types and react accordingly
  3815. if (navigator.mozGetUserMedia) {
  3816. webrtcDetectedBrowser = 'firefox';
  3817. webrtcDetectedVersion = parseInt(navigator
  3818. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3819. webrtcDetectedType = 'moz';
  3820. webrtcDetectedDCSupport = 'SCTP';
  3821. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3822. AdapterJS.maybeFixConfiguration(pcConfig);
  3823. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3824. };
  3825. // The RTCSessionDescription object.
  3826. RTCSessionDescription = mozRTCSessionDescription;
  3827. window.RTCSessionDescription = RTCSessionDescription;
  3828. // The RTCIceCandidate object.
  3829. RTCIceCandidate = mozRTCIceCandidate;
  3830. window.RTCIceCandidate = RTCIceCandidate;
  3831. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3832. navigator.getUserMedia = window.getUserMedia;
  3833. // Shim for MediaStreamTrack.getSources.
  3834. MediaStreamTrack.getSources = function(successCb) {
  3835. setTimeout(function() {
  3836. var infos = [
  3837. { kind: 'audio', id: 'default', label:'', facing:'' },
  3838. { kind: 'video', id: 'default', label:'', facing:'' }
  3839. ];
  3840. successCb(infos);
  3841. }, 0);
  3842. };
  3843. createIceServer = function (url, username, password) {
  3844. var iceServer = null;
  3845. var url_parts = url.split(':');
  3846. if (url_parts[0].indexOf('stun') === 0) {
  3847. iceServer = { url : url };
  3848. } else if (url_parts[0].indexOf('turn') === 0) {
  3849. if (webrtcDetectedVersion < 27) {
  3850. var turn_url_parts = url.split('?');
  3851. if (turn_url_parts.length === 1 ||
  3852. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3853. iceServer = {
  3854. url : turn_url_parts[0],
  3855. credential : password,
  3856. username : username
  3857. };
  3858. }
  3859. } else {
  3860. iceServer = {
  3861. url : url,
  3862. credential : password,
  3863. username : username
  3864. };
  3865. }
  3866. }
  3867. return iceServer;
  3868. };
  3869. createIceServers = function (urls, username, password) {
  3870. var iceServers = [];
  3871. for (var i = 0; i < urls.length; i++) {
  3872. var iceServer = createIceServer(urls[i], username, password);
  3873. if (iceServer !== null) {
  3874. iceServers.push(iceServer);
  3875. }
  3876. }
  3877. return iceServers;
  3878. };
  3879. attachMediaStream = function (element, stream) {
  3880. element.mozSrcObject = stream;
  3881. if (stream !== null)
  3882. element.play();
  3883. return element;
  3884. };
  3885. reattachMediaStream = function (to, from) {
  3886. to.mozSrcObject = from.mozSrcObject;
  3887. to.play();
  3888. return to;
  3889. };
  3890. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3891. if (!callback) {
  3892. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3893. ': 1 argument required, but only 0 present.');
  3894. }
  3895. return callback([]);
  3896. };
  3897. // Fake get{Video,Audio}Tracks
  3898. if (!MediaStream.prototype.getVideoTracks) {
  3899. MediaStream.prototype.getVideoTracks = function () {
  3900. return [];
  3901. };
  3902. }
  3903. if (!MediaStream.prototype.getAudioTracks) {
  3904. MediaStream.prototype.getAudioTracks = function () {
  3905. return [];
  3906. };
  3907. }
  3908. AdapterJS.maybeThroughWebRTCReady();
  3909. } else if (navigator.webkitGetUserMedia) {
  3910. webrtcDetectedBrowser = 'chrome';
  3911. webrtcDetectedType = 'webkit';
  3912. webrtcDetectedVersion = parseInt(navigator
  3913. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3914. // check if browser is opera 20+
  3915. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3916. if (checkIfOpera !== null) {
  3917. webrtcDetectedBrowser = 'opera';
  3918. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3919. }
  3920. // check browser datachannel support
  3921. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3922. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3923. webrtcDetectedDCSupport = 'SCTP';
  3924. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3925. webrtcDetectedVersion > 24) {
  3926. webrtcDetectedDCSupport = 'RTP';
  3927. } else {
  3928. webrtcDetectedDCSupport = '';
  3929. }
  3930. createIceServer = function (url, username, password) {
  3931. var iceServer = null;
  3932. var url_parts = url.split(':');
  3933. if (url_parts[0].indexOf('stun') === 0) {
  3934. iceServer = { 'url' : url };
  3935. } else if (url_parts[0].indexOf('turn') === 0) {
  3936. iceServer = {
  3937. 'url' : url,
  3938. 'credential' : password,
  3939. 'username' : username
  3940. };
  3941. }
  3942. return iceServer;
  3943. };
  3944. createIceServers = function (urls, username, password) {
  3945. var iceServers = [];
  3946. if (webrtcDetectedVersion >= 34) {
  3947. iceServers = {
  3948. 'urls' : urls,
  3949. 'credential' : password,
  3950. 'username' : username
  3951. };
  3952. } else {
  3953. for (var i = 0; i < urls.length; i++) {
  3954. var iceServer = createIceServer(urls[i], username, password);
  3955. if (iceServer !== null) {
  3956. iceServers.push(iceServer);
  3957. }
  3958. }
  3959. }
  3960. return iceServers;
  3961. };
  3962. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3963. if (webrtcDetectedVersion < 34) {
  3964. AdapterJS.maybeFixConfiguration(pcConfig);
  3965. }
  3966. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3967. };
  3968. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3969. navigator.getUserMedia = window.getUserMedia;
  3970. attachMediaStream = function (element, stream) {
  3971. if (typeof element.srcObject !== 'undefined') {
  3972. element.srcObject = stream;
  3973. } else if (typeof element.mozSrcObject !== 'undefined') {
  3974. element.mozSrcObject = stream;
  3975. } else if (typeof element.src !== 'undefined') {
  3976. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3977. } else {
  3978. console.log('Error attaching stream to element.');
  3979. }
  3980. return element;
  3981. };
  3982. reattachMediaStream = function (to, from) {
  3983. to.src = from.src;
  3984. return to;
  3985. };
  3986. AdapterJS.maybeThroughWebRTCReady();
  3987. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3988. /Edge\/(\d+).(\d+)$/)) {
  3989. webrtcDetectedBrowser = 'edge';
  3990. webrtcDetectedVersion =
  3991. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3992. // the minimum version still supported by adapter.
  3993. webrtcMinimumVersion = 12;
  3994. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3995. attachMediaStream = function(element, stream) {
  3996. element.srcObject = stream;
  3997. return element;
  3998. };
  3999. reattachMediaStream = function(to, from) {
  4000. to.srcObject = from.srcObject;
  4001. return to;
  4002. };
  4003. AdapterJS.maybeThroughWebRTCReady();
  4004. } else { // TRY TO USE PLUGIN
  4005. // IE 9 is not offering an implementation of console.log until you open a console
  4006. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4007. /* jshint -W020 */
  4008. console = {} || console;
  4009. // Implemented based on console specs from MDN
  4010. // You may override these functions
  4011. console.log = function (arg) {};
  4012. console.info = function (arg) {};
  4013. console.error = function (arg) {};
  4014. console.dir = function (arg) {};
  4015. console.exception = function (arg) {};
  4016. console.trace = function (arg) {};
  4017. console.warn = function (arg) {};
  4018. console.count = function (arg) {};
  4019. console.debug = function (arg) {};
  4020. console.count = function (arg) {};
  4021. console.time = function (arg) {};
  4022. console.timeEnd = function (arg) {};
  4023. console.group = function (arg) {};
  4024. console.groupCollapsed = function (arg) {};
  4025. console.groupEnd = function (arg) {};
  4026. /* jshint +W020 */
  4027. }
  4028. webrtcDetectedType = 'plugin';
  4029. webrtcDetectedDCSupport = 'plugin';
  4030. AdapterJS.parseWebrtcDetectedBrowser();
  4031. isIE = webrtcDetectedBrowser === 'IE';
  4032. /* jshint -W035 */
  4033. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4034. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4035. /* empty because it needs to prevent the function from running. */
  4036. }
  4037. };
  4038. /* jshint +W035 */
  4039. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4040. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4041. // Call immediately if possible
  4042. // Once the plugin is set, the code will always take this path
  4043. callback();
  4044. } else {
  4045. // otherwise start a 100ms interval
  4046. var checkPluginReadyState = setInterval(function () {
  4047. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4048. clearInterval(checkPluginReadyState);
  4049. callback();
  4050. }
  4051. }, 100);
  4052. }
  4053. };
  4054. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4055. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4056. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4057. });
  4058. };
  4059. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4060. // only inject once the page is ready
  4061. if (document.readyState !== 'complete') {
  4062. return;
  4063. }
  4064. // Prevent multiple injections
  4065. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4066. return;
  4067. }
  4068. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4069. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4070. var frag = document.createDocumentFragment();
  4071. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4072. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4073. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4074. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4075. '<param name="pluginId" value="' +
  4076. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4077. '<param name="windowless" value="false" /> ' +
  4078. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4079. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4080. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4081. // uncomment to be able to use virtual cams
  4082. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4083. '</object>';
  4084. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4085. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4086. }
  4087. document.body.appendChild(frag);
  4088. // Need to re-fetch the plugin
  4089. AdapterJS.WebRTCPlugin.plugin =
  4090. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4091. } else {
  4092. // Load Plugin
  4093. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4094. AdapterJS.WebRTCPlugin.plugin.id =
  4095. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4096. // IE will only start the plugin if it's ACTUALLY visible
  4097. if (isIE) {
  4098. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4099. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4100. } else { // The size of the plugin on Safari should be 0x0px
  4101. // so that the autorisation prompt is at the top
  4102. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4103. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4104. }
  4105. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4106. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4107. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4108. '<param name="pluginId" value="' +
  4109. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4110. '<param name="windowless" value="false" /> ' +
  4111. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4112. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4113. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4114. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4115. }
  4116. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4117. };
  4118. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4119. function (comName, plugName, installedCb, notInstalledCb) {
  4120. if (!isIE) {
  4121. var pluginArray = navigator.plugins;
  4122. for (var i = 0; i < pluginArray.length; i++) {
  4123. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4124. installedCb();
  4125. return;
  4126. }
  4127. }
  4128. notInstalledCb();
  4129. } else {
  4130. try {
  4131. var axo = new ActiveXObject(comName + '.' + plugName);
  4132. } catch (e) {
  4133. notInstalledCb();
  4134. return;
  4135. }
  4136. installedCb();
  4137. }
  4138. };
  4139. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4140. if (AdapterJS.WebRTCPlugin.pluginState ===
  4141. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4142. console.error("AdapterJS - WebRTC interface has already been defined");
  4143. return;
  4144. }
  4145. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4146. AdapterJS.isDefined = function (variable) {
  4147. return variable !== null && variable !== undefined;
  4148. };
  4149. createIceServer = function (url, username, password) {
  4150. var iceServer = null;
  4151. var url_parts = url.split(':');
  4152. if (url_parts[0].indexOf('stun') === 0) {
  4153. iceServer = {
  4154. 'url' : url,
  4155. 'hasCredentials' : false
  4156. };
  4157. } else if (url_parts[0].indexOf('turn') === 0) {
  4158. iceServer = {
  4159. 'url' : url,
  4160. 'hasCredentials' : true,
  4161. 'credential' : password,
  4162. 'username' : username
  4163. };
  4164. }
  4165. return iceServer;
  4166. };
  4167. createIceServers = function (urls, username, password) {
  4168. var iceServers = [];
  4169. for (var i = 0; i < urls.length; ++i) {
  4170. iceServers.push(createIceServer(urls[i], username, password));
  4171. }
  4172. return iceServers;
  4173. };
  4174. RTCSessionDescription = function (info) {
  4175. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4176. return AdapterJS.WebRTCPlugin.plugin.
  4177. ConstructSessionDescription(info.type, info.sdp);
  4178. };
  4179. RTCPeerConnection = function (servers, constraints) {
  4180. var iceServers = null;
  4181. if (servers) {
  4182. iceServers = servers.iceServers;
  4183. for (var i = 0; i < iceServers.length; i++) {
  4184. if (iceServers[i].urls && !iceServers[i].url) {
  4185. iceServers[i].url = iceServers[i].urls;
  4186. }
  4187. iceServers[i].hasCredentials = AdapterJS.
  4188. isDefined(iceServers[i].username) &&
  4189. AdapterJS.isDefined(iceServers[i].credential);
  4190. }
  4191. }
  4192. var mandatory = (constraints && constraints.mandatory) ?
  4193. constraints.mandatory : null;
  4194. var optional = (constraints && constraints.optional) ?
  4195. constraints.optional : null;
  4196. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4197. return AdapterJS.WebRTCPlugin.plugin.
  4198. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4199. iceServers, mandatory, optional);
  4200. };
  4201. MediaStreamTrack = {};
  4202. MediaStreamTrack.getSources = function (callback) {
  4203. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4204. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4205. });
  4206. };
  4207. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4208. constraints.audio = constraints.audio || false;
  4209. constraints.video = constraints.video || false;
  4210. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4211. AdapterJS.WebRTCPlugin.plugin.
  4212. getUserMedia(constraints, successCallback, failureCallback);
  4213. });
  4214. };
  4215. window.navigator.getUserMedia = window.getUserMedia;
  4216. attachMediaStream = function (element, stream) {
  4217. if (!element || !element.parentNode) {
  4218. return;
  4219. }
  4220. var streamId;
  4221. if (stream === null) {
  4222. streamId = '';
  4223. } else {
  4224. if (typeof stream.enableSoundTracks !== 'undefined') {
  4225. stream.enableSoundTracks(true);
  4226. }
  4227. streamId = stream.id;
  4228. }
  4229. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4230. var nodeName = element.nodeName.toLowerCase();
  4231. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4232. var tag;
  4233. switch(nodeName) {
  4234. case 'audio':
  4235. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4236. break;
  4237. case 'video':
  4238. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4239. break;
  4240. default:
  4241. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4242. }
  4243. var frag = document.createDocumentFragment();
  4244. var temp = document.createElement('div');
  4245. var classHTML = '';
  4246. if (element.className) {
  4247. classHTML = 'class="' + element.className + '" ';
  4248. } else if (element.attributes && element.attributes['class']) {
  4249. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4250. }
  4251. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4252. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4253. '<param name="pluginId" value="' + elementId + '" /> ' +
  4254. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4255. '<param name="windowless" value="true" /> ' +
  4256. '<param name="streamId" value="' + streamId + '" /> ' +
  4257. '<param name="tag" value="' + tag + '" /> ' +
  4258. '</object>';
  4259. while (temp.firstChild) {
  4260. frag.appendChild(temp.firstChild);
  4261. }
  4262. var height = '';
  4263. var width = '';
  4264. if (element.clientWidth || element.clientHeight) {
  4265. width = element.clientWidth;
  4266. height = element.clientHeight;
  4267. }
  4268. else if (element.width || element.height) {
  4269. width = element.width;
  4270. height = element.height;
  4271. }
  4272. element.parentNode.insertBefore(frag, element);
  4273. frag = document.getElementById(elementId);
  4274. frag.width = width;
  4275. frag.height = height;
  4276. element.parentNode.removeChild(element);
  4277. } else { // already an <object> tag, just change the stream id
  4278. var children = element.children;
  4279. for (var i = 0; i !== children.length; ++i) {
  4280. if (children[i].name === 'streamId') {
  4281. children[i].value = streamId;
  4282. break;
  4283. }
  4284. }
  4285. element.setStreamId(streamId);
  4286. }
  4287. var newElement = document.getElementById(elementId);
  4288. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4289. return newElement;
  4290. };
  4291. reattachMediaStream = function (to, from) {
  4292. var stream = null;
  4293. var children = from.children;
  4294. for (var i = 0; i !== children.length; ++i) {
  4295. if (children[i].name === 'streamId') {
  4296. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4297. stream = AdapterJS.WebRTCPlugin.plugin
  4298. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4299. break;
  4300. }
  4301. }
  4302. if (stream !== null) {
  4303. return attachMediaStream(to, stream);
  4304. } else {
  4305. console.log('Could not find the stream associated with this element');
  4306. }
  4307. };
  4308. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4309. properties = Object.getOwnPropertyNames( prototype );
  4310. for(prop in properties) {
  4311. propName = properties[prop];
  4312. if (typeof(propName.slice) === 'function') {
  4313. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4314. if (isIE) {
  4315. destElem.attachEvent(propName,srcElem[propName]);
  4316. } else {
  4317. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4318. }
  4319. } else {
  4320. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4321. }
  4322. }
  4323. }
  4324. var subPrototype = Object.getPrototypeOf(prototype)
  4325. if(subPrototype != null) {
  4326. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4327. }
  4328. }
  4329. RTCIceCandidate = function (candidate) {
  4330. if (!candidate.sdpMid) {
  4331. candidate.sdpMid = '';
  4332. }
  4333. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4334. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4335. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4336. );
  4337. };
  4338. // inject plugin
  4339. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4340. AdapterJS.WebRTCPlugin.injectPlugin();
  4341. };
  4342. // This function will be called if the plugin is needed (browser different
  4343. // from Chrome or Firefox), but the plugin is not installed.
  4344. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4345. function() {
  4346. AdapterJS.addEvent(document,
  4347. 'readystatechange',
  4348. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4349. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4350. };
  4351. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4352. if (AdapterJS.options.hidePluginInstallPrompt) {
  4353. return;
  4354. }
  4355. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4356. if(downloadLink) { // if download link
  4357. var popupString;
  4358. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4359. popupString = 'This website requires you to install the ' +
  4360. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4361. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4362. ' WebRTC Plugin</a>' +
  4363. ' to work on this browser.';
  4364. } else { // no portal link, just print a generic explanation
  4365. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4366. }
  4367. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4368. } else { // no download link, just print a generic explanation
  4369. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4370. }
  4371. };
  4372. // Try to detect the plugin and act accordingly
  4373. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4374. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4375. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4376. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4377. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4378. }
  4379. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4380. },{"jitsi-meet-logger":48}],21:[function(require,module,exports){
  4381. (function (__filename){
  4382. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4383. function supportsLocalStorage() {
  4384. try {
  4385. return 'localStorage' in window && window.localStorage !== null;
  4386. } catch (e) {
  4387. logger.log("localstorage is not supported");
  4388. return false;
  4389. }
  4390. }
  4391. function generateUniqueId() {
  4392. function _p8() {
  4393. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4394. }
  4395. return _p8() + _p8() + _p8() + _p8();
  4396. }
  4397. function Settings(conferenceID) {
  4398. this.email = '';
  4399. this.displayName = '';
  4400. this.userId;
  4401. this.language = null;
  4402. this.confSettings = null;
  4403. this.conferenceID = conferenceID;
  4404. if (supportsLocalStorage()) {
  4405. if(!window.localStorage.getItem(conferenceID))
  4406. this.confSettings = {};
  4407. else
  4408. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4409. if(!this.confSettings.jitsiMeetId) {
  4410. this.confSettings.jitsiMeetId = generateUniqueId();
  4411. logger.log("generated id",
  4412. this.confSettings.jitsiMeetId);
  4413. this.save();
  4414. }
  4415. this.userId = this.confSettings.jitsiMeetId || '';
  4416. this.email = this.confSettings.email || '';
  4417. this.displayName = this.confSettings.displayname || '';
  4418. this.language = this.confSettings.language;
  4419. } else {
  4420. logger.log("local storage is not supported");
  4421. this.userId = generateUniqueId();
  4422. }
  4423. }
  4424. Settings.prototype.save = function () {
  4425. if(!supportsLocalStorage())
  4426. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4427. }
  4428. Settings.prototype.setDisplayName = function (newDisplayName) {
  4429. this.displayName = newDisplayName;
  4430. if(this.confSettings != null)
  4431. this.confSettings.displayname = displayName;
  4432. this.save();
  4433. return this.displayName;
  4434. },
  4435. Settings.prototype.setEmail = function (newEmail) {
  4436. this.email = newEmail;
  4437. if(this.confSettings != null)
  4438. this.confSettings.email = newEmail;
  4439. this.save();
  4440. return this.email;
  4441. },
  4442. Settings.prototype.getSettings = function () {
  4443. return {
  4444. email: this.email,
  4445. displayName: this.displayName,
  4446. uid: this.userId,
  4447. language: this.language
  4448. };
  4449. },
  4450. Settings.prototype.setLanguage = function (lang) {
  4451. this.language = lang;
  4452. if(this.confSettings != null)
  4453. this.confSettings.language = lang;
  4454. this.save();
  4455. }
  4456. module.exports = Settings;
  4457. }).call(this,"/modules/settings/Settings.js")
  4458. },{"jitsi-meet-logger":48}],22:[function(require,module,exports){
  4459. /* global config */
  4460. /**
  4461. * Provides statistics for the local stream.
  4462. */
  4463. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4464. /**
  4465. * Size of the webaudio analyzer buffer.
  4466. * @type {number}
  4467. */
  4468. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4469. /**
  4470. * Value of the webaudio analyzer smoothing time parameter.
  4471. * @type {number}
  4472. */
  4473. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4474. /**
  4475. * Converts time domain data array to audio level.
  4476. * @param samples the time domain data array.
  4477. * @returns {number} the audio level
  4478. */
  4479. function timeDomainDataToAudioLevel(samples) {
  4480. var maxVolume = 0;
  4481. var length = samples.length;
  4482. for (var i = 0; i < length; i++) {
  4483. if (maxVolume < samples[i])
  4484. maxVolume = samples[i];
  4485. }
  4486. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4487. }
  4488. /**
  4489. * Animates audio level change
  4490. * @param newLevel the new audio level
  4491. * @param lastLevel the last audio level
  4492. * @returns {Number} the audio level to be set
  4493. */
  4494. function animateLevel(newLevel, lastLevel) {
  4495. var value = 0;
  4496. var diff = lastLevel - newLevel;
  4497. if(diff > 0.2) {
  4498. value = lastLevel - 0.2;
  4499. }
  4500. else if(diff < -0.4) {
  4501. value = lastLevel + 0.4;
  4502. }
  4503. else {
  4504. value = newLevel;
  4505. }
  4506. return parseFloat(value.toFixed(3));
  4507. }
  4508. /**
  4509. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4510. *
  4511. * @param stream the local stream
  4512. * @param interval stats refresh interval given in ms.
  4513. * @param callback function that receives the audio levels.
  4514. * @constructor
  4515. */
  4516. function LocalStatsCollector(stream, interval, callback) {
  4517. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4518. this.stream = stream;
  4519. this.intervalId = null;
  4520. this.intervalMilis = interval;
  4521. this.audioLevel = 0;
  4522. this.callback = callback;
  4523. }
  4524. /**
  4525. * Starts the collecting the statistics.
  4526. */
  4527. LocalStatsCollector.prototype.start = function () {
  4528. if (!window.AudioContext ||
  4529. RTCBrowserType.isTemasysPluginUsed())
  4530. return;
  4531. var context = new AudioContext();
  4532. var analyser = context.createAnalyser();
  4533. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4534. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4535. var source = context.createMediaStreamSource(this.stream);
  4536. source.connect(analyser);
  4537. var self = this;
  4538. this.intervalId = setInterval(
  4539. function () {
  4540. var array = new Uint8Array(analyser.frequencyBinCount);
  4541. analyser.getByteTimeDomainData(array);
  4542. var audioLevel = timeDomainDataToAudioLevel(array);
  4543. if (audioLevel != self.audioLevel) {
  4544. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4545. self.callback(self.audioLevel);
  4546. }
  4547. },
  4548. this.intervalMilis
  4549. );
  4550. };
  4551. /**
  4552. * Stops collecting the statistics.
  4553. */
  4554. LocalStatsCollector.prototype.stop = function () {
  4555. if (this.intervalId) {
  4556. clearInterval(this.intervalId);
  4557. this.intervalId = null;
  4558. }
  4559. };
  4560. module.exports = LocalStatsCollector;
  4561. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4562. (function (__filename){
  4563. /* global require, ssrc2jid */
  4564. /* jshint -W117 */
  4565. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4566. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4567. var StatisticsEvents = require("../../service/statistics/Events");
  4568. /* Whether we support the browser we are running into for logging statistics */
  4569. var browserSupported = RTCBrowserType.isChrome() ||
  4570. RTCBrowserType.isOpera();
  4571. var keyMap = {};
  4572. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4573. "ssrc": "ssrc",
  4574. "packetsReceived": "packetsReceived",
  4575. "packetsLost": "packetsLost",
  4576. "packetsSent": "packetsSent",
  4577. "bytesReceived": "bytesReceived",
  4578. "bytesSent": "bytesSent"
  4579. };
  4580. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4581. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4582. "sendBandwidth": "googAvailableSendBandwidth",
  4583. "remoteAddress": "googRemoteAddress",
  4584. "transportType": "googTransportType",
  4585. "localAddress": "googLocalAddress",
  4586. "activeConnection": "googActiveConnection",
  4587. "ssrc": "ssrc",
  4588. "packetsReceived": "packetsReceived",
  4589. "packetsSent": "packetsSent",
  4590. "packetsLost": "packetsLost",
  4591. "bytesReceived": "bytesReceived",
  4592. "bytesSent": "bytesSent",
  4593. "googFrameHeightReceived": "googFrameHeightReceived",
  4594. "googFrameWidthReceived": "googFrameWidthReceived",
  4595. "googFrameHeightSent": "googFrameHeightSent",
  4596. "googFrameWidthSent": "googFrameWidthSent",
  4597. "audioInputLevel": "audioInputLevel",
  4598. "audioOutputLevel": "audioOutputLevel"
  4599. };
  4600. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4601. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4602. /**
  4603. * Calculates packet lost percent using the number of lost packets and the
  4604. * number of all packet.
  4605. * @param lostPackets the number of lost packets
  4606. * @param totalPackets the number of all packets.
  4607. * @returns {number} packet loss percent
  4608. */
  4609. function calculatePacketLoss(lostPackets, totalPackets) {
  4610. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4611. return 0;
  4612. return Math.round((lostPackets/totalPackets)*100);
  4613. }
  4614. function getStatValue(item, name) {
  4615. var browserType = RTCBrowserType.getBrowserType();
  4616. if (!keyMap[browserType][name])
  4617. throw "The property isn't supported!";
  4618. var key = keyMap[browserType][name];
  4619. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4620. item.stat(key) : item[key];
  4621. }
  4622. function formatAudioLevel(audioLevel) {
  4623. return Math.min(Math.max(audioLevel, 0), 1);
  4624. }
  4625. /**
  4626. * Checks whether a certain record should be included in the logged statistics.
  4627. */
  4628. function acceptStat(reportId, reportType, statName) {
  4629. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4630. return false;
  4631. if (reportType == "ssrc") {
  4632. if (statName == "googTrackId" ||
  4633. statName == "transportId" ||
  4634. statName == "ssrc")
  4635. return false;
  4636. }
  4637. return true;
  4638. }
  4639. /**
  4640. * Checks whether a certain record should be included in the logged statistics.
  4641. */
  4642. function acceptReport(id, type) {
  4643. if (id.substring(0, 15) == "googCertificate" ||
  4644. id.substring(0, 9) == "googTrack" ||
  4645. id.substring(0, 20) == "googLibjingleSession")
  4646. return false;
  4647. if (type == "googComponent")
  4648. return false;
  4649. return true;
  4650. }
  4651. /**
  4652. * Peer statistics data holder.
  4653. * @constructor
  4654. */
  4655. function PeerStats()
  4656. {
  4657. this.ssrc2Loss = {};
  4658. this.ssrc2AudioLevel = {};
  4659. this.ssrc2bitrate = {};
  4660. this.ssrc2resolution = {};
  4661. }
  4662. /**
  4663. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4664. * represented by this instance.
  4665. * @param lossRate new packet loss rate value to be set.
  4666. */
  4667. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4668. {
  4669. this.ssrc2Loss = lossRate;
  4670. };
  4671. /**
  4672. * Sets resolution that belong to the ssrc
  4673. * represented by this instance.
  4674. * @param resolution new resolution value to be set.
  4675. */
  4676. PeerStats.prototype.setSsrcResolution = function (resolution)
  4677. {
  4678. if(resolution === null && this.ssrc2resolution[ssrc])
  4679. {
  4680. delete this.ssrc2resolution[ssrc];
  4681. }
  4682. else if(resolution !== null)
  4683. this.ssrc2resolution[ssrc] = resolution;
  4684. };
  4685. /**
  4686. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4687. * represented by this instance.
  4688. * @param ssrc audio or video RTP stream SSRC.
  4689. * @param bitrate new bitrate value to be set.
  4690. */
  4691. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4692. {
  4693. if(this.ssrc2bitrate[ssrc])
  4694. {
  4695. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4696. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4697. }
  4698. else {
  4699. this.ssrc2bitrate[ssrc] = bitrate;
  4700. }
  4701. };
  4702. /**
  4703. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4704. * the stream which belongs to the peer represented by this instance.
  4705. * @param ssrc RTP stream SSRC for which current audio level value will be
  4706. * updated.
  4707. * @param audioLevel the new audio level value to be set. Value is truncated to
  4708. * fit the range from 0 to 1.
  4709. */
  4710. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4711. {
  4712. // Range limit 0 - 1
  4713. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4714. };
  4715. function ConferenceStats() {
  4716. /**
  4717. * The bandwidth
  4718. * @type {{}}
  4719. */
  4720. this.bandwidth = {};
  4721. /**
  4722. * The bit rate
  4723. * @type {{}}
  4724. */
  4725. this.bitrate = {};
  4726. /**
  4727. * The packet loss rate
  4728. * @type {{}}
  4729. */
  4730. this.packetLoss = null;
  4731. /**
  4732. * Array with the transport information.
  4733. * @type {Array}
  4734. */
  4735. this.transport = [];
  4736. }
  4737. /**
  4738. * <tt>StatsCollector</tt> registers for stats updates of given
  4739. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4740. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4741. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4742. * instance as an event source.
  4743. *
  4744. * @param peerconnection webRTC peer connection object.
  4745. * @param interval stats refresh interval given in ms.
  4746. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4747. * called on stats update.
  4748. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4749. * @constructor
  4750. */
  4751. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4752. {
  4753. this.peerconnection = peerconnection;
  4754. this.baselineAudioLevelsReport = null;
  4755. this.currentAudioLevelsReport = null;
  4756. this.currentStatsReport = null;
  4757. this.baselineStatsReport = null;
  4758. this.audioLevelsIntervalId = null;
  4759. this.eventEmitter = eventEmitter;
  4760. this.config = config || {};
  4761. this.conferenceStats = new ConferenceStats();
  4762. /**
  4763. * Gather PeerConnection stats once every this many milliseconds.
  4764. */
  4765. this.GATHER_INTERVAL = 15000;
  4766. /**
  4767. * Log stats via the focus once every this many milliseconds.
  4768. */
  4769. this.LOG_INTERVAL = 60000;
  4770. /**
  4771. * Gather stats and store them in this.statsToBeLogged.
  4772. */
  4773. this.gatherStatsIntervalId = null;
  4774. /**
  4775. * Send the stats already saved in this.statsToBeLogged to be logged via
  4776. * the focus.
  4777. */
  4778. this.logStatsIntervalId = null;
  4779. /**
  4780. * Stores the statistics which will be send to the focus to be logged.
  4781. */
  4782. this.statsToBeLogged =
  4783. {
  4784. timestamps: [],
  4785. stats: {}
  4786. };
  4787. // Updates stats interval
  4788. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4789. this.statsIntervalId = null;
  4790. this.statsIntervalMilis = statsInterval;
  4791. // Map of ssrcs to PeerStats
  4792. this.ssrc2stats = {};
  4793. }
  4794. module.exports = StatsCollector;
  4795. /**
  4796. * Stops stats updates.
  4797. */
  4798. StatsCollector.prototype.stop = function () {
  4799. if (this.audioLevelsIntervalId) {
  4800. clearInterval(this.audioLevelsIntervalId);
  4801. this.audioLevelsIntervalId = null;
  4802. }
  4803. if (this.statsIntervalId)
  4804. {
  4805. clearInterval(this.statsIntervalId);
  4806. this.statsIntervalId = null;
  4807. }
  4808. if(this.logStatsIntervalId)
  4809. {
  4810. clearInterval(this.logStatsIntervalId);
  4811. this.logStatsIntervalId = null;
  4812. }
  4813. if(this.gatherStatsIntervalId)
  4814. {
  4815. clearInterval(this.gatherStatsIntervalId);
  4816. this.gatherStatsIntervalId = null;
  4817. }
  4818. };
  4819. /**
  4820. * Callback passed to <tt>getStats</tt> method.
  4821. * @param error an error that occurred on <tt>getStats</tt> call.
  4822. */
  4823. StatsCollector.prototype.errorCallback = function (error)
  4824. {
  4825. logger.error("Get stats error", error);
  4826. this.stop();
  4827. };
  4828. /**
  4829. * Starts stats updates.
  4830. */
  4831. StatsCollector.prototype.start = function ()
  4832. {
  4833. var self = this;
  4834. this.audioLevelsIntervalId = setInterval(
  4835. function () {
  4836. // Interval updates
  4837. self.peerconnection.getStats(
  4838. function (report) {
  4839. var results = null;
  4840. if (!report || !report.result ||
  4841. typeof report.result != 'function') {
  4842. results = report;
  4843. }
  4844. else {
  4845. results = report.result();
  4846. }
  4847. //logger.error("Got interval report", results);
  4848. self.currentAudioLevelsReport = results;
  4849. self.processAudioLevelReport();
  4850. self.baselineAudioLevelsReport =
  4851. self.currentAudioLevelsReport;
  4852. },
  4853. self.errorCallback
  4854. );
  4855. },
  4856. self.audioLevelsIntervalMilis
  4857. );
  4858. // if (!this.config.disableStats && browserSupported) {
  4859. // this.statsIntervalId = setInterval(
  4860. // function () {
  4861. // // Interval updates
  4862. // self.peerconnection.getStats(
  4863. // function (report) {
  4864. // var results = null;
  4865. // if (!report || !report.result ||
  4866. // typeof report.result != 'function') {
  4867. // //firefox
  4868. // results = report;
  4869. // }
  4870. // else {
  4871. // //chrome
  4872. // results = report.result();
  4873. // }
  4874. // //logger.error("Got interval report", results);
  4875. // self.currentStatsReport = results;
  4876. // try {
  4877. // self.processStatsReport();
  4878. // }
  4879. // catch (e) {
  4880. // logger.error("Unsupported key:" + e, e);
  4881. // }
  4882. //
  4883. // self.baselineStatsReport = self.currentStatsReport;
  4884. // },
  4885. // self.errorCallback
  4886. // );
  4887. // },
  4888. // self.statsIntervalMilis
  4889. // );
  4890. // }
  4891. //
  4892. // if (this.config.logStats && browserSupported) {
  4893. // this.gatherStatsIntervalId = setInterval(
  4894. // function () {
  4895. // self.peerconnection.getStats(
  4896. // function (report) {
  4897. // self.addStatsToBeLogged(report.result());
  4898. // },
  4899. // function () {
  4900. // }
  4901. // );
  4902. // },
  4903. // this.GATHER_INTERVAL
  4904. // );
  4905. //
  4906. // this.logStatsIntervalId = setInterval(
  4907. // function() { self.logStats(); },
  4908. // this.LOG_INTERVAL);
  4909. // }
  4910. };
  4911. /**
  4912. * Converts the stats to the format used for logging, and saves the data in
  4913. * this.statsToBeLogged.
  4914. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4915. */
  4916. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4917. var self = this;
  4918. var num_records = this.statsToBeLogged.timestamps.length;
  4919. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4920. reports.map(function (report) {
  4921. if (!acceptReport(report.id, report.type))
  4922. return;
  4923. var stat = self.statsToBeLogged.stats[report.id];
  4924. if (!stat) {
  4925. stat = self.statsToBeLogged.stats[report.id] = {};
  4926. }
  4927. stat.type = report.type;
  4928. report.names().map(function (name) {
  4929. if (!acceptStat(report.id, report.type, name))
  4930. return;
  4931. var values = stat[name];
  4932. if (!values) {
  4933. values = stat[name] = [];
  4934. }
  4935. while (values.length < num_records) {
  4936. values.push(null);
  4937. }
  4938. values.push(report.stat(name));
  4939. });
  4940. });
  4941. };
  4942. //FIXME:
  4943. //StatsCollector.prototype.logStats = function () {
  4944. //
  4945. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4946. // return;
  4947. // // Reset the stats
  4948. // this.statsToBeLogged.stats = {};
  4949. // this.statsToBeLogged.timestamps = [];
  4950. //};
  4951. /**
  4952. * Stats processing logic.
  4953. */
  4954. StatsCollector.prototype.processStatsReport = function () {
  4955. if (!this.baselineStatsReport) {
  4956. return;
  4957. }
  4958. for (var idx in this.currentStatsReport) {
  4959. var now = this.currentStatsReport[idx];
  4960. try {
  4961. if (getStatValue(now, 'receiveBandwidth') ||
  4962. getStatValue(now, 'sendBandwidth')) {
  4963. this.conferenceStats.bandwidth = {
  4964. "download": Math.round(
  4965. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4966. "upload": Math.round(
  4967. (getStatValue(now, 'sendBandwidth')) / 1000)
  4968. };
  4969. }
  4970. }
  4971. catch(e){/*not supported*/}
  4972. if(now.type == 'googCandidatePair')
  4973. {
  4974. var ip, type, localIP, active;
  4975. try {
  4976. ip = getStatValue(now, 'remoteAddress');
  4977. type = getStatValue(now, "transportType");
  4978. localIP = getStatValue(now, "localAddress");
  4979. active = getStatValue(now, "activeConnection");
  4980. }
  4981. catch(e){/*not supported*/}
  4982. if(!ip || !type || !localIP || active != "true")
  4983. continue;
  4984. var addressSaved = false;
  4985. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4986. {
  4987. if(this.conferenceStats.transport[i].ip == ip &&
  4988. this.conferenceStats.transport[i].type == type &&
  4989. this.conferenceStats.transport[i].localip == localIP)
  4990. {
  4991. addressSaved = true;
  4992. }
  4993. }
  4994. if(addressSaved)
  4995. continue;
  4996. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4997. continue;
  4998. }
  4999. if(now.type == "candidatepair")
  5000. {
  5001. if(now.state == "succeeded")
  5002. continue;
  5003. var local = this.currentStatsReport[now.localCandidateId];
  5004. var remote = this.currentStatsReport[now.remoteCandidateId];
  5005. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5006. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5007. }
  5008. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5009. now.type != "inboundrtp") {
  5010. continue;
  5011. }
  5012. var before = this.baselineStatsReport[idx];
  5013. if (!before) {
  5014. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5015. continue;
  5016. }
  5017. var ssrc = getStatValue(now, 'ssrc');
  5018. if(!ssrc)
  5019. continue;
  5020. var ssrcStats = this.ssrc2stats[ssrc];
  5021. if (!ssrcStats) {
  5022. ssrcStats = new PeerStats();
  5023. this.ssrc2stats[ssrc] = ssrcStats;
  5024. }
  5025. var isDownloadStream = true;
  5026. var key = 'packetsReceived';
  5027. var packetsNow = getStatValue(now, key);
  5028. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5029. isDownloadStream = false;
  5030. key = 'packetsSent';
  5031. packetsNow = getStatValue(now, key);
  5032. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5033. console.warn("No packetsReceived nor packetsSent stat found");
  5034. continue;
  5035. }
  5036. }
  5037. if (!packetsNow || packetsNow < 0)
  5038. packetsNow = 0;
  5039. var packetsBefore = getStatValue(before, key);
  5040. if (!packetsBefore || packetsBefore < 0)
  5041. packetsBefore = 0;
  5042. var packetRate = packetsNow - packetsBefore;
  5043. if (!packetRate || packetRate < 0)
  5044. packetRate = 0;
  5045. var currentLoss = getStatValue(now, 'packetsLost');
  5046. if (!currentLoss || currentLoss < 0)
  5047. currentLoss = 0;
  5048. var previousLoss = getStatValue(before, 'packetsLost');
  5049. if (!previousLoss || previousLoss < 0)
  5050. previousLoss = 0;
  5051. var lossRate = currentLoss - previousLoss;
  5052. if (!lossRate || lossRate < 0)
  5053. lossRate = 0;
  5054. var packetsTotal = (packetRate + lossRate);
  5055. ssrcStats.setSsrcLoss(ssrc,
  5056. {"packetsTotal": packetsTotal,
  5057. "packetsLost": lossRate,
  5058. "isDownloadStream": isDownloadStream});
  5059. var bytesReceived = 0, bytesSent = 0;
  5060. if(getStatValue(now, "bytesReceived")) {
  5061. bytesReceived = getStatValue(now, "bytesReceived") -
  5062. getStatValue(before, "bytesReceived");
  5063. }
  5064. if (getStatValue(now, "bytesSent")) {
  5065. bytesSent = getStatValue(now, "bytesSent") -
  5066. getStatValue(before, "bytesSent");
  5067. }
  5068. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5069. if (bytesReceived <= 0 || time <= 0) {
  5070. bytesReceived = 0;
  5071. } else {
  5072. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5073. }
  5074. if (bytesSent <= 0 || time <= 0) {
  5075. bytesSent = 0;
  5076. } else {
  5077. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5078. }
  5079. ssrcStats.setSsrcBitrate(ssrc, {
  5080. "download": bytesReceived,
  5081. "upload": bytesSent});
  5082. var resolution = {height: null, width: null};
  5083. try {
  5084. if (getStatValue(now, "googFrameHeightReceived") &&
  5085. getStatValue(now, "googFrameWidthReceived")) {
  5086. resolution.height =
  5087. getStatValue(now, "googFrameHeightReceived");
  5088. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5089. }
  5090. else if (getStatValue(now, "googFrameHeightSent") &&
  5091. getStatValue(now, "googFrameWidthSent")) {
  5092. resolution.height = getStatValue(now, "googFrameHeightSent");
  5093. resolution.width = getStatValue(now, "googFrameWidthSent");
  5094. }
  5095. }
  5096. catch(e){/*not supported*/}
  5097. if (resolution.height && resolution.width) {
  5098. ssrcStats.setSsrcResolution(ssrc, resolution);
  5099. } else {
  5100. ssrcStats.setSsrcResolution(ssrc, null);
  5101. }
  5102. }
  5103. var self = this;
  5104. // Jid stats
  5105. var totalPackets = {download: 0, upload: 0};
  5106. var lostPackets = {download: 0, upload: 0};
  5107. var bitrateDownload = 0;
  5108. var bitrateUpload = 0;
  5109. var resolutions = {};
  5110. Object.keys(this.ssrc2stats).forEach(
  5111. function (jid) {
  5112. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5113. function (ssrc) {
  5114. var type = "upload";
  5115. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5116. type = "download";
  5117. totalPackets[type] +=
  5118. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5119. lostPackets[type] +=
  5120. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5121. }
  5122. );
  5123. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5124. function (ssrc) {
  5125. bitrateDownload +=
  5126. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5127. bitrateUpload +=
  5128. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5129. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5130. }
  5131. );
  5132. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5133. }
  5134. );
  5135. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5136. this.conferenceStats.packetLoss = {
  5137. total:
  5138. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5139. totalPackets.download + totalPackets.upload),
  5140. download:
  5141. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5142. upload:
  5143. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5144. };
  5145. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5146. {
  5147. "bitrate": this.conferenceStats.bitrate,
  5148. "packetLoss": this.conferenceStats.packetLoss,
  5149. "bandwidth": this.conferenceStats.bandwidth,
  5150. "resolution": resolutions,
  5151. "transport": this.conferenceStats.transport
  5152. });
  5153. this.conferenceStats.transport = [];
  5154. };
  5155. /**
  5156. * Stats processing logic.
  5157. */
  5158. StatsCollector.prototype.processAudioLevelReport = function () {
  5159. if (!this.baselineAudioLevelsReport) {
  5160. return;
  5161. }
  5162. for (var idx in this.currentAudioLevelsReport) {
  5163. var now = this.currentAudioLevelsReport[idx];
  5164. //if we don't have "packetsReceived" this is local stream
  5165. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5166. continue;
  5167. }
  5168. var before = this.baselineAudioLevelsReport[idx];
  5169. if (!before) {
  5170. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5171. continue;
  5172. }
  5173. var ssrc = getStatValue(now, 'ssrc');
  5174. if (!ssrc) {
  5175. if((Date.now() - now.timestamp) < 3000)
  5176. logger.warn("No ssrc: ");
  5177. continue;
  5178. }
  5179. var ssrcStats = this.ssrc2stats[ssrc];
  5180. if (!ssrcStats) {
  5181. ssrcStats = new PeerStats();
  5182. this.ssrc2stats[ssrc] = ssrcStats;
  5183. }
  5184. // Audio level
  5185. var audioLevel = null;
  5186. try {
  5187. audioLevel = getStatValue(now, 'audioInputLevel');
  5188. if (!audioLevel)
  5189. audioLevel = getStatValue(now, 'audioOutputLevel');
  5190. }
  5191. catch(e) {/*not supported*/
  5192. logger.warn("Audio Levels are not available in the statistics.");
  5193. clearInterval(this.audioLevelsIntervalId);
  5194. return;
  5195. }
  5196. if (audioLevel) {
  5197. // TODO: can't find specs about what this value really is,
  5198. // but it seems to vary between 0 and around 32k.
  5199. audioLevel = audioLevel / 32767;
  5200. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5201. this.eventEmitter.emit(
  5202. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5203. }
  5204. }
  5205. };
  5206. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5207. },{"../../service/statistics/Events":85,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],24:[function(require,module,exports){
  5208. /* global require, APP */
  5209. var LocalStats = require("./LocalStatsCollector.js");
  5210. var RTPStats = require("./RTPStatsCollector.js");
  5211. var EventEmitter = require("events");
  5212. var StatisticsEvents = require("../../service/statistics/Events");
  5213. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  5214. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5215. //var CallStats = require("./CallStats");
  5216. //var RTCEvents = require("../../service/RTC/RTCEvents");
  5217. //
  5218. //function onDisposeConference(onUnload) {
  5219. // CallStats.sendTerminateEvent();
  5220. // stopRemote();
  5221. // if(onUnload) {
  5222. // stopLocal();
  5223. // eventEmitter.removeAllListeners();
  5224. // }
  5225. //}
  5226. var eventEmitter = new EventEmitter();
  5227. function Statistics() {
  5228. this.rtpStats = null;
  5229. this.eventEmitter = new EventEmitter();
  5230. }
  5231. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5232. if (this.rtpStats) {
  5233. this.rtpStats.stop();
  5234. }
  5235. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5236. this.rtpStats.start();
  5237. }
  5238. Statistics.localStats = [];
  5239. Statistics.startLocalStats = function (stream, callback) {
  5240. var localStats = new LocalStats(stream, 200, callback);
  5241. this.localStats.push(localStats);
  5242. localStats.start();
  5243. }
  5244. Statistics.prototype.addAudioLevelListener = function(listener)
  5245. {
  5246. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5247. }
  5248. Statistics.prototype.removeAudioLevelListener = function(listener)
  5249. {
  5250. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5251. }
  5252. Statistics.prototype.dispose = function () {
  5253. Statistics.stopAllLocalStats();
  5254. this.stopRemote();
  5255. if(this.eventEmitter)
  5256. this.eventEmitter.removeAllListeners();
  5257. if(eventEmitter)
  5258. eventEmitter.removeAllListeners();
  5259. }
  5260. Statistics.stopAllLocalStats = function () {
  5261. for(var i = 0; i < this.localStats.length; i++)
  5262. this.localStats[i].stop();
  5263. this.localStats = [];
  5264. }
  5265. Statistics.stopLocalStats = function (stream) {
  5266. for(var i = 0; i < Statistics.localStats.length; i++)
  5267. if(Statistics.localStats[i].stream === stream){
  5268. var localStats = Statistics.localStats.splice(i, 1);
  5269. localStats.stop();
  5270. break;
  5271. }
  5272. }
  5273. Statistics.prototype.stopRemote = function () {
  5274. if (this.rtpStats) {
  5275. this.rtpStats.stop();
  5276. this.eventEmitter.emit(StatisticsEvents.STOP);
  5277. this.rtpStats = null;
  5278. }
  5279. };
  5280. /**
  5281. * Obtains audio level reported in the stats for specified peer.
  5282. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5283. * audio level.
  5284. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5285. * level.
  5286. * @returns {*} a float form 0 to 1 that represents current audio level or
  5287. * <tt>null</tt> if for any reason the value is not available
  5288. * at this time.
  5289. */
  5290. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5291. var peerStats = this.rtpStats.jid2stats[peerJid];
  5292. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5293. };
  5294. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5295. //
  5296. //var statistics = {
  5297. // /**
  5298. // * Indicates that this audio level is for local jid.
  5299. // * @type {string}
  5300. // */
  5301. // LOCAL_JID: 'local',
  5302. //
  5303. // addConnectionStatsListener: function(listener)
  5304. // {
  5305. // eventEmitter.on("statistics.connectionstats", listener);
  5306. // },
  5307. //
  5308. // removeConnectionStatsListener: function(listener)
  5309. // {
  5310. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5311. // },
  5312. //
  5313. //
  5314. // addRemoteStatsStopListener: function(listener)
  5315. // {
  5316. // eventEmitter.on("statistics.stop", listener);
  5317. // },
  5318. //
  5319. // removeRemoteStatsStopListener: function(listener)
  5320. // {
  5321. // eventEmitter.removeListener("statistics.stop", listener);
  5322. // },
  5323. //
  5324. //
  5325. // stopRemoteStatistics: function()
  5326. // {
  5327. // stopRemote();
  5328. // },
  5329. //
  5330. //// Already implemented with the constructor
  5331. // start: function () {
  5332. // APP.RTC.addStreamListener(onStreamCreated,
  5333. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5334. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5335. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5336. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5337. // startRemoteStats(event.peerconnection);
  5338. //// CallStats.init(event);
  5339. // });
  5340. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5341. //// CallStats.init(session);
  5342. //// });
  5343. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5344. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5345. //// CallStats.sendMuteEvent(mute, "audio");
  5346. //// });
  5347. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5348. //// CallStats.sendSetupFailedEvent();
  5349. //// });
  5350. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5351. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5352. //// CallStats.sendMuteEvent(mute, "video");
  5353. //// });
  5354. // }
  5355. //};
  5356. module.exports = Statistics;
  5357. },{"../../service/statistics/Events":85,"../../service/statistics/constants":86,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":44}],25:[function(require,module,exports){
  5358. /**
  5359. /**
  5360. * @const
  5361. */
  5362. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5363. /**
  5364. * Hexadecimal digits.
  5365. * @const
  5366. */
  5367. var HEX_DIGITS = '0123456789abcdef';
  5368. /**
  5369. * Generates random int within the range [min, max]
  5370. * @param min the minimum value for the generated number
  5371. * @param max the maximum value for the generated number
  5372. * @returns random int number
  5373. */
  5374. function randomInt(min, max) {
  5375. return Math.floor(Math.random() * (max - min + 1)) + min;
  5376. }
  5377. /**
  5378. * Get random element from array or string.
  5379. * @param {Array|string} arr source
  5380. * @returns array element or string character
  5381. */
  5382. function randomElement(arr) {
  5383. return arr[randomInt(0, arr.length - 1)];
  5384. }
  5385. /**
  5386. * Generate random alphanumeric string.
  5387. * @param {number} length expected string length
  5388. * @returns {string} random string of specified length
  5389. */
  5390. function randomAlphanumStr(length) {
  5391. var result = '';
  5392. for (var i = 0; i < length; i += 1) {
  5393. result += randomElement(ALPHANUM);
  5394. }
  5395. return result;
  5396. }
  5397. /**
  5398. * Exported interface.
  5399. */
  5400. var RandomUtil = {
  5401. /**
  5402. * Returns a random hex digit.
  5403. * @returns {*}
  5404. */
  5405. randomHexDigit: function() {
  5406. return randomElement(HEX_DIGITS);
  5407. },
  5408. /**
  5409. * Returns a random string of hex digits with length 'len'.
  5410. * @param len the length.
  5411. */
  5412. randomHexString: function (len) {
  5413. var ret = '';
  5414. while (len--) {
  5415. ret += this.randomHexDigit();
  5416. }
  5417. return ret;
  5418. },
  5419. randomElement: randomElement,
  5420. randomAlphanumStr: randomAlphanumStr
  5421. };
  5422. module.exports = RandomUtil;
  5423. },{}],26:[function(require,module,exports){
  5424. (function (__filename){
  5425. /* global Strophe, $, $pres, $iq, $msg */
  5426. /* jshint -W101,-W069 */
  5427. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5428. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5429. var Moderator = require("./moderator");
  5430. var EventEmitter = require("events");
  5431. var Recorder = require("./recording");
  5432. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  5433. var parser = {
  5434. packet2JSON: function (packet, nodes) {
  5435. var self = this;
  5436. $(packet).children().each(function (index) {
  5437. var tagName = $(this).prop("tagName");
  5438. var node = {
  5439. tagName: tagName
  5440. };
  5441. node.attributes = {};
  5442. $($(this)[0].attributes).each(function( index, attr ) {
  5443. node.attributes[ attr.name ] = attr.value;
  5444. });
  5445. var text = Strophe.getText($(this)[0]);
  5446. if (text) {
  5447. node.value = text;
  5448. }
  5449. node.children = [];
  5450. nodes.push(node);
  5451. self.packet2JSON($(this), node.children);
  5452. });
  5453. },
  5454. JSON2packet: function (nodes, packet) {
  5455. for(var i = 0; i < nodes.length; i++) {
  5456. var node = nodes[i];
  5457. if(!node || node === null){
  5458. continue;
  5459. }
  5460. packet.c(node.tagName, node.attributes);
  5461. if(node.value)
  5462. packet.t(node.value);
  5463. if(node.children)
  5464. this.JSON2packet(node.children, packet);
  5465. packet.up();
  5466. }
  5467. // packet.up();
  5468. }
  5469. };
  5470. /**
  5471. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5472. * @param pres the presence JSON
  5473. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5474. */
  5475. function filterNodeFromPresenceJSON(pres, nodeName){
  5476. var res = [];
  5477. for(var i = 0; i < pres.length; i++)
  5478. if(pres[i].tagName === nodeName)
  5479. res.push(pres[i]);
  5480. return res;
  5481. }
  5482. function ChatRoom(connection, jid, password, XMPP, options) {
  5483. this.eventEmitter = new EventEmitter();
  5484. this.xmpp = XMPP;
  5485. this.connection = connection;
  5486. this.roomjid = Strophe.getBareJidFromJid(jid);
  5487. this.myroomjid = jid;
  5488. this.password = password;
  5489. logger.info("Joined MUC as " + this.myroomjid);
  5490. this.members = {};
  5491. this.presMap = {};
  5492. this.presHandlers = {};
  5493. this.joined = false;
  5494. this.role = 'none';
  5495. this.focusMucJid = null;
  5496. this.bridgeIsDown = false;
  5497. this.options = options || {};
  5498. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5499. this.initPresenceMap();
  5500. this.session = null;
  5501. var self = this;
  5502. this.lastPresences = {};
  5503. this.phoneNumber = null;
  5504. this.phonePin = null;
  5505. }
  5506. ChatRoom.prototype.initPresenceMap = function () {
  5507. this.presMap['to'] = this.myroomjid;
  5508. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5509. this.presMap["nodes"] = [];
  5510. this.presMap["nodes"].push( {
  5511. "tagName": "user-agent",
  5512. "value": navigator.userAgent,
  5513. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5514. });
  5515. };
  5516. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5517. this.presMap["nodes"].push( {
  5518. "tagName": "devices",
  5519. "children": [
  5520. {
  5521. "tagName": "audio",
  5522. "value": devices.audio,
  5523. },
  5524. {
  5525. "tagName": "video",
  5526. "value": devices.video,
  5527. }
  5528. ]
  5529. });
  5530. };
  5531. ChatRoom.prototype.join = function (password) {
  5532. if(password)
  5533. this.password = password;
  5534. var self = this;
  5535. this.moderator.allocateConferenceFocus(function()
  5536. {
  5537. self.sendPresence(true);
  5538. }.bind(this));
  5539. };
  5540. ChatRoom.prototype.sendPresence = function (fromJoin) {
  5541. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  5542. // Too early to send presence - not initialized
  5543. return;
  5544. }
  5545. var pres = $pres({to: this.presMap['to'] });
  5546. pres.c('x', {xmlns: this.presMap['xns']});
  5547. if (this.password) {
  5548. pres.c('password').t(this.password).up();
  5549. }
  5550. pres.up();
  5551. // Send XEP-0115 'c' stanza that contains our capabilities info
  5552. if (this.connection.caps) {
  5553. this.connection.caps.node = this.xmpp.options.clientNode;
  5554. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5555. }
  5556. parser.JSON2packet(this.presMap.nodes, pres);
  5557. this.connection.send(pres);
  5558. };
  5559. ChatRoom.prototype.doLeave = function () {
  5560. logger.log("do leave", this.myroomjid);
  5561. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5562. this.presMap.length = 0;
  5563. this.connection.send(pres);
  5564. };
  5565. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5566. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5567. var getForm = $iq({type: 'get', to: this.roomjid})
  5568. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5569. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5570. var self = this;
  5571. this.connection.sendIQ(getForm, function (form) {
  5572. if (!$(form).find(
  5573. '>query>x[xmlns="jabber:x:data"]' +
  5574. '>field[var="muc#roomconfig_whois"]').length) {
  5575. logger.error('non-anonymous rooms not supported');
  5576. return;
  5577. }
  5578. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5579. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5580. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5581. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5582. .c('value')
  5583. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5584. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5585. .c('value').t('anyone').up().up();
  5586. self.connection.sendIQ(formSubmit);
  5587. }, function (error) {
  5588. logger.error("Error getting room configuration form");
  5589. });
  5590. };
  5591. ChatRoom.prototype.onPresence = function (pres) {
  5592. var from = pres.getAttribute('from');
  5593. // Parse roles.
  5594. var member = {};
  5595. member.show = $(pres).find('>show').text();
  5596. member.status = $(pres).find('>status').text();
  5597. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5598. member.affiliation = tmp.attr('affiliation');
  5599. member.role = tmp.attr('role');
  5600. // Focus recognition
  5601. member.jid = tmp.attr('jid');
  5602. member.isFocus = false;
  5603. if (member.jid
  5604. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5605. member.isFocus = true;
  5606. }
  5607. $(pres).find(">x").remove();
  5608. var nodes = [];
  5609. parser.packet2JSON(pres, nodes);
  5610. this.lastPresences[from] = nodes;
  5611. var jibri = null;
  5612. for(var i = 0; i < nodes.length; i++)
  5613. {
  5614. var node = nodes[i];
  5615. switch(node.tagName)
  5616. {
  5617. case "nick":
  5618. member.nick = node.value;
  5619. if(!member.isFocus) {
  5620. var displayName = !this.xmpp.options.displayJids
  5621. ? member.nick : Strophe.getResourceFromJid(from);
  5622. if (displayName && displayName.length > 0) {
  5623. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5624. }
  5625. }
  5626. break;
  5627. case "userId":
  5628. member.id = node.value;
  5629. break;
  5630. case "email":
  5631. member.email = node.value;
  5632. break;
  5633. case "bridgeIsDown":
  5634. if(!this.bridgeIsDown) {
  5635. this.bridgeIsDown = true;
  5636. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5637. }
  5638. break;
  5639. case "jibri-recording-status":
  5640. var jibri = node;
  5641. break;
  5642. case "call-control":
  5643. var att = node.attributes;
  5644. if(!att)
  5645. break;
  5646. this.phoneNumber = att.phone || null;
  5647. this.phonePin = att.pin || null;
  5648. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  5649. break;
  5650. default :
  5651. this.processNode(node, from);
  5652. }
  5653. }
  5654. if (from == this.myroomjid) {
  5655. if (member.affiliation == 'owner')
  5656. if (this.role !== member.role) {
  5657. this.role = member.role;
  5658. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5659. }
  5660. if (!this.joined) {
  5661. this.joined = true;
  5662. console.log("(TIME) MUC joined:\t", window.performance.now());
  5663. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5664. }
  5665. } else if (this.members[from] === undefined) {
  5666. // new participant
  5667. this.members[from] = member;
  5668. logger.log('entered', from, member);
  5669. if (member.isFocus) {
  5670. this.focusMucJid = from;
  5671. if(!this.recording) {
  5672. this.recording = new Recorder(this.options.recordingType,
  5673. this.eventEmitter, this.connection, this.focusMucJid,
  5674. this.options.jirecon, this.roomjid);
  5675. if(this.lastJibri)
  5676. this.recording.handleJibriPresence(this.lastJibri);
  5677. }
  5678. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5679. }
  5680. else {
  5681. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5682. }
  5683. } else {
  5684. // Presence update for existing participant
  5685. // Watch role change:
  5686. if (this.members[from].role != member.role) {
  5687. this.members[from].role = member.role;
  5688. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5689. }
  5690. // store the new display name
  5691. if(member.displayName)
  5692. this.members[from].displayName = member.displayName;
  5693. }
  5694. if(!member.isFocus)
  5695. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5696. // Trigger status message update
  5697. if (member.status) {
  5698. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5699. }
  5700. if(jibri)
  5701. {
  5702. this.lastJibri = jibri;
  5703. if(this.recording)
  5704. this.recording.handleJibriPresence(jibri);
  5705. }
  5706. };
  5707. ChatRoom.prototype.processNode = function (node, from) {
  5708. if(this.presHandlers[node.tagName])
  5709. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  5710. };
  5711. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5712. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5713. msg.c('body', body).up();
  5714. if (nickname) {
  5715. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5716. }
  5717. this.connection.send(msg);
  5718. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5719. };
  5720. ChatRoom.prototype.setSubject = function (subject) {
  5721. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5722. msg.c('subject', subject);
  5723. this.connection.send(msg);
  5724. logger.log("topic changed to " + subject);
  5725. };
  5726. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5727. delete this.lastPresences[jid];
  5728. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5729. this.moderator.onMucMemberLeft(jid);
  5730. };
  5731. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5732. // room destroyed ?
  5733. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5734. '>destroy').length) {
  5735. var reason;
  5736. var reasonSelect = $(pres).find(
  5737. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5738. '>destroy>reason');
  5739. if (reasonSelect.length) {
  5740. reason = reasonSelect.text();
  5741. }
  5742. this.xmpp.leaveRoom(this.roomjid);
  5743. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5744. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5745. return true;
  5746. }
  5747. // Status code 110 indicates that this notification is "self-presence".
  5748. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5749. delete this.members[from];
  5750. this.onParticipantLeft(from);
  5751. }
  5752. // If the status code is 110 this means we're leaving and we would like
  5753. // to remove everyone else from our view, so we trigger the event.
  5754. else if (Object.keys(this.members).length > 1) {
  5755. for (var i in this.members) {
  5756. var member = this.members[i];
  5757. delete this.members[i];
  5758. this.onParticipantLeft(member);
  5759. }
  5760. }
  5761. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5762. if (this.myroomjid === from) {
  5763. this.xmpp.leaveRoom(this.roomjid);
  5764. this.eventEmitter.emit(XMPPEvents.KICKED);
  5765. }
  5766. }
  5767. };
  5768. ChatRoom.prototype.onMessage = function (msg, from) {
  5769. var nick =
  5770. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5771. .text() ||
  5772. Strophe.getResourceFromJid(from);
  5773. var txt = $(msg).find('>body').text();
  5774. var type = msg.getAttribute("type");
  5775. if (type == "error") {
  5776. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5777. $(msg).find('>text').text(), txt);
  5778. return true;
  5779. }
  5780. var subject = $(msg).find('>subject');
  5781. if (subject.length) {
  5782. var subjectText = subject.text();
  5783. if (subjectText || subjectText === "") {
  5784. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5785. logger.log("Subject is changed to " + subjectText);
  5786. }
  5787. }
  5788. // xep-0203 delay
  5789. var stamp = $(msg).find('>delay').attr('stamp');
  5790. if (!stamp) {
  5791. // or xep-0091 delay, UTC timestamp
  5792. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5793. if (stamp) {
  5794. // the format is CCYYMMDDThh:mm:ss
  5795. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5796. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5797. }
  5798. }
  5799. if (txt) {
  5800. logger.log('chat', nick, txt);
  5801. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5802. from, nick, txt, this.myroomjid, stamp);
  5803. }
  5804. };
  5805. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5806. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5807. logger.log('on password required', from);
  5808. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5809. } else if ($(pres).find(
  5810. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5811. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5812. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5813. // enter the room by replying with 'not-authorized'. This would
  5814. // result in reconnection from authorized domain.
  5815. // We're either missing Jicofo/Prosody config for anonymous
  5816. // domains or something is wrong.
  5817. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5818. } else {
  5819. logger.warn('onPresError ', pres);
  5820. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5821. }
  5822. } else {
  5823. logger.warn('onPresError ', pres);
  5824. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5825. }
  5826. };
  5827. ChatRoom.prototype.kick = function (jid) {
  5828. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5829. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5830. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5831. .c('reason').t('You have been kicked.').up().up().up();
  5832. this.connection.sendIQ(
  5833. kickIQ,
  5834. function (result) {
  5835. logger.log('Kick participant with jid: ', jid, result);
  5836. },
  5837. function (error) {
  5838. logger.log('Kick participant error: ', error);
  5839. });
  5840. };
  5841. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5842. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5843. var ob = this;
  5844. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5845. function (res) {
  5846. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5847. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5848. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5849. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5850. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5851. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5852. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5853. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5854. ob.connection.sendIQ(formsubmit,
  5855. onSuccess,
  5856. onError);
  5857. } else {
  5858. onNotSupported();
  5859. }
  5860. }, onError);
  5861. };
  5862. ChatRoom.prototype.addToPresence = function (key, values) {
  5863. values.tagName = key;
  5864. this.presMap["nodes"].push(values);
  5865. };
  5866. ChatRoom.prototype.removeFromPresence = function (key) {
  5867. for(var i = 0; i < this.presMap.nodes.length; i++)
  5868. {
  5869. if(key === this.presMap.nodes[i].tagName)
  5870. this.presMap.nodes.splice(i, 1);
  5871. }
  5872. };
  5873. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5874. this.presHandlers[name] = handler;
  5875. };
  5876. ChatRoom.prototype.removePresenceListener = function (name) {
  5877. delete this.presHandlers[name];
  5878. };
  5879. ChatRoom.prototype.isModerator = function () {
  5880. return this.role === 'moderator';
  5881. };
  5882. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5883. if (this.members[peerJid]) {
  5884. return this.members[peerJid].role;
  5885. }
  5886. return null;
  5887. };
  5888. ChatRoom.prototype.setJingleSession = function(session){
  5889. this.session = session;
  5890. this.session.room = this;
  5891. };
  5892. ChatRoom.prototype.removeStream = function (stream, callback) {
  5893. if(!this.session)
  5894. return;
  5895. this.session.removeStream(stream, callback);
  5896. };
  5897. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5898. if(this.session) {
  5899. // FIXME: will block switchInProgress on true value in case of exception
  5900. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5901. } else {
  5902. // We are done immediately
  5903. logger.warn("No conference handler or conference not started yet");
  5904. callback();
  5905. }
  5906. };
  5907. ChatRoom.prototype.addStream = function (stream, callback) {
  5908. if(this.session) {
  5909. // FIXME: will block switchInProgress on true value in case of exception
  5910. this.session.addStream(stream, callback);
  5911. } else {
  5912. // We are done immediately
  5913. logger.warn("No conference handler or conference not started yet");
  5914. callback();
  5915. }
  5916. };
  5917. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5918. var self = this;
  5919. var localCallback = function (mute) {
  5920. self.sendVideoInfoPresence(mute);
  5921. if(callback)
  5922. callback(mute);
  5923. };
  5924. if(this.session)
  5925. {
  5926. this.session.setVideoMute(
  5927. mute, localCallback, options);
  5928. }
  5929. else {
  5930. localCallback(mute);
  5931. }
  5932. };
  5933. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5934. //This will be for remote streams only
  5935. // if (this.forceMuted && !mute) {
  5936. // logger.info("Asking focus for unmute");
  5937. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5938. // // FIXME: wait for result before resetting muted status
  5939. // this.forceMuted = false;
  5940. // }
  5941. return this.sendAudioInfoPresence(mute, callback);
  5942. };
  5943. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5944. this.removeFromPresence("audiomuted");
  5945. this.addToPresence("audiomuted",
  5946. {attributes:
  5947. {"audions": "http://jitsi.org/jitmeet/audio"},
  5948. value: mute.toString()});
  5949. };
  5950. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5951. this.addAudioInfoToPresence(mute);
  5952. if(this.connection) {
  5953. this.sendPresence();
  5954. }
  5955. if(callback)
  5956. callback();
  5957. };
  5958. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5959. this.removeFromPresence("videomuted");
  5960. this.addToPresence("videomuted",
  5961. {attributes:
  5962. {"videons": "http://jitsi.org/jitmeet/video"},
  5963. value: mute.toString()});
  5964. };
  5965. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5966. this.addVideoInfoToPresence(mute);
  5967. if(!this.connection)
  5968. return;
  5969. this.sendPresence();
  5970. };
  5971. ChatRoom.prototype.addListener = function(type, listener) {
  5972. this.eventEmitter.on(type, listener);
  5973. };
  5974. ChatRoom.prototype.removeListener = function (type, listener) {
  5975. this.eventEmitter.removeListener(type, listener);
  5976. };
  5977. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5978. if(this.lastPresences[data.peerjid])
  5979. {
  5980. var pres = this.lastPresences[data.peerjid];
  5981. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5982. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5983. data.videomuted = ((videomuted.length > 0
  5984. && videomuted[0]
  5985. && videomuted[0]["value"] === "true")? true : false);
  5986. data.audiomuted = ((audiomuted.length > 0
  5987. && audiomuted[0]
  5988. && audiomuted[0]["value"] === "true")? true : false);
  5989. }
  5990. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5991. };
  5992. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5993. if (!this.session)
  5994. return null;
  5995. return this.session.getSsrcOwner(ssrc);
  5996. };
  5997. /**
  5998. * Returns true if the recording is supproted and false if not.
  5999. */
  6000. ChatRoom.prototype.isRecordingSupported = function () {
  6001. if(this.recording)
  6002. return this.recording.isSupported();
  6003. return false;
  6004. };
  6005. /**
  6006. * Returns null if the recording is not supported, "on" if the recording started
  6007. * and "off" if the recording is not started.
  6008. */
  6009. ChatRoom.prototype.getRecordingState = function () {
  6010. if(this.recording)
  6011. return this.recording.getState();
  6012. return "off";
  6013. }
  6014. /**
  6015. * Returns the url of the recorded video.
  6016. */
  6017. ChatRoom.prototype.getRecordingURL = function () {
  6018. if(this.recording)
  6019. return this.recording.getURL();
  6020. return null;
  6021. }
  6022. /**
  6023. * Starts/stops the recording
  6024. * @param token token for authentication
  6025. * @param statusChangeHandler {function} receives the new status as argument.
  6026. */
  6027. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  6028. if(this.recording)
  6029. return this.recording.toggleRecording(options, statusChangeHandler);
  6030. return statusChangeHandler("error",
  6031. new Error("The conference is not created yet!"));
  6032. }
  6033. /**
  6034. * Returns true if the SIP calls are supported and false otherwise
  6035. */
  6036. ChatRoom.prototype.isSIPCallingSupported = function () {
  6037. if(this.moderator)
  6038. return this.moderator.isSipGatewayEnabled();
  6039. return false;
  6040. }
  6041. /**
  6042. * Dials a number.
  6043. * @param number the number
  6044. */
  6045. ChatRoom.prototype.dial = function (number) {
  6046. return this.connection.rayo.dial(number, "fromnumber",
  6047. Strophe.getNodeFromJid(this.myroomjid), this.password,
  6048. this.focusMucJid);
  6049. }
  6050. /**
  6051. * Hangup an existing call
  6052. */
  6053. ChatRoom.prototype.hangup = function () {
  6054. return this.connection.rayo.hangup();
  6055. }
  6056. /**
  6057. * Returns the phone number for joining the conference.
  6058. */
  6059. ChatRoom.prototype.getPhoneNumber = function () {
  6060. return this.phoneNumber;
  6061. }
  6062. /**
  6063. * Returns the pin for joining the conference with phone.
  6064. */
  6065. ChatRoom.prototype.getPhonePin = function () {
  6066. return this.phonePin;
  6067. }
  6068. /**
  6069. * Returns the connection state for the current session.
  6070. */
  6071. ChatRoom.prototype.getConnectionState = function () {
  6072. if(!this.session)
  6073. return null;
  6074. return this.session.getIceConnectionState();
  6075. }
  6076. /**
  6077. * Mutes remote participant.
  6078. * @param jid of the participant
  6079. * @param mute
  6080. */
  6081. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  6082. logger.info("set mute", mute);
  6083. var iqToFocus = $iq(
  6084. {to: this.focusMucJid, type: 'set'})
  6085. .c('mute', {
  6086. xmlns: 'http://jitsi.org/jitmeet/audio',
  6087. jid: jid
  6088. })
  6089. .t(mute.toString())
  6090. .up();
  6091. this.connection.sendIQ(
  6092. iqToFocus,
  6093. function (result) {
  6094. logger.log('set mute', result);
  6095. },
  6096. function (error) {
  6097. logger.log('set mute error', error);
  6098. });
  6099. }
  6100. ChatRoom.prototype.onMute = function (iq) {
  6101. var from = iq.getAttribute('from');
  6102. if (from !== this.focusMucJid) {
  6103. logger.warn("Ignored mute from non focus peer");
  6104. return false;
  6105. }
  6106. var mute = $(iq).find('mute');
  6107. if (mute.length) {
  6108. var doMuteAudio = mute.text() === "true";
  6109. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  6110. }
  6111. return true;
  6112. }
  6113. module.exports = ChatRoom;
  6114. }).call(this,"/modules/xmpp/ChatRoom.js")
  6115. },{"../../service/xmpp/XMPPEvents":87,"./moderator":34,"./recording":35,"events":44,"jitsi-meet-logger":48}],27:[function(require,module,exports){
  6116. (function (__filename){
  6117. /*
  6118. * JingleSession provides an API to manage a single Jingle session. We will
  6119. * have different implementations depending on the underlying interface used
  6120. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  6121. */
  6122. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6123. function JingleSession(me, sid, connection, service, eventEmitter) {
  6124. /**
  6125. * Our JID.
  6126. */
  6127. this.me = me;
  6128. /**
  6129. * The Jingle session identifier.
  6130. */
  6131. this.sid = sid;
  6132. /**
  6133. * The XMPP connection.
  6134. */
  6135. this.connection = connection;
  6136. /**
  6137. * The XMPP service.
  6138. */
  6139. this.service = service;
  6140. /**
  6141. * The event emitter.
  6142. */
  6143. this.eventEmitter = eventEmitter;
  6144. /**
  6145. * Whether to use dripping or not. Dripping is sending trickle candidates
  6146. * not one-by-one.
  6147. * Note: currently we do not support 'false'.
  6148. */
  6149. this.usedrip = true;
  6150. /**
  6151. * When dripping is used, stores ICE candidates which are to be sent.
  6152. */
  6153. this.drip_container = [];
  6154. // Media constraints. Is this WebRTC only?
  6155. this.media_constraints = null;
  6156. // ICE servers config (RTCConfiguration?).
  6157. this.ice_config = {};
  6158. // The chat room instance associated with the session.
  6159. this.room = null;
  6160. }
  6161. /**
  6162. * Prepares this object to initiate a session.
  6163. * @param peerjid the JID of the remote peer.
  6164. * @param isInitiator whether we will be the Jingle initiator.
  6165. * @param media_constraints
  6166. * @param ice_config
  6167. */
  6168. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  6169. media_constraints, ice_config) {
  6170. this.media_constraints = media_constraints;
  6171. this.ice_config = ice_config;
  6172. if (this.state !== null) {
  6173. logger.error('attempt to initiate on session ' + this.sid +
  6174. 'in state ' + this.state);
  6175. return;
  6176. }
  6177. this.state = 'pending';
  6178. this.initiator = isInitiator ? this.me : peerjid;
  6179. this.responder = !isInitiator ? this.me : peerjid;
  6180. this.peerjid = peerjid;
  6181. this.doInitialize();
  6182. };
  6183. /**
  6184. * Finishes initialization.
  6185. */
  6186. JingleSession.prototype.doInitialize = function() {};
  6187. /**
  6188. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  6189. * Note: currently only used on transport-info
  6190. */
  6191. JingleSession.prototype.addIceCandidates = function(contents) {};
  6192. /**
  6193. * Handles an 'add-source' event.
  6194. *
  6195. * @param contents an array of Jingle 'content' elements.
  6196. */
  6197. JingleSession.prototype.addSources = function(contents) {};
  6198. /**
  6199. * Handles a 'remove-source' event.
  6200. *
  6201. * @param contents an array of Jingle 'content' elements.
  6202. */
  6203. JingleSession.prototype.removeSources = function(contents) {};
  6204. /**
  6205. * Terminates this Jingle session (stops sending media and closes the streams?)
  6206. */
  6207. JingleSession.prototype.terminate = function() {};
  6208. /**
  6209. * Sends a Jingle session-terminate message to the peer and terminates the
  6210. * session.
  6211. * @param reason
  6212. * @param text
  6213. */
  6214. JingleSession.prototype.sendTerminate = function(reason, text) {};
  6215. /**
  6216. * Handles an offer from the remote peer (prepares to accept a session).
  6217. * @param jingle the 'jingle' XML element.
  6218. */
  6219. JingleSession.prototype.setOffer = function(jingle) {};
  6220. /**
  6221. * Handles an answer from the remote peer (prepares to accept a session).
  6222. * @param jingle the 'jingle' XML element.
  6223. */
  6224. JingleSession.prototype.setAnswer = function(jingle) {};
  6225. module.exports = JingleSession;
  6226. }).call(this,"/modules/xmpp/JingleSession.js")
  6227. },{"jitsi-meet-logger":48}],28:[function(require,module,exports){
  6228. (function (__filename){
  6229. /* jshint -W117 */
  6230. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6231. var JingleSession = require("./JingleSession");
  6232. var TraceablePeerConnection = require("./TraceablePeerConnection");
  6233. var SDPDiffer = require("./SDPDiffer");
  6234. var SDPUtil = require("./SDPUtil");
  6235. var SDP = require("./SDP");
  6236. var async = require("async");
  6237. var transform = require("sdp-transform");
  6238. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6239. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6240. var SSRCReplacement = require("./LocalSSRCReplacement");
  6241. var RTC = require("../RTC/RTC");
  6242. // Jingle stuff
  6243. function JingleSessionPC(me, sid, connection, service) {
  6244. JingleSession.call(this, me, sid, connection, service);
  6245. this.initiator = null;
  6246. this.responder = null;
  6247. this.peerjid = null;
  6248. this.state = null;
  6249. this.localSDP = null;
  6250. this.remoteSDP = null;
  6251. this.relayedStreams = [];
  6252. this.usetrickle = true;
  6253. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  6254. this.hadstuncandidate = false;
  6255. this.hadturncandidate = false;
  6256. this.lasticecandidate = false;
  6257. this.statsinterval = null;
  6258. this.reason = null;
  6259. this.addssrc = [];
  6260. this.removessrc = [];
  6261. this.pendingop = null;
  6262. this.switchstreams = false;
  6263. this.addingStreams = false;
  6264. this.wait = true;
  6265. /**
  6266. * A map that stores SSRCs of local streams
  6267. * @type {{}} maps media type('audio' or 'video') to SSRC number
  6268. */
  6269. this.localStreamsSSRC = {};
  6270. this.ssrcOwners = {};
  6271. this.ssrcVideoTypes = {};
  6272. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  6273. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  6274. /**
  6275. * The indicator which determines whether the (local) video has been muted
  6276. * in response to a user command in contrast to an automatic decision made
  6277. * by the application logic.
  6278. */
  6279. this.videoMuteByUser = false;
  6280. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  6281. // We start with the queue paused. We resume it when the signaling state is
  6282. // stable and the ice connection state is connected.
  6283. this.modifySourcesQueue.pause();
  6284. }
  6285. //XXX this is badly broken...
  6286. JingleSessionPC.prototype = JingleSession.prototype;
  6287. JingleSessionPC.prototype.constructor = JingleSessionPC;
  6288. JingleSessionPC.prototype.setOffer = function(offer) {
  6289. this.setRemoteDescription(offer, 'offer');
  6290. };
  6291. JingleSessionPC.prototype.setAnswer = function(answer) {
  6292. this.setRemoteDescription(answer, 'answer');
  6293. };
  6294. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  6295. var signalingState = this.peerconnection.signalingState;
  6296. var iceConnectionState = this.peerconnection.iceConnectionState;
  6297. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  6298. this.modifySourcesQueue.resume();
  6299. } else {
  6300. this.modifySourcesQueue.pause();
  6301. }
  6302. };
  6303. JingleSessionPC.prototype.doInitialize = function () {
  6304. var self = this;
  6305. this.hadstuncandidate = false;
  6306. this.hadturncandidate = false;
  6307. this.lasticecandidate = false;
  6308. // True if reconnect is in progress
  6309. this.isreconnect = false;
  6310. // Set to true if the connection was ever stable
  6311. this.wasstable = false;
  6312. this.peerconnection = new TraceablePeerConnection(
  6313. this.connection.jingle.ice_config,
  6314. RTC.getPCConstraints(),
  6315. this);
  6316. this.peerconnection.onicecandidate = function (event) {
  6317. var protocol;
  6318. if (event && event.candidate) {
  6319. protocol = (typeof event.candidate.protocol === 'string')
  6320. ? event.candidate.protocol.toLowerCase() : '';
  6321. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6322. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6323. return;
  6324. }
  6325. }
  6326. self.sendIceCandidate(event.candidate);
  6327. };
  6328. this.peerconnection.onaddstream = function (event) {
  6329. if (event.stream.id !== 'default') {
  6330. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  6331. self.remoteStreamAdded(event);
  6332. } else {
  6333. // This is a recvonly stream. Clients that implement Unified Plan,
  6334. // such as Firefox use recvonly "streams/channels/tracks" for
  6335. // receiving remote stream/tracks, as opposed to Plan B where there
  6336. // are only 3 channels: audio, video and data.
  6337. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  6338. }
  6339. };
  6340. this.peerconnection.onremovestream = function (event) {
  6341. // Remove the stream from remoteStreams
  6342. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  6343. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  6344. };
  6345. this.peerconnection.onsignalingstatechange = function (event) {
  6346. if (!(self && self.peerconnection)) return;
  6347. if (self.peerconnection.signalingState === 'stable') {
  6348. self.wasstable = true;
  6349. }
  6350. self.updateModifySourcesQueue();
  6351. };
  6352. /**
  6353. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6354. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6355. * RTCPeerConnection.iceConnectionState changes.
  6356. *
  6357. * @param event the event containing information about the change
  6358. */
  6359. this.peerconnection.oniceconnectionstatechange = function (event) {
  6360. if (!(self && self.peerconnection)) return;
  6361. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6362. ":\t", window.performance.now());
  6363. self.updateModifySourcesQueue();
  6364. switch (self.peerconnection.iceConnectionState) {
  6365. case 'connected':
  6366. // Informs interested parties that the connection has been restored.
  6367. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6368. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6369. self.isreconnect = false;
  6370. break;
  6371. case 'disconnected':
  6372. self.isreconnect = true;
  6373. // Informs interested parties that the connection has been interrupted.
  6374. if (self.wasstable)
  6375. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6376. break;
  6377. case 'failed':
  6378. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6379. break;
  6380. }
  6381. onIceConnectionStateChange(self.sid, self);
  6382. };
  6383. this.peerconnection.onnegotiationneeded = function (event) {
  6384. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6385. };
  6386. this.relayedStreams.forEach(function(stream) {
  6387. self.peerconnection.addStream(stream);
  6388. });
  6389. };
  6390. function onIceConnectionStateChange(sid, session) {
  6391. switch (session.peerconnection.iceConnectionState) {
  6392. case 'checking':
  6393. session.timeChecking = (new Date()).getTime();
  6394. session.firstconnect = true;
  6395. break;
  6396. case 'completed': // on caller side
  6397. case 'connected':
  6398. if (session.firstconnect) {
  6399. session.firstconnect = false;
  6400. var metadata = {};
  6401. metadata.setupTime
  6402. = (new Date()).getTime() - session.timeChecking;
  6403. session.peerconnection.getStats(function (res) {
  6404. if(res && res.result) {
  6405. res.result().forEach(function (report) {
  6406. if (report.type == 'googCandidatePair' &&
  6407. report.stat('googActiveConnection') == 'true') {
  6408. metadata.localCandidateType
  6409. = report.stat('googLocalCandidateType');
  6410. metadata.remoteCandidateType
  6411. = report.stat('googRemoteCandidateType');
  6412. // log pair as well so we can get nice pie
  6413. // charts
  6414. metadata.candidatePair
  6415. = report.stat('googLocalCandidateType') +
  6416. ';' +
  6417. report.stat('googRemoteCandidateType');
  6418. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6419. {
  6420. metadata.ipv6 = true;
  6421. }
  6422. }
  6423. });
  6424. }
  6425. });
  6426. }
  6427. break;
  6428. }
  6429. }
  6430. JingleSessionPC.prototype.accept = function () {
  6431. this.state = 'active';
  6432. var pranswer = this.peerconnection.localDescription;
  6433. if (!pranswer || pranswer.type != 'pranswer') {
  6434. return;
  6435. }
  6436. logger.log('going from pranswer to answer');
  6437. if (this.usetrickle) {
  6438. // remove candidates already sent from session-accept
  6439. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6440. for (var i = 0; i < lines.length; i++) {
  6441. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6442. }
  6443. }
  6444. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6445. // FIXME: change any inactive to sendrecv or whatever they were originally
  6446. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6447. }
  6448. var prsdp = new SDP(pranswer.sdp);
  6449. if (self.webrtcIceTcpDisable) {
  6450. prsdp.removeTcpCandidates = true;
  6451. }
  6452. if (self.webrtcIceUdpDisable) {
  6453. prsdp.removeUdpCandidates = true;
  6454. }
  6455. var accept = $iq({to: this.peerjid,
  6456. type: 'set'})
  6457. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6458. action: 'session-accept',
  6459. initiator: this.initiator,
  6460. responder: this.responder,
  6461. sid: this.sid });
  6462. // FIXME why do we generate session-accept in 3 different places ?
  6463. prsdp.toJingle(
  6464. accept,
  6465. this.initiator == this.me ? 'initiator' : 'responder');
  6466. var sdp = this.peerconnection.localDescription.sdp;
  6467. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6468. // FIXME: change any inactive to sendrecv or whatever they were originally
  6469. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6470. }
  6471. var self = this;
  6472. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6473. function () {
  6474. //logger.log('setLocalDescription success');
  6475. self.setLocalDescription();
  6476. SSRCReplacement.processSessionInit(accept);
  6477. self.connection.sendIQ(accept,
  6478. function () {
  6479. var ack = {};
  6480. ack.source = 'answer';
  6481. $(document).trigger('ack.jingle', [self.sid, ack]);
  6482. },
  6483. function (stanza) {
  6484. var error = ($(stanza).find('error').length) ? {
  6485. code: $(stanza).find('error').attr('code'),
  6486. reason: $(stanza).find('error :first')[0].tagName
  6487. }:{};
  6488. error.source = 'answer';
  6489. JingleSessionPC.onJingleError(self.sid, error);
  6490. },
  6491. 10000);
  6492. },
  6493. function (e) {
  6494. logger.error('setLocalDescription failed', e);
  6495. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6496. }
  6497. );
  6498. };
  6499. JingleSessionPC.prototype.terminate = function (reason) {
  6500. this.state = 'ended';
  6501. this.reason = reason;
  6502. this.peerconnection.close();
  6503. if (this.statsinterval !== null) {
  6504. window.clearInterval(this.statsinterval);
  6505. this.statsinterval = null;
  6506. }
  6507. };
  6508. JingleSessionPC.prototype.active = function () {
  6509. return this.state == 'active';
  6510. };
  6511. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6512. var self = this;
  6513. if (candidate && !this.lasticecandidate) {
  6514. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6515. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6516. if (!(ice && jcand)) {
  6517. logger.error('failed to get ice && jcand');
  6518. return;
  6519. }
  6520. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6521. if (jcand.type === 'srflx') {
  6522. this.hadstuncandidate = true;
  6523. } else if (jcand.type === 'relay') {
  6524. this.hadturncandidate = true;
  6525. }
  6526. if (this.usetrickle) {
  6527. if (this.usedrip) {
  6528. if (this.drip_container.length === 0) {
  6529. // start 20ms callout
  6530. window.setTimeout(function () {
  6531. if (self.drip_container.length === 0) return;
  6532. self.sendIceCandidates(self.drip_container);
  6533. self.drip_container = [];
  6534. }, 20);
  6535. }
  6536. this.drip_container.push(candidate);
  6537. return;
  6538. } else {
  6539. self.sendIceCandidate([candidate]);
  6540. }
  6541. }
  6542. } else {
  6543. //logger.log('sendIceCandidate: last candidate.');
  6544. if (!this.usetrickle) {
  6545. //logger.log('should send full offer now...');
  6546. //FIXME why do we generate session-accept in 3 different places ?
  6547. var init = $iq({to: this.peerjid,
  6548. type: 'set'})
  6549. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6550. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6551. initiator: this.initiator,
  6552. sid: this.sid});
  6553. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6554. if (self.webrtcIceTcpDisable) {
  6555. this.localSDP.removeTcpCandidates = true;
  6556. }
  6557. if (self.webrtcIceUdpDisable) {
  6558. this.localSDP.removeUdpCandidates = true;
  6559. }
  6560. var sendJingle = function (ssrc) {
  6561. if(!ssrc)
  6562. ssrc = {};
  6563. self.localSDP.toJingle(
  6564. init,
  6565. self.initiator == self.me ? 'initiator' : 'responder',
  6566. ssrc);
  6567. SSRCReplacement.processSessionInit(init);
  6568. self.connection.sendIQ(init,
  6569. function () {
  6570. //logger.log('session initiate ack');
  6571. var ack = {};
  6572. ack.source = 'offer';
  6573. $(document).trigger('ack.jingle', [self.sid, ack]);
  6574. },
  6575. function (stanza) {
  6576. self.state = 'error';
  6577. self.peerconnection.close();
  6578. var error = ($(stanza).find('error').length) ? {
  6579. code: $(stanza).find('error').attr('code'),
  6580. reason: $(stanza).find('error :first')[0].tagName,
  6581. }:{};
  6582. error.source = 'offer';
  6583. JingleSessionPC.onJingleError(self.sid, error);
  6584. },
  6585. 10000);
  6586. };
  6587. sendJingle();
  6588. }
  6589. this.lasticecandidate = true;
  6590. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6591. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6592. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6593. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6594. }
  6595. }
  6596. };
  6597. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6598. logger.log('sendIceCandidates', candidates);
  6599. var cand = $iq({to: this.peerjid, type: 'set'})
  6600. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6601. action: 'transport-info',
  6602. initiator: this.initiator,
  6603. sid: this.sid});
  6604. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6605. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6606. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6607. if (cands.length > 0) {
  6608. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6609. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6610. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6611. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6612. }).c('transport', ice);
  6613. for (var i = 0; i < cands.length; i++) {
  6614. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6615. }
  6616. // add fingerprint
  6617. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6618. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6619. tmp.required = true;
  6620. cand.c(
  6621. 'fingerprint',
  6622. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6623. .t(tmp.fingerprint);
  6624. delete tmp.fingerprint;
  6625. cand.attrs(tmp);
  6626. cand.up();
  6627. }
  6628. cand.up(); // transport
  6629. cand.up(); // content
  6630. }
  6631. }
  6632. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6633. //logger.log('was this the last candidate', this.lasticecandidate);
  6634. this.connection.sendIQ(cand,
  6635. function () {
  6636. var ack = {};
  6637. ack.source = 'transportinfo';
  6638. $(document).trigger('ack.jingle', [this.sid, ack]);
  6639. },
  6640. function (stanza) {
  6641. var error = ($(stanza).find('error').length) ? {
  6642. code: $(stanza).find('error').attr('code'),
  6643. reason: $(stanza).find('error :first')[0].tagName,
  6644. }:{};
  6645. error.source = 'transportinfo';
  6646. JingleSessionPC.onJingleError(this.sid, error);
  6647. },
  6648. 10000);
  6649. };
  6650. JingleSessionPC.prototype.sendOffer = function () {
  6651. //logger.log('sendOffer...');
  6652. var self = this;
  6653. this.peerconnection.createOffer(function (sdp) {
  6654. self.createdOffer(sdp);
  6655. },
  6656. function (e) {
  6657. logger.error('createOffer failed', e);
  6658. },
  6659. this.media_constraints
  6660. );
  6661. };
  6662. // FIXME createdOffer is never used in jitsi-meet
  6663. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6664. //logger.log('createdOffer', sdp);
  6665. var self = this;
  6666. this.localSDP = new SDP(sdp.sdp);
  6667. //this.localSDP.mangle();
  6668. var sendJingle = function () {
  6669. var init = $iq({to: this.peerjid,
  6670. type: 'set'})
  6671. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6672. action: 'session-initiate',
  6673. initiator: this.initiator,
  6674. sid: this.sid});
  6675. self.localSDP.toJingle(
  6676. init,
  6677. this.initiator == this.me ? 'initiator' : 'responder');
  6678. SSRCReplacement.processSessionInit(init);
  6679. self.connection.sendIQ(init,
  6680. function () {
  6681. var ack = {};
  6682. ack.source = 'offer';
  6683. $(document).trigger('ack.jingle', [self.sid, ack]);
  6684. },
  6685. function (stanza) {
  6686. self.state = 'error';
  6687. self.peerconnection.close();
  6688. var error = ($(stanza).find('error').length) ? {
  6689. code: $(stanza).find('error').attr('code'),
  6690. reason: $(stanza).find('error :first')[0].tagName,
  6691. }:{};
  6692. error.source = 'offer';
  6693. JingleSessionPC.onJingleError(self.sid, error);
  6694. },
  6695. 10000);
  6696. }
  6697. sdp.sdp = this.localSDP.raw;
  6698. this.peerconnection.setLocalDescription(sdp,
  6699. function () {
  6700. if(self.usetrickle)
  6701. {
  6702. sendJingle();
  6703. }
  6704. self.setLocalDescription();
  6705. //logger.log('setLocalDescription success');
  6706. },
  6707. function (e) {
  6708. logger.error('setLocalDescription failed', e);
  6709. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6710. }
  6711. );
  6712. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6713. for (var i = 0; i < cands.length; i++) {
  6714. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6715. if (cand.type == 'srflx') {
  6716. this.hadstuncandidate = true;
  6717. } else if (cand.type == 'relay') {
  6718. this.hadturncandidate = true;
  6719. }
  6720. }
  6721. };
  6722. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6723. var self = this;
  6724. $(contents).each(function (idx, content) {
  6725. var name = $(content).attr('name');
  6726. var mediaType = this.getAttribute('name');
  6727. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6728. ssrcs.each(function () {
  6729. var ssrc = this.getAttribute('ssrc');
  6730. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6731. function () {
  6732. var owner = this.getAttribute('owner');
  6733. self.ssrcOwners[ssrc] = owner;
  6734. }
  6735. );
  6736. });
  6737. });
  6738. };
  6739. /**
  6740. * Returns the SSRC of local audio stream.
  6741. * @param mediaType 'audio' or 'video' media type
  6742. * @returns {*} the SSRC number of local audio or video stream.
  6743. */
  6744. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6745. return this.localStreamsSSRC[mediaType];
  6746. };
  6747. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6748. return this.ssrcOwners[ssrc];
  6749. };
  6750. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6751. //logger.log('setting remote description... ', desctype);
  6752. this.remoteSDP = new SDP('');
  6753. if (self.webrtcIceTcpDisable) {
  6754. this.remoteSDP.removeTcpCandidates = true;
  6755. }
  6756. if (self.webrtcIceUdpDisable) {
  6757. this.remoteSDP.removeUdpCandidates = true;
  6758. }
  6759. this.remoteSDP.fromJingle(elem);
  6760. this.readSsrcInfo($(elem).find(">content"));
  6761. if (this.peerconnection.remoteDescription) {
  6762. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6763. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6764. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6765. for (var i = 0; i < pranswer.media.length; i++) {
  6766. // make sure we have ice ufrag and pwd
  6767. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6768. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6769. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6770. } else {
  6771. logger.warn('no ice ufrag?');
  6772. }
  6773. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6774. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6775. } else {
  6776. logger.warn('no ice pwd?');
  6777. }
  6778. }
  6779. // copy over candidates
  6780. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6781. for (var j = 0; j < lines.length; j++) {
  6782. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6783. }
  6784. }
  6785. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6786. }
  6787. }
  6788. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6789. this.peerconnection.setRemoteDescription(remotedesc,
  6790. function () {
  6791. //logger.log('setRemoteDescription success');
  6792. },
  6793. function (e) {
  6794. logger.error('setRemoteDescription error', e);
  6795. JingleSessionPC.onJingleFatalError(self, e);
  6796. }
  6797. );
  6798. };
  6799. /**
  6800. * Adds remote ICE candidates to this Jingle session.
  6801. * @param elem An array of Jingle "content" elements?
  6802. */
  6803. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6804. var self = this;
  6805. if (this.peerconnection.signalingState == 'closed') {
  6806. return;
  6807. }
  6808. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6809. logger.log('trickle ice candidate arriving before session accept...');
  6810. // create a PRANSWER for setRemoteDescription
  6811. if (!this.remoteSDP) {
  6812. var cobbled = 'v=0\r\n' +
  6813. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6814. 's=-\r\n' +
  6815. 't=0 0\r\n';
  6816. // first, take some things from the local description
  6817. for (var i = 0; i < this.localSDP.media.length; i++) {
  6818. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6819. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6820. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6821. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6822. }
  6823. cobbled += 'a=inactive\r\n';
  6824. }
  6825. this.remoteSDP = new SDP(cobbled);
  6826. }
  6827. // then add things like ice and dtls from remote candidate
  6828. elem.each(function () {
  6829. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6830. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6831. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6832. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6833. var tmp = $(this).find('transport');
  6834. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6835. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6836. tmp = $(this).find('transport>fingerprint');
  6837. if (tmp.length) {
  6838. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6839. } else {
  6840. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6841. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6842. }
  6843. break;
  6844. }
  6845. }
  6846. }
  6847. });
  6848. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6849. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6850. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6851. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6852. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6853. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6854. }).length == this.remoteSDP.media.length;
  6855. if (iscomplete) {
  6856. logger.log('setting pranswer');
  6857. try {
  6858. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6859. function() {
  6860. },
  6861. function(e) {
  6862. logger.log('setRemoteDescription pranswer failed', e.toString());
  6863. });
  6864. } catch (e) {
  6865. logger.error('setting pranswer failed', e);
  6866. }
  6867. } else {
  6868. //logger.log('not yet setting pranswer');
  6869. }
  6870. }
  6871. // operate on each content element
  6872. elem.each(function () {
  6873. // would love to deactivate this, but firefox still requires it
  6874. var idx = -1;
  6875. var i;
  6876. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6877. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6878. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6879. idx = i;
  6880. break;
  6881. }
  6882. }
  6883. if (idx == -1) { // fall back to localdescription
  6884. for (i = 0; i < self.localSDP.media.length; i++) {
  6885. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6886. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6887. idx = i;
  6888. break;
  6889. }
  6890. }
  6891. }
  6892. var name = $(this).attr('name');
  6893. // TODO: check ice-pwd and ice-ufrag?
  6894. $(this).find('transport>candidate').each(function () {
  6895. var line, candidate;
  6896. var protocol = this.getAttribute('protocol');
  6897. protocol =
  6898. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6899. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6900. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6901. return;
  6902. }
  6903. line = SDPUtil.candidateFromJingle(this);
  6904. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6905. sdpMid: name,
  6906. candidate: line});
  6907. try {
  6908. self.peerconnection.addIceCandidate(candidate);
  6909. } catch (e) {
  6910. logger.error('addIceCandidate failed', e.toString(), line);
  6911. }
  6912. });
  6913. });
  6914. };
  6915. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6916. //logger.log('createAnswer', provisional);
  6917. var self = this;
  6918. this.peerconnection.createAnswer(
  6919. function (sdp) {
  6920. self.createdAnswer(sdp, provisional);
  6921. },
  6922. function (e) {
  6923. logger.error('createAnswer failed', e);
  6924. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6925. },
  6926. this.media_constraints
  6927. );
  6928. };
  6929. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6930. //logger.log('createAnswer callback');
  6931. var self = this;
  6932. this.localSDP = new SDP(sdp.sdp);
  6933. //this.localSDP.mangle();
  6934. this.usepranswer = provisional === true;
  6935. if (this.usetrickle) {
  6936. if (this.usepranswer) {
  6937. sdp.type = 'pranswer';
  6938. for (var i = 0; i < this.localSDP.media.length; i++) {
  6939. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6940. }
  6941. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6942. }
  6943. }
  6944. var self = this;
  6945. var sendJingle = function (ssrcs) {
  6946. // FIXME why do we generate session-accept in 3 different places ?
  6947. var accept = $iq({to: self.peerjid,
  6948. type: 'set'})
  6949. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6950. action: 'session-accept',
  6951. initiator: self.initiator,
  6952. responder: self.responder,
  6953. sid: self.sid });
  6954. if (self.webrtcIceTcpDisable) {
  6955. self.localSDP.removeTcpCandidates = true;
  6956. }
  6957. if (self.webrtcIceUdpDisable) {
  6958. self.localSDP.removeUdpCandidates = true;
  6959. }
  6960. self.localSDP.toJingle(
  6961. accept,
  6962. self.initiator == self.me ? 'initiator' : 'responder',
  6963. ssrcs);
  6964. SSRCReplacement.processSessionInit(accept);
  6965. self.connection.sendIQ(accept,
  6966. function () {
  6967. var ack = {};
  6968. ack.source = 'answer';
  6969. $(document).trigger('ack.jingle', [self.sid, ack]);
  6970. },
  6971. function (stanza) {
  6972. var error = ($(stanza).find('error').length) ? {
  6973. code: $(stanza).find('error').attr('code'),
  6974. reason: $(stanza).find('error :first')[0].tagName,
  6975. }:{};
  6976. error.source = 'answer';
  6977. JingleSessionPC.onJingleError(self.sid, error);
  6978. },
  6979. 10000);
  6980. }
  6981. sdp.sdp = this.localSDP.raw;
  6982. this.peerconnection.setLocalDescription(sdp,
  6983. function () {
  6984. //logger.log('setLocalDescription success');
  6985. if (self.usetrickle && !self.usepranswer) {
  6986. sendJingle();
  6987. }
  6988. self.setLocalDescription();
  6989. },
  6990. function (e) {
  6991. logger.error('setLocalDescription failed', e);
  6992. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6993. }
  6994. );
  6995. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6996. for (var j = 0; j < cands.length; j++) {
  6997. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6998. if (cand.type == 'srflx') {
  6999. this.hadstuncandidate = true;
  7000. } else if (cand.type == 'relay') {
  7001. this.hadturncandidate = true;
  7002. }
  7003. }
  7004. };
  7005. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  7006. var self = this,
  7007. term = $iq({to: this.peerjid,
  7008. type: 'set'})
  7009. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7010. action: 'session-terminate',
  7011. initiator: this.initiator,
  7012. sid: this.sid})
  7013. .c('reason')
  7014. .c(reason || 'success');
  7015. if (text) {
  7016. term.up().c('text').t(text);
  7017. }
  7018. this.connection.sendIQ(term,
  7019. function () {
  7020. self.peerconnection.close();
  7021. self.peerconnection = null;
  7022. self.terminate();
  7023. var ack = {};
  7024. ack.source = 'terminate';
  7025. $(document).trigger('ack.jingle', [self.sid, ack]);
  7026. },
  7027. function (stanza) {
  7028. var error = ($(stanza).find('error').length) ? {
  7029. code: $(stanza).find('error').attr('code'),
  7030. reason: $(stanza).find('error :first')[0].tagName,
  7031. }:{};
  7032. $(document).trigger('ack.jingle', [self.sid, error]);
  7033. },
  7034. 10000);
  7035. if (this.statsinterval !== null) {
  7036. window.clearInterval(this.statsinterval);
  7037. this.statsinterval = null;
  7038. }
  7039. };
  7040. /**
  7041. * Handles a Jingle source-add message for this Jingle session.
  7042. * @param elem An array of Jingle "content" elements.
  7043. */
  7044. JingleSessionPC.prototype.addSource = function (elem) {
  7045. var self = this;
  7046. // FIXME: dirty waiting
  7047. if (!this.peerconnection.localDescription)
  7048. {
  7049. logger.warn("addSource - localDescription not ready yet")
  7050. setTimeout(function()
  7051. {
  7052. self.addSource(elem);
  7053. },
  7054. 200
  7055. );
  7056. return;
  7057. }
  7058. logger.log('addssrc', new Date().getTime());
  7059. logger.log('ice', this.peerconnection.iceConnectionState);
  7060. this.readSsrcInfo(elem);
  7061. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7062. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7063. $(elem).each(function (idx, content) {
  7064. var name = $(content).attr('name');
  7065. var lines = '';
  7066. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7067. var semantics = this.getAttribute('semantics');
  7068. var ssrcs = $(this).find('>source').map(function () {
  7069. return this.getAttribute('ssrc');
  7070. }).get();
  7071. if (ssrcs.length) {
  7072. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7073. }
  7074. });
  7075. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7076. tmp.each(function () {
  7077. var ssrc = $(this).attr('ssrc');
  7078. if(mySdp.containsSSRC(ssrc)){
  7079. /**
  7080. * This happens when multiple participants change their streams at the same time and
  7081. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  7082. * addssrc are scheduled for update IQ. See
  7083. */
  7084. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  7085. return;
  7086. }
  7087. if (sdp.containsSSRC(ssrc)) {
  7088. logger.warn("Source-add request for existing SSRC: " + ssrc);
  7089. return;
  7090. }
  7091. $(this).find('>parameter').each(function () {
  7092. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7093. if ($(this).attr('value') && $(this).attr('value').length)
  7094. lines += ':' + $(this).attr('value');
  7095. lines += '\r\n';
  7096. });
  7097. });
  7098. sdp.media.forEach(function(media, idx) {
  7099. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7100. return;
  7101. sdp.media[idx] += lines;
  7102. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  7103. self.addssrc[idx] += lines;
  7104. });
  7105. sdp.raw = sdp.session + sdp.media.join('');
  7106. });
  7107. this.modifySourcesQueue.push(function() {
  7108. // When a source is added and if this is FF, a new channel is allocated
  7109. // for receiving the added source. We need to diffuse the SSRC of this
  7110. // new recvonly channel to the rest of the peers.
  7111. logger.log('modify sources done');
  7112. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7113. logger.log("SDPs", mySdp, newSdp);
  7114. self.notifyMySSRCUpdate(mySdp, newSdp);
  7115. });
  7116. };
  7117. /**
  7118. * Handles a Jingle source-remove message for this Jingle session.
  7119. * @param elem An array of Jingle "content" elements.
  7120. */
  7121. JingleSessionPC.prototype.removeSource = function (elem) {
  7122. var self = this;
  7123. // FIXME: dirty waiting
  7124. if (!this.peerconnection.localDescription) {
  7125. logger.warn("removeSource - localDescription not ready yet");
  7126. setTimeout(function() {
  7127. self.removeSource(elem);
  7128. },
  7129. 200
  7130. );
  7131. return;
  7132. }
  7133. logger.log('removessrc', new Date().getTime());
  7134. logger.log('ice', this.peerconnection.iceConnectionState);
  7135. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7136. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7137. $(elem).each(function (idx, content) {
  7138. var name = $(content).attr('name');
  7139. var lines = '';
  7140. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7141. var semantics = this.getAttribute('semantics');
  7142. var ssrcs = $(this).find('>source').map(function () {
  7143. return this.getAttribute('ssrc');
  7144. }).get();
  7145. if (ssrcs.length) {
  7146. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7147. }
  7148. });
  7149. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7150. tmp.each(function () {
  7151. var ssrc = $(this).attr('ssrc');
  7152. // This should never happen, but can be useful for bug detection
  7153. if(mySdp.containsSSRC(ssrc)){
  7154. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  7155. return;
  7156. }
  7157. $(this).find('>parameter').each(function () {
  7158. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7159. if ($(this).attr('value') && $(this).attr('value').length)
  7160. lines += ':' + $(this).attr('value');
  7161. lines += '\r\n';
  7162. });
  7163. });
  7164. sdp.media.forEach(function(media, idx) {
  7165. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7166. return;
  7167. sdp.media[idx] += lines;
  7168. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  7169. self.removessrc[idx] += lines;
  7170. });
  7171. sdp.raw = sdp.session + sdp.media.join('');
  7172. });
  7173. this.modifySourcesQueue.push(function() {
  7174. // When a source is removed and if this is FF, the recvonly channel that
  7175. // receives the remote stream is deactivated . We need to diffuse the
  7176. // recvonly SSRC removal to the rest of the peers.
  7177. logger.log('modify sources done');
  7178. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7179. logger.log("SDPs", mySdp, newSdp);
  7180. self.notifyMySSRCUpdate(mySdp, newSdp);
  7181. });
  7182. };
  7183. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  7184. var self = this;
  7185. if (this.peerconnection.signalingState == 'closed') return;
  7186. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  7187. || this.switchstreams || this.addingStreams)){
  7188. // There is nothing to do since scheduled job might have been executed by another succeeding call
  7189. this.setLocalDescription();
  7190. if(successCallback){
  7191. successCallback();
  7192. }
  7193. queueCallback();
  7194. return;
  7195. }
  7196. // Reset switch streams flags
  7197. this.switchstreams = false;
  7198. this.addingStreams = false;
  7199. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7200. // add sources
  7201. this.addssrc.forEach(function(lines, idx) {
  7202. sdp.media[idx] += lines;
  7203. });
  7204. this.addssrc = [];
  7205. // remove sources
  7206. this.removessrc.forEach(function(lines, idx) {
  7207. lines = lines.split('\r\n');
  7208. lines.pop(); // remove empty last element;
  7209. lines.forEach(function(line) {
  7210. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  7211. });
  7212. });
  7213. this.removessrc = [];
  7214. sdp.raw = sdp.session + sdp.media.join('');
  7215. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  7216. function() {
  7217. if(self.signalingState == 'closed') {
  7218. logger.error("createAnswer attempt on closed state");
  7219. queueCallback("createAnswer attempt on closed state");
  7220. return;
  7221. }
  7222. self.peerconnection.createAnswer(
  7223. function(modifiedAnswer) {
  7224. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  7225. if (self.pendingop !== null) {
  7226. var sdp = new SDP(modifiedAnswer.sdp);
  7227. if (sdp.media.length > 1) {
  7228. switch(self.pendingop) {
  7229. case 'mute':
  7230. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  7231. break;
  7232. case 'unmute':
  7233. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  7234. break;
  7235. }
  7236. sdp.raw = sdp.session + sdp.media.join('');
  7237. modifiedAnswer.sdp = sdp.raw;
  7238. }
  7239. self.pendingop = null;
  7240. }
  7241. // FIXME: pushing down an answer while ice connection state
  7242. // is still checking is bad...
  7243. //logger.log(self.peerconnection.iceConnectionState);
  7244. // trying to work around another chrome bug
  7245. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  7246. self.peerconnection.setLocalDescription(modifiedAnswer,
  7247. function() {
  7248. //logger.log('modified setLocalDescription ok');
  7249. self.setLocalDescription();
  7250. if(successCallback){
  7251. successCallback();
  7252. }
  7253. queueCallback();
  7254. },
  7255. function(error) {
  7256. logger.error('modified setLocalDescription failed', error);
  7257. queueCallback(error);
  7258. }
  7259. );
  7260. },
  7261. function(error) {
  7262. logger.error('modified answer failed', error);
  7263. queueCallback(error);
  7264. }
  7265. );
  7266. },
  7267. function(error) {
  7268. logger.error('modify failed', error);
  7269. queueCallback(error);
  7270. }
  7271. );
  7272. };
  7273. /**
  7274. * Switches video streams.
  7275. * @param newStream new stream that will be used as video of this session.
  7276. * @param oldStream old video stream of this session.
  7277. * @param successCallback callback executed after successful stream switch.
  7278. * @param isAudio whether the streams are audio (if true) or video (if false).
  7279. */
  7280. JingleSessionPC.prototype.switchStreams =
  7281. function (newStream, oldStream, successCallback, isAudio) {
  7282. var self = this;
  7283. var sender, newTrack;
  7284. var senderKind = isAudio ? 'audio' : 'video';
  7285. // Remember SDP to figure out added/removed SSRCs
  7286. var oldSdp = null;
  7287. if (self.peerconnection) {
  7288. if (self.peerconnection.localDescription) {
  7289. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7290. }
  7291. if (RTCBrowserType.getBrowserType() ===
  7292. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  7293. // On Firefox we don't replace MediaStreams as this messes up the
  7294. // m-lines (which can't be removed in Plan Unified) and brings a lot
  7295. // of complications. Instead, we use the RTPSender and replace just
  7296. // the track.
  7297. // Find the right sender (for audio or video)
  7298. self.peerconnection.peerconnection.getSenders().some(function (s) {
  7299. if (s.track && s.track.kind === senderKind) {
  7300. sender = s;
  7301. return true;
  7302. }
  7303. });
  7304. if (sender) {
  7305. // We assume that our streams have a single track, either audio
  7306. // or video.
  7307. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  7308. newStream.getVideoTracks()[0];
  7309. sender.replaceTrack(newTrack)
  7310. .then(function() {
  7311. console.log("Replaced a track, isAudio=" + isAudio);
  7312. })
  7313. .catch(function(err) {
  7314. console.log("Failed to replace a track: " + err);
  7315. });
  7316. } else {
  7317. console.log("Cannot switch tracks: no RTPSender.");
  7318. }
  7319. } else {
  7320. self.peerconnection.removeStream(oldStream, true);
  7321. if (newStream) {
  7322. self.peerconnection.addStream(newStream);
  7323. }
  7324. }
  7325. }
  7326. // Conference is not active
  7327. if (!oldSdp) {
  7328. successCallback();
  7329. return;
  7330. }
  7331. self.switchstreams = true;
  7332. self.modifySourcesQueue.push(function() {
  7333. logger.log('modify sources done');
  7334. successCallback();
  7335. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7336. logger.log("SDPs", oldSdp, newSdp);
  7337. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7338. });
  7339. };
  7340. /**
  7341. * Adds streams.
  7342. * @param stream new stream that will be added.
  7343. * @param success_callback callback executed after successful stream addition.
  7344. */
  7345. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7346. var self = this;
  7347. // Remember SDP to figure out added/removed SSRCs
  7348. var oldSdp = null;
  7349. if(this.peerconnection) {
  7350. if(this.peerconnection.localDescription) {
  7351. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7352. }
  7353. if(stream)
  7354. this.peerconnection.addStream(stream);
  7355. }
  7356. // Conference is not active
  7357. if(!oldSdp || !this.peerconnection) {
  7358. callback();
  7359. return;
  7360. }
  7361. this.addingStreams = true;
  7362. this.modifySourcesQueue.push(function() {
  7363. logger.log('modify sources done');
  7364. callback();
  7365. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7366. logger.log("SDPs", oldSdp, newSdp);
  7367. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7368. });
  7369. }
  7370. /**
  7371. * Remove streams.
  7372. * @param stream stream that will be removed.
  7373. * @param success_callback callback executed after successful stream addition.
  7374. */
  7375. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7376. var self = this;
  7377. // Remember SDP to figure out added/removed SSRCs
  7378. var oldSdp = null;
  7379. if(this.peerconnection) {
  7380. if(this.peerconnection.localDescription) {
  7381. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7382. }
  7383. if(stream)
  7384. this.peerconnection.removeStream(stream);
  7385. }
  7386. // Conference is not active
  7387. if(!oldSdp || !this.peerconnection) {
  7388. callback();
  7389. return;
  7390. }
  7391. this.addingStreams = true;
  7392. this.modifySourcesQueue.push(function() {
  7393. logger.log('modify sources done');
  7394. callback();
  7395. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7396. logger.log("SDPs", oldSdp, newSdp);
  7397. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7398. });
  7399. }
  7400. /**
  7401. * Figures out added/removed ssrcs and send update IQs.
  7402. * @param old_sdp SDP object for old description.
  7403. * @param new_sdp SDP object for new description.
  7404. */
  7405. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7406. if (!(this.peerconnection.signalingState == 'stable' &&
  7407. this.peerconnection.iceConnectionState == 'connected')){
  7408. logger.log("Too early to send updates");
  7409. return;
  7410. }
  7411. // send source-remove IQ.
  7412. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7413. var remove = $iq({to: this.peerjid, type: 'set'})
  7414. .c('jingle', {
  7415. xmlns: 'urn:xmpp:jingle:1',
  7416. action: 'source-remove',
  7417. initiator: this.initiator,
  7418. sid: this.sid
  7419. }
  7420. );
  7421. var removed = sdpDiffer.toJingle(remove);
  7422. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7423. // it in the current form
  7424. if (removed)
  7425. remove = SSRCReplacement.processSourceRemove(remove);
  7426. if (removed && remove) {
  7427. logger.info("Sending source-remove", remove);
  7428. this.connection.sendIQ(remove,
  7429. function (res) {
  7430. logger.info('got remove result', res);
  7431. },
  7432. function (err) {
  7433. logger.error('got remove error', err);
  7434. }
  7435. );
  7436. } else {
  7437. logger.log('removal not necessary');
  7438. }
  7439. // send source-add IQ.
  7440. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7441. var add = $iq({to: this.peerjid, type: 'set'})
  7442. .c('jingle', {
  7443. xmlns: 'urn:xmpp:jingle:1',
  7444. action: 'source-add',
  7445. initiator: this.initiator,
  7446. sid: this.sid
  7447. }
  7448. );
  7449. var added = sdpDiffer.toJingle(add);
  7450. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7451. // it in the current form
  7452. if (added)
  7453. add = SSRCReplacement.processSourceAdd(add);
  7454. if (added && add) {
  7455. logger.info("Sending source-add", add);
  7456. this.connection.sendIQ(add,
  7457. function (res) {
  7458. logger.info('got add result', res);
  7459. },
  7460. function (err) {
  7461. logger.error('got add error', err);
  7462. }
  7463. );
  7464. } else {
  7465. logger.log('addition not necessary');
  7466. }
  7467. };
  7468. /**
  7469. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7470. *
  7471. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7472. * tracks; otherwise, <tt>false</tt>
  7473. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7474. * tracks have been enabled/disabled. The function may, optionally, return
  7475. * another function which is to be invoked after the whole mute/unmute operation
  7476. * has completed successfully.
  7477. * @param options an object which specifies optional arguments such as the
  7478. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7479. * specifies whether the method was initiated in response to a user command (in
  7480. * contrast to an automatic decision made by the application logic)
  7481. */
  7482. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7483. var byUser;
  7484. if (options) {
  7485. byUser = options.byUser;
  7486. if (typeof byUser === 'undefined') {
  7487. byUser = true;
  7488. }
  7489. } else {
  7490. byUser = true;
  7491. }
  7492. // The user's command to mute the (local) video takes precedence over any
  7493. // automatic decision made by the application logic.
  7494. if (byUser) {
  7495. this.videoMuteByUser = mute;
  7496. } else if (this.videoMuteByUser) {
  7497. return;
  7498. }
  7499. this.hardMuteVideo(mute);
  7500. var self = this;
  7501. var oldSdp = null;
  7502. if(self.peerconnection) {
  7503. if(self.peerconnection.localDescription) {
  7504. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7505. }
  7506. }
  7507. this.modifySourcesQueue.push(function() {
  7508. logger.log('modify sources done');
  7509. callback(mute);
  7510. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7511. logger.log("SDPs", oldSdp, newSdp);
  7512. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7513. });
  7514. };
  7515. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7516. this.pendingop = muted ? 'mute' : 'unmute';
  7517. };
  7518. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7519. var info = $iq({to: this.peerjid,
  7520. type: 'set'})
  7521. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7522. action: 'session-info',
  7523. initiator: this.initiator,
  7524. sid: this.sid });
  7525. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7526. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7527. if (content) {
  7528. info.attrs({'name': content});
  7529. }
  7530. this.connection.send(info);
  7531. };
  7532. JingleSessionPC.prototype.sendRinging = function () {
  7533. var info = $iq({to: this.peerjid,
  7534. type: 'set'})
  7535. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7536. action: 'session-info',
  7537. initiator: this.initiator,
  7538. sid: this.sid });
  7539. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7540. this.connection.send(info);
  7541. };
  7542. JingleSessionPC.prototype.getStats = function (interval) {
  7543. var self = this;
  7544. var recv = {audio: 0, video: 0};
  7545. var lost = {audio: 0, video: 0};
  7546. var lastrecv = {audio: 0, video: 0};
  7547. var lastlost = {audio: 0, video: 0};
  7548. var loss = {audio: 0, video: 0};
  7549. var delta = {audio: 0, video: 0};
  7550. this.statsinterval = window.setInterval(function () {
  7551. if (self && self.peerconnection && self.peerconnection.getStats) {
  7552. self.peerconnection.getStats(function (stats) {
  7553. var results = stats.result();
  7554. // TODO: there are so much statistics you can get from this..
  7555. for (var i = 0; i < results.length; ++i) {
  7556. if (results[i].type == 'ssrc') {
  7557. var packetsrecv = results[i].stat('packetsReceived');
  7558. var packetslost = results[i].stat('packetsLost');
  7559. if (packetsrecv && packetslost) {
  7560. packetsrecv = parseInt(packetsrecv, 10);
  7561. packetslost = parseInt(packetslost, 10);
  7562. if (results[i].stat('googFrameRateReceived')) {
  7563. lastlost.video = lost.video;
  7564. lastrecv.video = recv.video;
  7565. recv.video = packetsrecv;
  7566. lost.video = packetslost;
  7567. } else {
  7568. lastlost.audio = lost.audio;
  7569. lastrecv.audio = recv.audio;
  7570. recv.audio = packetsrecv;
  7571. lost.audio = packetslost;
  7572. }
  7573. }
  7574. }
  7575. }
  7576. delta.audio = recv.audio - lastrecv.audio;
  7577. delta.video = recv.video - lastrecv.video;
  7578. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7579. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7580. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7581. });
  7582. }
  7583. }, interval || 3000);
  7584. return this.statsinterval;
  7585. };
  7586. JingleSessionPC.onJingleError = function (session, error)
  7587. {
  7588. logger.error("Jingle error", error);
  7589. }
  7590. JingleSessionPC.onJingleFatalError = function (session, error)
  7591. {
  7592. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7593. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7594. }
  7595. JingleSessionPC.prototype.setLocalDescription = function () {
  7596. var self = this;
  7597. var newssrcs = [];
  7598. if(!this.peerconnection.localDescription)
  7599. return;
  7600. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7601. var i;
  7602. session.media.forEach(function (media) {
  7603. if (media.ssrcs && media.ssrcs.length > 0) {
  7604. // TODO(gp) maybe exclude FID streams?
  7605. media.ssrcs.forEach(function (ssrc) {
  7606. if (ssrc.attribute !== 'cname') {
  7607. return;
  7608. }
  7609. newssrcs.push({
  7610. 'ssrc': ssrc.id,
  7611. 'type': media.type
  7612. });
  7613. // FIXME allows for only one SSRC per media type
  7614. self.localStreamsSSRC[media.type] = ssrc.id;
  7615. });
  7616. }
  7617. });
  7618. logger.log('new ssrcs', newssrcs);
  7619. // Bind us as local SSRCs owner
  7620. if (newssrcs.length > 0) {
  7621. for (i = 0; i < newssrcs.length; i++) {
  7622. var ssrc = newssrcs[i].ssrc;
  7623. var myJid = self.me;
  7624. self.ssrcOwners[ssrc] = myJid;
  7625. }
  7626. }
  7627. }
  7628. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7629. JingleSessionPC.prototype.sendKeyframe = function () {
  7630. var pc = this.peerconnection;
  7631. logger.log('sendkeyframe', pc.iceConnectionState);
  7632. if (pc.iceConnectionState !== 'connected') return; // safe...
  7633. var self = this;
  7634. pc.setRemoteDescription(
  7635. pc.remoteDescription,
  7636. function () {
  7637. pc.createAnswer(
  7638. function (modifiedAnswer) {
  7639. pc.setLocalDescription(
  7640. modifiedAnswer,
  7641. function () {
  7642. // noop
  7643. },
  7644. function (error) {
  7645. logger.log('triggerKeyframe setLocalDescription failed', error);
  7646. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7647. }
  7648. );
  7649. },
  7650. function (error) {
  7651. logger.log('triggerKeyframe createAnswer failed', error);
  7652. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7653. }
  7654. );
  7655. },
  7656. function (error) {
  7657. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7658. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7659. }
  7660. );
  7661. }
  7662. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7663. var self = this;
  7664. var thessrc;
  7665. var streamId = RTC.getStreamID(data.stream);
  7666. // look up an associated JID for a stream id
  7667. if (!streamId) {
  7668. logger.error("No stream ID for", data.stream);
  7669. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7670. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7671. var ssrclines = this.peerconnection.remoteDescription?
  7672. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7673. ssrclines = ssrclines.filter(function (line) {
  7674. // NOTE(gp) previously we filtered on the mslabel, but that property
  7675. // is not always present.
  7676. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7677. if (RTCBrowserType.isTemasysPluginUsed()) {
  7678. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7679. } else {
  7680. return ((line.indexOf('msid:' + streamId) !== -1));
  7681. }
  7682. });
  7683. if (ssrclines.length) {
  7684. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7685. if (!self.ssrcOwners[thessrc]) {
  7686. logger.error("No SSRC owner known for: " + thessrc);
  7687. return;
  7688. }
  7689. data.peerjid = self.ssrcOwners[thessrc];
  7690. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7691. } else {
  7692. logger.error("No SSRC lines for ", streamId);
  7693. }
  7694. }
  7695. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7696. var isVideo = data.stream.getVideoTracks().length > 0;
  7697. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7698. if (isVideo &&
  7699. data.peerjid && this.peerjid === data.peerjid &&
  7700. data.stream.getVideoTracks().length === 0 &&
  7701. RTC.localVideo.getTracks().length > 0) {
  7702. window.setTimeout(function () {
  7703. self.sendKeyframe();
  7704. }, 3000);
  7705. }
  7706. }
  7707. /**
  7708. * Returns the ice connection state for the peer connection.
  7709. * @returns the ice connection state for the peer connection.
  7710. */
  7711. JingleSessionPC.prototype.getIceConnectionState = function () {
  7712. return this.peerconnection.iceConnectionState;
  7713. }
  7714. module.exports = JingleSessionPC;
  7715. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7716. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":43,"jitsi-meet-logger":48,"sdp-transform":76}],29:[function(require,module,exports){
  7717. (function (__filename){
  7718. /* global $ */
  7719. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7720. /*
  7721. Here we do modifications of local video SSRCs. There are 2 situations we have
  7722. to handle:
  7723. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7724. have no local camera and it is not generated automatically, but SSRC=1 is
  7725. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7726. and we won't be able to request video key frames correctly.
  7727. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7728. in future. It turned out that Chrome may keep on using the SSRC of removed
  7729. video stream in RTCP even though a new one has been created. So we just
  7730. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7731. notifications are blocked once first video SSRC is advertised to the focus.
  7732. What this hack does:
  7733. 1. Stores the SSRC of the first video stream created by
  7734. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7735. b) watching for 'source-add' for new video stream if it has not been
  7736. created in step a)
  7737. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7738. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7739. returned to the other parts of the application.
  7740. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7741. blocks those notifications. This makes Jicofo and all participants think
  7742. that it exists all the time even if the video stream has been removed or
  7743. replaced locally. Thanks to that there is no additional signaling activity
  7744. on video mute or when switching to the desktop stream.
  7745. */
  7746. var SDP = require('./SDP');
  7747. var RandomUtil = require('../util/RandomUtil');
  7748. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7749. /**
  7750. * The hack is enabled on all browsers except FF by default
  7751. * FIXME finish the hack once removeStream method is implemented in FF
  7752. * @type {boolean}
  7753. */
  7754. var isEnabled = !RTCBrowserType.isFirefox();
  7755. /**
  7756. * Stored SSRC of local video stream.
  7757. */
  7758. var localVideoSSRC;
  7759. /**
  7760. * SSRC used for recvonly video stream when we have no local camera.
  7761. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7762. * instead of 1.
  7763. */
  7764. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7765. /**
  7766. * cname for <tt>localRecvOnlySSRC</tt>
  7767. */
  7768. var localRecvOnlyCName;
  7769. /**
  7770. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7771. * from given Jingle IQ.
  7772. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7773. * @param actionName display name of the action which will be printed in log
  7774. * messages.
  7775. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7776. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7777. * other SSRCs left to be signaled after removing it.
  7778. */
  7779. var filterOutSource = function (modifyIq, actionName) {
  7780. var modifyIqTree = $(modifyIq.tree());
  7781. if (!localVideoSSRC)
  7782. return modifyIqTree[0];
  7783. var videoSSRC = modifyIqTree.find(
  7784. '>jingle>content[name="video"]' +
  7785. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7786. if (!videoSSRC.length) {
  7787. return modifyIqTree[0];
  7788. }
  7789. logger.info(
  7790. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7791. videoSSRC.remove();
  7792. // Check if any sources still left to be added/removed
  7793. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7794. return modifyIqTree[0];
  7795. } else {
  7796. return null;
  7797. }
  7798. };
  7799. /**
  7800. * Scans given Jingle IQ for video SSRC and stores it.
  7801. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7802. */
  7803. var storeLocalVideoSSRC = function (jingleIq) {
  7804. var videoSSRCs =
  7805. $(jingleIq.tree())
  7806. .find('>jingle>content[name="video"]>description>source');
  7807. videoSSRCs.each(function (idx, ssrcElem) {
  7808. if (localVideoSSRC)
  7809. return;
  7810. // We consider SSRC real only if it has msid attribute
  7811. // recvonly streams in FF do not have it as well as local SSRCs
  7812. // we generate for recvonly streams in Chrome
  7813. var ssrSel = $(ssrcElem);
  7814. var msid = ssrSel.find('>parameter[name="msid"]');
  7815. if (msid.length) {
  7816. var ssrcVal = ssrSel.attr('ssrc');
  7817. if (ssrcVal) {
  7818. localVideoSSRC = ssrcVal;
  7819. logger.info('Stored local video SSRC' +
  7820. ' for future re-use: ' + localVideoSSRC);
  7821. }
  7822. }
  7823. });
  7824. };
  7825. /**
  7826. * Generates new label/mslabel attribute
  7827. * @returns {string} label/mslabel attribute
  7828. */
  7829. function generateLabel() {
  7830. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7831. "-" + RandomUtil.randomHexString(4) + "-" +
  7832. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  7833. }
  7834. /**
  7835. * Generates new SSRC for local video recvonly stream.
  7836. * FIXME what about eventual SSRC collision ?
  7837. */
  7838. function generateRecvonlySSRC() {
  7839. localVideoSSRC = localRecvOnlySSRC =
  7840. localVideoSSRC ?
  7841. localVideoSSRC : Math.random().toString(10).substring(2, 11);
  7842. localRecvOnlyCName =
  7843. Math.random().toString(36).substring(2);
  7844. localRecvOnlyMSLabel = generateLabel();
  7845. localRecvOnlyLabel = generateLabel();
  7846. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  7847. logger.info(
  7848. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7849. ", cname: " + localRecvOnlyCName);
  7850. }
  7851. var LocalSSRCReplacement = {
  7852. /**
  7853. * Method must be called before 'session-initiate' or 'session-invite' is
  7854. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7855. *
  7856. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7857. * which will be scanned for local video SSRC.
  7858. */
  7859. processSessionInit: function (sessionInit) {
  7860. if (!isEnabled)
  7861. return;
  7862. if (localVideoSSRC) {
  7863. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7864. return;
  7865. }
  7866. storeLocalVideoSSRC(sessionInit);
  7867. },
  7868. /**
  7869. * If we have local video SSRC stored searched given
  7870. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7871. * with the stored one.
  7872. * @param localDescription local description object that will have local
  7873. * video SSRC replaced with the stored one
  7874. * @returns modified <tt>localDescription</tt> object.
  7875. */
  7876. mungeLocalVideoSSRC: function (localDescription) {
  7877. if (!isEnabled)
  7878. return localDescription;
  7879. if (!localDescription) {
  7880. logger.warn("localDescription is null or undefined");
  7881. return localDescription;
  7882. }
  7883. // IF we have local video SSRC stored make sure it is replaced
  7884. // with old SSRC
  7885. var sdp = new SDP(localDescription.sdp);
  7886. if (sdp.media.length < 2)
  7887. return;
  7888. if (localVideoSSRC && sdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7889. !sdp.containsSSRC(localVideoSSRC)) {
  7890. // Get new video SSRC
  7891. var map = sdp.getMediaSsrcMap();
  7892. var videoPart = map[1];
  7893. var videoSSRCs = videoPart.ssrcs;
  7894. var newSSRC = Object.keys(videoSSRCs)[0];
  7895. logger.info(
  7896. "Replacing new video SSRC: " + newSSRC +
  7897. " with " + localVideoSSRC);
  7898. localDescription.sdp =
  7899. sdp.raw.replace(
  7900. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7901. 'a=ssrc:' + localVideoSSRC);
  7902. }
  7903. else if (sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7904. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7905. // Make sure we have any SSRC for recvonly video stream
  7906. if (!localRecvOnlySSRC) {
  7907. generateRecvonlySSRC();
  7908. }
  7909. logger.info('No SSRC in video recvonly stream' +
  7910. ' - adding SSRC: ' + localRecvOnlySSRC);
  7911. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7912. ' cname:' + localRecvOnlyCName + '\r\n' +
  7913. 'a=ssrc:' + localRecvOnlySSRC +
  7914. ' msid:' + localRecvOnlyMSID + '\r\n' +
  7915. 'a=ssrc:' + localRecvOnlySSRC +
  7916. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  7917. 'a=ssrc:' + localRecvOnlySSRC +
  7918. ' label:' + localRecvOnlyLabel + '\r\n';
  7919. localDescription.sdp = sdp.session + sdp.media.join('');
  7920. }
  7921. return localDescription;
  7922. },
  7923. /**
  7924. * Method must be called before 'source-add' notification is sent. In case
  7925. * we have local video SSRC advertised already it will be removed from the
  7926. * notification. If no other SSRCs are described by given IQ null will be
  7927. * returned which means that there is no point in sending the notification.
  7928. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7929. * @returns modified 'source-add' IQ which can be sent to the focus or
  7930. * <tt>null</tt> if no notification shall be sent. It is no longer
  7931. * a Strophe IQ Builder instance, but DOM element tree.
  7932. */
  7933. processSourceAdd: function (sourceAdd) {
  7934. if (!isEnabled)
  7935. return sourceAdd;
  7936. if (!localVideoSSRC) {
  7937. // Store local SSRC if available
  7938. storeLocalVideoSSRC(sourceAdd);
  7939. return sourceAdd;
  7940. } else {
  7941. return filterOutSource(sourceAdd, 'source-add');
  7942. }
  7943. },
  7944. /**
  7945. * Method must be called before 'source-remove' notification is sent.
  7946. * Removes local video SSRC from the notification. If there are no other
  7947. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7948. * means that there is no point in sending the notification.
  7949. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7950. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7951. * <tt>null</tt> if no notification shall be sent. It is no longer
  7952. * a Strophe IQ Builder instance, but DOM element tree.
  7953. */
  7954. processSourceRemove: function (sourceRemove) {
  7955. if (!isEnabled)
  7956. return sourceRemove;
  7957. return filterOutSource(sourceRemove, 'source-remove');
  7958. },
  7959. /**
  7960. * Turns the hack on or off
  7961. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7962. * to disable it
  7963. */
  7964. setEnabled: function (enabled) {
  7965. isEnabled = enabled;
  7966. }
  7967. };
  7968. module.exports = LocalSSRCReplacement;
  7969. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7970. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":48}],30:[function(require,module,exports){
  7971. (function (__filename){
  7972. /* jshint -W117 */
  7973. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7974. var SDPUtil = require("./SDPUtil");
  7975. // SDP STUFF
  7976. function SDP(sdp) {
  7977. /**
  7978. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7979. * @type {boolean}
  7980. */
  7981. this.removeTcpCandidates = false;
  7982. /**
  7983. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7984. * @type {boolean}
  7985. */
  7986. this.removeUdpCandidates = false;
  7987. this.media = sdp.split('\r\nm=');
  7988. for (var i = 1; i < this.media.length; i++) {
  7989. this.media[i] = 'm=' + this.media[i];
  7990. if (i != this.media.length - 1) {
  7991. this.media[i] += '\r\n';
  7992. }
  7993. }
  7994. this.session = this.media.shift() + '\r\n';
  7995. this.raw = this.session + this.media.join('');
  7996. }
  7997. /**
  7998. * Returns map of MediaChannel mapped per channel idx.
  7999. */
  8000. SDP.prototype.getMediaSsrcMap = function() {
  8001. var self = this;
  8002. var media_ssrcs = {};
  8003. var tmp;
  8004. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  8005. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  8006. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  8007. var media = {
  8008. mediaindex: mediaindex,
  8009. mid: mid,
  8010. ssrcs: {},
  8011. ssrcGroups: []
  8012. };
  8013. media_ssrcs[mediaindex] = media;
  8014. tmp.forEach(function (line) {
  8015. var linessrc = line.substring(7).split(' ')[0];
  8016. // allocate new ChannelSsrc
  8017. if(!media.ssrcs[linessrc]) {
  8018. media.ssrcs[linessrc] = {
  8019. ssrc: linessrc,
  8020. lines: []
  8021. };
  8022. }
  8023. media.ssrcs[linessrc].lines.push(line);
  8024. });
  8025. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  8026. tmp.forEach(function(line){
  8027. var idx = line.indexOf(' ');
  8028. var semantics = line.substr(0, idx).substr(13);
  8029. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8030. if (ssrcs.length) {
  8031. media.ssrcGroups.push({
  8032. semantics: semantics,
  8033. ssrcs: ssrcs
  8034. });
  8035. }
  8036. });
  8037. }
  8038. return media_ssrcs;
  8039. };
  8040. /**
  8041. * Returns <tt>true</tt> if this SDP contains given SSRC.
  8042. * @param ssrc the ssrc to check.
  8043. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  8044. */
  8045. SDP.prototype.containsSSRC = function (ssrc) {
  8046. // FIXME this code is really strange - improve it if you can
  8047. var medias = this.getMediaSsrcMap();
  8048. var result = false;
  8049. Object.keys(medias).forEach(function (mediaindex) {
  8050. if (result)
  8051. return;
  8052. if (medias[mediaindex].ssrcs[ssrc]) {
  8053. result = true;
  8054. }
  8055. });
  8056. return result;
  8057. };
  8058. // remove iSAC and CN from SDP
  8059. SDP.prototype.mangle = function () {
  8060. var i, j, mline, lines, rtpmap, newdesc;
  8061. for (i = 0; i < this.media.length; i++) {
  8062. lines = this.media[i].split('\r\n');
  8063. lines.pop(); // remove empty last element
  8064. mline = SDPUtil.parse_mline(lines.shift());
  8065. if (mline.media != 'audio')
  8066. continue;
  8067. newdesc = '';
  8068. mline.fmt.length = 0;
  8069. for (j = 0; j < lines.length; j++) {
  8070. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  8071. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  8072. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  8073. continue;
  8074. mline.fmt.push(rtpmap.id);
  8075. newdesc += lines[j] + '\r\n';
  8076. } else {
  8077. newdesc += lines[j] + '\r\n';
  8078. }
  8079. }
  8080. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  8081. this.media[i] += newdesc;
  8082. }
  8083. this.raw = this.session + this.media.join('');
  8084. };
  8085. // remove lines matching prefix from session section
  8086. SDP.prototype.removeSessionLines = function(prefix) {
  8087. var self = this;
  8088. var lines = SDPUtil.find_lines(this.session, prefix);
  8089. lines.forEach(function(line) {
  8090. self.session = self.session.replace(line + '\r\n', '');
  8091. });
  8092. this.raw = this.session + this.media.join('');
  8093. return lines;
  8094. }
  8095. // remove lines matching prefix from a media section specified by mediaindex
  8096. // TODO: non-numeric mediaindex could match mid
  8097. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  8098. var self = this;
  8099. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  8100. lines.forEach(function(line) {
  8101. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  8102. });
  8103. this.raw = this.session + this.media.join('');
  8104. return lines;
  8105. }
  8106. // add content's to a jingle element
  8107. SDP.prototype.toJingle = function (elem, thecreator) {
  8108. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  8109. var self = this;
  8110. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  8111. // new bundle plan
  8112. if (SDPUtil.find_line(this.session, 'a=group:')) {
  8113. lines = SDPUtil.find_lines(this.session, 'a=group:');
  8114. for (i = 0; i < lines.length; i++) {
  8115. tmp = lines[i].split(' ');
  8116. var semantics = tmp.shift().substr(8);
  8117. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  8118. for (j = 0; j < tmp.length; j++) {
  8119. elem.c('content', {name: tmp[j]}).up();
  8120. }
  8121. elem.up();
  8122. }
  8123. }
  8124. for (i = 0; i < this.media.length; i++) {
  8125. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  8126. if (!(mline.media === 'audio' ||
  8127. mline.media === 'video' ||
  8128. mline.media === 'application'))
  8129. {
  8130. continue;
  8131. }
  8132. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  8133. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  8134. } else {
  8135. ssrc = false;
  8136. }
  8137. elem.c('content', {creator: thecreator, name: mline.media});
  8138. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  8139. // prefer identifier from a=mid if present
  8140. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  8141. elem.attrs({ name: mid });
  8142. }
  8143. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  8144. elem.c('description',
  8145. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  8146. media: mline.media });
  8147. if (ssrc) {
  8148. elem.attrs({ssrc: ssrc});
  8149. }
  8150. for (j = 0; j < mline.fmt.length; j++) {
  8151. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  8152. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  8153. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  8154. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  8155. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  8156. for (k = 0; k < tmp.length; k++) {
  8157. elem.c('parameter', tmp[k]).up();
  8158. }
  8159. }
  8160. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  8161. elem.up();
  8162. }
  8163. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  8164. elem.c('encryption', {required: 1});
  8165. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  8166. crypto.forEach(function(line) {
  8167. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  8168. });
  8169. elem.up(); // end of encryption
  8170. }
  8171. if (ssrc) {
  8172. // new style mapping
  8173. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8174. // FIXME: group by ssrc and support multiple different ssrcs
  8175. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  8176. if(ssrclines.length > 0) {
  8177. ssrclines.forEach(function (line) {
  8178. var idx = line.indexOf(' ');
  8179. var linessrc = line.substr(0, idx).substr(7);
  8180. if (linessrc != ssrc) {
  8181. elem.up();
  8182. ssrc = linessrc;
  8183. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8184. }
  8185. var kv = line.substr(idx + 1);
  8186. elem.c('parameter');
  8187. if (kv.indexOf(':') == -1) {
  8188. elem.attrs({ name: kv });
  8189. } else {
  8190. var k = kv.split(':', 2)[0];
  8191. elem.attrs({ name: k });
  8192. var v = kv.split(':', 2)[1];
  8193. v = SDPUtil.filter_special_chars(v);
  8194. elem.attrs({ value: v });
  8195. }
  8196. elem.up();
  8197. });
  8198. } else {
  8199. elem.up();
  8200. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8201. elem.c('parameter');
  8202. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  8203. elem.up();
  8204. var msid = null;
  8205. if(mline.media == "audio")
  8206. {
  8207. msid = APP.RTC.localAudio._getId();
  8208. }
  8209. else
  8210. {
  8211. msid = APP.RTC.localVideo._getId();
  8212. }
  8213. if(msid != null)
  8214. {
  8215. msid = SDPUtil.filter_special_chars(msid);
  8216. elem.c('parameter');
  8217. elem.attrs({name: "msid", value:msid});
  8218. elem.up();
  8219. elem.c('parameter');
  8220. elem.attrs({name: "mslabel", value:msid});
  8221. elem.up();
  8222. elem.c('parameter');
  8223. elem.attrs({name: "label", value:msid});
  8224. elem.up();
  8225. }
  8226. }
  8227. elem.up();
  8228. // XEP-0339 handle ssrc-group attributes
  8229. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  8230. ssrc_group_lines.forEach(function(line) {
  8231. var idx = line.indexOf(' ');
  8232. var semantics = line.substr(0, idx).substr(13);
  8233. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8234. if (ssrcs.length) {
  8235. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8236. ssrcs.forEach(function(ssrc) {
  8237. elem.c('source', { ssrc: ssrc })
  8238. .up();
  8239. });
  8240. elem.up();
  8241. }
  8242. });
  8243. }
  8244. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  8245. elem.c('rtcp-mux').up();
  8246. }
  8247. // XEP-0293 -- map a=rtcp-fb:*
  8248. this.rtcpFbToJingle(i, elem, '*');
  8249. // XEP-0294
  8250. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  8251. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  8252. for (j = 0; j < lines.length; j++) {
  8253. tmp = SDPUtil.parse_extmap(lines[j]);
  8254. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  8255. uri: tmp.uri,
  8256. id: tmp.value });
  8257. if (tmp.hasOwnProperty('direction')) {
  8258. switch (tmp.direction) {
  8259. case 'sendonly':
  8260. elem.attrs({senders: 'responder'});
  8261. break;
  8262. case 'recvonly':
  8263. elem.attrs({senders: 'initiator'});
  8264. break;
  8265. case 'sendrecv':
  8266. elem.attrs({senders: 'both'});
  8267. break;
  8268. case 'inactive':
  8269. elem.attrs({senders: 'none'});
  8270. break;
  8271. }
  8272. }
  8273. // TODO: handle params
  8274. elem.up();
  8275. }
  8276. }
  8277. elem.up(); // end of description
  8278. }
  8279. // map ice-ufrag/pwd, dtls fingerprint, candidates
  8280. this.transportToJingle(i, elem);
  8281. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  8282. elem.attrs({senders: 'both'});
  8283. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  8284. elem.attrs({senders: 'initiator'});
  8285. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  8286. elem.attrs({senders: 'responder'});
  8287. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  8288. elem.attrs({senders: 'none'});
  8289. }
  8290. if (mline.port == '0') {
  8291. // estos hack to reject an m-line
  8292. elem.attrs({senders: 'rejected'});
  8293. }
  8294. elem.up(); // end of content
  8295. }
  8296. elem.up();
  8297. return elem;
  8298. };
  8299. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  8300. var tmp, sctpmap, sctpAttrs, fingerprints;
  8301. var self = this;
  8302. elem.c('transport');
  8303. // XEP-0343 DTLS/SCTP
  8304. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  8305. {
  8306. sctpmap = SDPUtil.find_line(
  8307. this.media[mediaindex], 'a=sctpmap:', self.session);
  8308. if (sctpmap)
  8309. {
  8310. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  8311. elem.c('sctpmap',
  8312. {
  8313. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  8314. number: sctpAttrs[0], /* SCTP port */
  8315. protocol: sctpAttrs[1] /* protocol */
  8316. });
  8317. // Optional stream count attribute
  8318. if (sctpAttrs.length > 2)
  8319. elem.attrs({ streams: sctpAttrs[2]});
  8320. elem.up();
  8321. }
  8322. }
  8323. // XEP-0320
  8324. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  8325. fingerprints.forEach(function(line) {
  8326. tmp = SDPUtil.parse_fingerprint(line);
  8327. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  8328. elem.c('fingerprint').t(tmp.fingerprint);
  8329. delete tmp.fingerprint;
  8330. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  8331. if (line) {
  8332. tmp.setup = line.substr(8);
  8333. }
  8334. elem.attrs(tmp);
  8335. elem.up(); // end of fingerprint
  8336. });
  8337. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  8338. if (tmp) {
  8339. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  8340. elem.attrs(tmp);
  8341. // XEP-0176
  8342. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  8343. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  8344. lines.forEach(function (line) {
  8345. var candidate = SDPUtil.candidateToJingle(line);
  8346. var protocol = (candidate &&
  8347. typeof candidate.protocol === 'string')
  8348. ? candidate.protocol.toLowerCase() : '';
  8349. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8350. (self.removeUdpCandidates && protocol === 'udp')) {
  8351. return;
  8352. }
  8353. elem.c('candidate', candidate).up();
  8354. });
  8355. }
  8356. }
  8357. elem.up(); // end of transport
  8358. }
  8359. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  8360. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  8361. lines.forEach(function (line) {
  8362. var tmp = SDPUtil.parse_rtcpfb(line);
  8363. if (tmp.type == 'trr-int') {
  8364. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  8365. elem.up();
  8366. } else {
  8367. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  8368. if (tmp.params.length > 0) {
  8369. elem.attrs({'subtype': tmp.params[0]});
  8370. }
  8371. elem.up();
  8372. }
  8373. });
  8374. };
  8375. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8376. var media = '';
  8377. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8378. if (tmp.length) {
  8379. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8380. if (tmp.attr('value')) {
  8381. media += tmp.attr('value');
  8382. } else {
  8383. media += '0';
  8384. }
  8385. media += '\r\n';
  8386. }
  8387. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8388. tmp.each(function () {
  8389. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8390. if ($(this).attr('subtype')) {
  8391. media += ' ' + $(this).attr('subtype');
  8392. }
  8393. media += '\r\n';
  8394. });
  8395. return media;
  8396. };
  8397. // construct an SDP from a jingle stanza
  8398. SDP.prototype.fromJingle = function (jingle) {
  8399. var self = this;
  8400. this.raw = 'v=0\r\n' +
  8401. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8402. 's=-\r\n' +
  8403. 't=0 0\r\n';
  8404. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8405. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8406. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8407. var contents = $(group).find('>content').map(function (idx, content) {
  8408. return content.getAttribute('name');
  8409. }).get();
  8410. if (contents.length > 0) {
  8411. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8412. }
  8413. });
  8414. }
  8415. this.session = this.raw;
  8416. jingle.find('>content').each(function () {
  8417. var m = self.jingle2media($(this));
  8418. self.media.push(m);
  8419. });
  8420. // reconstruct msid-semantic -- apparently not necessary
  8421. /*
  8422. var msid = SDPUtil.parse_ssrc(this.raw);
  8423. if (msid.hasOwnProperty('mslabel')) {
  8424. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8425. }
  8426. */
  8427. this.raw = this.session + this.media.join('');
  8428. };
  8429. // translate a jingle content element into an an SDP media part
  8430. SDP.prototype.jingle2media = function (content) {
  8431. var media = '',
  8432. desc = content.find('description'),
  8433. ssrc = desc.attr('ssrc'),
  8434. self = this,
  8435. tmp;
  8436. var sctp = content.find(
  8437. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8438. tmp = { media: desc.attr('media') };
  8439. tmp.port = '1';
  8440. if (content.attr('senders') == 'rejected') {
  8441. // estos hack to reject an m-line.
  8442. tmp.port = '0';
  8443. }
  8444. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8445. if (sctp.length)
  8446. tmp.proto = 'DTLS/SCTP';
  8447. else
  8448. tmp.proto = 'RTP/SAVPF';
  8449. } else {
  8450. tmp.proto = 'RTP/AVPF';
  8451. }
  8452. if (!sctp.length) {
  8453. tmp.fmt = desc.find('payload-type').map(
  8454. function () { return this.getAttribute('id'); }).get();
  8455. media += SDPUtil.build_mline(tmp) + '\r\n';
  8456. } else {
  8457. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8458. media += 'a=sctpmap:' + sctp.attr('number') +
  8459. ' ' + sctp.attr('protocol');
  8460. var streamCount = sctp.attr('streams');
  8461. if (streamCount)
  8462. media += ' ' + streamCount + '\r\n';
  8463. else
  8464. media += '\r\n';
  8465. }
  8466. media += 'c=IN IP4 0.0.0.0\r\n';
  8467. if (!sctp.length)
  8468. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8469. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8470. if (tmp.length) {
  8471. if (tmp.attr('ufrag')) {
  8472. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8473. }
  8474. if (tmp.attr('pwd')) {
  8475. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8476. }
  8477. tmp.find('>fingerprint').each(function () {
  8478. // FIXME: check namespace at some point
  8479. media += 'a=fingerprint:' + this.getAttribute('hash');
  8480. media += ' ' + $(this).text();
  8481. media += '\r\n';
  8482. if (this.getAttribute('setup')) {
  8483. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8484. }
  8485. });
  8486. }
  8487. switch (content.attr('senders')) {
  8488. case 'initiator':
  8489. media += 'a=sendonly\r\n';
  8490. break;
  8491. case 'responder':
  8492. media += 'a=recvonly\r\n';
  8493. break;
  8494. case 'none':
  8495. media += 'a=inactive\r\n';
  8496. break;
  8497. case 'both':
  8498. media += 'a=sendrecv\r\n';
  8499. break;
  8500. }
  8501. media += 'a=mid:' + content.attr('name') + '\r\n';
  8502. // <description><rtcp-mux/></description>
  8503. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8504. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8505. if (desc.find('rtcp-mux').length) {
  8506. media += 'a=rtcp-mux\r\n';
  8507. }
  8508. if (desc.find('encryption').length) {
  8509. desc.find('encryption>crypto').each(function () {
  8510. media += 'a=crypto:' + this.getAttribute('tag');
  8511. media += ' ' + this.getAttribute('crypto-suite');
  8512. media += ' ' + this.getAttribute('key-params');
  8513. if (this.getAttribute('session-params')) {
  8514. media += ' ' + this.getAttribute('session-params');
  8515. }
  8516. media += '\r\n';
  8517. });
  8518. }
  8519. desc.find('payload-type').each(function () {
  8520. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8521. if ($(this).find('>parameter').length) {
  8522. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8523. media += $(this).find('parameter').map(function () {
  8524. return (this.getAttribute('name')
  8525. ? (this.getAttribute('name') + '=') : '') +
  8526. this.getAttribute('value');
  8527. }).get().join('; ');
  8528. media += '\r\n';
  8529. }
  8530. // xep-0293
  8531. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8532. });
  8533. // xep-0293
  8534. media += self.rtcpFbFromJingle(desc, '*');
  8535. // xep-0294
  8536. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8537. tmp.each(function () {
  8538. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8539. });
  8540. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8541. var protocol = this.getAttribute('protocol');
  8542. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8543. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8544. (self.removeUdpCandidates && protocol === 'udp')) {
  8545. return;
  8546. }
  8547. media += SDPUtil.candidateFromJingle(this);
  8548. });
  8549. // XEP-0339 handle ssrc-group attributes
  8550. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8551. var semantics = this.getAttribute('semantics');
  8552. var ssrcs = $(this).find('>source').map(function() {
  8553. return this.getAttribute('ssrc');
  8554. }).get();
  8555. if (ssrcs.length) {
  8556. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8557. }
  8558. });
  8559. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8560. tmp.each(function () {
  8561. var ssrc = this.getAttribute('ssrc');
  8562. $(this).find('>parameter').each(function () {
  8563. var name = this.getAttribute('name');
  8564. var value = this.getAttribute('value');
  8565. value = SDPUtil.filter_special_chars(value);
  8566. media += 'a=ssrc:' + ssrc + ' ' + name;
  8567. if (value && value.length)
  8568. media += ':' + value;
  8569. media += '\r\n';
  8570. });
  8571. });
  8572. return media;
  8573. };
  8574. module.exports = SDP;
  8575. }).call(this,"/modules/xmpp/SDP.js")
  8576. },{"./SDPUtil":32,"jitsi-meet-logger":48}],31:[function(require,module,exports){
  8577. var SDPUtil = require("./SDPUtil");
  8578. function SDPDiffer(mySDP, otherSDP)
  8579. {
  8580. this.mySDP = mySDP;
  8581. this.otherSDP = otherSDP;
  8582. }
  8583. /**
  8584. * Returns map of MediaChannel that contains media contained in
  8585. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8586. */
  8587. SDPDiffer.prototype.getNewMedia = function() {
  8588. // this could be useful in Array.prototype.
  8589. function arrayEquals(array) {
  8590. // if the other array is a falsy value, return
  8591. if (!array)
  8592. return false;
  8593. // compare lengths - can save a lot of time
  8594. if (this.length != array.length)
  8595. return false;
  8596. for (var i = 0, l=this.length; i < l; i++) {
  8597. // Check if we have nested arrays
  8598. if (this[i] instanceof Array && array[i] instanceof Array) {
  8599. // recurse into the nested arrays
  8600. if (!this[i].equals(array[i]))
  8601. return false;
  8602. }
  8603. else if (this[i] != array[i]) {
  8604. // Warning - two different object instances will never be
  8605. // equal: {x:20} != {x:20}
  8606. return false;
  8607. }
  8608. }
  8609. return true;
  8610. }
  8611. var myMedias = this.mySDP.getMediaSsrcMap();
  8612. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8613. var newMedia = {};
  8614. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8615. var myMedia = myMedias[othersMediaIdx];
  8616. var othersMedia = othersMedias[othersMediaIdx];
  8617. if(!myMedia && othersMedia) {
  8618. // Add whole channel
  8619. newMedia[othersMediaIdx] = othersMedia;
  8620. return;
  8621. }
  8622. // Look for new ssrcs across the channel
  8623. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8624. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8625. // Allocate channel if we've found ssrc that doesn't exist in
  8626. // our channel
  8627. if(!newMedia[othersMediaIdx]){
  8628. newMedia[othersMediaIdx] = {
  8629. mediaindex: othersMedia.mediaindex,
  8630. mid: othersMedia.mid,
  8631. ssrcs: {},
  8632. ssrcGroups: []
  8633. };
  8634. }
  8635. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8636. }
  8637. });
  8638. // Look for new ssrc groups across the channels
  8639. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8640. // try to match the other ssrc-group with an ssrc-group of ours
  8641. var matched = false;
  8642. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8643. var mySsrcGroup = myMedia.ssrcGroups[i];
  8644. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8645. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8646. [mySsrcGroup.ssrcs])) {
  8647. matched = true;
  8648. break;
  8649. }
  8650. }
  8651. if (!matched) {
  8652. // Allocate channel if we've found an ssrc-group that doesn't
  8653. // exist in our channel
  8654. if(!newMedia[othersMediaIdx]){
  8655. newMedia[othersMediaIdx] = {
  8656. mediaindex: othersMedia.mediaindex,
  8657. mid: othersMedia.mid,
  8658. ssrcs: {},
  8659. ssrcGroups: []
  8660. };
  8661. }
  8662. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8663. }
  8664. });
  8665. });
  8666. return newMedia;
  8667. };
  8668. /**
  8669. * TODO: document!
  8670. */
  8671. SDPDiffer.prototype.toJingle = function(modify) {
  8672. var sdpMediaSsrcs = this.getNewMedia();
  8673. var modified = false;
  8674. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8675. modified = true;
  8676. var media = sdpMediaSsrcs[mediaindex];
  8677. modify.c('content', {name: media.mid});
  8678. modify.c('description',
  8679. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8680. // FIXME: not completely sure this operates on blocks and / or handles
  8681. // different ssrcs correctly
  8682. // generate sources from lines
  8683. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8684. var mediaSsrc = media.ssrcs[ssrcNum];
  8685. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8686. modify.attrs({ssrc: mediaSsrc.ssrc});
  8687. // iterate over ssrc lines
  8688. mediaSsrc.lines.forEach(function (line) {
  8689. var idx = line.indexOf(' ');
  8690. var kv = line.substr(idx + 1);
  8691. modify.c('parameter');
  8692. if (kv.indexOf(':') == -1) {
  8693. modify.attrs({ name: kv });
  8694. } else {
  8695. var nv = kv.split(':', 2);
  8696. var name = nv[0];
  8697. var value = SDPUtil.filter_special_chars(nv[1]);
  8698. modify.attrs({ name: name });
  8699. modify.attrs({ value: value });
  8700. }
  8701. modify.up(); // end of parameter
  8702. });
  8703. modify.up(); // end of source
  8704. });
  8705. // generate source groups from lines
  8706. media.ssrcGroups.forEach(function(ssrcGroup) {
  8707. if (ssrcGroup.ssrcs.length) {
  8708. modify.c('ssrc-group', {
  8709. semantics: ssrcGroup.semantics,
  8710. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8711. });
  8712. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8713. modify.c('source', { ssrc: ssrc })
  8714. .up(); // end of source
  8715. });
  8716. modify.up(); // end of ssrc-group
  8717. }
  8718. });
  8719. modify.up(); // end of description
  8720. modify.up(); // end of content
  8721. });
  8722. return modified;
  8723. };
  8724. module.exports = SDPDiffer;
  8725. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8726. (function (__filename){
  8727. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8728. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8729. SDPUtil = {
  8730. filter_special_chars: function (text) {
  8731. return text.replace(/[\\\/\{,\}\+]/g, "");
  8732. },
  8733. iceparams: function (mediadesc, sessiondesc) {
  8734. var data = null;
  8735. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8736. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8737. data = {
  8738. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8739. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8740. };
  8741. }
  8742. return data;
  8743. },
  8744. parse_iceufrag: function (line) {
  8745. return line.substring(12);
  8746. },
  8747. build_iceufrag: function (frag) {
  8748. return 'a=ice-ufrag:' + frag;
  8749. },
  8750. parse_icepwd: function (line) {
  8751. return line.substring(10);
  8752. },
  8753. build_icepwd: function (pwd) {
  8754. return 'a=ice-pwd:' + pwd;
  8755. },
  8756. parse_mid: function (line) {
  8757. return line.substring(6);
  8758. },
  8759. parse_mline: function (line) {
  8760. var parts = line.substring(2).split(' '),
  8761. data = {};
  8762. data.media = parts.shift();
  8763. data.port = parts.shift();
  8764. data.proto = parts.shift();
  8765. if (parts[parts.length - 1] === '') { // trailing whitespace
  8766. parts.pop();
  8767. }
  8768. data.fmt = parts;
  8769. return data;
  8770. },
  8771. build_mline: function (mline) {
  8772. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8773. },
  8774. parse_rtpmap: function (line) {
  8775. var parts = line.substring(9).split(' '),
  8776. data = {};
  8777. data.id = parts.shift();
  8778. parts = parts[0].split('/');
  8779. data.name = parts.shift();
  8780. data.clockrate = parts.shift();
  8781. data.channels = parts.length ? parts.shift() : '1';
  8782. return data;
  8783. },
  8784. /**
  8785. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8786. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8787. * @returns [SCTP port number, protocol, streams]
  8788. */
  8789. parse_sctpmap: function (line)
  8790. {
  8791. var parts = line.substring(10).split(' ');
  8792. var sctpPort = parts[0];
  8793. var protocol = parts[1];
  8794. // Stream count is optional
  8795. var streamCount = parts.length > 2 ? parts[2] : null;
  8796. return [sctpPort, protocol, streamCount];// SCTP port
  8797. },
  8798. build_rtpmap: function (el) {
  8799. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8800. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8801. line += '/' + el.getAttribute('channels');
  8802. }
  8803. return line;
  8804. },
  8805. parse_crypto: function (line) {
  8806. var parts = line.substring(9).split(' '),
  8807. data = {};
  8808. data.tag = parts.shift();
  8809. data['crypto-suite'] = parts.shift();
  8810. data['key-params'] = parts.shift();
  8811. if (parts.length) {
  8812. data['session-params'] = parts.join(' ');
  8813. }
  8814. return data;
  8815. },
  8816. parse_fingerprint: function (line) { // RFC 4572
  8817. var parts = line.substring(14).split(' '),
  8818. data = {};
  8819. data.hash = parts.shift();
  8820. data.fingerprint = parts.shift();
  8821. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8822. return data;
  8823. },
  8824. parse_fmtp: function (line) {
  8825. var parts = line.split(' '),
  8826. i, key, value,
  8827. data = [];
  8828. parts.shift();
  8829. parts = parts.join(' ').split(';');
  8830. for (i = 0; i < parts.length; i++) {
  8831. key = parts[i].split('=')[0];
  8832. while (key.length && key[0] == ' ') {
  8833. key = key.substring(1);
  8834. }
  8835. value = parts[i].split('=')[1];
  8836. if (key && value) {
  8837. data.push({name: key, value: value});
  8838. } else if (key) {
  8839. // rfc 4733 (DTMF) style stuff
  8840. data.push({name: '', value: key});
  8841. }
  8842. }
  8843. return data;
  8844. },
  8845. parse_icecandidate: function (line) {
  8846. var candidate = {},
  8847. elems = line.split(' ');
  8848. candidate.foundation = elems[0].substring(12);
  8849. candidate.component = elems[1];
  8850. candidate.protocol = elems[2].toLowerCase();
  8851. candidate.priority = elems[3];
  8852. candidate.ip = elems[4];
  8853. candidate.port = elems[5];
  8854. // elems[6] => "typ"
  8855. candidate.type = elems[7];
  8856. candidate.generation = 0; // default value, may be overwritten below
  8857. for (var i = 8; i < elems.length; i += 2) {
  8858. switch (elems[i]) {
  8859. case 'raddr':
  8860. candidate['rel-addr'] = elems[i + 1];
  8861. break;
  8862. case 'rport':
  8863. candidate['rel-port'] = elems[i + 1];
  8864. break;
  8865. case 'generation':
  8866. candidate.generation = elems[i + 1];
  8867. break;
  8868. case 'tcptype':
  8869. candidate.tcptype = elems[i + 1];
  8870. break;
  8871. default: // TODO
  8872. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8873. }
  8874. }
  8875. candidate.network = '1';
  8876. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8877. return candidate;
  8878. },
  8879. build_icecandidate: function (cand) {
  8880. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8881. line += ' ';
  8882. switch (cand.type) {
  8883. case 'srflx':
  8884. case 'prflx':
  8885. case 'relay':
  8886. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8887. line += 'raddr';
  8888. line += ' ';
  8889. line += cand['rel-addr'];
  8890. line += ' ';
  8891. line += 'rport';
  8892. line += ' ';
  8893. line += cand['rel-port'];
  8894. line += ' ';
  8895. }
  8896. break;
  8897. }
  8898. if (cand.hasOwnAttribute('tcptype')) {
  8899. line += 'tcptype';
  8900. line += ' ';
  8901. line += cand.tcptype;
  8902. line += ' ';
  8903. }
  8904. line += 'generation';
  8905. line += ' ';
  8906. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8907. return line;
  8908. },
  8909. parse_ssrc: function (desc) {
  8910. // proprietary mapping of a=ssrc lines
  8911. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8912. // and parse according to that
  8913. var lines = desc.split('\r\n'),
  8914. data = {};
  8915. for (var i = 0; i < lines.length; i++) {
  8916. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8917. var idx = lines[i].indexOf(' ');
  8918. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8919. }
  8920. }
  8921. return data;
  8922. },
  8923. parse_rtcpfb: function (line) {
  8924. var parts = line.substr(10).split(' ');
  8925. var data = {};
  8926. data.pt = parts.shift();
  8927. data.type = parts.shift();
  8928. data.params = parts;
  8929. return data;
  8930. },
  8931. parse_extmap: function (line) {
  8932. var parts = line.substr(9).split(' ');
  8933. var data = {};
  8934. data.value = parts.shift();
  8935. if (data.value.indexOf('/') != -1) {
  8936. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8937. data.value = data.value.substr(0, data.value.indexOf('/'));
  8938. } else {
  8939. data.direction = 'both';
  8940. }
  8941. data.uri = parts.shift();
  8942. data.params = parts;
  8943. return data;
  8944. },
  8945. find_line: function (haystack, needle, sessionpart) {
  8946. var lines = haystack.split('\r\n');
  8947. for (var i = 0; i < lines.length; i++) {
  8948. if (lines[i].substring(0, needle.length) == needle) {
  8949. return lines[i];
  8950. }
  8951. }
  8952. if (!sessionpart) {
  8953. return false;
  8954. }
  8955. // search session part
  8956. lines = sessionpart.split('\r\n');
  8957. for (var j = 0; j < lines.length; j++) {
  8958. if (lines[j].substring(0, needle.length) == needle) {
  8959. return lines[j];
  8960. }
  8961. }
  8962. return false;
  8963. },
  8964. find_lines: function (haystack, needle, sessionpart) {
  8965. var lines = haystack.split('\r\n'),
  8966. needles = [];
  8967. for (var i = 0; i < lines.length; i++) {
  8968. if (lines[i].substring(0, needle.length) == needle)
  8969. needles.push(lines[i]);
  8970. }
  8971. if (needles.length || !sessionpart) {
  8972. return needles;
  8973. }
  8974. // search session part
  8975. lines = sessionpart.split('\r\n');
  8976. for (var j = 0; j < lines.length; j++) {
  8977. if (lines[j].substring(0, needle.length) == needle) {
  8978. needles.push(lines[j]);
  8979. }
  8980. }
  8981. return needles;
  8982. },
  8983. candidateToJingle: function (line) {
  8984. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8985. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8986. if (line.indexOf('candidate:') === 0) {
  8987. line = 'a=' + line;
  8988. } else if (line.substring(0, 12) != 'a=candidate:') {
  8989. logger.log('parseCandidate called with a line that is not a candidate line');
  8990. logger.log(line);
  8991. return null;
  8992. }
  8993. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8994. line = line.substring(0, line.length - 2);
  8995. var candidate = {},
  8996. elems = line.split(' '),
  8997. i;
  8998. if (elems[6] != 'typ') {
  8999. logger.log('did not find typ in the right place');
  9000. logger.log(line);
  9001. return null;
  9002. }
  9003. candidate.foundation = elems[0].substring(12);
  9004. candidate.component = elems[1];
  9005. candidate.protocol = elems[2].toLowerCase();
  9006. candidate.priority = elems[3];
  9007. candidate.ip = elems[4];
  9008. candidate.port = elems[5];
  9009. // elems[6] => "typ"
  9010. candidate.type = elems[7];
  9011. candidate.generation = '0'; // default, may be overwritten below
  9012. for (i = 8; i < elems.length; i += 2) {
  9013. switch (elems[i]) {
  9014. case 'raddr':
  9015. candidate['rel-addr'] = elems[i + 1];
  9016. break;
  9017. case 'rport':
  9018. candidate['rel-port'] = elems[i + 1];
  9019. break;
  9020. case 'generation':
  9021. candidate.generation = elems[i + 1];
  9022. break;
  9023. case 'tcptype':
  9024. candidate.tcptype = elems[i + 1];
  9025. break;
  9026. default: // TODO
  9027. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9028. }
  9029. }
  9030. candidate.network = '1';
  9031. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9032. return candidate;
  9033. },
  9034. candidateFromJingle: function (cand) {
  9035. var line = 'a=candidate:';
  9036. line += cand.getAttribute('foundation');
  9037. line += ' ';
  9038. line += cand.getAttribute('component');
  9039. line += ' ';
  9040. var protocol = cand.getAttribute('protocol');
  9041. // use tcp candidates for FF
  9042. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  9043. protocol = 'tcp';
  9044. }
  9045. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  9046. line += ' ';
  9047. line += cand.getAttribute('priority');
  9048. line += ' ';
  9049. line += cand.getAttribute('ip');
  9050. line += ' ';
  9051. line += cand.getAttribute('port');
  9052. line += ' ';
  9053. line += 'typ';
  9054. line += ' ' + cand.getAttribute('type');
  9055. line += ' ';
  9056. switch (cand.getAttribute('type')) {
  9057. case 'srflx':
  9058. case 'prflx':
  9059. case 'relay':
  9060. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  9061. line += 'raddr';
  9062. line += ' ';
  9063. line += cand.getAttribute('rel-addr');
  9064. line += ' ';
  9065. line += 'rport';
  9066. line += ' ';
  9067. line += cand.getAttribute('rel-port');
  9068. line += ' ';
  9069. }
  9070. break;
  9071. }
  9072. if (protocol.toLowerCase() == 'tcp') {
  9073. line += 'tcptype';
  9074. line += ' ';
  9075. line += cand.getAttribute('tcptype');
  9076. line += ' ';
  9077. }
  9078. line += 'generation';
  9079. line += ' ';
  9080. line += cand.getAttribute('generation') || '0';
  9081. return line + '\r\n';
  9082. }
  9083. };
  9084. module.exports = SDPUtil;
  9085. }).call(this,"/modules/xmpp/SDPUtil.js")
  9086. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],33:[function(require,module,exports){
  9087. (function (__filename){
  9088. /* global $ */
  9089. var RTC = require('../RTC/RTC');
  9090. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9091. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  9092. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9093. var SSRCReplacement = require("./LocalSSRCReplacement");
  9094. function TraceablePeerConnection(ice_config, constraints, session) {
  9095. var self = this;
  9096. this.session = session;
  9097. var RTCPeerConnectionType = null;
  9098. if (RTCBrowserType.isFirefox()) {
  9099. RTCPeerConnectionType = mozRTCPeerConnection;
  9100. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  9101. RTCPeerConnectionType = RTCPeerConnection;
  9102. } else {
  9103. RTCPeerConnectionType = webkitRTCPeerConnection;
  9104. }
  9105. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  9106. this.updateLog = [];
  9107. this.stats = {};
  9108. this.statsinterval = null;
  9109. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9110. var Interop = require('sdp-interop').Interop;
  9111. this.interop = new Interop();
  9112. var Simulcast = require('sdp-simulcast');
  9113. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  9114. // override as desired
  9115. this.trace = function (what, info) {
  9116. /*logger.warn('WTRACE', what, info);
  9117. if (info && RTCBrowserType.isIExplorer()) {
  9118. if (info.length > 1024) {
  9119. logger.warn('WTRACE', what, info.substr(1024));
  9120. }
  9121. if (info.length > 2048) {
  9122. logger.warn('WTRACE', what, info.substr(2048));
  9123. }
  9124. }*/
  9125. self.updateLog.push({
  9126. time: new Date(),
  9127. type: what,
  9128. value: info || ""
  9129. });
  9130. };
  9131. this.onicecandidate = null;
  9132. this.peerconnection.onicecandidate = function (event) {
  9133. // FIXME: this causes stack overflow with Temasys Plugin
  9134. if (!RTCBrowserType.isTemasysPluginUsed())
  9135. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  9136. if (self.onicecandidate !== null) {
  9137. self.onicecandidate(event);
  9138. }
  9139. };
  9140. this.onaddstream = null;
  9141. this.peerconnection.onaddstream = function (event) {
  9142. self.trace('onaddstream', event.stream.id);
  9143. if (self.onaddstream !== null) {
  9144. self.onaddstream(event);
  9145. }
  9146. };
  9147. this.onremovestream = null;
  9148. this.peerconnection.onremovestream = function (event) {
  9149. self.trace('onremovestream', event.stream.id);
  9150. if (self.onremovestream !== null) {
  9151. self.onremovestream(event);
  9152. }
  9153. };
  9154. this.onsignalingstatechange = null;
  9155. this.peerconnection.onsignalingstatechange = function (event) {
  9156. self.trace('onsignalingstatechange', self.signalingState);
  9157. if (self.onsignalingstatechange !== null) {
  9158. self.onsignalingstatechange(event);
  9159. }
  9160. };
  9161. this.oniceconnectionstatechange = null;
  9162. this.peerconnection.oniceconnectionstatechange = function (event) {
  9163. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  9164. if (self.oniceconnectionstatechange !== null) {
  9165. self.oniceconnectionstatechange(event);
  9166. }
  9167. };
  9168. this.onnegotiationneeded = null;
  9169. this.peerconnection.onnegotiationneeded = function (event) {
  9170. self.trace('onnegotiationneeded');
  9171. if (self.onnegotiationneeded !== null) {
  9172. self.onnegotiationneeded(event);
  9173. }
  9174. };
  9175. self.ondatachannel = null;
  9176. this.peerconnection.ondatachannel = function (event) {
  9177. self.trace('ondatachannel', event);
  9178. if (self.ondatachannel !== null) {
  9179. self.ondatachannel(event);
  9180. }
  9181. };
  9182. // XXX: do all non-firefox browsers which we support also support this?
  9183. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  9184. this.statsinterval = window.setInterval(function() {
  9185. self.peerconnection.getStats(function(stats) {
  9186. var results = stats.result();
  9187. var now = new Date();
  9188. for (var i = 0; i < results.length; ++i) {
  9189. results[i].names().forEach(function (name) {
  9190. var id = results[i].id + '-' + name;
  9191. if (!self.stats[id]) {
  9192. self.stats[id] = {
  9193. startTime: now,
  9194. endTime: now,
  9195. values: [],
  9196. times: []
  9197. };
  9198. }
  9199. self.stats[id].values.push(results[i].stat(name));
  9200. self.stats[id].times.push(now.getTime());
  9201. if (self.stats[id].values.length > self.maxstats) {
  9202. self.stats[id].values.shift();
  9203. self.stats[id].times.shift();
  9204. }
  9205. self.stats[id].endTime = now;
  9206. });
  9207. }
  9208. });
  9209. }, 1000);
  9210. }
  9211. }
  9212. /**
  9213. * Returns a string representation of a SessionDescription object.
  9214. */
  9215. var dumpSDP = function(description) {
  9216. if (typeof description === 'undefined' || description == null) {
  9217. return '';
  9218. }
  9219. return 'type: ' + description.type + '\r\n' + description.sdp;
  9220. };
  9221. /**
  9222. * Takes a SessionDescription object and returns a "normalized" version.
  9223. * Currently it only takes care of ordering the a=ssrc lines.
  9224. */
  9225. var normalizePlanB = function(desc) {
  9226. if (typeof desc !== 'object' || desc === null ||
  9227. typeof desc.sdp !== 'string') {
  9228. logger.warn('An empty description was passed as an argument.');
  9229. return desc;
  9230. }
  9231. var transform = require('sdp-transform');
  9232. var session = transform.parse(desc.sdp);
  9233. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  9234. Array.isArray(session.media)) {
  9235. session.media.forEach(function (mLine) {
  9236. // Chrome appears to be picky about the order in which a=ssrc lines
  9237. // are listed in an m-line when rtx is enabled (and thus there are
  9238. // a=ssrc-group lines with FID semantics). Specifically if we have
  9239. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  9240. // the "a=ssrc:S1" lines, SRD fails.
  9241. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  9242. // first.
  9243. var firstSsrcs = [];
  9244. var newSsrcLines = [];
  9245. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  9246. mLine.ssrcGroups.forEach(function (group) {
  9247. if (typeof group.semantics !== 'undefined' &&
  9248. group.semantics === 'FID') {
  9249. if (typeof group.ssrcs !== 'undefined') {
  9250. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  9251. }
  9252. }
  9253. });
  9254. }
  9255. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  9256. var i;
  9257. for (i = 0; i<mLine.ssrcs.length; i++){
  9258. if (typeof mLine.ssrcs[i] === 'object'
  9259. && typeof mLine.ssrcs[i].id !== 'undefined'
  9260. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  9261. newSsrcLines.push(mLine.ssrcs[i]);
  9262. delete mLine.ssrcs[i];
  9263. }
  9264. }
  9265. for (i = 0; i<mLine.ssrcs.length; i++){
  9266. if (typeof mLine.ssrcs[i] !== 'undefined') {
  9267. newSsrcLines.push(mLine.ssrcs[i]);
  9268. }
  9269. }
  9270. mLine.ssrcs = newSsrcLines;
  9271. }
  9272. });
  9273. }
  9274. var resStr = transform.write(session);
  9275. return new RTCSessionDescription({
  9276. type: desc.type,
  9277. sdp: resStr
  9278. });
  9279. };
  9280. var getters = {
  9281. signalingState: function () {
  9282. return this.peerconnection.signalingState;
  9283. },
  9284. iceConnectionState: function () {
  9285. return this.peerconnection.iceConnectionState;
  9286. },
  9287. localDescription: function() {
  9288. var desc = this.peerconnection.localDescription;
  9289. // FIXME this should probably be after the Unified Plan -> Plan B
  9290. // transformation.
  9291. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  9292. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  9293. // if we're running on FF, transform to Plan B first.
  9294. if (RTCBrowserType.usesUnifiedPlan()) {
  9295. desc = this.interop.toPlanB(desc);
  9296. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  9297. }
  9298. return desc;
  9299. },
  9300. remoteDescription: function() {
  9301. var desc = this.peerconnection.remoteDescription;
  9302. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  9303. // if we're running on FF, transform to Plan B first.
  9304. if (RTCBrowserType.usesUnifiedPlan()) {
  9305. desc = this.interop.toPlanB(desc);
  9306. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  9307. }
  9308. return desc;
  9309. }
  9310. };
  9311. Object.keys(getters).forEach(function (prop) {
  9312. Object.defineProperty(
  9313. TraceablePeerConnection.prototype,
  9314. prop, {
  9315. get: getters[prop]
  9316. }
  9317. );
  9318. });
  9319. TraceablePeerConnection.prototype.addStream = function (stream) {
  9320. this.trace('addStream', stream.id);
  9321. try
  9322. {
  9323. this.peerconnection.addStream(stream);
  9324. }
  9325. catch (e)
  9326. {
  9327. logger.error(e);
  9328. }
  9329. };
  9330. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  9331. this.trace('removeStream', stream.id);
  9332. if(stopStreams) {
  9333. RTC.stopMediaStream(stream);
  9334. }
  9335. try {
  9336. // FF doesn't support this yet.
  9337. if (this.peerconnection.removeStream)
  9338. this.peerconnection.removeStream(stream);
  9339. } catch (e) {
  9340. logger.error(e);
  9341. }
  9342. };
  9343. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  9344. this.trace('createDataChannel', label, opts);
  9345. return this.peerconnection.createDataChannel(label, opts);
  9346. };
  9347. TraceablePeerConnection.prototype.setLocalDescription
  9348. = function (description, successCallback, failureCallback) {
  9349. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  9350. // if we're running on FF, transform to Plan A first.
  9351. if (RTCBrowserType.usesUnifiedPlan()) {
  9352. description = this.interop.toUnifiedPlan(description);
  9353. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  9354. }
  9355. var self = this;
  9356. this.peerconnection.setLocalDescription(description,
  9357. function () {
  9358. self.trace('setLocalDescriptionOnSuccess');
  9359. successCallback();
  9360. },
  9361. function (err) {
  9362. self.trace('setLocalDescriptionOnFailure', err);
  9363. failureCallback(err);
  9364. }
  9365. );
  9366. /*
  9367. if (this.statsinterval === null && this.maxstats > 0) {
  9368. // start gathering stats
  9369. }
  9370. */
  9371. };
  9372. TraceablePeerConnection.prototype.setRemoteDescription
  9373. = function (description, successCallback, failureCallback) {
  9374. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9375. // TODO the focus should squeze or explode the remote simulcast
  9376. description = this.simulcast.mungeRemoteDescription(description);
  9377. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9378. // if we're running on FF, transform to Plan A first.
  9379. if (RTCBrowserType.usesUnifiedPlan()) {
  9380. description = this.interop.toUnifiedPlan(description);
  9381. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9382. }
  9383. if (RTCBrowserType.usesPlanB()) {
  9384. description = normalizePlanB(description);
  9385. }
  9386. var self = this;
  9387. this.peerconnection.setRemoteDescription(description,
  9388. function () {
  9389. self.trace('setRemoteDescriptionOnSuccess');
  9390. successCallback();
  9391. },
  9392. function (err) {
  9393. self.trace('setRemoteDescriptionOnFailure', err);
  9394. failureCallback(err);
  9395. }
  9396. );
  9397. /*
  9398. if (this.statsinterval === null && this.maxstats > 0) {
  9399. // start gathering stats
  9400. }
  9401. */
  9402. };
  9403. TraceablePeerConnection.prototype.close = function () {
  9404. this.trace('stop');
  9405. if (this.statsinterval !== null) {
  9406. window.clearInterval(this.statsinterval);
  9407. this.statsinterval = null;
  9408. }
  9409. this.peerconnection.close();
  9410. };
  9411. TraceablePeerConnection.prototype.createOffer
  9412. = function (successCallback, failureCallback, constraints) {
  9413. var self = this;
  9414. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9415. this.peerconnection.createOffer(
  9416. function (offer) {
  9417. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9418. // NOTE this is not tested because in meet the focus generates the
  9419. // offer.
  9420. // if we're running on FF, transform to Plan B first.
  9421. if (RTCBrowserType.usesUnifiedPlan()) {
  9422. offer = self.interop.toPlanB(offer);
  9423. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9424. }
  9425. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9426. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9427. offer = self.simulcast.mungeLocalDescription(offer);
  9428. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9429. }
  9430. successCallback(offer);
  9431. },
  9432. function(err) {
  9433. self.trace('createOfferOnFailure', err);
  9434. failureCallback(err);
  9435. },
  9436. constraints
  9437. );
  9438. };
  9439. TraceablePeerConnection.prototype.createAnswer
  9440. = function (successCallback, failureCallback, constraints) {
  9441. var self = this;
  9442. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9443. this.peerconnection.createAnswer(
  9444. function (answer) {
  9445. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9446. // if we're running on FF, transform to Plan A first.
  9447. if (RTCBrowserType.usesUnifiedPlan()) {
  9448. answer = self.interop.toPlanB(answer);
  9449. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9450. }
  9451. // munge local video SSRC
  9452. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9453. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9454. answer = self.simulcast.mungeLocalDescription(answer);
  9455. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9456. }
  9457. successCallback(answer);
  9458. },
  9459. function(err) {
  9460. self.trace('createAnswerOnFailure', err);
  9461. failureCallback(err);
  9462. },
  9463. constraints
  9464. );
  9465. };
  9466. TraceablePeerConnection.prototype.addIceCandidate
  9467. = function (candidate, successCallback, failureCallback) {
  9468. //var self = this;
  9469. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9470. this.peerconnection.addIceCandidate(candidate);
  9471. /* maybe later
  9472. this.peerconnection.addIceCandidate(candidate,
  9473. function () {
  9474. self.trace('addIceCandidateOnSuccess');
  9475. successCallback();
  9476. },
  9477. function (err) {
  9478. self.trace('addIceCandidateOnFailure', err);
  9479. failureCallback(err);
  9480. }
  9481. );
  9482. */
  9483. };
  9484. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9485. // TODO: Is this the correct way to handle Opera, Temasys?
  9486. if (RTCBrowserType.isFirefox()) {
  9487. // ignore for now...
  9488. if(!errback)
  9489. errback = function () {};
  9490. this.peerconnection.getStats(null, callback, errback);
  9491. } else {
  9492. this.peerconnection.getStats(callback);
  9493. }
  9494. };
  9495. module.exports = TraceablePeerConnection;
  9496. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9497. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":48,"sdp-interop":66,"sdp-simulcast":73,"sdp-transform":76}],34:[function(require,module,exports){
  9498. (function (__filename){
  9499. /* global $, $iq, Promise, Strophe */
  9500. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9501. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9502. var Settings = require("../settings/Settings");
  9503. var AuthenticationEvents
  9504. = require("../../service/authentication/AuthenticationEvents");
  9505. function createExpBackoffTimer(step) {
  9506. var count = 1;
  9507. return function (reset) {
  9508. // Reset call
  9509. if (reset) {
  9510. count = 1;
  9511. return;
  9512. }
  9513. // Calculate next timeout
  9514. var timeout = Math.pow(2, count - 1);
  9515. count += 1;
  9516. return timeout * step;
  9517. };
  9518. }
  9519. function Moderator(roomName, xmpp, emitter) {
  9520. this.roomName = roomName;
  9521. this.xmppService = xmpp;
  9522. this.getNextTimeout = createExpBackoffTimer(1000);
  9523. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9524. // External authentication stuff
  9525. this.externalAuthEnabled = false;
  9526. this.settings = new Settings(roomName);
  9527. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9528. // it will be enabled automatically if focus detects the component through
  9529. // service discovery.
  9530. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  9531. this.xmppService.options.hosts.call_control !== undefined;
  9532. this.eventEmitter = emitter;
  9533. this.connection = this.xmppService.connection;
  9534. this.focusUserJid;
  9535. //FIXME:
  9536. // Message listener that talks to POPUP window
  9537. function listener(event) {
  9538. if (event.data && event.data.sessionId) {
  9539. if (event.origin !== window.location.origin) {
  9540. logger.warn("Ignoring sessionId from different origin: " +
  9541. event.origin);
  9542. return;
  9543. }
  9544. localStorage.setItem('sessionId', event.data.sessionId);
  9545. // After popup is closed we will authenticate
  9546. }
  9547. }
  9548. // Register
  9549. if (window.addEventListener) {
  9550. window.addEventListener("message", listener, false);
  9551. } else {
  9552. window.attachEvent("onmessage", listener);
  9553. }
  9554. }
  9555. Moderator.prototype.isExternalAuthEnabled = function () {
  9556. return this.externalAuthEnabled;
  9557. };
  9558. Moderator.prototype.isSipGatewayEnabled = function () {
  9559. return this.sipGatewayEnabled;
  9560. };
  9561. Moderator.prototype.onMucMemberLeft = function (jid) {
  9562. logger.info("Someone left is it focus ? " + jid);
  9563. var resource = Strophe.getResourceFromJid(jid);
  9564. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9565. logger.info(
  9566. "Focus has left the room - leaving conference");
  9567. //hangUp();
  9568. // We'd rather reload to have everything re-initialized
  9569. //FIXME: show some message before reload
  9570. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9571. }
  9572. };
  9573. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9574. if (!this.focusUserJid) {
  9575. this.focusUserJid = focusJid;
  9576. logger.info("Focus jid set to: " + this.focusUserJid);
  9577. }
  9578. };
  9579. Moderator.prototype.getFocusUserJid = function () {
  9580. return this.focusUserJid;
  9581. };
  9582. Moderator.prototype.getFocusComponent = function () {
  9583. // Get focus component address
  9584. var focusComponent = this.xmppService.options.hosts.focus;
  9585. // If not specified use default: 'focus.domain'
  9586. if (!focusComponent) {
  9587. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9588. }
  9589. return focusComponent;
  9590. };
  9591. Moderator.prototype.createConferenceIq = function () {
  9592. // Generate create conference IQ
  9593. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9594. // Session Id used for authentication
  9595. var sessionId = localStorage.getItem('sessionId');
  9596. var machineUID = this.settings.getSettings().uid;
  9597. logger.info(
  9598. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9599. elem.c('conference', {
  9600. xmlns: 'http://jitsi.org/protocol/focus',
  9601. room: this.roomName,
  9602. 'machine-uid': machineUID
  9603. });
  9604. if (sessionId) {
  9605. elem.attrs({ 'session-id': sessionId});
  9606. }
  9607. if (this.xmppService.options.hosts.bridge !== undefined) {
  9608. elem.c(
  9609. 'property', {
  9610. name: 'bridge',
  9611. value: this.xmppService.options.hosts.bridge
  9612. }).up();
  9613. }
  9614. if (this.xmppService.options.enforcedBridge !== undefined) {
  9615. elem.c(
  9616. 'property', {
  9617. name: 'enforcedBridge',
  9618. value: this.xmppService.options.enforcedBridge
  9619. }).up();
  9620. }
  9621. // Tell the focus we have Jigasi configured
  9622. if (this.xmppService.options.hosts.call_control !== undefined) {
  9623. elem.c(
  9624. 'property', {
  9625. name: 'call_control',
  9626. value: this.xmppService.options.hosts.call_control
  9627. }).up();
  9628. }
  9629. if (this.xmppService.options.channelLastN !== undefined) {
  9630. elem.c(
  9631. 'property', {
  9632. name: 'channelLastN',
  9633. value: this.xmppService.options.channelLastN
  9634. }).up();
  9635. }
  9636. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9637. elem.c(
  9638. 'property', {
  9639. name: 'adaptiveLastN',
  9640. value: this.xmppService.options.adaptiveLastN
  9641. }).up();
  9642. }
  9643. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9644. elem.c(
  9645. 'property', {
  9646. name: 'adaptiveSimulcast',
  9647. value: this.xmppService.options.adaptiveSimulcast
  9648. }).up();
  9649. }
  9650. if (this.xmppService.options.openSctp !== undefined) {
  9651. elem.c(
  9652. 'property', {
  9653. name: 'openSctp',
  9654. value: this.xmppService.options.openSctp
  9655. }).up();
  9656. }
  9657. if (this.xmppService.options.startAudioMuted !== undefined)
  9658. {
  9659. elem.c(
  9660. 'property', {
  9661. name: 'startAudioMuted',
  9662. value: this.xmppService.options.startAudioMuted
  9663. }).up();
  9664. }
  9665. if (this.xmppService.options.startVideoMuted !== undefined)
  9666. {
  9667. elem.c(
  9668. 'property', {
  9669. name: 'startVideoMuted',
  9670. value: this.xmppService.options.startVideoMuted
  9671. }).up();
  9672. }
  9673. elem.c(
  9674. 'property', {
  9675. name: 'simulcastMode',
  9676. value: 'rewriting'
  9677. }).up();
  9678. elem.up();
  9679. return elem;
  9680. };
  9681. Moderator.prototype.parseSessionId = function (resultIq) {
  9682. var sessionId = $(resultIq).find('conference').attr('session-id');
  9683. if (sessionId) {
  9684. logger.info('Received sessionId: ' + sessionId);
  9685. localStorage.setItem('sessionId', sessionId);
  9686. }
  9687. };
  9688. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9689. this.setFocusUserJid(
  9690. $(resultIq).find('conference').attr('focusjid'));
  9691. var authenticationEnabled
  9692. = $(resultIq).find(
  9693. '>conference>property' +
  9694. '[name=\'authentication\'][value=\'true\']').length > 0;
  9695. logger.info("Authentication enabled: " + authenticationEnabled);
  9696. this.externalAuthEnabled = $(resultIq).find(
  9697. '>conference>property' +
  9698. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9699. console.info(
  9700. 'External authentication enabled: ' + this.externalAuthEnabled);
  9701. if (!this.externalAuthEnabled) {
  9702. // We expect to receive sessionId in 'internal' authentication mode
  9703. this.parseSessionId(resultIq);
  9704. }
  9705. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9706. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9707. authenticationEnabled, authIdentity);
  9708. // Check if focus has auto-detected Jigasi component(this will be also
  9709. // included if we have passed our host from the config)
  9710. if ($(resultIq).find(
  9711. '>conference>property' +
  9712. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9713. this.sipGatewayEnabled = true;
  9714. }
  9715. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9716. };
  9717. // FIXME = we need to show the fact that we're waiting for the focus
  9718. // to the user(or that focus is not available)
  9719. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9720. // Try to use focus user JID from the config
  9721. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9722. // Send create conference IQ
  9723. var iq = this.createConferenceIq();
  9724. var self = this;
  9725. this.connection.sendIQ(
  9726. iq,
  9727. function (result) {
  9728. // Setup config options
  9729. self.parseConfigOptions(result);
  9730. if ('true' === $(result).find('conference').attr('ready')) {
  9731. // Reset both timers
  9732. self.getNextTimeout(true);
  9733. self.getNextErrorTimeout(true);
  9734. // Exec callback
  9735. callback();
  9736. } else {
  9737. var waitMs = self.getNextTimeout();
  9738. logger.info("Waiting for the focus... " + waitMs);
  9739. // Reset error timeout
  9740. self.getNextErrorTimeout(true);
  9741. window.setTimeout(
  9742. function () {
  9743. self.allocateConferenceFocus(callback);
  9744. }, waitMs);
  9745. }
  9746. },
  9747. function (error) {
  9748. // Invalid session ? remove and try again
  9749. // without session ID to get a new one
  9750. var invalidSession
  9751. = $(error).find('>error>session-invalid').length;
  9752. if (invalidSession) {
  9753. logger.info("Session expired! - removing");
  9754. localStorage.removeItem("sessionId");
  9755. }
  9756. if ($(error).find('>error>graceful-shutdown').length) {
  9757. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9758. return;
  9759. }
  9760. // Check for error returned by the reservation system
  9761. var reservationErr = $(error).find('>error>reservation-error');
  9762. if (reservationErr.length) {
  9763. // Trigger error event
  9764. var errorCode = reservationErr.attr('error-code');
  9765. var errorMsg;
  9766. if ($(error).find('>error>text')) {
  9767. errorMsg = $(error).find('>error>text').text();
  9768. }
  9769. self.eventEmitter.emit(
  9770. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9771. return;
  9772. }
  9773. // Not authorized to create new room
  9774. if ($(error).find('>error>not-authorized').length) {
  9775. logger.warn("Unauthorized to start the conference", error);
  9776. var toDomain
  9777. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9778. if (toDomain !==
  9779. this.xmppService.options.hosts.anonymousdomain) {
  9780. //FIXME: "is external" should come either from
  9781. // the focus or config.js
  9782. self.externalAuthEnabled = true;
  9783. }
  9784. self.eventEmitter.emit(
  9785. XMPPEvents.AUTHENTICATION_REQUIRED,
  9786. function () {
  9787. self.allocateConferenceFocus(
  9788. callback);
  9789. });
  9790. return;
  9791. }
  9792. var waitMs = self.getNextErrorTimeout();
  9793. logger.error("Focus error, retry after " + waitMs, error);
  9794. // Show message
  9795. var focusComponent = self.getFocusComponent();
  9796. var retrySec = waitMs / 1000;
  9797. //FIXME: message is duplicated ?
  9798. // Do not show in case of session invalid
  9799. // which means just a retry
  9800. if (!invalidSession) {
  9801. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9802. focusComponent, retrySec);
  9803. }
  9804. // Reset response timeout
  9805. self.getNextTimeout(true);
  9806. window.setTimeout(
  9807. function () {
  9808. self.allocateConferenceFocus(callback);
  9809. }, waitMs);
  9810. }
  9811. );
  9812. };
  9813. Moderator.prototype.authenticate = function () {
  9814. var self = this;
  9815. return new Promise(function (resolve, reject) {
  9816. self.connection.sendIQ(
  9817. self.createConferenceIq(),
  9818. function (result) {
  9819. self.parseSessionId(result);
  9820. resolve();
  9821. }, function (error) {
  9822. var code = $(error).find('>error').attr('code');
  9823. reject(error, code);
  9824. }
  9825. );
  9826. });
  9827. };
  9828. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  9829. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9830. iq.c('login-url', {
  9831. xmlns: 'http://jitsi.org/protocol/focus',
  9832. room: this.roomName,
  9833. 'machine-uid': this.settings.getSettings().uid
  9834. });
  9835. this.connection.sendIQ(
  9836. iq,
  9837. function (result) {
  9838. var url = $(result).find('login-url').attr('url');
  9839. url = url = decodeURIComponent(url);
  9840. if (url) {
  9841. logger.info("Got auth url: " + url);
  9842. urlCallback(url);
  9843. } else {
  9844. logger.error(
  9845. "Failed to get auth url from the focus", result);
  9846. failureCallback(result);
  9847. }
  9848. },
  9849. function (error) {
  9850. logger.error("Get auth url error", error);
  9851. failureCallback(error);
  9852. }
  9853. );
  9854. };
  9855. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  9856. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9857. iq.c('login-url', {
  9858. xmlns: 'http://jitsi.org/protocol/focus',
  9859. room: this.roomName,
  9860. 'machine-uid': this.settings.getSettings().uid,
  9861. popup: true
  9862. });
  9863. this.connection.sendIQ(
  9864. iq,
  9865. function (result) {
  9866. var url = $(result).find('login-url').attr('url');
  9867. url = url = decodeURIComponent(url);
  9868. if (url) {
  9869. logger.info("Got POPUP auth url: " + url);
  9870. urlCallback(url);
  9871. } else {
  9872. logger.error(
  9873. "Failed to get POPUP auth url from the focus", result);
  9874. failureCallback(result);
  9875. }
  9876. },
  9877. function (error) {
  9878. logger.error('Get POPUP auth url error', error);
  9879. failureCallback(error);
  9880. }
  9881. );
  9882. };
  9883. Moderator.prototype.logout = function (callback) {
  9884. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9885. var sessionId = localStorage.getItem('sessionId');
  9886. if (!sessionId) {
  9887. callback();
  9888. return;
  9889. }
  9890. iq.c('logout', {
  9891. xmlns: 'http://jitsi.org/protocol/focus',
  9892. 'session-id': sessionId
  9893. });
  9894. this.connection.sendIQ(
  9895. iq,
  9896. function (result) {
  9897. var logoutUrl = $(result).find('logout').attr('logout-url');
  9898. if (logoutUrl) {
  9899. logoutUrl = decodeURIComponent(logoutUrl);
  9900. }
  9901. logger.info("Log out OK, url: " + logoutUrl, result);
  9902. localStorage.removeItem('sessionId');
  9903. callback(logoutUrl);
  9904. },
  9905. function (error) {
  9906. logger.error("Logout error", error);
  9907. }
  9908. );
  9909. };
  9910. module.exports = Moderator;
  9911. }).call(this,"/modules/xmpp/moderator.js")
  9912. },{"../../service/authentication/AuthenticationEvents":83,"../../service/xmpp/XMPPEvents":87,"../settings/Settings":21,"jitsi-meet-logger":48}],35:[function(require,module,exports){
  9913. (function (__filename){
  9914. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  9915. Toolbar, Util, Promise */
  9916. var XMPPEvents = require("../../service/XMPP/XMPPEvents");
  9917. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9918. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  9919. roomjid) {
  9920. this.eventEmitter = eventEmitter;
  9921. this.connection = connection;
  9922. this.state = "off";
  9923. this.focusMucJid = focusMucJid;
  9924. this.jirecon = jirecon;
  9925. this.url = null;
  9926. this.type = type;
  9927. this._isSupported = ((type === Recording.types.JIBRI)
  9928. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  9929. /**
  9930. * The ID of the jirecon recording session. Jirecon generates it when we
  9931. * initially start recording, and it needs to be used in subsequent requests
  9932. * to jirecon.
  9933. */
  9934. this.jireconRid = null;
  9935. this.roomjid = roomjid;
  9936. }
  9937. Recording.types = {
  9938. COLIBRI: "colibri",
  9939. JIRECON: "jirecon",
  9940. JIBRI: "jibri"
  9941. };
  9942. Recording.prototype.handleJibriPresence = function (jibri) {
  9943. var attributes = jibri.attributes;
  9944. if(!attributes)
  9945. return;
  9946. this._isSupported =
  9947. (attributes.status && attributes.status !== "undefined");
  9948. if(this._isSupported) {
  9949. this.url = attributes.url || null;
  9950. this.state = attributes.status || "off";
  9951. }
  9952. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  9953. };
  9954. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  9955. options) {
  9956. if (state == this.state){
  9957. errCallback(new Error("Invalid state!"));
  9958. }
  9959. options = options || {};
  9960. // FIXME jibri does not accept IQ without 'url' attribute set ?
  9961. var iq = $iq({to: this.focusMucJid, type: 'set'})
  9962. .c('jibri', {
  9963. "xmlns": 'http://jitsi.org/protocol/jibri',
  9964. "action": (state === 'on') ? 'start' : 'stop',
  9965. "streamid": options.streamId,
  9966. "follow-entity": options.followEntity
  9967. }).up();
  9968. logger.log('Set jibri recording: '+state, iq.nodeTree);
  9969. console.log(iq.nodeTree);
  9970. this.connection.sendIQ(
  9971. iq,
  9972. function (result) {
  9973. callback($(result).find('jibri').attr('state'),
  9974. $(result).find('jibri').attr('url'));
  9975. },
  9976. function (error) {
  9977. logger.log('Failed to start recording, error: ', error);
  9978. errCallback(error);
  9979. });
  9980. };
  9981. Recording.prototype.setRecordingJirecon =
  9982. function (state, callback, errCallback, options) {
  9983. if (state == this.state){
  9984. errCallback(new Error("Invalid state!"));
  9985. }
  9986. var iq = $iq({to: this.jirecon, type: 'set'})
  9987. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  9988. action: (state === 'on') ? 'start' : 'stop',
  9989. mucjid: this.roomjid});
  9990. if (state === 'off'){
  9991. iq.attrs({rid: this.jireconRid});
  9992. }
  9993. console.log('Start recording');
  9994. var self = this;
  9995. this.connection.sendIQ(
  9996. iq,
  9997. function (result) {
  9998. // TODO wait for an IQ with the real status, since this is
  9999. // provisional?
  10000. self.jireconRid = $(result).find('recording').attr('rid');
  10001. console.log('Recording ' +
  10002. ((state === 'on') ? 'started' : 'stopped') +
  10003. '(jirecon)' + result);
  10004. self.state = state;
  10005. if (state === 'off'){
  10006. self.jireconRid = null;
  10007. }
  10008. callback(state);
  10009. },
  10010. function (error) {
  10011. console.log('Failed to start recording, error: ', error);
  10012. errCallback(error);
  10013. });
  10014. };
  10015. // Sends a COLIBRI message which enables or disables (according to 'state')
  10016. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  10017. // with the new recording state, according to the IQ.
  10018. Recording.prototype.setRecordingColibri =
  10019. function (state, callback, errCallback, options) {
  10020. var elem = $iq({to: this.focusMucJid, type: 'set'});
  10021. elem.c('conference', {
  10022. xmlns: 'http://jitsi.org/protocol/colibri'
  10023. });
  10024. elem.c('recording', {state: state, token: options.token});
  10025. var self = this;
  10026. this.connection.sendIQ(elem,
  10027. function (result) {
  10028. console.log('Set recording "', state, '". Result:', result);
  10029. var recordingElem = $(result).find('>conference>recording');
  10030. var newState = recordingElem.attr('state');
  10031. self.state = newState;
  10032. callback(newState);
  10033. if (newState === 'pending') {
  10034. self.connection.addHandler(function(iq){
  10035. var state = $(iq).find('recording').attr('state');
  10036. if (state) {
  10037. self.state = newState;
  10038. callback(state);
  10039. }
  10040. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  10041. }
  10042. },
  10043. function (error) {
  10044. console.warn(error);
  10045. errCallback(error);
  10046. }
  10047. );
  10048. };
  10049. Recording.prototype.setRecording =
  10050. function (state, callback, errCallback, options) {
  10051. switch(this.type){
  10052. case Recording.types.JIRECON:
  10053. this.setRecordingJirecon(state, callback, errCallback, options);
  10054. break;
  10055. case Recording.types.COLIBRI:
  10056. this.setRecordingColibri(state, callback, errCallback, options);
  10057. break;
  10058. case Recording.types.JIBRI:
  10059. this.setRecordingJibri(state, callback, errCallback, options);
  10060. break;
  10061. default:
  10062. console.error("Unknown recording type!");
  10063. return;
  10064. }
  10065. };
  10066. /**
  10067. *Starts/stops the recording
  10068. * @param token token for authentication
  10069. * @param statusChangeHandler {function} receives the new status as argument.
  10070. */
  10071. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  10072. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  10073. (!options.streamId && this.type === Recording.types.JIBRI)){
  10074. statusChangeHandler("error", new Error("No token passed!"));
  10075. logger.error("No token passed!");
  10076. return;
  10077. }
  10078. var oldState = this.state;
  10079. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  10080. var self = this;
  10081. this.setRecording(newState,
  10082. function (state, url) {
  10083. logger.log("New recording state: ", state);
  10084. if (state && state !== oldState) {
  10085. self.state = state;
  10086. self.url = url;
  10087. statusChangeHandler(state);
  10088. } else {
  10089. statusChangeHandler("error", new Error("Status not changed!"));
  10090. }
  10091. }, function (error) {
  10092. statusChangeHandler("error", error);
  10093. }, options);
  10094. };
  10095. /**
  10096. * Returns true if the recording is supproted and false if not.
  10097. */
  10098. Recording.prototype.isSupported = function () {
  10099. return this._isSupported;
  10100. };
  10101. /**
  10102. * Returns null if the recording is not supported, "on" if the recording started
  10103. * and "off" if the recording is not started.
  10104. */
  10105. Recording.prototype.getState = function () {
  10106. return this.state;
  10107. };
  10108. /**
  10109. * Returns the url of the recorded video.
  10110. */
  10111. Recording.prototype.getURL = function () {
  10112. return this.url;
  10113. };
  10114. module.exports = Recording;
  10115. }).call(this,"/modules/xmpp/recording.js")
  10116. },{"../../service/XMPP/XMPPEvents":82,"jitsi-meet-logger":48}],36:[function(require,module,exports){
  10117. (function (__filename){
  10118. /* jshint -W117 */
  10119. /* a simple MUC connection plugin
  10120. * can only handle a single MUC room
  10121. */
  10122. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10123. var ChatRoom = require("./ChatRoom");
  10124. module.exports = function(XMPP) {
  10125. Strophe.addConnectionPlugin('emuc', {
  10126. connection: null,
  10127. rooms: {},//map with the rooms
  10128. init: function (conn) {
  10129. this.connection = conn;
  10130. // add handlers (just once)
  10131. this.connection.addHandler(this.onPresence.bind(this), null,
  10132. 'presence', null, null, null, null);
  10133. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  10134. null, 'presence', 'unavailable', null);
  10135. this.connection.addHandler(this.onPresenceError.bind(this), null,
  10136. 'presence', 'error', null);
  10137. this.connection.addHandler(this.onMessage.bind(this), null,
  10138. 'message', null, null);
  10139. this.connection.addHandler(this.onMute.bind(this),
  10140. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  10141. },
  10142. createRoom: function (jid, password, options) {
  10143. var roomJid = Strophe.getBareJidFromJid(jid);
  10144. if (this.rooms[roomJid]) {
  10145. logger.error("You are already in the room!");
  10146. return;
  10147. }
  10148. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  10149. return this.rooms[roomJid];
  10150. },
  10151. doLeave: function (jid) {
  10152. this.rooms[jid].doLeave();
  10153. delete this.rooms[jid];
  10154. },
  10155. onPresence: function (pres) {
  10156. var from = pres.getAttribute('from');
  10157. // What is this for? A workaround for something?
  10158. if (pres.getAttribute('type')) {
  10159. return true;
  10160. }
  10161. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10162. if(!room)
  10163. return;
  10164. // Parse status.
  10165. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  10166. room.createNonAnonymousRoom();
  10167. }
  10168. room.onPresence(pres);
  10169. return true;
  10170. },
  10171. onPresenceUnavailable: function (pres) {
  10172. var from = pres.getAttribute('from');
  10173. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10174. if(!room)
  10175. return;
  10176. room.onPresenceUnavailable(pres, from);
  10177. return true;
  10178. },
  10179. onPresenceError: function (pres) {
  10180. var from = pres.getAttribute('from');
  10181. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10182. if(!room)
  10183. return;
  10184. room.onPresenceError(pres, from);
  10185. return true;
  10186. },
  10187. onMessage: function (msg) {
  10188. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  10189. var from = msg.getAttribute('from');
  10190. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10191. if(!room)
  10192. return;
  10193. room.onMessage(msg, from);
  10194. return true;
  10195. },
  10196. setJingleSession: function (from, session) {
  10197. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10198. if(!room)
  10199. return;
  10200. room.setJingleSession(session);
  10201. },
  10202. onMute: function(iq) {
  10203. var from = iq.getAttribute('from');
  10204. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10205. if(!room)
  10206. return;
  10207. room.onMute(iq);
  10208. return true;
  10209. }
  10210. });
  10211. };
  10212. }).call(this,"/modules/xmpp/strophe.emuc.js")
  10213. },{"./ChatRoom":26,"jitsi-meet-logger":48}],37:[function(require,module,exports){
  10214. (function (__filename){
  10215. /* jshint -W117 */
  10216. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10217. var JingleSession = require("./JingleSessionPC");
  10218. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10219. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10220. module.exports = function(XMPP, eventEmitter) {
  10221. Strophe.addConnectionPlugin('jingle', {
  10222. connection: null,
  10223. sessions: {},
  10224. jid2session: {},
  10225. ice_config: {iceServers: []},
  10226. media_constraints: {
  10227. mandatory: {
  10228. 'OfferToReceiveAudio': true,
  10229. 'OfferToReceiveVideo': true
  10230. }
  10231. // MozDontOfferDataChannel: true when this is firefox
  10232. },
  10233. init: function (conn) {
  10234. this.connection = conn;
  10235. if (this.connection.disco) {
  10236. // http://xmpp.org/extensions/xep-0167.html#support
  10237. // http://xmpp.org/extensions/xep-0176.html#support
  10238. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  10239. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  10240. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  10241. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  10242. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  10243. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  10244. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  10245. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  10246. || RTCBrowserType.isTemasysPluginUsed()) {
  10247. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  10248. }
  10249. // this is dealt with by SDP O/A so we don't need to announce this
  10250. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  10251. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  10252. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  10253. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  10254. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  10255. }
  10256. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  10257. },
  10258. onJingle: function (iq) {
  10259. var sid = $(iq).find('jingle').attr('sid');
  10260. var action = $(iq).find('jingle').attr('action');
  10261. var fromJid = iq.getAttribute('from');
  10262. // send ack first
  10263. var ack = $iq({type: 'result',
  10264. to: fromJid,
  10265. id: iq.getAttribute('id')
  10266. });
  10267. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  10268. var sess = this.sessions[sid];
  10269. if ('session-initiate' != action) {
  10270. if (sess === null) {
  10271. ack.type = 'error';
  10272. ack.c('error', {type: 'cancel'})
  10273. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10274. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10275. this.connection.send(ack);
  10276. return true;
  10277. }
  10278. // local jid is not checked
  10279. if (fromJid != sess.peerjid) {
  10280. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  10281. ack.type = 'error';
  10282. ack.c('error', {type: 'cancel'})
  10283. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10284. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10285. this.connection.send(ack);
  10286. return true;
  10287. }
  10288. } else if (sess !== undefined) {
  10289. // existing session with same session id
  10290. // this might be out-of-order if the sess.peerjid is the same as from
  10291. ack.type = 'error';
  10292. ack.c('error', {type: 'cancel'})
  10293. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  10294. logger.warn('duplicate session id', sid);
  10295. this.connection.send(ack);
  10296. return true;
  10297. }
  10298. // FIXME: check for a defined action
  10299. this.connection.send(ack);
  10300. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  10301. switch (action) {
  10302. case 'session-initiate':
  10303. console.log("(TIME) received session-initiate:\t",
  10304. window.performance.now());
  10305. var startMuted = $(iq).find('jingle>startmuted');
  10306. if (startMuted && startMuted.length > 0) {
  10307. var audioMuted = startMuted.attr("audio");
  10308. var videoMuted = startMuted.attr("video");
  10309. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  10310. audioMuted === "true", videoMuted === "true");
  10311. }
  10312. sess = new JingleSession(
  10313. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  10314. this.connection, XMPP);
  10315. // configure session
  10316. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  10317. this.connection.emuc.setJingleSession(fromBareJid, sess);
  10318. sess.media_constraints = this.media_constraints;
  10319. sess.ice_config = this.ice_config;
  10320. sess.initialize(fromJid, false);
  10321. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  10322. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  10323. sess.setOffer($(iq).find('>jingle'));
  10324. this.sessions[sess.sid] = sess;
  10325. this.jid2session[sess.peerjid] = sess;
  10326. // the callback should either
  10327. // .sendAnswer and .accept
  10328. // or .sendTerminate -- not necessarily synchronous
  10329. sess.sendAnswer();
  10330. sess.accept();
  10331. break;
  10332. case 'session-accept':
  10333. sess.setAnswer($(iq).find('>jingle'));
  10334. sess.accept();
  10335. break;
  10336. case 'session-terminate':
  10337. // If this is not the focus sending the terminate, we have
  10338. // nothing more to do here.
  10339. if (Object.keys(this.sessions).length < 1
  10340. || !(this.sessions[Object.keys(this.sessions)[0]]
  10341. instanceof JingleSession))
  10342. {
  10343. break;
  10344. }
  10345. logger.log('terminating...', sess.sid);
  10346. sess.terminate();
  10347. this.terminate(sess.sid);
  10348. if ($(iq).find('>jingle>reason').length) {
  10349. $(document).trigger('callterminated.jingle', [
  10350. sess.sid,
  10351. sess.peerjid,
  10352. $(iq).find('>jingle>reason>:first')[0].tagName,
  10353. $(iq).find('>jingle>reason>text').text()
  10354. ]);
  10355. } else {
  10356. $(document).trigger('callterminated.jingle',
  10357. [sess.sid, sess.peerjid]);
  10358. }
  10359. break;
  10360. case 'transport-info':
  10361. sess.addIceCandidate($(iq).find('>jingle>content'));
  10362. break;
  10363. case 'session-info':
  10364. var affected;
  10365. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10366. $(document).trigger('ringing.jingle', [sess.sid]);
  10367. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10368. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10369. $(document).trigger('mute.jingle', [sess.sid, affected]);
  10370. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10371. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10372. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  10373. }
  10374. break;
  10375. case 'addsource': // FIXME: proprietary, un-jingleish
  10376. case 'source-add': // FIXME: proprietary
  10377. sess.addSource($(iq).find('>jingle>content'));
  10378. break;
  10379. case 'removesource': // FIXME: proprietary, un-jingleish
  10380. case 'source-remove': // FIXME: proprietary
  10381. sess.removeSource($(iq).find('>jingle>content'));
  10382. break;
  10383. default:
  10384. logger.warn('jingle action not implemented', action);
  10385. break;
  10386. }
  10387. return true;
  10388. },
  10389. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  10390. if (sid === null || sid === undefined) {
  10391. for (sid in this.sessions) {
  10392. if (this.sessions[sid].state != 'ended') {
  10393. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10394. this.sessions[sid].terminate();
  10395. }
  10396. delete this.jid2session[this.sessions[sid].peerjid];
  10397. delete this.sessions[sid];
  10398. }
  10399. } else if (this.sessions.hasOwnProperty(sid)) {
  10400. if (this.sessions[sid].state != 'ended') {
  10401. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10402. this.sessions[sid].terminate();
  10403. }
  10404. delete this.jid2session[this.sessions[sid].peerjid];
  10405. delete this.sessions[sid];
  10406. }
  10407. },
  10408. getStunAndTurnCredentials: function () {
  10409. // get stun and turn configuration from server via xep-0215
  10410. // uses time-limited credentials as described in
  10411. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  10412. //
  10413. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  10414. // for a prosody module which implements this
  10415. //
  10416. // currently, this doesn't work with updateIce and therefore credentials with a long
  10417. // validity have to be fetched before creating the peerconnection
  10418. // TODO: implement refresh via updateIce as described in
  10419. // https://code.google.com/p/webrtc/issues/detail?id=1650
  10420. var self = this;
  10421. this.connection.sendIQ(
  10422. $iq({type: 'get', to: this.connection.domain})
  10423. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  10424. function (res) {
  10425. var iceservers = [];
  10426. $(res).find('>services>service').each(function (idx, el) {
  10427. el = $(el);
  10428. var dict = {};
  10429. var type = el.attr('type');
  10430. switch (type) {
  10431. case 'stun':
  10432. dict.url = 'stun:' + el.attr('host');
  10433. if (el.attr('port')) {
  10434. dict.url += ':' + el.attr('port');
  10435. }
  10436. iceservers.push(dict);
  10437. break;
  10438. case 'turn':
  10439. case 'turns':
  10440. dict.url = type + ':';
  10441. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  10442. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  10443. dict.url += el.attr('username') + '@';
  10444. } else {
  10445. dict.username = el.attr('username'); // only works in M28
  10446. }
  10447. }
  10448. dict.url += el.attr('host');
  10449. if (el.attr('port') && el.attr('port') != '3478') {
  10450. dict.url += ':' + el.attr('port');
  10451. }
  10452. if (el.attr('transport') && el.attr('transport') != 'udp') {
  10453. dict.url += '?transport=' + el.attr('transport');
  10454. }
  10455. if (el.attr('password')) {
  10456. dict.credential = el.attr('password');
  10457. }
  10458. iceservers.push(dict);
  10459. break;
  10460. }
  10461. });
  10462. self.ice_config.iceServers = iceservers;
  10463. },
  10464. function (err) {
  10465. logger.warn('getting turn credentials failed', err);
  10466. logger.warn('is mod_turncredentials or similar installed?');
  10467. }
  10468. );
  10469. // implement push?
  10470. },
  10471. /**
  10472. * Returns the data saved in 'updateLog' in a format to be logged.
  10473. */
  10474. getLog: function () {
  10475. var data = {};
  10476. var self = this;
  10477. Object.keys(this.sessions).forEach(function (sid) {
  10478. var session = self.sessions[sid];
  10479. if (session.peerconnection && session.peerconnection.updateLog) {
  10480. // FIXME: should probably be a .dump call
  10481. data["jingle_" + session.sid] = {
  10482. updateLog: session.peerconnection.updateLog,
  10483. stats: session.peerconnection.stats,
  10484. url: window.location.href
  10485. };
  10486. }
  10487. });
  10488. return data;
  10489. }
  10490. });
  10491. };
  10492. }).call(this,"/modules/xmpp/strophe.jingle.js")
  10493. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":48}],38:[function(require,module,exports){
  10494. /* global Strophe */
  10495. module.exports = function () {
  10496. Strophe.addConnectionPlugin('logger', {
  10497. // logs raw stanzas and makes them available for download as JSON
  10498. connection: null,
  10499. log: [],
  10500. init: function (conn) {
  10501. this.connection = conn;
  10502. this.connection.rawInput = this.log_incoming.bind(this);
  10503. this.connection.rawOutput = this.log_outgoing.bind(this);
  10504. },
  10505. log_incoming: function (stanza) {
  10506. this.log.push([new Date().getTime(), 'incoming', stanza]);
  10507. },
  10508. log_outgoing: function (stanza) {
  10509. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  10510. }
  10511. });
  10512. };
  10513. },{}],39:[function(require,module,exports){
  10514. (function (__filename){
  10515. /* global $, $iq, Strophe */
  10516. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10517. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10518. /**
  10519. * Ping every 20 sec
  10520. */
  10521. var PING_INTERVAL = 20000;
  10522. /**
  10523. * Ping timeout error after 15 sec of waiting.
  10524. */
  10525. var PING_TIMEOUT = 15000;
  10526. /**
  10527. * Will close the connection after 3 consecutive ping errors.
  10528. */
  10529. var PING_THRESHOLD = 3;
  10530. /**
  10531. * XEP-0199 ping plugin.
  10532. *
  10533. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  10534. */
  10535. module.exports = function (XMPP, eventEmitter) {
  10536. Strophe.addConnectionPlugin('ping', {
  10537. connection: null,
  10538. failedPings: 0,
  10539. /**
  10540. * Initializes the plugin. Method called by Strophe.
  10541. * @param connection Strophe connection instance.
  10542. */
  10543. init: function (connection) {
  10544. this.connection = connection;
  10545. Strophe.addNamespace('PING', "urn:xmpp:ping");
  10546. },
  10547. /**
  10548. * Sends "ping" to given <tt>jid</tt>
  10549. * @param jid the JID to which ping request will be sent.
  10550. * @param success callback called on success.
  10551. * @param error callback called on error.
  10552. * @param timeout ms how long are we going to wait for the response. On
  10553. * timeout <tt>error<//t> callback is called with undefined error
  10554. * argument.
  10555. */
  10556. ping: function (jid, success, error, timeout) {
  10557. var iq = $iq({type: 'get', to: jid});
  10558. iq.c('ping', {xmlns: Strophe.NS.PING});
  10559. this.connection.sendIQ(iq, success, error, timeout);
  10560. },
  10561. /**
  10562. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  10563. * @param jid the JID to be checked for ping support.
  10564. * @param callback function with boolean argument which will be
  10565. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  10566. */
  10567. hasPingSupport: function (jid, callback) {
  10568. this.connection.disco.info(
  10569. jid, null,
  10570. function (result) {
  10571. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  10572. callback(ping.length > 0);
  10573. },
  10574. function (error) {
  10575. logger.error("Ping feature discovery error", error);
  10576. callback(false);
  10577. }
  10578. );
  10579. },
  10580. /**
  10581. * Starts to send ping in given interval to specified remote JID.
  10582. * This plugin supports only one such task and <tt>stopInterval</tt>
  10583. * must be called before starting a new one.
  10584. * @param remoteJid remote JID to which ping requests will be sent to.
  10585. * @param interval task interval in ms.
  10586. */
  10587. startInterval: function (remoteJid, interval) {
  10588. if (this.intervalId) {
  10589. logger.error("Ping task scheduled already");
  10590. return;
  10591. }
  10592. if (!interval)
  10593. interval = PING_INTERVAL;
  10594. var self = this;
  10595. this.intervalId = window.setInterval(function () {
  10596. self.ping(remoteJid,
  10597. function (result) {
  10598. // Ping OK
  10599. self.failedPings = 0;
  10600. },
  10601. function (error) {
  10602. self.failedPings += 1;
  10603. logger.error(
  10604. "Ping " + (error ? "error" : "timeout"), error);
  10605. if (self.failedPings >= PING_THRESHOLD) {
  10606. self.connection.disconnect();
  10607. }
  10608. }, PING_TIMEOUT);
  10609. }, interval);
  10610. logger.info("XMPP pings will be sent every " + interval + " ms");
  10611. },
  10612. /**
  10613. * Stops current "ping" interval task.
  10614. */
  10615. stopInterval: function () {
  10616. if (this.intervalId) {
  10617. window.clearInterval(this.intervalId);
  10618. this.intervalId = null;
  10619. this.failedPings = 0;
  10620. logger.info("Ping interval cleared");
  10621. }
  10622. }
  10623. });
  10624. };
  10625. }).call(this,"/modules/xmpp/strophe.ping.js")
  10626. },{"../../service/xmpp/XMPPEvents":87,"jitsi-meet-logger":48}],40:[function(require,module,exports){
  10627. (function (__filename){
  10628. /* jshint -W117 */
  10629. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10630. module.exports = function() {
  10631. Strophe.addConnectionPlugin('rayo',
  10632. {
  10633. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10634. connection: null,
  10635. init: function (conn) {
  10636. this.connection = conn;
  10637. if (this.connection.disco) {
  10638. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10639. }
  10640. this.connection.addHandler(
  10641. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  10642. null, null);
  10643. },
  10644. onRayo: function (iq) {
  10645. logger.info("Rayo IQ", iq);
  10646. },
  10647. dial: function (to, from, roomName, roomPass, focusMucJid) {
  10648. var self = this;
  10649. return new Promise(function (resolve, reject) {
  10650. if(!focusMucJid) {
  10651. reject(new Error("Internal error!"));
  10652. return;
  10653. }
  10654. var req = $iq(
  10655. {
  10656. type: 'set',
  10657. to: focusMucJid
  10658. }
  10659. );
  10660. req.c('dial',
  10661. {
  10662. xmlns: self.RAYO_XMLNS,
  10663. to: to,
  10664. from: from
  10665. });
  10666. req.c('header',
  10667. {
  10668. name: 'JvbRoomName',
  10669. value: roomName
  10670. }).up();
  10671. if (roomPass !== null && roomPass.length) {
  10672. req.c('header',
  10673. {
  10674. name: 'JvbRoomPassword',
  10675. value: roomPass
  10676. }).up();
  10677. }
  10678. self.connection.sendIQ(
  10679. req,
  10680. function (result) {
  10681. logger.info('Dial result ', result);
  10682. var resource = $(result).find('ref').attr('uri');
  10683. self.call_resource =
  10684. resource.substr('xmpp:'.length);
  10685. logger.info(
  10686. "Received call resource: " +
  10687. self.call_resource);
  10688. resolve();
  10689. },
  10690. function (error) {
  10691. logger.info('Dial error ', error);
  10692. reject(error);
  10693. }
  10694. );
  10695. });
  10696. },
  10697. hangup: function () {
  10698. var self = this;
  10699. return new Promise(function (resolve, reject) {
  10700. if (!self.call_resource) {
  10701. reject(new Error("No call in progress"));
  10702. logger.warn("No call in progress");
  10703. return;
  10704. }
  10705. var req = $iq(
  10706. {
  10707. type: 'set',
  10708. to: self.call_resource
  10709. }
  10710. );
  10711. req.c('hangup',
  10712. {
  10713. xmlns: self.RAYO_XMLNS
  10714. });
  10715. self.connection.sendIQ(
  10716. req,
  10717. function (result) {
  10718. logger.info('Hangup result ', result);
  10719. self.call_resource = null;
  10720. resolve();
  10721. },
  10722. function (error) {
  10723. logger.info('Hangup error ', error);
  10724. self.call_resource = null;
  10725. reject(new Error('Hangup error '));
  10726. }
  10727. );
  10728. });
  10729. }
  10730. }
  10731. );
  10732. };
  10733. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10734. },{"jitsi-meet-logger":48}],41:[function(require,module,exports){
  10735. (function (__filename){
  10736. /* global Strophe */
  10737. /**
  10738. * Strophe logger implementation. Logs from level WARN and above.
  10739. */
  10740. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10741. module.exports = function () {
  10742. Strophe.log = function (level, msg) {
  10743. switch (level) {
  10744. case Strophe.LogLevel.WARN:
  10745. logger.warn("Strophe: " + msg);
  10746. break;
  10747. case Strophe.LogLevel.ERROR:
  10748. case Strophe.LogLevel.FATAL:
  10749. logger.error("Strophe: " + msg);
  10750. break;
  10751. }
  10752. };
  10753. Strophe.getStatusString = function (status) {
  10754. switch (status) {
  10755. case Strophe.Status.ERROR:
  10756. return "ERROR";
  10757. case Strophe.Status.CONNECTING:
  10758. return "CONNECTING";
  10759. case Strophe.Status.CONNFAIL:
  10760. return "CONNFAIL";
  10761. case Strophe.Status.AUTHENTICATING:
  10762. return "AUTHENTICATING";
  10763. case Strophe.Status.AUTHFAIL:
  10764. return "AUTHFAIL";
  10765. case Strophe.Status.CONNECTED:
  10766. return "CONNECTED";
  10767. case Strophe.Status.DISCONNECTED:
  10768. return "DISCONNECTED";
  10769. case Strophe.Status.DISCONNECTING:
  10770. return "DISCONNECTING";
  10771. case Strophe.Status.ATTACHED:
  10772. return "ATTACHED";
  10773. default:
  10774. return "unknown";
  10775. }
  10776. };
  10777. };
  10778. }).call(this,"/modules/xmpp/strophe.util.js")
  10779. },{"jitsi-meet-logger":48}],42:[function(require,module,exports){
  10780. (function (__filename){
  10781. /* global $, APP, config, Strophe*/
  10782. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10783. var EventEmitter = require("events");
  10784. var Pako = require("pako");
  10785. var RTCEvents = require("../../service/RTC/RTCEvents");
  10786. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10787. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10788. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10789. var RTC = require("../RTC/RTC");
  10790. var authenticatedUser = false;
  10791. function createConnection(bosh) {
  10792. bosh = bosh || '/http-bind';
  10793. // Append token as URL param
  10794. if (this.token) {
  10795. bosh += bosh.indexOf('?') == -1 ?
  10796. '?token=' + this.token : '&token=' + this.token;
  10797. }
  10798. return new Strophe.Connection(bosh);
  10799. };
  10800. //!!!!!!!!!! FIXME: ...
  10801. function initStrophePlugins(XMPP)
  10802. {
  10803. require("./strophe.emuc")(XMPP);
  10804. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10805. // require("./strophe.moderate")(XMPP, eventEmitter);
  10806. require("./strophe.util")();
  10807. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10808. require("./strophe.rayo")();
  10809. require("./strophe.logger")();
  10810. }
  10811. //!!!!!!!!!! FIXME: ...
  10812. ///**
  10813. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10814. // * video type in MUC presence.
  10815. // * @param localStream new or modified <tt>LocalStream</tt>.
  10816. // */
  10817. //function broadcastLocalVideoType(localStream) {
  10818. // if (localStream.videoType)
  10819. // XMPP.addToPresence('videoType', localStream.videoType);
  10820. //}
  10821. //
  10822. //function registerListeners() {
  10823. // RTC.addStreamListener(
  10824. // broadcastLocalVideoType,
  10825. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10826. // );
  10827. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10828. // XMPP.addToPresence("devices", devices);
  10829. // });
  10830. //}
  10831. function XMPP(options) {
  10832. this.eventEmitter = new EventEmitter();
  10833. this.connection = null;
  10834. this.disconnectInProgress = false;
  10835. this.forceMuted = false;
  10836. this.options = options;
  10837. initStrophePlugins(this);
  10838. // registerListeners();
  10839. this.connection = createConnection(options.bosh);
  10840. }
  10841. XMPP.prototype.getConnection = function(){ return connection; };
  10842. XMPP.prototype._connect = function (jid, password) {
  10843. var self = this;
  10844. // connection.connect() starts the connection process.
  10845. //
  10846. // As the connection process proceeds, the user supplied callback will
  10847. // be triggered multiple times with status updates. The callback should
  10848. // take two arguments - the status code and the error condition.
  10849. //
  10850. // The status code will be one of the values in the Strophe.Status
  10851. // constants. The error condition will be one of the conditions defined
  10852. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10853. //
  10854. // The Parameters wait, hold and route are optional and only relevant
  10855. // for BOSH connections. Please see XEP 124 for a more detailed
  10856. // explanation of the optional parameters.
  10857. //
  10858. // Connection status constants for use by the connection handler
  10859. // callback.
  10860. //
  10861. // Status.ERROR - An error has occurred (websockets specific)
  10862. // Status.CONNECTING - The connection is currently being made
  10863. // Status.CONNFAIL - The connection attempt failed
  10864. // Status.AUTHENTICATING - The connection is authenticating
  10865. // Status.AUTHFAIL - The authentication attempt failed
  10866. // Status.CONNECTED - The connection has succeeded
  10867. // Status.DISCONNECTED - The connection has been terminated
  10868. // Status.DISCONNECTING - The connection is currently being terminated
  10869. // Status.ATTACHED - The connection has been attached
  10870. var anonymousConnectionFailed = false;
  10871. var connectionFailed = false;
  10872. var lastErrorMsg;
  10873. this.connection.connect(jid, password, function (status, msg) {
  10874. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10875. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10876. if (status === Strophe.Status.CONNECTED) {
  10877. if (self.options.useStunTurn) {
  10878. self.connection.jingle.getStunAndTurnCredentials();
  10879. }
  10880. logger.info("My Jabber ID: " + self.connection.jid);
  10881. // Schedule ping ?
  10882. var pingJid = self.connection.domain;
  10883. self.connection.ping.hasPingSupport(
  10884. pingJid,
  10885. function (hasPing) {
  10886. if (hasPing)
  10887. self.connection.ping.startInterval(pingJid);
  10888. else
  10889. logger.warn("Ping NOT supported by " + pingJid);
  10890. }
  10891. );
  10892. if (password)
  10893. authenticatedUser = true;
  10894. if (self.connection && self.connection.connected &&
  10895. Strophe.getResourceFromJid(self.connection.jid)) {
  10896. // .connected is true while connecting?
  10897. // self.connection.send($pres());
  10898. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10899. Strophe.getResourceFromJid(self.connection.jid));
  10900. }
  10901. } else if (status === Strophe.Status.CONNFAIL) {
  10902. if (msg === 'x-strophe-bad-non-anon-jid') {
  10903. anonymousConnectionFailed = true;
  10904. }
  10905. else
  10906. {
  10907. connectionFailed = true;
  10908. }
  10909. lastErrorMsg = msg;
  10910. } else if (status === Strophe.Status.DISCONNECTED) {
  10911. // Stop ping interval
  10912. self.connection.ping.stopInterval();
  10913. self.disconnectInProgress = false;
  10914. if (anonymousConnectionFailed) {
  10915. // prompt user for username and password
  10916. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10917. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10918. } else if(connectionFailed) {
  10919. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10920. JitsiConnectionErrors.OTHER_ERROR,
  10921. msg ? msg : lastErrorMsg);
  10922. } else {
  10923. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10924. msg ? msg : lastErrorMsg);
  10925. }
  10926. } else if (status === Strophe.Status.AUTHFAIL) {
  10927. // wrong password or username, prompt user
  10928. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10929. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10930. }
  10931. });
  10932. }
  10933. XMPP.prototype.connect = function (jid, password) {
  10934. if(!jid) {
  10935. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10936. // Force authenticated domain if room is appended with '?login=true'
  10937. if (this.options.hosts.anonymousdomain &&
  10938. window.location.search.indexOf("login=true") !== -1) {
  10939. configDomain = this.options.hosts.domain;
  10940. }
  10941. jid = configDomain || window.location.hostname;
  10942. }
  10943. return this._connect(jid, password);
  10944. };
  10945. XMPP.prototype.createRoom = function (roomName, options) {
  10946. var roomjid = roomName + '@' + this.options.hosts.muc;
  10947. if (options.useNicks) {
  10948. if (options.nick) {
  10949. roomjid += '/' + options.nick;
  10950. } else {
  10951. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10952. }
  10953. } else {
  10954. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10955. if(!authenticatedUser)
  10956. tmpJid = tmpJid.substr(0, 8);
  10957. roomjid += '/' + tmpJid;
  10958. }
  10959. return this.connection.emuc.createRoom(roomjid, null, options);
  10960. }
  10961. XMPP.prototype.addListener = function(type, listener) {
  10962. this.eventEmitter.on(type, listener);
  10963. };
  10964. XMPP.prototype.removeListener = function (type, listener) {
  10965. this.eventEmitter.removeListener(type, listener);
  10966. };
  10967. //FIXME: this should work with the room
  10968. XMPP.prototype.leaveRoom = function (jid) {
  10969. var handler = this.connection.jingle.jid2session[jid];
  10970. if (handler && handler.peerconnection) {
  10971. // FIXME: probably removing streams is not required and close() should
  10972. // be enough
  10973. if (RTC.localAudio) {
  10974. handler.peerconnection.removeStream(
  10975. RTC.localAudio.getOriginalStream(), true);
  10976. }
  10977. if (RTC.localVideo) {
  10978. handler.peerconnection.removeStream(
  10979. RTC.localVideo.getOriginalStream(), true);
  10980. }
  10981. handler.peerconnection.close();
  10982. }
  10983. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10984. this.connection.emuc.doLeave(jid);
  10985. };
  10986. /**
  10987. * Sends 'data' as a log message to the focus. Returns true iff a message
  10988. * was sent.
  10989. * @param data
  10990. * @returns {boolean} true iff a message was sent.
  10991. */
  10992. XMPP.prototype.sendLogs = function (data) {
  10993. if(!this.connection.emuc.focusMucJid)
  10994. return false;
  10995. var deflate = true;
  10996. var content = JSON.stringify(data);
  10997. if (deflate) {
  10998. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10999. }
  11000. content = Base64.encode(content);
  11001. // XEP-0337-ish
  11002. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  11003. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  11004. id: 'PeerConnectionStats'});
  11005. message.c('message').t(content).up();
  11006. if (deflate) {
  11007. message.c('tag', {name: "deflated", value: "true"}).up();
  11008. }
  11009. message.up();
  11010. this.connection.send(message);
  11011. return true;
  11012. };
  11013. // Gets the logs from strophe.jingle.
  11014. XMPP.prototype.getJingleLog = function () {
  11015. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  11016. };
  11017. // Gets the logs from strophe.
  11018. XMPP.prototype.getXmppLog = function () {
  11019. return this.connection.logger ? this.connection.logger.log : null;
  11020. };
  11021. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  11022. this.connection.rayo.dial(to, from, roomName,roomPass);
  11023. };
  11024. XMPP.prototype.setMute = function (jid, mute) {
  11025. this.connection.moderate.setMute(jid, mute);
  11026. };
  11027. XMPP.prototype.eject = function (jid) {
  11028. this.connection.moderate.eject(jid);
  11029. };
  11030. XMPP.prototype.getSessions = function () {
  11031. return this.connection.jingle.sessions;
  11032. };
  11033. XMPP.prototype.disconnect = function () {
  11034. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  11035. {
  11036. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  11037. return;
  11038. }
  11039. this.disconnectInProgress = true;
  11040. this.connection.disconnect();
  11041. };
  11042. /**
  11043. * Gets the SSRC of local media stream.
  11044. * @param mediaType the media type that tells whether we want to get
  11045. * the SSRC of local audio or video stream.
  11046. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  11047. * not available.
  11048. */
  11049. XMPP.prototype.getLocalSSRC = function (mediaType) {
  11050. if (this.connection.jingle.activecall &&
  11051. this.connection.jingle.activecall.peerconnection) {
  11052. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  11053. } else {
  11054. return null;
  11055. }
  11056. };
  11057. module.exports = XMPP;
  11058. }).call(this,"/modules/xmpp/xmpp.js")
  11059. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":80,"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"./strophe.emuc":36,"./strophe.jingle":37,"./strophe.logger":38,"./strophe.ping":39,"./strophe.rayo":40,"./strophe.util":41,"events":44,"jitsi-meet-logger":48,"pako":49}],43:[function(require,module,exports){
  11060. (function (process){
  11061. /*!
  11062. * async
  11063. * https://github.com/caolan/async
  11064. *
  11065. * Copyright 2010-2014 Caolan McMahon
  11066. * Released under the MIT license
  11067. */
  11068. /*jshint onevar: false, indent:4 */
  11069. /*global setImmediate: false, setTimeout: false, console: false */
  11070. (function () {
  11071. var async = {};
  11072. // global on the server, window in the browser
  11073. var root, previous_async;
  11074. root = this;
  11075. if (root != null) {
  11076. previous_async = root.async;
  11077. }
  11078. async.noConflict = function () {
  11079. root.async = previous_async;
  11080. return async;
  11081. };
  11082. function only_once(fn) {
  11083. var called = false;
  11084. return function() {
  11085. if (called) throw new Error("Callback was already called.");
  11086. called = true;
  11087. fn.apply(root, arguments);
  11088. }
  11089. }
  11090. //// cross-browser compatiblity functions ////
  11091. var _toString = Object.prototype.toString;
  11092. var _isArray = Array.isArray || function (obj) {
  11093. return _toString.call(obj) === '[object Array]';
  11094. };
  11095. var _each = function (arr, iterator) {
  11096. if (arr.forEach) {
  11097. return arr.forEach(iterator);
  11098. }
  11099. for (var i = 0; i < arr.length; i += 1) {
  11100. iterator(arr[i], i, arr);
  11101. }
  11102. };
  11103. var _map = function (arr, iterator) {
  11104. if (arr.map) {
  11105. return arr.map(iterator);
  11106. }
  11107. var results = [];
  11108. _each(arr, function (x, i, a) {
  11109. results.push(iterator(x, i, a));
  11110. });
  11111. return results;
  11112. };
  11113. var _reduce = function (arr, iterator, memo) {
  11114. if (arr.reduce) {
  11115. return arr.reduce(iterator, memo);
  11116. }
  11117. _each(arr, function (x, i, a) {
  11118. memo = iterator(memo, x, i, a);
  11119. });
  11120. return memo;
  11121. };
  11122. var _keys = function (obj) {
  11123. if (Object.keys) {
  11124. return Object.keys(obj);
  11125. }
  11126. var keys = [];
  11127. for (var k in obj) {
  11128. if (obj.hasOwnProperty(k)) {
  11129. keys.push(k);
  11130. }
  11131. }
  11132. return keys;
  11133. };
  11134. //// exported async module functions ////
  11135. //// nextTick implementation with browser-compatible fallback ////
  11136. if (typeof process === 'undefined' || !(process.nextTick)) {
  11137. if (typeof setImmediate === 'function') {
  11138. async.nextTick = function (fn) {
  11139. // not a direct alias for IE10 compatibility
  11140. setImmediate(fn);
  11141. };
  11142. async.setImmediate = async.nextTick;
  11143. }
  11144. else {
  11145. async.nextTick = function (fn) {
  11146. setTimeout(fn, 0);
  11147. };
  11148. async.setImmediate = async.nextTick;
  11149. }
  11150. }
  11151. else {
  11152. async.nextTick = process.nextTick;
  11153. if (typeof setImmediate !== 'undefined') {
  11154. async.setImmediate = function (fn) {
  11155. // not a direct alias for IE10 compatibility
  11156. setImmediate(fn);
  11157. };
  11158. }
  11159. else {
  11160. async.setImmediate = async.nextTick;
  11161. }
  11162. }
  11163. async.each = function (arr, iterator, callback) {
  11164. callback = callback || function () {};
  11165. if (!arr.length) {
  11166. return callback();
  11167. }
  11168. var completed = 0;
  11169. _each(arr, function (x) {
  11170. iterator(x, only_once(done) );
  11171. });
  11172. function done(err) {
  11173. if (err) {
  11174. callback(err);
  11175. callback = function () {};
  11176. }
  11177. else {
  11178. completed += 1;
  11179. if (completed >= arr.length) {
  11180. callback();
  11181. }
  11182. }
  11183. }
  11184. };
  11185. async.forEach = async.each;
  11186. async.eachSeries = function (arr, iterator, callback) {
  11187. callback = callback || function () {};
  11188. if (!arr.length) {
  11189. return callback();
  11190. }
  11191. var completed = 0;
  11192. var iterate = function () {
  11193. iterator(arr[completed], function (err) {
  11194. if (err) {
  11195. callback(err);
  11196. callback = function () {};
  11197. }
  11198. else {
  11199. completed += 1;
  11200. if (completed >= arr.length) {
  11201. callback();
  11202. }
  11203. else {
  11204. iterate();
  11205. }
  11206. }
  11207. });
  11208. };
  11209. iterate();
  11210. };
  11211. async.forEachSeries = async.eachSeries;
  11212. async.eachLimit = function (arr, limit, iterator, callback) {
  11213. var fn = _eachLimit(limit);
  11214. fn.apply(null, [arr, iterator, callback]);
  11215. };
  11216. async.forEachLimit = async.eachLimit;
  11217. var _eachLimit = function (limit) {
  11218. return function (arr, iterator, callback) {
  11219. callback = callback || function () {};
  11220. if (!arr.length || limit <= 0) {
  11221. return callback();
  11222. }
  11223. var completed = 0;
  11224. var started = 0;
  11225. var running = 0;
  11226. (function replenish () {
  11227. if (completed >= arr.length) {
  11228. return callback();
  11229. }
  11230. while (running < limit && started < arr.length) {
  11231. started += 1;
  11232. running += 1;
  11233. iterator(arr[started - 1], function (err) {
  11234. if (err) {
  11235. callback(err);
  11236. callback = function () {};
  11237. }
  11238. else {
  11239. completed += 1;
  11240. running -= 1;
  11241. if (completed >= arr.length) {
  11242. callback();
  11243. }
  11244. else {
  11245. replenish();
  11246. }
  11247. }
  11248. });
  11249. }
  11250. })();
  11251. };
  11252. };
  11253. var doParallel = function (fn) {
  11254. return function () {
  11255. var args = Array.prototype.slice.call(arguments);
  11256. return fn.apply(null, [async.each].concat(args));
  11257. };
  11258. };
  11259. var doParallelLimit = function(limit, fn) {
  11260. return function () {
  11261. var args = Array.prototype.slice.call(arguments);
  11262. return fn.apply(null, [_eachLimit(limit)].concat(args));
  11263. };
  11264. };
  11265. var doSeries = function (fn) {
  11266. return function () {
  11267. var args = Array.prototype.slice.call(arguments);
  11268. return fn.apply(null, [async.eachSeries].concat(args));
  11269. };
  11270. };
  11271. var _asyncMap = function (eachfn, arr, iterator, callback) {
  11272. arr = _map(arr, function (x, i) {
  11273. return {index: i, value: x};
  11274. });
  11275. if (!callback) {
  11276. eachfn(arr, function (x, callback) {
  11277. iterator(x.value, function (err) {
  11278. callback(err);
  11279. });
  11280. });
  11281. } else {
  11282. var results = [];
  11283. eachfn(arr, function (x, callback) {
  11284. iterator(x.value, function (err, v) {
  11285. results[x.index] = v;
  11286. callback(err);
  11287. });
  11288. }, function (err) {
  11289. callback(err, results);
  11290. });
  11291. }
  11292. };
  11293. async.map = doParallel(_asyncMap);
  11294. async.mapSeries = doSeries(_asyncMap);
  11295. async.mapLimit = function (arr, limit, iterator, callback) {
  11296. return _mapLimit(limit)(arr, iterator, callback);
  11297. };
  11298. var _mapLimit = function(limit) {
  11299. return doParallelLimit(limit, _asyncMap);
  11300. };
  11301. // reduce only has a series version, as doing reduce in parallel won't
  11302. // work in many situations.
  11303. async.reduce = function (arr, memo, iterator, callback) {
  11304. async.eachSeries(arr, function (x, callback) {
  11305. iterator(memo, x, function (err, v) {
  11306. memo = v;
  11307. callback(err);
  11308. });
  11309. }, function (err) {
  11310. callback(err, memo);
  11311. });
  11312. };
  11313. // inject alias
  11314. async.inject = async.reduce;
  11315. // foldl alias
  11316. async.foldl = async.reduce;
  11317. async.reduceRight = function (arr, memo, iterator, callback) {
  11318. var reversed = _map(arr, function (x) {
  11319. return x;
  11320. }).reverse();
  11321. async.reduce(reversed, memo, iterator, callback);
  11322. };
  11323. // foldr alias
  11324. async.foldr = async.reduceRight;
  11325. var _filter = function (eachfn, arr, iterator, callback) {
  11326. var results = [];
  11327. arr = _map(arr, function (x, i) {
  11328. return {index: i, value: x};
  11329. });
  11330. eachfn(arr, function (x, callback) {
  11331. iterator(x.value, function (v) {
  11332. if (v) {
  11333. results.push(x);
  11334. }
  11335. callback();
  11336. });
  11337. }, function (err) {
  11338. callback(_map(results.sort(function (a, b) {
  11339. return a.index - b.index;
  11340. }), function (x) {
  11341. return x.value;
  11342. }));
  11343. });
  11344. };
  11345. async.filter = doParallel(_filter);
  11346. async.filterSeries = doSeries(_filter);
  11347. // select alias
  11348. async.select = async.filter;
  11349. async.selectSeries = async.filterSeries;
  11350. var _reject = function (eachfn, arr, iterator, callback) {
  11351. var results = [];
  11352. arr = _map(arr, function (x, i) {
  11353. return {index: i, value: x};
  11354. });
  11355. eachfn(arr, function (x, callback) {
  11356. iterator(x.value, function (v) {
  11357. if (!v) {
  11358. results.push(x);
  11359. }
  11360. callback();
  11361. });
  11362. }, function (err) {
  11363. callback(_map(results.sort(function (a, b) {
  11364. return a.index - b.index;
  11365. }), function (x) {
  11366. return x.value;
  11367. }));
  11368. });
  11369. };
  11370. async.reject = doParallel(_reject);
  11371. async.rejectSeries = doSeries(_reject);
  11372. var _detect = function (eachfn, arr, iterator, main_callback) {
  11373. eachfn(arr, function (x, callback) {
  11374. iterator(x, function (result) {
  11375. if (result) {
  11376. main_callback(x);
  11377. main_callback = function () {};
  11378. }
  11379. else {
  11380. callback();
  11381. }
  11382. });
  11383. }, function (err) {
  11384. main_callback();
  11385. });
  11386. };
  11387. async.detect = doParallel(_detect);
  11388. async.detectSeries = doSeries(_detect);
  11389. async.some = function (arr, iterator, main_callback) {
  11390. async.each(arr, function (x, callback) {
  11391. iterator(x, function (v) {
  11392. if (v) {
  11393. main_callback(true);
  11394. main_callback = function () {};
  11395. }
  11396. callback();
  11397. });
  11398. }, function (err) {
  11399. main_callback(false);
  11400. });
  11401. };
  11402. // any alias
  11403. async.any = async.some;
  11404. async.every = function (arr, iterator, main_callback) {
  11405. async.each(arr, function (x, callback) {
  11406. iterator(x, function (v) {
  11407. if (!v) {
  11408. main_callback(false);
  11409. main_callback = function () {};
  11410. }
  11411. callback();
  11412. });
  11413. }, function (err) {
  11414. main_callback(true);
  11415. });
  11416. };
  11417. // all alias
  11418. async.all = async.every;
  11419. async.sortBy = function (arr, iterator, callback) {
  11420. async.map(arr, function (x, callback) {
  11421. iterator(x, function (err, criteria) {
  11422. if (err) {
  11423. callback(err);
  11424. }
  11425. else {
  11426. callback(null, {value: x, criteria: criteria});
  11427. }
  11428. });
  11429. }, function (err, results) {
  11430. if (err) {
  11431. return callback(err);
  11432. }
  11433. else {
  11434. var fn = function (left, right) {
  11435. var a = left.criteria, b = right.criteria;
  11436. return a < b ? -1 : a > b ? 1 : 0;
  11437. };
  11438. callback(null, _map(results.sort(fn), function (x) {
  11439. return x.value;
  11440. }));
  11441. }
  11442. });
  11443. };
  11444. async.auto = function (tasks, callback) {
  11445. callback = callback || function () {};
  11446. var keys = _keys(tasks);
  11447. var remainingTasks = keys.length
  11448. if (!remainingTasks) {
  11449. return callback();
  11450. }
  11451. var results = {};
  11452. var listeners = [];
  11453. var addListener = function (fn) {
  11454. listeners.unshift(fn);
  11455. };
  11456. var removeListener = function (fn) {
  11457. for (var i = 0; i < listeners.length; i += 1) {
  11458. if (listeners[i] === fn) {
  11459. listeners.splice(i, 1);
  11460. return;
  11461. }
  11462. }
  11463. };
  11464. var taskComplete = function () {
  11465. remainingTasks--
  11466. _each(listeners.slice(0), function (fn) {
  11467. fn();
  11468. });
  11469. };
  11470. addListener(function () {
  11471. if (!remainingTasks) {
  11472. var theCallback = callback;
  11473. // prevent final callback from calling itself if it errors
  11474. callback = function () {};
  11475. theCallback(null, results);
  11476. }
  11477. });
  11478. _each(keys, function (k) {
  11479. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  11480. var taskCallback = function (err) {
  11481. var args = Array.prototype.slice.call(arguments, 1);
  11482. if (args.length <= 1) {
  11483. args = args[0];
  11484. }
  11485. if (err) {
  11486. var safeResults = {};
  11487. _each(_keys(results), function(rkey) {
  11488. safeResults[rkey] = results[rkey];
  11489. });
  11490. safeResults[k] = args;
  11491. callback(err, safeResults);
  11492. // stop subsequent errors hitting callback multiple times
  11493. callback = function () {};
  11494. }
  11495. else {
  11496. results[k] = args;
  11497. async.setImmediate(taskComplete);
  11498. }
  11499. };
  11500. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  11501. var ready = function () {
  11502. return _reduce(requires, function (a, x) {
  11503. return (a && results.hasOwnProperty(x));
  11504. }, true) && !results.hasOwnProperty(k);
  11505. };
  11506. if (ready()) {
  11507. task[task.length - 1](taskCallback, results);
  11508. }
  11509. else {
  11510. var listener = function () {
  11511. if (ready()) {
  11512. removeListener(listener);
  11513. task[task.length - 1](taskCallback, results);
  11514. }
  11515. };
  11516. addListener(listener);
  11517. }
  11518. });
  11519. };
  11520. async.retry = function(times, task, callback) {
  11521. var DEFAULT_TIMES = 5;
  11522. var attempts = [];
  11523. // Use defaults if times not passed
  11524. if (typeof times === 'function') {
  11525. callback = task;
  11526. task = times;
  11527. times = DEFAULT_TIMES;
  11528. }
  11529. // Make sure times is a number
  11530. times = parseInt(times, 10) || DEFAULT_TIMES;
  11531. var wrappedTask = function(wrappedCallback, wrappedResults) {
  11532. var retryAttempt = function(task, finalAttempt) {
  11533. return function(seriesCallback) {
  11534. task(function(err, result){
  11535. seriesCallback(!err || finalAttempt, {err: err, result: result});
  11536. }, wrappedResults);
  11537. };
  11538. };
  11539. while (times) {
  11540. attempts.push(retryAttempt(task, !(times-=1)));
  11541. }
  11542. async.series(attempts, function(done, data){
  11543. data = data[data.length - 1];
  11544. (wrappedCallback || callback)(data.err, data.result);
  11545. });
  11546. }
  11547. // If a callback is passed, run this as a controll flow
  11548. return callback ? wrappedTask() : wrappedTask
  11549. };
  11550. async.waterfall = function (tasks, callback) {
  11551. callback = callback || function () {};
  11552. if (!_isArray(tasks)) {
  11553. var err = new Error('First argument to waterfall must be an array of functions');
  11554. return callback(err);
  11555. }
  11556. if (!tasks.length) {
  11557. return callback();
  11558. }
  11559. var wrapIterator = function (iterator) {
  11560. return function (err) {
  11561. if (err) {
  11562. callback.apply(null, arguments);
  11563. callback = function () {};
  11564. }
  11565. else {
  11566. var args = Array.prototype.slice.call(arguments, 1);
  11567. var next = iterator.next();
  11568. if (next) {
  11569. args.push(wrapIterator(next));
  11570. }
  11571. else {
  11572. args.push(callback);
  11573. }
  11574. async.setImmediate(function () {
  11575. iterator.apply(null, args);
  11576. });
  11577. }
  11578. };
  11579. };
  11580. wrapIterator(async.iterator(tasks))();
  11581. };
  11582. var _parallel = function(eachfn, tasks, callback) {
  11583. callback = callback || function () {};
  11584. if (_isArray(tasks)) {
  11585. eachfn.map(tasks, function (fn, callback) {
  11586. if (fn) {
  11587. fn(function (err) {
  11588. var args = Array.prototype.slice.call(arguments, 1);
  11589. if (args.length <= 1) {
  11590. args = args[0];
  11591. }
  11592. callback.call(null, err, args);
  11593. });
  11594. }
  11595. }, callback);
  11596. }
  11597. else {
  11598. var results = {};
  11599. eachfn.each(_keys(tasks), function (k, callback) {
  11600. tasks[k](function (err) {
  11601. var args = Array.prototype.slice.call(arguments, 1);
  11602. if (args.length <= 1) {
  11603. args = args[0];
  11604. }
  11605. results[k] = args;
  11606. callback(err);
  11607. });
  11608. }, function (err) {
  11609. callback(err, results);
  11610. });
  11611. }
  11612. };
  11613. async.parallel = function (tasks, callback) {
  11614. _parallel({ map: async.map, each: async.each }, tasks, callback);
  11615. };
  11616. async.parallelLimit = function(tasks, limit, callback) {
  11617. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  11618. };
  11619. async.series = function (tasks, callback) {
  11620. callback = callback || function () {};
  11621. if (_isArray(tasks)) {
  11622. async.mapSeries(tasks, function (fn, callback) {
  11623. if (fn) {
  11624. fn(function (err) {
  11625. var args = Array.prototype.slice.call(arguments, 1);
  11626. if (args.length <= 1) {
  11627. args = args[0];
  11628. }
  11629. callback.call(null, err, args);
  11630. });
  11631. }
  11632. }, callback);
  11633. }
  11634. else {
  11635. var results = {};
  11636. async.eachSeries(_keys(tasks), function (k, callback) {
  11637. tasks[k](function (err) {
  11638. var args = Array.prototype.slice.call(arguments, 1);
  11639. if (args.length <= 1) {
  11640. args = args[0];
  11641. }
  11642. results[k] = args;
  11643. callback(err);
  11644. });
  11645. }, function (err) {
  11646. callback(err, results);
  11647. });
  11648. }
  11649. };
  11650. async.iterator = function (tasks) {
  11651. var makeCallback = function (index) {
  11652. var fn = function () {
  11653. if (tasks.length) {
  11654. tasks[index].apply(null, arguments);
  11655. }
  11656. return fn.next();
  11657. };
  11658. fn.next = function () {
  11659. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11660. };
  11661. return fn;
  11662. };
  11663. return makeCallback(0);
  11664. };
  11665. async.apply = function (fn) {
  11666. var args = Array.prototype.slice.call(arguments, 1);
  11667. return function () {
  11668. return fn.apply(
  11669. null, args.concat(Array.prototype.slice.call(arguments))
  11670. );
  11671. };
  11672. };
  11673. var _concat = function (eachfn, arr, fn, callback) {
  11674. var r = [];
  11675. eachfn(arr, function (x, cb) {
  11676. fn(x, function (err, y) {
  11677. r = r.concat(y || []);
  11678. cb(err);
  11679. });
  11680. }, function (err) {
  11681. callback(err, r);
  11682. });
  11683. };
  11684. async.concat = doParallel(_concat);
  11685. async.concatSeries = doSeries(_concat);
  11686. async.whilst = function (test, iterator, callback) {
  11687. if (test()) {
  11688. iterator(function (err) {
  11689. if (err) {
  11690. return callback(err);
  11691. }
  11692. async.whilst(test, iterator, callback);
  11693. });
  11694. }
  11695. else {
  11696. callback();
  11697. }
  11698. };
  11699. async.doWhilst = function (iterator, test, callback) {
  11700. iterator(function (err) {
  11701. if (err) {
  11702. return callback(err);
  11703. }
  11704. var args = Array.prototype.slice.call(arguments, 1);
  11705. if (test.apply(null, args)) {
  11706. async.doWhilst(iterator, test, callback);
  11707. }
  11708. else {
  11709. callback();
  11710. }
  11711. });
  11712. };
  11713. async.until = function (test, iterator, callback) {
  11714. if (!test()) {
  11715. iterator(function (err) {
  11716. if (err) {
  11717. return callback(err);
  11718. }
  11719. async.until(test, iterator, callback);
  11720. });
  11721. }
  11722. else {
  11723. callback();
  11724. }
  11725. };
  11726. async.doUntil = function (iterator, test, callback) {
  11727. iterator(function (err) {
  11728. if (err) {
  11729. return callback(err);
  11730. }
  11731. var args = Array.prototype.slice.call(arguments, 1);
  11732. if (!test.apply(null, args)) {
  11733. async.doUntil(iterator, test, callback);
  11734. }
  11735. else {
  11736. callback();
  11737. }
  11738. });
  11739. };
  11740. async.queue = function (worker, concurrency) {
  11741. if (concurrency === undefined) {
  11742. concurrency = 1;
  11743. }
  11744. function _insert(q, data, pos, callback) {
  11745. if (!q.started){
  11746. q.started = true;
  11747. }
  11748. if (!_isArray(data)) {
  11749. data = [data];
  11750. }
  11751. if(data.length == 0) {
  11752. // call drain immediately if there are no tasks
  11753. return async.setImmediate(function() {
  11754. if (q.drain) {
  11755. q.drain();
  11756. }
  11757. });
  11758. }
  11759. _each(data, function(task) {
  11760. var item = {
  11761. data: task,
  11762. callback: typeof callback === 'function' ? callback : null
  11763. };
  11764. if (pos) {
  11765. q.tasks.unshift(item);
  11766. } else {
  11767. q.tasks.push(item);
  11768. }
  11769. if (q.saturated && q.tasks.length === q.concurrency) {
  11770. q.saturated();
  11771. }
  11772. async.setImmediate(q.process);
  11773. });
  11774. }
  11775. var workers = 0;
  11776. var q = {
  11777. tasks: [],
  11778. concurrency: concurrency,
  11779. saturated: null,
  11780. empty: null,
  11781. drain: null,
  11782. started: false,
  11783. paused: false,
  11784. push: function (data, callback) {
  11785. _insert(q, data, false, callback);
  11786. },
  11787. kill: function () {
  11788. q.drain = null;
  11789. q.tasks = [];
  11790. },
  11791. unshift: function (data, callback) {
  11792. _insert(q, data, true, callback);
  11793. },
  11794. process: function () {
  11795. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11796. var task = q.tasks.shift();
  11797. if (q.empty && q.tasks.length === 0) {
  11798. q.empty();
  11799. }
  11800. workers += 1;
  11801. var next = function () {
  11802. workers -= 1;
  11803. if (task.callback) {
  11804. task.callback.apply(task, arguments);
  11805. }
  11806. if (q.drain && q.tasks.length + workers === 0) {
  11807. q.drain();
  11808. }
  11809. q.process();
  11810. };
  11811. var cb = only_once(next);
  11812. worker(task.data, cb);
  11813. }
  11814. },
  11815. length: function () {
  11816. return q.tasks.length;
  11817. },
  11818. running: function () {
  11819. return workers;
  11820. },
  11821. idle: function() {
  11822. return q.tasks.length + workers === 0;
  11823. },
  11824. pause: function () {
  11825. if (q.paused === true) { return; }
  11826. q.paused = true;
  11827. q.process();
  11828. },
  11829. resume: function () {
  11830. if (q.paused === false) { return; }
  11831. q.paused = false;
  11832. q.process();
  11833. }
  11834. };
  11835. return q;
  11836. };
  11837. async.priorityQueue = function (worker, concurrency) {
  11838. function _compareTasks(a, b){
  11839. return a.priority - b.priority;
  11840. };
  11841. function _binarySearch(sequence, item, compare) {
  11842. var beg = -1,
  11843. end = sequence.length - 1;
  11844. while (beg < end) {
  11845. var mid = beg + ((end - beg + 1) >>> 1);
  11846. if (compare(item, sequence[mid]) >= 0) {
  11847. beg = mid;
  11848. } else {
  11849. end = mid - 1;
  11850. }
  11851. }
  11852. return beg;
  11853. }
  11854. function _insert(q, data, priority, callback) {
  11855. if (!q.started){
  11856. q.started = true;
  11857. }
  11858. if (!_isArray(data)) {
  11859. data = [data];
  11860. }
  11861. if(data.length == 0) {
  11862. // call drain immediately if there are no tasks
  11863. return async.setImmediate(function() {
  11864. if (q.drain) {
  11865. q.drain();
  11866. }
  11867. });
  11868. }
  11869. _each(data, function(task) {
  11870. var item = {
  11871. data: task,
  11872. priority: priority,
  11873. callback: typeof callback === 'function' ? callback : null
  11874. };
  11875. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11876. if (q.saturated && q.tasks.length === q.concurrency) {
  11877. q.saturated();
  11878. }
  11879. async.setImmediate(q.process);
  11880. });
  11881. }
  11882. // Start with a normal queue
  11883. var q = async.queue(worker, concurrency);
  11884. // Override push to accept second parameter representing priority
  11885. q.push = function (data, priority, callback) {
  11886. _insert(q, data, priority, callback);
  11887. };
  11888. // Remove unshift function
  11889. delete q.unshift;
  11890. return q;
  11891. };
  11892. async.cargo = function (worker, payload) {
  11893. var working = false,
  11894. tasks = [];
  11895. var cargo = {
  11896. tasks: tasks,
  11897. payload: payload,
  11898. saturated: null,
  11899. empty: null,
  11900. drain: null,
  11901. drained: true,
  11902. push: function (data, callback) {
  11903. if (!_isArray(data)) {
  11904. data = [data];
  11905. }
  11906. _each(data, function(task) {
  11907. tasks.push({
  11908. data: task,
  11909. callback: typeof callback === 'function' ? callback : null
  11910. });
  11911. cargo.drained = false;
  11912. if (cargo.saturated && tasks.length === payload) {
  11913. cargo.saturated();
  11914. }
  11915. });
  11916. async.setImmediate(cargo.process);
  11917. },
  11918. process: function process() {
  11919. if (working) return;
  11920. if (tasks.length === 0) {
  11921. if(cargo.drain && !cargo.drained) cargo.drain();
  11922. cargo.drained = true;
  11923. return;
  11924. }
  11925. var ts = typeof payload === 'number'
  11926. ? tasks.splice(0, payload)
  11927. : tasks.splice(0, tasks.length);
  11928. var ds = _map(ts, function (task) {
  11929. return task.data;
  11930. });
  11931. if(cargo.empty) cargo.empty();
  11932. working = true;
  11933. worker(ds, function () {
  11934. working = false;
  11935. var args = arguments;
  11936. _each(ts, function (data) {
  11937. if (data.callback) {
  11938. data.callback.apply(null, args);
  11939. }
  11940. });
  11941. process();
  11942. });
  11943. },
  11944. length: function () {
  11945. return tasks.length;
  11946. },
  11947. running: function () {
  11948. return working;
  11949. }
  11950. };
  11951. return cargo;
  11952. };
  11953. var _console_fn = function (name) {
  11954. return function (fn) {
  11955. var args = Array.prototype.slice.call(arguments, 1);
  11956. fn.apply(null, args.concat([function (err) {
  11957. var args = Array.prototype.slice.call(arguments, 1);
  11958. if (typeof console !== 'undefined') {
  11959. if (err) {
  11960. if (console.error) {
  11961. console.error(err);
  11962. }
  11963. }
  11964. else if (console[name]) {
  11965. _each(args, function (x) {
  11966. console[name](x);
  11967. });
  11968. }
  11969. }
  11970. }]));
  11971. };
  11972. };
  11973. async.log = _console_fn('log');
  11974. async.dir = _console_fn('dir');
  11975. /*async.info = _console_fn('info');
  11976. async.warn = _console_fn('warn');
  11977. async.error = _console_fn('error');*/
  11978. async.memoize = function (fn, hasher) {
  11979. var memo = {};
  11980. var queues = {};
  11981. hasher = hasher || function (x) {
  11982. return x;
  11983. };
  11984. var memoized = function () {
  11985. var args = Array.prototype.slice.call(arguments);
  11986. var callback = args.pop();
  11987. var key = hasher.apply(null, args);
  11988. if (key in memo) {
  11989. async.nextTick(function () {
  11990. callback.apply(null, memo[key]);
  11991. });
  11992. }
  11993. else if (key in queues) {
  11994. queues[key].push(callback);
  11995. }
  11996. else {
  11997. queues[key] = [callback];
  11998. fn.apply(null, args.concat([function () {
  11999. memo[key] = arguments;
  12000. var q = queues[key];
  12001. delete queues[key];
  12002. for (var i = 0, l = q.length; i < l; i++) {
  12003. q[i].apply(null, arguments);
  12004. }
  12005. }]));
  12006. }
  12007. };
  12008. memoized.memo = memo;
  12009. memoized.unmemoized = fn;
  12010. return memoized;
  12011. };
  12012. async.unmemoize = function (fn) {
  12013. return function () {
  12014. return (fn.unmemoized || fn).apply(null, arguments);
  12015. };
  12016. };
  12017. async.times = function (count, iterator, callback) {
  12018. var counter = [];
  12019. for (var i = 0; i < count; i++) {
  12020. counter.push(i);
  12021. }
  12022. return async.map(counter, iterator, callback);
  12023. };
  12024. async.timesSeries = function (count, iterator, callback) {
  12025. var counter = [];
  12026. for (var i = 0; i < count; i++) {
  12027. counter.push(i);
  12028. }
  12029. return async.mapSeries(counter, iterator, callback);
  12030. };
  12031. async.seq = function (/* functions... */) {
  12032. var fns = arguments;
  12033. return function () {
  12034. var that = this;
  12035. var args = Array.prototype.slice.call(arguments);
  12036. var callback = args.pop();
  12037. async.reduce(fns, args, function (newargs, fn, cb) {
  12038. fn.apply(that, newargs.concat([function () {
  12039. var err = arguments[0];
  12040. var nextargs = Array.prototype.slice.call(arguments, 1);
  12041. cb(err, nextargs);
  12042. }]))
  12043. },
  12044. function (err, results) {
  12045. callback.apply(that, [err].concat(results));
  12046. });
  12047. };
  12048. };
  12049. async.compose = function (/* functions... */) {
  12050. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  12051. };
  12052. var _applyEach = function (eachfn, fns /*args...*/) {
  12053. var go = function () {
  12054. var that = this;
  12055. var args = Array.prototype.slice.call(arguments);
  12056. var callback = args.pop();
  12057. return eachfn(fns, function (fn, cb) {
  12058. fn.apply(that, args.concat([cb]));
  12059. },
  12060. callback);
  12061. };
  12062. if (arguments.length > 2) {
  12063. var args = Array.prototype.slice.call(arguments, 2);
  12064. return go.apply(this, args);
  12065. }
  12066. else {
  12067. return go;
  12068. }
  12069. };
  12070. async.applyEach = doParallel(_applyEach);
  12071. async.applyEachSeries = doSeries(_applyEach);
  12072. async.forever = function (fn, callback) {
  12073. function next(err) {
  12074. if (err) {
  12075. if (callback) {
  12076. return callback(err);
  12077. }
  12078. throw err;
  12079. }
  12080. fn(next);
  12081. }
  12082. next();
  12083. };
  12084. // Node.js
  12085. if (typeof module !== 'undefined' && module.exports) {
  12086. module.exports = async;
  12087. }
  12088. // AMD / RequireJS
  12089. else if (typeof define !== 'undefined' && define.amd) {
  12090. define([], function () {
  12091. return async;
  12092. });
  12093. }
  12094. // included directly via <script> tag
  12095. else {
  12096. root.async = async;
  12097. }
  12098. }());
  12099. }).call(this,require('_process'))
  12100. },{"_process":45}],44:[function(require,module,exports){
  12101. // Copyright Joyent, Inc. and other Node contributors.
  12102. //
  12103. // Permission is hereby granted, free of charge, to any person obtaining a
  12104. // copy of this software and associated documentation files (the
  12105. // "Software"), to deal in the Software without restriction, including
  12106. // without limitation the rights to use, copy, modify, merge, publish,
  12107. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12108. // persons to whom the Software is furnished to do so, subject to the
  12109. // following conditions:
  12110. //
  12111. // The above copyright notice and this permission notice shall be included
  12112. // in all copies or substantial portions of the Software.
  12113. //
  12114. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12115. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12116. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12117. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12118. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12119. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12120. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12121. function EventEmitter() {
  12122. this._events = this._events || {};
  12123. this._maxListeners = this._maxListeners || undefined;
  12124. }
  12125. module.exports = EventEmitter;
  12126. // Backwards-compat with node 0.10.x
  12127. EventEmitter.EventEmitter = EventEmitter;
  12128. EventEmitter.prototype._events = undefined;
  12129. EventEmitter.prototype._maxListeners = undefined;
  12130. // By default EventEmitters will print a warning if more than 10 listeners are
  12131. // added to it. This is a useful default which helps finding memory leaks.
  12132. EventEmitter.defaultMaxListeners = 10;
  12133. // Obviously not all Emitters should be limited to 10. This function allows
  12134. // that to be increased. Set to zero for unlimited.
  12135. EventEmitter.prototype.setMaxListeners = function(n) {
  12136. if (!isNumber(n) || n < 0 || isNaN(n))
  12137. throw TypeError('n must be a positive number');
  12138. this._maxListeners = n;
  12139. return this;
  12140. };
  12141. EventEmitter.prototype.emit = function(type) {
  12142. var er, handler, len, args, i, listeners;
  12143. if (!this._events)
  12144. this._events = {};
  12145. // If there is no 'error' event listener then throw.
  12146. if (type === 'error') {
  12147. if (!this._events.error ||
  12148. (isObject(this._events.error) && !this._events.error.length)) {
  12149. er = arguments[1];
  12150. if (er instanceof Error) {
  12151. throw er; // Unhandled 'error' event
  12152. }
  12153. throw TypeError('Uncaught, unspecified "error" event.');
  12154. }
  12155. }
  12156. handler = this._events[type];
  12157. if (isUndefined(handler))
  12158. return false;
  12159. if (isFunction(handler)) {
  12160. switch (arguments.length) {
  12161. // fast cases
  12162. case 1:
  12163. handler.call(this);
  12164. break;
  12165. case 2:
  12166. handler.call(this, arguments[1]);
  12167. break;
  12168. case 3:
  12169. handler.call(this, arguments[1], arguments[2]);
  12170. break;
  12171. // slower
  12172. default:
  12173. len = arguments.length;
  12174. args = new Array(len - 1);
  12175. for (i = 1; i < len; i++)
  12176. args[i - 1] = arguments[i];
  12177. handler.apply(this, args);
  12178. }
  12179. } else if (isObject(handler)) {
  12180. len = arguments.length;
  12181. args = new Array(len - 1);
  12182. for (i = 1; i < len; i++)
  12183. args[i - 1] = arguments[i];
  12184. listeners = handler.slice();
  12185. len = listeners.length;
  12186. for (i = 0; i < len; i++)
  12187. listeners[i].apply(this, args);
  12188. }
  12189. return true;
  12190. };
  12191. EventEmitter.prototype.addListener = function(type, listener) {
  12192. var m;
  12193. if (!isFunction(listener))
  12194. throw TypeError('listener must be a function');
  12195. if (!this._events)
  12196. this._events = {};
  12197. // To avoid recursion in the case that type === "newListener"! Before
  12198. // adding it to the listeners, first emit "newListener".
  12199. if (this._events.newListener)
  12200. this.emit('newListener', type,
  12201. isFunction(listener.listener) ?
  12202. listener.listener : listener);
  12203. if (!this._events[type])
  12204. // Optimize the case of one listener. Don't need the extra array object.
  12205. this._events[type] = listener;
  12206. else if (isObject(this._events[type]))
  12207. // If we've already got an array, just append.
  12208. this._events[type].push(listener);
  12209. else
  12210. // Adding the second element, need to change to array.
  12211. this._events[type] = [this._events[type], listener];
  12212. // Check for listener leak
  12213. if (isObject(this._events[type]) && !this._events[type].warned) {
  12214. var m;
  12215. if (!isUndefined(this._maxListeners)) {
  12216. m = this._maxListeners;
  12217. } else {
  12218. m = EventEmitter.defaultMaxListeners;
  12219. }
  12220. if (m && m > 0 && this._events[type].length > m) {
  12221. this._events[type].warned = true;
  12222. console.error('(node) warning: possible EventEmitter memory ' +
  12223. 'leak detected. %d listeners added. ' +
  12224. 'Use emitter.setMaxListeners() to increase limit.',
  12225. this._events[type].length);
  12226. if (typeof console.trace === 'function') {
  12227. // not supported in IE 10
  12228. console.trace();
  12229. }
  12230. }
  12231. }
  12232. return this;
  12233. };
  12234. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  12235. EventEmitter.prototype.once = function(type, listener) {
  12236. if (!isFunction(listener))
  12237. throw TypeError('listener must be a function');
  12238. var fired = false;
  12239. function g() {
  12240. this.removeListener(type, g);
  12241. if (!fired) {
  12242. fired = true;
  12243. listener.apply(this, arguments);
  12244. }
  12245. }
  12246. g.listener = listener;
  12247. this.on(type, g);
  12248. return this;
  12249. };
  12250. // emits a 'removeListener' event iff the listener was removed
  12251. EventEmitter.prototype.removeListener = function(type, listener) {
  12252. var list, position, length, i;
  12253. if (!isFunction(listener))
  12254. throw TypeError('listener must be a function');
  12255. if (!this._events || !this._events[type])
  12256. return this;
  12257. list = this._events[type];
  12258. length = list.length;
  12259. position = -1;
  12260. if (list === listener ||
  12261. (isFunction(list.listener) && list.listener === listener)) {
  12262. delete this._events[type];
  12263. if (this._events.removeListener)
  12264. this.emit('removeListener', type, listener);
  12265. } else if (isObject(list)) {
  12266. for (i = length; i-- > 0;) {
  12267. if (list[i] === listener ||
  12268. (list[i].listener && list[i].listener === listener)) {
  12269. position = i;
  12270. break;
  12271. }
  12272. }
  12273. if (position < 0)
  12274. return this;
  12275. if (list.length === 1) {
  12276. list.length = 0;
  12277. delete this._events[type];
  12278. } else {
  12279. list.splice(position, 1);
  12280. }
  12281. if (this._events.removeListener)
  12282. this.emit('removeListener', type, listener);
  12283. }
  12284. return this;
  12285. };
  12286. EventEmitter.prototype.removeAllListeners = function(type) {
  12287. var key, listeners;
  12288. if (!this._events)
  12289. return this;
  12290. // not listening for removeListener, no need to emit
  12291. if (!this._events.removeListener) {
  12292. if (arguments.length === 0)
  12293. this._events = {};
  12294. else if (this._events[type])
  12295. delete this._events[type];
  12296. return this;
  12297. }
  12298. // emit removeListener for all listeners on all events
  12299. if (arguments.length === 0) {
  12300. for (key in this._events) {
  12301. if (key === 'removeListener') continue;
  12302. this.removeAllListeners(key);
  12303. }
  12304. this.removeAllListeners('removeListener');
  12305. this._events = {};
  12306. return this;
  12307. }
  12308. listeners = this._events[type];
  12309. if (isFunction(listeners)) {
  12310. this.removeListener(type, listeners);
  12311. } else {
  12312. // LIFO order
  12313. while (listeners.length)
  12314. this.removeListener(type, listeners[listeners.length - 1]);
  12315. }
  12316. delete this._events[type];
  12317. return this;
  12318. };
  12319. EventEmitter.prototype.listeners = function(type) {
  12320. var ret;
  12321. if (!this._events || !this._events[type])
  12322. ret = [];
  12323. else if (isFunction(this._events[type]))
  12324. ret = [this._events[type]];
  12325. else
  12326. ret = this._events[type].slice();
  12327. return ret;
  12328. };
  12329. EventEmitter.listenerCount = function(emitter, type) {
  12330. var ret;
  12331. if (!emitter._events || !emitter._events[type])
  12332. ret = 0;
  12333. else if (isFunction(emitter._events[type]))
  12334. ret = 1;
  12335. else
  12336. ret = emitter._events[type].length;
  12337. return ret;
  12338. };
  12339. function isFunction(arg) {
  12340. return typeof arg === 'function';
  12341. }
  12342. function isNumber(arg) {
  12343. return typeof arg === 'number';
  12344. }
  12345. function isObject(arg) {
  12346. return typeof arg === 'object' && arg !== null;
  12347. }
  12348. function isUndefined(arg) {
  12349. return arg === void 0;
  12350. }
  12351. },{}],45:[function(require,module,exports){
  12352. // shim for using process in browser
  12353. var process = module.exports = {};
  12354. var queue = [];
  12355. var draining = false;
  12356. var currentQueue;
  12357. var queueIndex = -1;
  12358. function cleanUpNextTick() {
  12359. draining = false;
  12360. if (currentQueue.length) {
  12361. queue = currentQueue.concat(queue);
  12362. } else {
  12363. queueIndex = -1;
  12364. }
  12365. if (queue.length) {
  12366. drainQueue();
  12367. }
  12368. }
  12369. function drainQueue() {
  12370. if (draining) {
  12371. return;
  12372. }
  12373. var timeout = setTimeout(cleanUpNextTick);
  12374. draining = true;
  12375. var len = queue.length;
  12376. while(len) {
  12377. currentQueue = queue;
  12378. queue = [];
  12379. while (++queueIndex < len) {
  12380. if (currentQueue) {
  12381. currentQueue[queueIndex].run();
  12382. }
  12383. }
  12384. queueIndex = -1;
  12385. len = queue.length;
  12386. }
  12387. currentQueue = null;
  12388. draining = false;
  12389. clearTimeout(timeout);
  12390. }
  12391. process.nextTick = function (fun) {
  12392. var args = new Array(arguments.length - 1);
  12393. if (arguments.length > 1) {
  12394. for (var i = 1; i < arguments.length; i++) {
  12395. args[i - 1] = arguments[i];
  12396. }
  12397. }
  12398. queue.push(new Item(fun, args));
  12399. if (queue.length === 1 && !draining) {
  12400. setTimeout(drainQueue, 0);
  12401. }
  12402. };
  12403. // v8 likes predictible objects
  12404. function Item(fun, array) {
  12405. this.fun = fun;
  12406. this.array = array;
  12407. }
  12408. Item.prototype.run = function () {
  12409. this.fun.apply(null, this.array);
  12410. };
  12411. process.title = 'browser';
  12412. process.browser = true;
  12413. process.env = {};
  12414. process.argv = [];
  12415. process.version = ''; // empty string to avoid regexp issues
  12416. process.versions = {};
  12417. function noop() {}
  12418. process.on = noop;
  12419. process.addListener = noop;
  12420. process.once = noop;
  12421. process.off = noop;
  12422. process.removeListener = noop;
  12423. process.removeAllListeners = noop;
  12424. process.emit = noop;
  12425. process.binding = function (name) {
  12426. throw new Error('process.binding is not supported');
  12427. };
  12428. process.cwd = function () { return '/' };
  12429. process.chdir = function (dir) {
  12430. throw new Error('process.chdir is not supported');
  12431. };
  12432. process.umask = function() { return 0; };
  12433. },{}],46:[function(require,module,exports){
  12434. (function (process,global){
  12435. /*!
  12436. * @overview es6-promise - a tiny implementation of Promises/A+.
  12437. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  12438. * @license Licensed under MIT license
  12439. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  12440. * @version 3.0.2
  12441. */
  12442. (function() {
  12443. "use strict";
  12444. function lib$es6$promise$utils$$objectOrFunction(x) {
  12445. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  12446. }
  12447. function lib$es6$promise$utils$$isFunction(x) {
  12448. return typeof x === 'function';
  12449. }
  12450. function lib$es6$promise$utils$$isMaybeThenable(x) {
  12451. return typeof x === 'object' && x !== null;
  12452. }
  12453. var lib$es6$promise$utils$$_isArray;
  12454. if (!Array.isArray) {
  12455. lib$es6$promise$utils$$_isArray = function (x) {
  12456. return Object.prototype.toString.call(x) === '[object Array]';
  12457. };
  12458. } else {
  12459. lib$es6$promise$utils$$_isArray = Array.isArray;
  12460. }
  12461. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  12462. var lib$es6$promise$asap$$len = 0;
  12463. var lib$es6$promise$asap$$toString = {}.toString;
  12464. var lib$es6$promise$asap$$vertxNext;
  12465. var lib$es6$promise$asap$$customSchedulerFn;
  12466. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  12467. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  12468. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  12469. lib$es6$promise$asap$$len += 2;
  12470. if (lib$es6$promise$asap$$len === 2) {
  12471. // If len is 2, that means that we need to schedule an async flush.
  12472. // If additional callbacks are queued before the queue is flushed, they
  12473. // will be processed by this flush that we are scheduling.
  12474. if (lib$es6$promise$asap$$customSchedulerFn) {
  12475. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  12476. } else {
  12477. lib$es6$promise$asap$$scheduleFlush();
  12478. }
  12479. }
  12480. }
  12481. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  12482. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  12483. }
  12484. function lib$es6$promise$asap$$setAsap(asapFn) {
  12485. lib$es6$promise$asap$$asap = asapFn;
  12486. }
  12487. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  12488. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  12489. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  12490. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  12491. // test for web worker but not in IE10
  12492. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  12493. typeof importScripts !== 'undefined' &&
  12494. typeof MessageChannel !== 'undefined';
  12495. // node
  12496. function lib$es6$promise$asap$$useNextTick() {
  12497. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  12498. // see https://github.com/cujojs/when/issues/410 for details
  12499. return function() {
  12500. process.nextTick(lib$es6$promise$asap$$flush);
  12501. };
  12502. }
  12503. // vertx
  12504. function lib$es6$promise$asap$$useVertxTimer() {
  12505. return function() {
  12506. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  12507. };
  12508. }
  12509. function lib$es6$promise$asap$$useMutationObserver() {
  12510. var iterations = 0;
  12511. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  12512. var node = document.createTextNode('');
  12513. observer.observe(node, { characterData: true });
  12514. return function() {
  12515. node.data = (iterations = ++iterations % 2);
  12516. };
  12517. }
  12518. // web worker
  12519. function lib$es6$promise$asap$$useMessageChannel() {
  12520. var channel = new MessageChannel();
  12521. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  12522. return function () {
  12523. channel.port2.postMessage(0);
  12524. };
  12525. }
  12526. function lib$es6$promise$asap$$useSetTimeout() {
  12527. return function() {
  12528. setTimeout(lib$es6$promise$asap$$flush, 1);
  12529. };
  12530. }
  12531. var lib$es6$promise$asap$$queue = new Array(1000);
  12532. function lib$es6$promise$asap$$flush() {
  12533. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  12534. var callback = lib$es6$promise$asap$$queue[i];
  12535. var arg = lib$es6$promise$asap$$queue[i+1];
  12536. callback(arg);
  12537. lib$es6$promise$asap$$queue[i] = undefined;
  12538. lib$es6$promise$asap$$queue[i+1] = undefined;
  12539. }
  12540. lib$es6$promise$asap$$len = 0;
  12541. }
  12542. function lib$es6$promise$asap$$attemptVertx() {
  12543. try {
  12544. var r = require;
  12545. var vertx = r('vertx');
  12546. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  12547. return lib$es6$promise$asap$$useVertxTimer();
  12548. } catch(e) {
  12549. return lib$es6$promise$asap$$useSetTimeout();
  12550. }
  12551. }
  12552. var lib$es6$promise$asap$$scheduleFlush;
  12553. // Decide what async method to use to triggering processing of queued callbacks:
  12554. if (lib$es6$promise$asap$$isNode) {
  12555. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  12556. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  12557. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  12558. } else if (lib$es6$promise$asap$$isWorker) {
  12559. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  12560. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  12561. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  12562. } else {
  12563. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  12564. }
  12565. function lib$es6$promise$$internal$$noop() {}
  12566. var lib$es6$promise$$internal$$PENDING = void 0;
  12567. var lib$es6$promise$$internal$$FULFILLED = 1;
  12568. var lib$es6$promise$$internal$$REJECTED = 2;
  12569. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12570. function lib$es6$promise$$internal$$selfFulfillment() {
  12571. return new TypeError("You cannot resolve a promise with itself");
  12572. }
  12573. function lib$es6$promise$$internal$$cannotReturnOwn() {
  12574. return new TypeError('A promises callback cannot return that same promise.');
  12575. }
  12576. function lib$es6$promise$$internal$$getThen(promise) {
  12577. try {
  12578. return promise.then;
  12579. } catch(error) {
  12580. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  12581. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  12582. }
  12583. }
  12584. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  12585. try {
  12586. then.call(value, fulfillmentHandler, rejectionHandler);
  12587. } catch(e) {
  12588. return e;
  12589. }
  12590. }
  12591. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  12592. lib$es6$promise$asap$$asap(function(promise) {
  12593. var sealed = false;
  12594. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  12595. if (sealed) { return; }
  12596. sealed = true;
  12597. if (thenable !== value) {
  12598. lib$es6$promise$$internal$$resolve(promise, value);
  12599. } else {
  12600. lib$es6$promise$$internal$$fulfill(promise, value);
  12601. }
  12602. }, function(reason) {
  12603. if (sealed) { return; }
  12604. sealed = true;
  12605. lib$es6$promise$$internal$$reject(promise, reason);
  12606. }, 'Settle: ' + (promise._label || ' unknown promise'));
  12607. if (!sealed && error) {
  12608. sealed = true;
  12609. lib$es6$promise$$internal$$reject(promise, error);
  12610. }
  12611. }, promise);
  12612. }
  12613. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  12614. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  12615. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  12616. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  12617. lib$es6$promise$$internal$$reject(promise, thenable._result);
  12618. } else {
  12619. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  12620. lib$es6$promise$$internal$$resolve(promise, value);
  12621. }, function(reason) {
  12622. lib$es6$promise$$internal$$reject(promise, reason);
  12623. });
  12624. }
  12625. }
  12626. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12627. if (maybeThenable.constructor === promise.constructor) {
  12628. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12629. } else {
  12630. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12631. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12632. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12633. } else if (then === undefined) {
  12634. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12635. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12636. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12637. } else {
  12638. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12639. }
  12640. }
  12641. }
  12642. function lib$es6$promise$$internal$$resolve(promise, value) {
  12643. if (promise === value) {
  12644. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12645. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12646. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12647. } else {
  12648. lib$es6$promise$$internal$$fulfill(promise, value);
  12649. }
  12650. }
  12651. function lib$es6$promise$$internal$$publishRejection(promise) {
  12652. if (promise._onerror) {
  12653. promise._onerror(promise._result);
  12654. }
  12655. lib$es6$promise$$internal$$publish(promise);
  12656. }
  12657. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12658. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12659. promise._result = value;
  12660. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12661. if (promise._subscribers.length !== 0) {
  12662. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12663. }
  12664. }
  12665. function lib$es6$promise$$internal$$reject(promise, reason) {
  12666. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12667. promise._state = lib$es6$promise$$internal$$REJECTED;
  12668. promise._result = reason;
  12669. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12670. }
  12671. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12672. var subscribers = parent._subscribers;
  12673. var length = subscribers.length;
  12674. parent._onerror = null;
  12675. subscribers[length] = child;
  12676. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12677. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12678. if (length === 0 && parent._state) {
  12679. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12680. }
  12681. }
  12682. function lib$es6$promise$$internal$$publish(promise) {
  12683. var subscribers = promise._subscribers;
  12684. var settled = promise._state;
  12685. if (subscribers.length === 0) { return; }
  12686. var child, callback, detail = promise._result;
  12687. for (var i = 0; i < subscribers.length; i += 3) {
  12688. child = subscribers[i];
  12689. callback = subscribers[i + settled];
  12690. if (child) {
  12691. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12692. } else {
  12693. callback(detail);
  12694. }
  12695. }
  12696. promise._subscribers.length = 0;
  12697. }
  12698. function lib$es6$promise$$internal$$ErrorObject() {
  12699. this.error = null;
  12700. }
  12701. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12702. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12703. try {
  12704. return callback(detail);
  12705. } catch(e) {
  12706. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12707. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12708. }
  12709. }
  12710. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12711. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12712. value, error, succeeded, failed;
  12713. if (hasCallback) {
  12714. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12715. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12716. failed = true;
  12717. error = value.error;
  12718. value = null;
  12719. } else {
  12720. succeeded = true;
  12721. }
  12722. if (promise === value) {
  12723. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12724. return;
  12725. }
  12726. } else {
  12727. value = detail;
  12728. succeeded = true;
  12729. }
  12730. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12731. // noop
  12732. } else if (hasCallback && succeeded) {
  12733. lib$es6$promise$$internal$$resolve(promise, value);
  12734. } else if (failed) {
  12735. lib$es6$promise$$internal$$reject(promise, error);
  12736. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12737. lib$es6$promise$$internal$$fulfill(promise, value);
  12738. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12739. lib$es6$promise$$internal$$reject(promise, value);
  12740. }
  12741. }
  12742. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12743. try {
  12744. resolver(function resolvePromise(value){
  12745. lib$es6$promise$$internal$$resolve(promise, value);
  12746. }, function rejectPromise(reason) {
  12747. lib$es6$promise$$internal$$reject(promise, reason);
  12748. });
  12749. } catch(e) {
  12750. lib$es6$promise$$internal$$reject(promise, e);
  12751. }
  12752. }
  12753. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12754. var enumerator = this;
  12755. enumerator._instanceConstructor = Constructor;
  12756. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12757. if (enumerator._validateInput(input)) {
  12758. enumerator._input = input;
  12759. enumerator.length = input.length;
  12760. enumerator._remaining = input.length;
  12761. enumerator._init();
  12762. if (enumerator.length === 0) {
  12763. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12764. } else {
  12765. enumerator.length = enumerator.length || 0;
  12766. enumerator._enumerate();
  12767. if (enumerator._remaining === 0) {
  12768. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12769. }
  12770. }
  12771. } else {
  12772. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12773. }
  12774. }
  12775. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12776. return lib$es6$promise$utils$$isArray(input);
  12777. };
  12778. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12779. return new Error('Array Methods must be provided an Array');
  12780. };
  12781. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12782. this._result = new Array(this.length);
  12783. };
  12784. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12785. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12786. var enumerator = this;
  12787. var length = enumerator.length;
  12788. var promise = enumerator.promise;
  12789. var input = enumerator._input;
  12790. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12791. enumerator._eachEntry(input[i], i);
  12792. }
  12793. };
  12794. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12795. var enumerator = this;
  12796. var c = enumerator._instanceConstructor;
  12797. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12798. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12799. entry._onerror = null;
  12800. enumerator._settledAt(entry._state, i, entry._result);
  12801. } else {
  12802. enumerator._willSettleAt(c.resolve(entry), i);
  12803. }
  12804. } else {
  12805. enumerator._remaining--;
  12806. enumerator._result[i] = entry;
  12807. }
  12808. };
  12809. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12810. var enumerator = this;
  12811. var promise = enumerator.promise;
  12812. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12813. enumerator._remaining--;
  12814. if (state === lib$es6$promise$$internal$$REJECTED) {
  12815. lib$es6$promise$$internal$$reject(promise, value);
  12816. } else {
  12817. enumerator._result[i] = value;
  12818. }
  12819. }
  12820. if (enumerator._remaining === 0) {
  12821. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12822. }
  12823. };
  12824. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12825. var enumerator = this;
  12826. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12827. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12828. }, function(reason) {
  12829. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12830. });
  12831. };
  12832. function lib$es6$promise$promise$all$$all(entries) {
  12833. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12834. }
  12835. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12836. function lib$es6$promise$promise$race$$race(entries) {
  12837. /*jshint validthis:true */
  12838. var Constructor = this;
  12839. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12840. if (!lib$es6$promise$utils$$isArray(entries)) {
  12841. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12842. return promise;
  12843. }
  12844. var length = entries.length;
  12845. function onFulfillment(value) {
  12846. lib$es6$promise$$internal$$resolve(promise, value);
  12847. }
  12848. function onRejection(reason) {
  12849. lib$es6$promise$$internal$$reject(promise, reason);
  12850. }
  12851. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12852. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12853. }
  12854. return promise;
  12855. }
  12856. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12857. function lib$es6$promise$promise$resolve$$resolve(object) {
  12858. /*jshint validthis:true */
  12859. var Constructor = this;
  12860. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12861. return object;
  12862. }
  12863. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12864. lib$es6$promise$$internal$$resolve(promise, object);
  12865. return promise;
  12866. }
  12867. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12868. function lib$es6$promise$promise$reject$$reject(reason) {
  12869. /*jshint validthis:true */
  12870. var Constructor = this;
  12871. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12872. lib$es6$promise$$internal$$reject(promise, reason);
  12873. return promise;
  12874. }
  12875. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12876. var lib$es6$promise$promise$$counter = 0;
  12877. function lib$es6$promise$promise$$needsResolver() {
  12878. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12879. }
  12880. function lib$es6$promise$promise$$needsNew() {
  12881. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12882. }
  12883. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12884. /**
  12885. Promise objects represent the eventual result of an asynchronous operation. The
  12886. primary way of interacting with a promise is through its `then` method, which
  12887. registers callbacks to receive either a promise's eventual value or the reason
  12888. why the promise cannot be fulfilled.
  12889. Terminology
  12890. -----------
  12891. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12892. - `thenable` is an object or function that defines a `then` method.
  12893. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12894. - `exception` is a value that is thrown using the throw statement.
  12895. - `reason` is a value that indicates why a promise was rejected.
  12896. - `settled` the final resting state of a promise, fulfilled or rejected.
  12897. A promise can be in one of three states: pending, fulfilled, or rejected.
  12898. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12899. state. Promises that are rejected have a rejection reason and are in the
  12900. rejected state. A fulfillment value is never a thenable.
  12901. Promises can also be said to *resolve* a value. If this value is also a
  12902. promise, then the original promise's settled state will match the value's
  12903. settled state. So a promise that *resolves* a promise that rejects will
  12904. itself reject, and a promise that *resolves* a promise that fulfills will
  12905. itself fulfill.
  12906. Basic Usage:
  12907. ------------
  12908. ```js
  12909. var promise = new Promise(function(resolve, reject) {
  12910. // on success
  12911. resolve(value);
  12912. // on failure
  12913. reject(reason);
  12914. });
  12915. promise.then(function(value) {
  12916. // on fulfillment
  12917. }, function(reason) {
  12918. // on rejection
  12919. });
  12920. ```
  12921. Advanced Usage:
  12922. ---------------
  12923. Promises shine when abstracting away asynchronous interactions such as
  12924. `XMLHttpRequest`s.
  12925. ```js
  12926. function getJSON(url) {
  12927. return new Promise(function(resolve, reject){
  12928. var xhr = new XMLHttpRequest();
  12929. xhr.open('GET', url);
  12930. xhr.onreadystatechange = handler;
  12931. xhr.responseType = 'json';
  12932. xhr.setRequestHeader('Accept', 'application/json');
  12933. xhr.send();
  12934. function handler() {
  12935. if (this.readyState === this.DONE) {
  12936. if (this.status === 200) {
  12937. resolve(this.response);
  12938. } else {
  12939. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12940. }
  12941. }
  12942. };
  12943. });
  12944. }
  12945. getJSON('/posts.json').then(function(json) {
  12946. // on fulfillment
  12947. }, function(reason) {
  12948. // on rejection
  12949. });
  12950. ```
  12951. Unlike callbacks, promises are great composable primitives.
  12952. ```js
  12953. Promise.all([
  12954. getJSON('/posts'),
  12955. getJSON('/comments')
  12956. ]).then(function(values){
  12957. values[0] // => postsJSON
  12958. values[1] // => commentsJSON
  12959. return values;
  12960. });
  12961. ```
  12962. @class Promise
  12963. @param {function} resolver
  12964. Useful for tooling.
  12965. @constructor
  12966. */
  12967. function lib$es6$promise$promise$$Promise(resolver) {
  12968. this._id = lib$es6$promise$promise$$counter++;
  12969. this._state = undefined;
  12970. this._result = undefined;
  12971. this._subscribers = [];
  12972. if (lib$es6$promise$$internal$$noop !== resolver) {
  12973. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12974. lib$es6$promise$promise$$needsResolver();
  12975. }
  12976. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12977. lib$es6$promise$promise$$needsNew();
  12978. }
  12979. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12980. }
  12981. }
  12982. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12983. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12984. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12985. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12986. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12987. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12988. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12989. lib$es6$promise$promise$$Promise.prototype = {
  12990. constructor: lib$es6$promise$promise$$Promise,
  12991. /**
  12992. The primary way of interacting with a promise is through its `then` method,
  12993. which registers callbacks to receive either a promise's eventual value or the
  12994. reason why the promise cannot be fulfilled.
  12995. ```js
  12996. findUser().then(function(user){
  12997. // user is available
  12998. }, function(reason){
  12999. // user is unavailable, and you are given the reason why
  13000. });
  13001. ```
  13002. Chaining
  13003. --------
  13004. The return value of `then` is itself a promise. This second, 'downstream'
  13005. promise is resolved with the return value of the first promise's fulfillment
  13006. or rejection handler, or rejected if the handler throws an exception.
  13007. ```js
  13008. findUser().then(function (user) {
  13009. return user.name;
  13010. }, function (reason) {
  13011. return 'default name';
  13012. }).then(function (userName) {
  13013. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  13014. // will be `'default name'`
  13015. });
  13016. findUser().then(function (user) {
  13017. throw new Error('Found user, but still unhappy');
  13018. }, function (reason) {
  13019. throw new Error('`findUser` rejected and we're unhappy');
  13020. }).then(function (value) {
  13021. // never reached
  13022. }, function (reason) {
  13023. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  13024. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  13025. });
  13026. ```
  13027. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  13028. ```js
  13029. findUser().then(function (user) {
  13030. throw new PedagogicalException('Upstream error');
  13031. }).then(function (value) {
  13032. // never reached
  13033. }).then(function (value) {
  13034. // never reached
  13035. }, function (reason) {
  13036. // The `PedgagocialException` is propagated all the way down to here
  13037. });
  13038. ```
  13039. Assimilation
  13040. ------------
  13041. Sometimes the value you want to propagate to a downstream promise can only be
  13042. retrieved asynchronously. This can be achieved by returning a promise in the
  13043. fulfillment or rejection handler. The downstream promise will then be pending
  13044. until the returned promise is settled. This is called *assimilation*.
  13045. ```js
  13046. findUser().then(function (user) {
  13047. return findCommentsByAuthor(user);
  13048. }).then(function (comments) {
  13049. // The user's comments are now available
  13050. });
  13051. ```
  13052. If the assimliated promise rejects, then the downstream promise will also reject.
  13053. ```js
  13054. findUser().then(function (user) {
  13055. return findCommentsByAuthor(user);
  13056. }).then(function (comments) {
  13057. // If `findCommentsByAuthor` fulfills, we'll have the value here
  13058. }, function (reason) {
  13059. // If `findCommentsByAuthor` rejects, we'll have the reason here
  13060. });
  13061. ```
  13062. Simple Example
  13063. --------------
  13064. Synchronous Example
  13065. ```javascript
  13066. var result;
  13067. try {
  13068. result = findResult();
  13069. // success
  13070. } catch(reason) {
  13071. // failure
  13072. }
  13073. ```
  13074. Errback Example
  13075. ```js
  13076. findResult(function(result, err){
  13077. if (err) {
  13078. // failure
  13079. } else {
  13080. // success
  13081. }
  13082. });
  13083. ```
  13084. Promise Example;
  13085. ```javascript
  13086. findResult().then(function(result){
  13087. // success
  13088. }, function(reason){
  13089. // failure
  13090. });
  13091. ```
  13092. Advanced Example
  13093. --------------
  13094. Synchronous Example
  13095. ```javascript
  13096. var author, books;
  13097. try {
  13098. author = findAuthor();
  13099. books = findBooksByAuthor(author);
  13100. // success
  13101. } catch(reason) {
  13102. // failure
  13103. }
  13104. ```
  13105. Errback Example
  13106. ```js
  13107. function foundBooks(books) {
  13108. }
  13109. function failure(reason) {
  13110. }
  13111. findAuthor(function(author, err){
  13112. if (err) {
  13113. failure(err);
  13114. // failure
  13115. } else {
  13116. try {
  13117. findBoooksByAuthor(author, function(books, err) {
  13118. if (err) {
  13119. failure(err);
  13120. } else {
  13121. try {
  13122. foundBooks(books);
  13123. } catch(reason) {
  13124. failure(reason);
  13125. }
  13126. }
  13127. });
  13128. } catch(error) {
  13129. failure(err);
  13130. }
  13131. // success
  13132. }
  13133. });
  13134. ```
  13135. Promise Example;
  13136. ```javascript
  13137. findAuthor().
  13138. then(findBooksByAuthor).
  13139. then(function(books){
  13140. // found books
  13141. }).catch(function(reason){
  13142. // something went wrong
  13143. });
  13144. ```
  13145. @method then
  13146. @param {Function} onFulfilled
  13147. @param {Function} onRejected
  13148. Useful for tooling.
  13149. @return {Promise}
  13150. */
  13151. then: function(onFulfillment, onRejection) {
  13152. var parent = this;
  13153. var state = parent._state;
  13154. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  13155. return this;
  13156. }
  13157. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  13158. var result = parent._result;
  13159. if (state) {
  13160. var callback = arguments[state - 1];
  13161. lib$es6$promise$asap$$asap(function(){
  13162. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  13163. });
  13164. } else {
  13165. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  13166. }
  13167. return child;
  13168. },
  13169. /**
  13170. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  13171. as the catch block of a try/catch statement.
  13172. ```js
  13173. function findAuthor(){
  13174. throw new Error('couldn't find that author');
  13175. }
  13176. // synchronous
  13177. try {
  13178. findAuthor();
  13179. } catch(reason) {
  13180. // something went wrong
  13181. }
  13182. // async with promises
  13183. findAuthor().catch(function(reason){
  13184. // something went wrong
  13185. });
  13186. ```
  13187. @method catch
  13188. @param {Function} onRejection
  13189. Useful for tooling.
  13190. @return {Promise}
  13191. */
  13192. 'catch': function(onRejection) {
  13193. return this.then(null, onRejection);
  13194. }
  13195. };
  13196. function lib$es6$promise$polyfill$$polyfill() {
  13197. var local;
  13198. if (typeof global !== 'undefined') {
  13199. local = global;
  13200. } else if (typeof self !== 'undefined') {
  13201. local = self;
  13202. } else {
  13203. try {
  13204. local = Function('return this')();
  13205. } catch (e) {
  13206. throw new Error('polyfill failed because global object is unavailable in this environment');
  13207. }
  13208. }
  13209. var P = local.Promise;
  13210. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  13211. return;
  13212. }
  13213. local.Promise = lib$es6$promise$promise$$default;
  13214. }
  13215. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  13216. var lib$es6$promise$umd$$ES6Promise = {
  13217. 'Promise': lib$es6$promise$promise$$default,
  13218. 'polyfill': lib$es6$promise$polyfill$$default
  13219. };
  13220. /* global define:true module:true window: true */
  13221. if (typeof define === 'function' && define['amd']) {
  13222. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  13223. } else if (typeof module !== 'undefined' && module['exports']) {
  13224. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  13225. } else if (typeof this !== 'undefined') {
  13226. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  13227. }
  13228. lib$es6$promise$polyfill$$default();
  13229. }).call(this);
  13230. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13231. },{"_process":45}],47:[function(require,module,exports){
  13232. /* Copyright @ 2015 Atlassian Pty Ltd
  13233. *
  13234. * Licensed under the Apache License, Version 2.0 (the "License");
  13235. * you may not use this file except in compliance with the License.
  13236. * You may obtain a copy of the License at
  13237. *
  13238. * http://www.apache.org/licenses/LICENSE-2.0
  13239. *
  13240. * Unless required by applicable law or agreed to in writing, software
  13241. * distributed under the License is distributed on an "AS IS" BASIS,
  13242. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13243. * See the License for the specific language governing permissions and
  13244. * limitations under the License.
  13245. */
  13246. /**
  13247. * Ordered log levels.
  13248. */
  13249. var levels = {
  13250. "trace": 0,
  13251. "debug": 1,
  13252. "info": 2,
  13253. "log": 3,
  13254. "warn": 4,
  13255. "error": 5
  13256. };
  13257. /**
  13258. * Parses Error's object stack trace and extracts information about the last
  13259. * caller before the log method was called.
  13260. * @returns JS object with info about the caller - method name, file location,
  13261. * line and column.
  13262. */
  13263. function getCallerInfo() {
  13264. var callerInfo = {
  13265. methodName: "",
  13266. fileLocation: "",
  13267. line: null,
  13268. column: null
  13269. };
  13270. //gets the part of the stack without the logger wrappers
  13271. var error = new Error();
  13272. var stack = error.stack? error.stack.split("\n") : [];
  13273. if(!stack || stack.length < 1) {
  13274. return callerInfo;
  13275. }
  13276. var m = null;
  13277. if(stack[3]) {
  13278. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  13279. }
  13280. if(!m || m.length <= 4) {
  13281. //Firefox && Safari
  13282. if(stack[2].indexOf("log@") === 0){
  13283. //Safari
  13284. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  13285. } else {
  13286. //Firefox
  13287. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  13288. }
  13289. return callerInfo;
  13290. }
  13291. callerInfo.methodName = m[1];
  13292. callerInfo.fileLocation = m[2];
  13293. callerInfo.line = m[3];
  13294. callerInfo.column = m[4];
  13295. return callerInfo;
  13296. }
  13297. /**
  13298. * Logs messages using the transports and level from the logger.
  13299. * @param logger a logger instance.
  13300. * @param level the log level of the message. See the levels variable.
  13301. * @param arguments array with arguments that will be logged.
  13302. */
  13303. function log() {
  13304. var logger = arguments[0], level = arguments[1],
  13305. args = Array.prototype.slice.call(arguments, 2);
  13306. if(levels[level] <= logger.level) {
  13307. return;
  13308. }
  13309. var callerInfo = getCallerInfo();
  13310. for(var i = 0; i < logger.transports.length; i++) {
  13311. var t = logger.transports[i];
  13312. var l = t[level];
  13313. if(l && typeof(l) === "function") {
  13314. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  13315. .apply(t, args);
  13316. }
  13317. }
  13318. }
  13319. /**
  13320. *
  13321. * Constructs new logger object.
  13322. * @param level the logging level for the new logger
  13323. * @param id optional identifier for the logger instance.
  13324. * @param transports optional list of handlers(objects) for the logs.
  13325. * The handlers must support - log, warn, error, debug, info, trace.
  13326. * @param format optional (NOT implemented) string.
  13327. */
  13328. function Logger(level, id, transports, format) {
  13329. this.id = id;
  13330. this.format = format;
  13331. if(!this.transports) {
  13332. this.transports = [];
  13333. this.transports.push(Logger.consoleTransport);
  13334. }
  13335. this.level = levels[level];
  13336. var methods = Object.keys(levels);
  13337. for(var i = 0; i < methods.length; i++){
  13338. this[methods[i]] =
  13339. log.bind(null, this, methods[i]);
  13340. }
  13341. }
  13342. /**
  13343. * Sets the log level for the logger.
  13344. * @param level the new log level.
  13345. */
  13346. Logger.prototype.setLevel = function (level) {
  13347. this.level = levels[level];
  13348. };
  13349. module.exports = Logger;
  13350. /**
  13351. * The default transport - console
  13352. */
  13353. Logger.consoleTransport = console;
  13354. /**
  13355. * Enum for the supported log levels.
  13356. */
  13357. Logger.levels = {
  13358. TRACE: "trace",
  13359. DEBUG: "debug",
  13360. INFO: "info",
  13361. LOG: "log",
  13362. WARN: "warn",
  13363. ERROR: "error"
  13364. };
  13365. },{}],48:[function(require,module,exports){
  13366. /* Copyright @ 2015 Atlassian Pty Ltd
  13367. *
  13368. * Licensed under the Apache License, Version 2.0 (the "License");
  13369. * you may not use this file except in compliance with the License.
  13370. * You may obtain a copy of the License at
  13371. *
  13372. * http://www.apache.org/licenses/LICENSE-2.0
  13373. *
  13374. * Unless required by applicable law or agreed to in writing, software
  13375. * distributed under the License is distributed on an "AS IS" BASIS,
  13376. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13377. * See the License for the specific language governing permissions and
  13378. * limitations under the License.
  13379. */
  13380. var Logger = require("./Logger");
  13381. /**
  13382. * Map with the created loggers with ID.
  13383. */
  13384. var idLoggers = {};
  13385. /**
  13386. * Array with the loggers without id.
  13387. */
  13388. var loggers = [];
  13389. /**
  13390. * Log level for the lbrary.
  13391. */
  13392. var curLevel = Logger.levels.TRACE;
  13393. module.exports = {
  13394. /**
  13395. * Creates new logger.
  13396. * @arguments the same as Logger constructor
  13397. */
  13398. getLogger: function(id, transports, format) {
  13399. var logger = new Logger(curLevel, id, transports, format);
  13400. if(id) {
  13401. idLoggers[id] = idLoggers[id] || [];
  13402. idLoggers[id].push(logger);
  13403. } else {
  13404. loggers.push(logger);
  13405. }
  13406. return logger;
  13407. },
  13408. /**
  13409. * Changes the log level for the existing loggers by id.
  13410. * @param level the new log level.
  13411. * @param id if specified the level will be changed only for loggers with the
  13412. * same id. Otherwise the operation will affect all loggers that don't
  13413. * have id.
  13414. */
  13415. setLogLevelById: function(level, id) {
  13416. var l = id? (idLoggers[id] || []) : loggers;
  13417. for(var i = 0; i < l.length; i++) {
  13418. l[i].setLevel(level);
  13419. }
  13420. },
  13421. /**
  13422. * Changes the log level for all existing loggers.
  13423. * @param level the new log level.
  13424. */
  13425. setLogLevel: function (level) {
  13426. curLevel = level;
  13427. var i = 0;
  13428. for(; i < loggers.length; i++) {
  13429. loggers[i].setLevel(level);
  13430. }
  13431. for(var id in idLoggers) {
  13432. var l = idLoggers[id] || [];
  13433. for(i = 0; i < l.length; i++) {
  13434. l[i].setLevel(level);
  13435. }
  13436. }
  13437. },
  13438. /**
  13439. * The supported log levels.
  13440. */
  13441. levels: Logger.levels
  13442. };
  13443. },{"./Logger":47}],49:[function(require,module,exports){
  13444. // Top level file is just a mixin of submodules & constants
  13445. 'use strict';
  13446. var assign = require('./lib/utils/common').assign;
  13447. var deflate = require('./lib/deflate');
  13448. var inflate = require('./lib/inflate');
  13449. var constants = require('./lib/zlib/constants');
  13450. var pako = {};
  13451. assign(pako, deflate, inflate, constants);
  13452. module.exports = pako;
  13453. },{"./lib/deflate":50,"./lib/inflate":51,"./lib/utils/common":52,"./lib/zlib/constants":55}],50:[function(require,module,exports){
  13454. 'use strict';
  13455. var zlib_deflate = require('./zlib/deflate.js');
  13456. var utils = require('./utils/common');
  13457. var strings = require('./utils/strings');
  13458. var msg = require('./zlib/messages');
  13459. var zstream = require('./zlib/zstream');
  13460. var toString = Object.prototype.toString;
  13461. /* Public constants ==========================================================*/
  13462. /* ===========================================================================*/
  13463. var Z_NO_FLUSH = 0;
  13464. var Z_FINISH = 4;
  13465. var Z_OK = 0;
  13466. var Z_STREAM_END = 1;
  13467. var Z_SYNC_FLUSH = 2;
  13468. var Z_DEFAULT_COMPRESSION = -1;
  13469. var Z_DEFAULT_STRATEGY = 0;
  13470. var Z_DEFLATED = 8;
  13471. /* ===========================================================================*/
  13472. /**
  13473. * class Deflate
  13474. *
  13475. * Generic JS-style wrapper for zlib calls. If you don't need
  13476. * streaming behaviour - use more simple functions: [[deflate]],
  13477. * [[deflateRaw]] and [[gzip]].
  13478. **/
  13479. /* internal
  13480. * Deflate.chunks -> Array
  13481. *
  13482. * Chunks of output data, if [[Deflate#onData]] not overriden.
  13483. **/
  13484. /**
  13485. * Deflate.result -> Uint8Array|Array
  13486. *
  13487. * Compressed result, generated by default [[Deflate#onData]]
  13488. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  13489. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  13490. * push a chunk with explicit flush (call [[Deflate#push]] with
  13491. * `Z_SYNC_FLUSH` param).
  13492. **/
  13493. /**
  13494. * Deflate.err -> Number
  13495. *
  13496. * Error code after deflate finished. 0 (Z_OK) on success.
  13497. * You will not need it in real life, because deflate errors
  13498. * are possible only on wrong options or bad `onData` / `onEnd`
  13499. * custom handlers.
  13500. **/
  13501. /**
  13502. * Deflate.msg -> String
  13503. *
  13504. * Error message, if [[Deflate.err]] != 0
  13505. **/
  13506. /**
  13507. * new Deflate(options)
  13508. * - options (Object): zlib deflate options.
  13509. *
  13510. * Creates new deflator instance with specified params. Throws exception
  13511. * on bad params. Supported options:
  13512. *
  13513. * - `level`
  13514. * - `windowBits`
  13515. * - `memLevel`
  13516. * - `strategy`
  13517. *
  13518. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13519. * for more information on these.
  13520. *
  13521. * Additional options, for internal needs:
  13522. *
  13523. * - `chunkSize` - size of generated data chunks (16K by default)
  13524. * - `raw` (Boolean) - do raw deflate
  13525. * - `gzip` (Boolean) - create gzip wrapper
  13526. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13527. * (each char code [0..255])
  13528. * - `header` (Object) - custom header for gzip
  13529. * - `text` (Boolean) - true if compressed data believed to be text
  13530. * - `time` (Number) - modification time, unix timestamp
  13531. * - `os` (Number) - operation system code
  13532. * - `extra` (Array) - array of bytes with extra data (max 65536)
  13533. * - `name` (String) - file name (binary string)
  13534. * - `comment` (String) - comment (binary string)
  13535. * - `hcrc` (Boolean) - true if header crc should be added
  13536. *
  13537. * ##### Example:
  13538. *
  13539. * ```javascript
  13540. * var pako = require('pako')
  13541. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13542. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13543. *
  13544. * var deflate = new pako.Deflate({ level: 3});
  13545. *
  13546. * deflate.push(chunk1, false);
  13547. * deflate.push(chunk2, true); // true -> last chunk
  13548. *
  13549. * if (deflate.err) { throw new Error(deflate.err); }
  13550. *
  13551. * console.log(deflate.result);
  13552. * ```
  13553. **/
  13554. var Deflate = function(options) {
  13555. this.options = utils.assign({
  13556. level: Z_DEFAULT_COMPRESSION,
  13557. method: Z_DEFLATED,
  13558. chunkSize: 16384,
  13559. windowBits: 15,
  13560. memLevel: 8,
  13561. strategy: Z_DEFAULT_STRATEGY,
  13562. to: ''
  13563. }, options || {});
  13564. var opt = this.options;
  13565. if (opt.raw && (opt.windowBits > 0)) {
  13566. opt.windowBits = -opt.windowBits;
  13567. }
  13568. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  13569. opt.windowBits += 16;
  13570. }
  13571. this.err = 0; // error code, if happens (0 = Z_OK)
  13572. this.msg = ''; // error message
  13573. this.ended = false; // used to avoid multiple onEnd() calls
  13574. this.chunks = []; // chunks of compressed data
  13575. this.strm = new zstream();
  13576. this.strm.avail_out = 0;
  13577. var status = zlib_deflate.deflateInit2(
  13578. this.strm,
  13579. opt.level,
  13580. opt.method,
  13581. opt.windowBits,
  13582. opt.memLevel,
  13583. opt.strategy
  13584. );
  13585. if (status !== Z_OK) {
  13586. throw new Error(msg[status]);
  13587. }
  13588. if (opt.header) {
  13589. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  13590. }
  13591. };
  13592. /**
  13593. * Deflate#push(data[, mode]) -> Boolean
  13594. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  13595. * converted to utf8 byte sequence.
  13596. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13597. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13598. *
  13599. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  13600. * new compressed chunks. Returns `true` on success. The last data block must have
  13601. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13602. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13603. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  13604. *
  13605. * On fail call [[Deflate#onEnd]] with error code and return false.
  13606. *
  13607. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13608. * array format is detected automatically). Also, don't skip last param and always
  13609. * use the same type in your code (boolean or number). That will improve JS speed.
  13610. *
  13611. * For regular `Array`-s make sure all elements are [0..255].
  13612. *
  13613. * ##### Example
  13614. *
  13615. * ```javascript
  13616. * push(chunk, false); // push one of data chunks
  13617. * ...
  13618. * push(chunk, true); // push last chunk
  13619. * ```
  13620. **/
  13621. Deflate.prototype.push = function(data, mode) {
  13622. var strm = this.strm;
  13623. var chunkSize = this.options.chunkSize;
  13624. var status, _mode;
  13625. if (this.ended) { return false; }
  13626. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13627. // Convert data if needed
  13628. if (typeof data === 'string') {
  13629. // If we need to compress text, change encoding to utf8.
  13630. strm.input = strings.string2buf(data);
  13631. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13632. strm.input = new Uint8Array(data);
  13633. } else {
  13634. strm.input = data;
  13635. }
  13636. strm.next_in = 0;
  13637. strm.avail_in = strm.input.length;
  13638. do {
  13639. if (strm.avail_out === 0) {
  13640. strm.output = new utils.Buf8(chunkSize);
  13641. strm.next_out = 0;
  13642. strm.avail_out = chunkSize;
  13643. }
  13644. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13645. if (status !== Z_STREAM_END && status !== Z_OK) {
  13646. this.onEnd(status);
  13647. this.ended = true;
  13648. return false;
  13649. }
  13650. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13651. if (this.options.to === 'string') {
  13652. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13653. } else {
  13654. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13655. }
  13656. }
  13657. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13658. // Finalize on the last chunk.
  13659. if (_mode === Z_FINISH) {
  13660. status = zlib_deflate.deflateEnd(this.strm);
  13661. this.onEnd(status);
  13662. this.ended = true;
  13663. return status === Z_OK;
  13664. }
  13665. // callback interim results if Z_SYNC_FLUSH.
  13666. if (_mode === Z_SYNC_FLUSH) {
  13667. this.onEnd(Z_OK);
  13668. strm.avail_out = 0;
  13669. return true;
  13670. }
  13671. return true;
  13672. };
  13673. /**
  13674. * Deflate#onData(chunk) -> Void
  13675. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13676. * on js engine support. When string output requested, each chunk
  13677. * will be string.
  13678. *
  13679. * By default, stores data blocks in `chunks[]` property and glue
  13680. * those in `onEnd`. Override this handler, if you need another behaviour.
  13681. **/
  13682. Deflate.prototype.onData = function(chunk) {
  13683. this.chunks.push(chunk);
  13684. };
  13685. /**
  13686. * Deflate#onEnd(status) -> Void
  13687. * - status (Number): deflate status. 0 (Z_OK) on success,
  13688. * other if not.
  13689. *
  13690. * Called once after you tell deflate that the input stream is
  13691. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13692. * or if an error happened. By default - join collected chunks,
  13693. * free memory and fill `results` / `err` properties.
  13694. **/
  13695. Deflate.prototype.onEnd = function(status) {
  13696. // On success - join
  13697. if (status === Z_OK) {
  13698. if (this.options.to === 'string') {
  13699. this.result = this.chunks.join('');
  13700. } else {
  13701. this.result = utils.flattenChunks(this.chunks);
  13702. }
  13703. }
  13704. this.chunks = [];
  13705. this.err = status;
  13706. this.msg = this.strm.msg;
  13707. };
  13708. /**
  13709. * deflate(data[, options]) -> Uint8Array|Array|String
  13710. * - data (Uint8Array|Array|String): input data to compress.
  13711. * - options (Object): zlib deflate options.
  13712. *
  13713. * Compress `data` with deflate alrorythm and `options`.
  13714. *
  13715. * Supported options are:
  13716. *
  13717. * - level
  13718. * - windowBits
  13719. * - memLevel
  13720. * - strategy
  13721. *
  13722. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13723. * for more information on these.
  13724. *
  13725. * Sugar (options):
  13726. *
  13727. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13728. * negative windowBits implicitly.
  13729. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13730. * (each char code [0..255])
  13731. *
  13732. * ##### Example:
  13733. *
  13734. * ```javascript
  13735. * var pako = require('pako')
  13736. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13737. *
  13738. * console.log(pako.deflate(data));
  13739. * ```
  13740. **/
  13741. function deflate(input, options) {
  13742. var deflator = new Deflate(options);
  13743. deflator.push(input, true);
  13744. // That will never happens, if you don't cheat with options :)
  13745. if (deflator.err) { throw deflator.msg; }
  13746. return deflator.result;
  13747. }
  13748. /**
  13749. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13750. * - data (Uint8Array|Array|String): input data to compress.
  13751. * - options (Object): zlib deflate options.
  13752. *
  13753. * The same as [[deflate]], but creates raw data, without wrapper
  13754. * (header and adler32 crc).
  13755. **/
  13756. function deflateRaw(input, options) {
  13757. options = options || {};
  13758. options.raw = true;
  13759. return deflate(input, options);
  13760. }
  13761. /**
  13762. * gzip(data[, options]) -> Uint8Array|Array|String
  13763. * - data (Uint8Array|Array|String): input data to compress.
  13764. * - options (Object): zlib deflate options.
  13765. *
  13766. * The same as [[deflate]], but create gzip wrapper instead of
  13767. * deflate one.
  13768. **/
  13769. function gzip(input, options) {
  13770. options = options || {};
  13771. options.gzip = true;
  13772. return deflate(input, options);
  13773. }
  13774. exports.Deflate = Deflate;
  13775. exports.deflate = deflate;
  13776. exports.deflateRaw = deflateRaw;
  13777. exports.gzip = gzip;
  13778. },{"./utils/common":52,"./utils/strings":53,"./zlib/deflate.js":57,"./zlib/messages":62,"./zlib/zstream":64}],51:[function(require,module,exports){
  13779. 'use strict';
  13780. var zlib_inflate = require('./zlib/inflate.js');
  13781. var utils = require('./utils/common');
  13782. var strings = require('./utils/strings');
  13783. var c = require('./zlib/constants');
  13784. var msg = require('./zlib/messages');
  13785. var zstream = require('./zlib/zstream');
  13786. var gzheader = require('./zlib/gzheader');
  13787. var toString = Object.prototype.toString;
  13788. /**
  13789. * class Inflate
  13790. *
  13791. * Generic JS-style wrapper for zlib calls. If you don't need
  13792. * streaming behaviour - use more simple functions: [[inflate]]
  13793. * and [[inflateRaw]].
  13794. **/
  13795. /* internal
  13796. * inflate.chunks -> Array
  13797. *
  13798. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13799. **/
  13800. /**
  13801. * Inflate.result -> Uint8Array|Array|String
  13802. *
  13803. * Uncompressed result, generated by default [[Inflate#onData]]
  13804. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13805. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13806. * push a chunk with explicit flush (call [[Inflate#push]] with
  13807. * `Z_SYNC_FLUSH` param).
  13808. **/
  13809. /**
  13810. * Inflate.err -> Number
  13811. *
  13812. * Error code after inflate finished. 0 (Z_OK) on success.
  13813. * Should be checked if broken data possible.
  13814. **/
  13815. /**
  13816. * Inflate.msg -> String
  13817. *
  13818. * Error message, if [[Inflate.err]] != 0
  13819. **/
  13820. /**
  13821. * new Inflate(options)
  13822. * - options (Object): zlib inflate options.
  13823. *
  13824. * Creates new inflator instance with specified params. Throws exception
  13825. * on bad params. Supported options:
  13826. *
  13827. * - `windowBits`
  13828. *
  13829. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13830. * for more information on these.
  13831. *
  13832. * Additional options, for internal needs:
  13833. *
  13834. * - `chunkSize` - size of generated data chunks (16K by default)
  13835. * - `raw` (Boolean) - do raw inflate
  13836. * - `to` (String) - if equal to 'string', then result will be converted
  13837. * from utf8 to utf16 (javascript) string. When string output requested,
  13838. * chunk length can differ from `chunkSize`, depending on content.
  13839. *
  13840. * By default, when no options set, autodetect deflate/gzip data format via
  13841. * wrapper header.
  13842. *
  13843. * ##### Example:
  13844. *
  13845. * ```javascript
  13846. * var pako = require('pako')
  13847. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13848. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13849. *
  13850. * var inflate = new pako.Inflate({ level: 3});
  13851. *
  13852. * inflate.push(chunk1, false);
  13853. * inflate.push(chunk2, true); // true -> last chunk
  13854. *
  13855. * if (inflate.err) { throw new Error(inflate.err); }
  13856. *
  13857. * console.log(inflate.result);
  13858. * ```
  13859. **/
  13860. var Inflate = function(options) {
  13861. this.options = utils.assign({
  13862. chunkSize: 16384,
  13863. windowBits: 0,
  13864. to: ''
  13865. }, options || {});
  13866. var opt = this.options;
  13867. // Force window size for `raw` data, if not set directly,
  13868. // because we have no header for autodetect.
  13869. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13870. opt.windowBits = -opt.windowBits;
  13871. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13872. }
  13873. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13874. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13875. !(options && options.windowBits)) {
  13876. opt.windowBits += 32;
  13877. }
  13878. // Gzip header has no info about windows size, we can do autodetect only
  13879. // for deflate. So, if window size not set, force it to max when gzip possible
  13880. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13881. // bit 3 (16) -> gzipped data
  13882. // bit 4 (32) -> autodetect gzip/deflate
  13883. if ((opt.windowBits & 15) === 0) {
  13884. opt.windowBits |= 15;
  13885. }
  13886. }
  13887. this.err = 0; // error code, if happens (0 = Z_OK)
  13888. this.msg = ''; // error message
  13889. this.ended = false; // used to avoid multiple onEnd() calls
  13890. this.chunks = []; // chunks of compressed data
  13891. this.strm = new zstream();
  13892. this.strm.avail_out = 0;
  13893. var status = zlib_inflate.inflateInit2(
  13894. this.strm,
  13895. opt.windowBits
  13896. );
  13897. if (status !== c.Z_OK) {
  13898. throw new Error(msg[status]);
  13899. }
  13900. this.header = new gzheader();
  13901. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13902. };
  13903. /**
  13904. * Inflate#push(data[, mode]) -> Boolean
  13905. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13906. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13907. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13908. *
  13909. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13910. * new output chunks. Returns `true` on success. The last data block must have
  13911. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13912. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13913. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13914. *
  13915. * On fail call [[Inflate#onEnd]] with error code and return false.
  13916. *
  13917. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13918. * format is detected automatically). Also, don't skip last param and always
  13919. * use the same type in your code (boolean or number). That will improve JS speed.
  13920. *
  13921. * For regular `Array`-s make sure all elements are [0..255].
  13922. *
  13923. * ##### Example
  13924. *
  13925. * ```javascript
  13926. * push(chunk, false); // push one of data chunks
  13927. * ...
  13928. * push(chunk, true); // push last chunk
  13929. * ```
  13930. **/
  13931. Inflate.prototype.push = function(data, mode) {
  13932. var strm = this.strm;
  13933. var chunkSize = this.options.chunkSize;
  13934. var status, _mode;
  13935. var next_out_utf8, tail, utf8str;
  13936. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13937. // when we check that all output data was flushed.
  13938. var allowBufError = false;
  13939. if (this.ended) { return false; }
  13940. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13941. // Convert data if needed
  13942. if (typeof data === 'string') {
  13943. // Only binary strings can be decompressed on practice
  13944. strm.input = strings.binstring2buf(data);
  13945. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13946. strm.input = new Uint8Array(data);
  13947. } else {
  13948. strm.input = data;
  13949. }
  13950. strm.next_in = 0;
  13951. strm.avail_in = strm.input.length;
  13952. do {
  13953. if (strm.avail_out === 0) {
  13954. strm.output = new utils.Buf8(chunkSize);
  13955. strm.next_out = 0;
  13956. strm.avail_out = chunkSize;
  13957. }
  13958. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13959. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13960. status = c.Z_OK;
  13961. allowBufError = false;
  13962. }
  13963. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13964. this.onEnd(status);
  13965. this.ended = true;
  13966. return false;
  13967. }
  13968. if (strm.next_out) {
  13969. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13970. if (this.options.to === 'string') {
  13971. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13972. tail = strm.next_out - next_out_utf8;
  13973. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13974. // move tail
  13975. strm.next_out = tail;
  13976. strm.avail_out = chunkSize - tail;
  13977. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13978. this.onData(utf8str);
  13979. } else {
  13980. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13981. }
  13982. }
  13983. }
  13984. // When no more input data, we should check that internal inflate buffers
  13985. // are flushed. The only way to do it when avail_out = 0 - run one more
  13986. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13987. // Here we set flag to process this error properly.
  13988. //
  13989. // NOTE. Deflate does not return error in this case and does not needs such
  13990. // logic.
  13991. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13992. allowBufError = true;
  13993. }
  13994. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13995. if (status === c.Z_STREAM_END) {
  13996. _mode = c.Z_FINISH;
  13997. }
  13998. // Finalize on the last chunk.
  13999. if (_mode === c.Z_FINISH) {
  14000. status = zlib_inflate.inflateEnd(this.strm);
  14001. this.onEnd(status);
  14002. this.ended = true;
  14003. return status === c.Z_OK;
  14004. }
  14005. // callback interim results if Z_SYNC_FLUSH.
  14006. if (_mode === c.Z_SYNC_FLUSH) {
  14007. this.onEnd(c.Z_OK);
  14008. strm.avail_out = 0;
  14009. return true;
  14010. }
  14011. return true;
  14012. };
  14013. /**
  14014. * Inflate#onData(chunk) -> Void
  14015. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14016. * on js engine support. When string output requested, each chunk
  14017. * will be string.
  14018. *
  14019. * By default, stores data blocks in `chunks[]` property and glue
  14020. * those in `onEnd`. Override this handler, if you need another behaviour.
  14021. **/
  14022. Inflate.prototype.onData = function(chunk) {
  14023. this.chunks.push(chunk);
  14024. };
  14025. /**
  14026. * Inflate#onEnd(status) -> Void
  14027. * - status (Number): inflate status. 0 (Z_OK) on success,
  14028. * other if not.
  14029. *
  14030. * Called either after you tell inflate that the input stream is
  14031. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14032. * or if an error happened. By default - join collected chunks,
  14033. * free memory and fill `results` / `err` properties.
  14034. **/
  14035. Inflate.prototype.onEnd = function(status) {
  14036. // On success - join
  14037. if (status === c.Z_OK) {
  14038. if (this.options.to === 'string') {
  14039. // Glue & convert here, until we teach pako to send
  14040. // utf8 alligned strings to onData
  14041. this.result = this.chunks.join('');
  14042. } else {
  14043. this.result = utils.flattenChunks(this.chunks);
  14044. }
  14045. }
  14046. this.chunks = [];
  14047. this.err = status;
  14048. this.msg = this.strm.msg;
  14049. };
  14050. /**
  14051. * inflate(data[, options]) -> Uint8Array|Array|String
  14052. * - data (Uint8Array|Array|String): input data to decompress.
  14053. * - options (Object): zlib inflate options.
  14054. *
  14055. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  14056. * format via wrapper header by default. That's why we don't provide
  14057. * separate `ungzip` method.
  14058. *
  14059. * Supported options are:
  14060. *
  14061. * - windowBits
  14062. *
  14063. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14064. * for more information.
  14065. *
  14066. * Sugar (options):
  14067. *
  14068. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14069. * negative windowBits implicitly.
  14070. * - `to` (String) - if equal to 'string', then result will be converted
  14071. * from utf8 to utf16 (javascript) string. When string output requested,
  14072. * chunk length can differ from `chunkSize`, depending on content.
  14073. *
  14074. *
  14075. * ##### Example:
  14076. *
  14077. * ```javascript
  14078. * var pako = require('pako')
  14079. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  14080. * , output;
  14081. *
  14082. * try {
  14083. * output = pako.inflate(input);
  14084. * } catch (err)
  14085. * console.log(err);
  14086. * }
  14087. * ```
  14088. **/
  14089. function inflate(input, options) {
  14090. var inflator = new Inflate(options);
  14091. inflator.push(input, true);
  14092. // That will never happens, if you don't cheat with options :)
  14093. if (inflator.err) { throw inflator.msg; }
  14094. return inflator.result;
  14095. }
  14096. /**
  14097. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  14098. * - data (Uint8Array|Array|String): input data to decompress.
  14099. * - options (Object): zlib inflate options.
  14100. *
  14101. * The same as [[inflate]], but creates raw data, without wrapper
  14102. * (header and adler32 crc).
  14103. **/
  14104. function inflateRaw(input, options) {
  14105. options = options || {};
  14106. options.raw = true;
  14107. return inflate(input, options);
  14108. }
  14109. /**
  14110. * ungzip(data[, options]) -> Uint8Array|Array|String
  14111. * - data (Uint8Array|Array|String): input data to decompress.
  14112. * - options (Object): zlib inflate options.
  14113. *
  14114. * Just shortcut to [[inflate]], because it autodetects format
  14115. * by header.content. Done for convenience.
  14116. **/
  14117. exports.Inflate = Inflate;
  14118. exports.inflate = inflate;
  14119. exports.inflateRaw = inflateRaw;
  14120. exports.ungzip = inflate;
  14121. },{"./utils/common":52,"./utils/strings":53,"./zlib/constants":55,"./zlib/gzheader":58,"./zlib/inflate.js":60,"./zlib/messages":62,"./zlib/zstream":64}],52:[function(require,module,exports){
  14122. 'use strict';
  14123. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  14124. (typeof Uint16Array !== 'undefined') &&
  14125. (typeof Int32Array !== 'undefined');
  14126. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  14127. var sources = Array.prototype.slice.call(arguments, 1);
  14128. while (sources.length) {
  14129. var source = sources.shift();
  14130. if (!source) { continue; }
  14131. if (typeof source !== 'object') {
  14132. throw new TypeError(source + 'must be non-object');
  14133. }
  14134. for (var p in source) {
  14135. if (source.hasOwnProperty(p)) {
  14136. obj[p] = source[p];
  14137. }
  14138. }
  14139. }
  14140. return obj;
  14141. };
  14142. // reduce buffer size, avoiding mem copy
  14143. exports.shrinkBuf = function (buf, size) {
  14144. if (buf.length === size) { return buf; }
  14145. if (buf.subarray) { return buf.subarray(0, size); }
  14146. buf.length = size;
  14147. return buf;
  14148. };
  14149. var fnTyped = {
  14150. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14151. if (src.subarray && dest.subarray) {
  14152. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  14153. return;
  14154. }
  14155. // Fallback to ordinary array
  14156. for (var i=0; i<len; i++) {
  14157. dest[dest_offs + i] = src[src_offs + i];
  14158. }
  14159. },
  14160. // Join array of chunks to single array.
  14161. flattenChunks: function(chunks) {
  14162. var i, l, len, pos, chunk, result;
  14163. // calculate data length
  14164. len = 0;
  14165. for (i=0, l=chunks.length; i<l; i++) {
  14166. len += chunks[i].length;
  14167. }
  14168. // join chunks
  14169. result = new Uint8Array(len);
  14170. pos = 0;
  14171. for (i=0, l=chunks.length; i<l; i++) {
  14172. chunk = chunks[i];
  14173. result.set(chunk, pos);
  14174. pos += chunk.length;
  14175. }
  14176. return result;
  14177. }
  14178. };
  14179. var fnUntyped = {
  14180. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14181. for (var i=0; i<len; i++) {
  14182. dest[dest_offs + i] = src[src_offs + i];
  14183. }
  14184. },
  14185. // Join array of chunks to single array.
  14186. flattenChunks: function(chunks) {
  14187. return [].concat.apply([], chunks);
  14188. }
  14189. };
  14190. // Enable/Disable typed arrays use, for testing
  14191. //
  14192. exports.setTyped = function (on) {
  14193. if (on) {
  14194. exports.Buf8 = Uint8Array;
  14195. exports.Buf16 = Uint16Array;
  14196. exports.Buf32 = Int32Array;
  14197. exports.assign(exports, fnTyped);
  14198. } else {
  14199. exports.Buf8 = Array;
  14200. exports.Buf16 = Array;
  14201. exports.Buf32 = Array;
  14202. exports.assign(exports, fnUntyped);
  14203. }
  14204. };
  14205. exports.setTyped(TYPED_OK);
  14206. },{}],53:[function(require,module,exports){
  14207. // String encode/decode helpers
  14208. 'use strict';
  14209. var utils = require('./common');
  14210. // Quick check if we can use fast array to bin string conversion
  14211. //
  14212. // - apply(Array) can fail on Android 2.2
  14213. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  14214. //
  14215. var STR_APPLY_OK = true;
  14216. var STR_APPLY_UIA_OK = true;
  14217. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  14218. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  14219. // Table with utf8 lengths (calculated by first byte of sequence)
  14220. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  14221. // because max possible codepoint is 0x10ffff
  14222. var _utf8len = new utils.Buf8(256);
  14223. for (var q=0; q<256; q++) {
  14224. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  14225. }
  14226. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  14227. // convert string to array (typed, when possible)
  14228. exports.string2buf = function (str) {
  14229. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  14230. // count binary size
  14231. for (m_pos = 0; m_pos < str_len; m_pos++) {
  14232. c = str.charCodeAt(m_pos);
  14233. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14234. c2 = str.charCodeAt(m_pos+1);
  14235. if ((c2 & 0xfc00) === 0xdc00) {
  14236. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14237. m_pos++;
  14238. }
  14239. }
  14240. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  14241. }
  14242. // allocate buffer
  14243. buf = new utils.Buf8(buf_len);
  14244. // convert
  14245. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  14246. c = str.charCodeAt(m_pos);
  14247. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14248. c2 = str.charCodeAt(m_pos+1);
  14249. if ((c2 & 0xfc00) === 0xdc00) {
  14250. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14251. m_pos++;
  14252. }
  14253. }
  14254. if (c < 0x80) {
  14255. /* one byte */
  14256. buf[i++] = c;
  14257. } else if (c < 0x800) {
  14258. /* two bytes */
  14259. buf[i++] = 0xC0 | (c >>> 6);
  14260. buf[i++] = 0x80 | (c & 0x3f);
  14261. } else if (c < 0x10000) {
  14262. /* three bytes */
  14263. buf[i++] = 0xE0 | (c >>> 12);
  14264. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14265. buf[i++] = 0x80 | (c & 0x3f);
  14266. } else {
  14267. /* four bytes */
  14268. buf[i++] = 0xf0 | (c >>> 18);
  14269. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  14270. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14271. buf[i++] = 0x80 | (c & 0x3f);
  14272. }
  14273. }
  14274. return buf;
  14275. };
  14276. // Helper (used in 2 places)
  14277. function buf2binstring(buf, len) {
  14278. // use fallback for big arrays to avoid stack overflow
  14279. if (len < 65537) {
  14280. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  14281. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  14282. }
  14283. }
  14284. var result = '';
  14285. for (var i=0; i < len; i++) {
  14286. result += String.fromCharCode(buf[i]);
  14287. }
  14288. return result;
  14289. }
  14290. // Convert byte array to binary string
  14291. exports.buf2binstring = function(buf) {
  14292. return buf2binstring(buf, buf.length);
  14293. };
  14294. // Convert binary string (typed, when possible)
  14295. exports.binstring2buf = function(str) {
  14296. var buf = new utils.Buf8(str.length);
  14297. for (var i=0, len=buf.length; i < len; i++) {
  14298. buf[i] = str.charCodeAt(i);
  14299. }
  14300. return buf;
  14301. };
  14302. // convert array to string
  14303. exports.buf2string = function (buf, max) {
  14304. var i, out, c, c_len;
  14305. var len = max || buf.length;
  14306. // Reserve max possible length (2 words per char)
  14307. // NB: by unknown reasons, Array is significantly faster for
  14308. // String.fromCharCode.apply than Uint16Array.
  14309. var utf16buf = new Array(len*2);
  14310. for (out=0, i=0; i<len;) {
  14311. c = buf[i++];
  14312. // quick process ascii
  14313. if (c < 0x80) { utf16buf[out++] = c; continue; }
  14314. c_len = _utf8len[c];
  14315. // skip 5 & 6 byte codes
  14316. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  14317. // apply mask on first byte
  14318. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  14319. // join the rest
  14320. while (c_len > 1 && i < len) {
  14321. c = (c << 6) | (buf[i++] & 0x3f);
  14322. c_len--;
  14323. }
  14324. // terminated by end of string?
  14325. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  14326. if (c < 0x10000) {
  14327. utf16buf[out++] = c;
  14328. } else {
  14329. c -= 0x10000;
  14330. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  14331. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  14332. }
  14333. }
  14334. return buf2binstring(utf16buf, out);
  14335. };
  14336. // Calculate max possible position in utf8 buffer,
  14337. // that will not break sequence. If that's not possible
  14338. // - (very small limits) return max size as is.
  14339. //
  14340. // buf[] - utf8 bytes array
  14341. // max - length limit (mandatory);
  14342. exports.utf8border = function(buf, max) {
  14343. var pos;
  14344. max = max || buf.length;
  14345. if (max > buf.length) { max = buf.length; }
  14346. // go back from last position, until start of sequence found
  14347. pos = max-1;
  14348. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  14349. // Fuckup - very small and broken sequence,
  14350. // return max, because we should return something anyway.
  14351. if (pos < 0) { return max; }
  14352. // If we came to start of buffer - that means vuffer is too small,
  14353. // return max too.
  14354. if (pos === 0) { return max; }
  14355. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  14356. };
  14357. },{"./common":52}],54:[function(require,module,exports){
  14358. 'use strict';
  14359. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  14360. // It doesn't worth to make additional optimizationa as in original.
  14361. // Small size is preferable.
  14362. function adler32(adler, buf, len, pos) {
  14363. var s1 = (adler & 0xffff) |0,
  14364. s2 = ((adler >>> 16) & 0xffff) |0,
  14365. n = 0;
  14366. while (len !== 0) {
  14367. // Set limit ~ twice less than 5552, to keep
  14368. // s2 in 31-bits, because we force signed ints.
  14369. // in other case %= will fail.
  14370. n = len > 2000 ? 2000 : len;
  14371. len -= n;
  14372. do {
  14373. s1 = (s1 + buf[pos++]) |0;
  14374. s2 = (s2 + s1) |0;
  14375. } while (--n);
  14376. s1 %= 65521;
  14377. s2 %= 65521;
  14378. }
  14379. return (s1 | (s2 << 16)) |0;
  14380. }
  14381. module.exports = adler32;
  14382. },{}],55:[function(require,module,exports){
  14383. module.exports = {
  14384. /* Allowed flush values; see deflate() and inflate() below for details */
  14385. Z_NO_FLUSH: 0,
  14386. Z_PARTIAL_FLUSH: 1,
  14387. Z_SYNC_FLUSH: 2,
  14388. Z_FULL_FLUSH: 3,
  14389. Z_FINISH: 4,
  14390. Z_BLOCK: 5,
  14391. Z_TREES: 6,
  14392. /* Return codes for the compression/decompression functions. Negative values
  14393. * are errors, positive values are used for special but normal events.
  14394. */
  14395. Z_OK: 0,
  14396. Z_STREAM_END: 1,
  14397. Z_NEED_DICT: 2,
  14398. Z_ERRNO: -1,
  14399. Z_STREAM_ERROR: -2,
  14400. Z_DATA_ERROR: -3,
  14401. //Z_MEM_ERROR: -4,
  14402. Z_BUF_ERROR: -5,
  14403. //Z_VERSION_ERROR: -6,
  14404. /* compression levels */
  14405. Z_NO_COMPRESSION: 0,
  14406. Z_BEST_SPEED: 1,
  14407. Z_BEST_COMPRESSION: 9,
  14408. Z_DEFAULT_COMPRESSION: -1,
  14409. Z_FILTERED: 1,
  14410. Z_HUFFMAN_ONLY: 2,
  14411. Z_RLE: 3,
  14412. Z_FIXED: 4,
  14413. Z_DEFAULT_STRATEGY: 0,
  14414. /* Possible values of the data_type field (though see inflate()) */
  14415. Z_BINARY: 0,
  14416. Z_TEXT: 1,
  14417. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  14418. Z_UNKNOWN: 2,
  14419. /* The deflate compression method */
  14420. Z_DEFLATED: 8
  14421. //Z_NULL: null // Use -1 or null inline, depending on var type
  14422. };
  14423. },{}],56:[function(require,module,exports){
  14424. 'use strict';
  14425. // Note: we can't get significant speed boost here.
  14426. // So write code to minimize size - no pregenerated tables
  14427. // and array tools dependencies.
  14428. // Use ordinary array, since untyped makes no boost here
  14429. function makeTable() {
  14430. var c, table = [];
  14431. for (var n =0; n < 256; n++) {
  14432. c = n;
  14433. for (var k =0; k < 8; k++) {
  14434. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  14435. }
  14436. table[n] = c;
  14437. }
  14438. return table;
  14439. }
  14440. // Create table on load. Just 255 signed longs. Not a problem.
  14441. var crcTable = makeTable();
  14442. function crc32(crc, buf, len, pos) {
  14443. var t = crcTable,
  14444. end = pos + len;
  14445. crc = crc ^ (-1);
  14446. for (var i = pos; i < end; i++) {
  14447. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  14448. }
  14449. return (crc ^ (-1)); // >>> 0;
  14450. }
  14451. module.exports = crc32;
  14452. },{}],57:[function(require,module,exports){
  14453. 'use strict';
  14454. var utils = require('../utils/common');
  14455. var trees = require('./trees');
  14456. var adler32 = require('./adler32');
  14457. var crc32 = require('./crc32');
  14458. var msg = require('./messages');
  14459. /* Public constants ==========================================================*/
  14460. /* ===========================================================================*/
  14461. /* Allowed flush values; see deflate() and inflate() below for details */
  14462. var Z_NO_FLUSH = 0;
  14463. var Z_PARTIAL_FLUSH = 1;
  14464. //var Z_SYNC_FLUSH = 2;
  14465. var Z_FULL_FLUSH = 3;
  14466. var Z_FINISH = 4;
  14467. var Z_BLOCK = 5;
  14468. //var Z_TREES = 6;
  14469. /* Return codes for the compression/decompression functions. Negative values
  14470. * are errors, positive values are used for special but normal events.
  14471. */
  14472. var Z_OK = 0;
  14473. var Z_STREAM_END = 1;
  14474. //var Z_NEED_DICT = 2;
  14475. //var Z_ERRNO = -1;
  14476. var Z_STREAM_ERROR = -2;
  14477. var Z_DATA_ERROR = -3;
  14478. //var Z_MEM_ERROR = -4;
  14479. var Z_BUF_ERROR = -5;
  14480. //var Z_VERSION_ERROR = -6;
  14481. /* compression levels */
  14482. //var Z_NO_COMPRESSION = 0;
  14483. //var Z_BEST_SPEED = 1;
  14484. //var Z_BEST_COMPRESSION = 9;
  14485. var Z_DEFAULT_COMPRESSION = -1;
  14486. var Z_FILTERED = 1;
  14487. var Z_HUFFMAN_ONLY = 2;
  14488. var Z_RLE = 3;
  14489. var Z_FIXED = 4;
  14490. var Z_DEFAULT_STRATEGY = 0;
  14491. /* Possible values of the data_type field (though see inflate()) */
  14492. //var Z_BINARY = 0;
  14493. //var Z_TEXT = 1;
  14494. //var Z_ASCII = 1; // = Z_TEXT
  14495. var Z_UNKNOWN = 2;
  14496. /* The deflate compression method */
  14497. var Z_DEFLATED = 8;
  14498. /*============================================================================*/
  14499. var MAX_MEM_LEVEL = 9;
  14500. /* Maximum value for memLevel in deflateInit2 */
  14501. var MAX_WBITS = 15;
  14502. /* 32K LZ77 window */
  14503. var DEF_MEM_LEVEL = 8;
  14504. var LENGTH_CODES = 29;
  14505. /* number of length codes, not counting the special END_BLOCK code */
  14506. var LITERALS = 256;
  14507. /* number of literal bytes 0..255 */
  14508. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14509. /* number of Literal or Length codes, including the END_BLOCK code */
  14510. var D_CODES = 30;
  14511. /* number of distance codes */
  14512. var BL_CODES = 19;
  14513. /* number of codes used to transfer the bit lengths */
  14514. var HEAP_SIZE = 2*L_CODES + 1;
  14515. /* maximum heap size */
  14516. var MAX_BITS = 15;
  14517. /* All codes must not exceed MAX_BITS bits */
  14518. var MIN_MATCH = 3;
  14519. var MAX_MATCH = 258;
  14520. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  14521. var PRESET_DICT = 0x20;
  14522. var INIT_STATE = 42;
  14523. var EXTRA_STATE = 69;
  14524. var NAME_STATE = 73;
  14525. var COMMENT_STATE = 91;
  14526. var HCRC_STATE = 103;
  14527. var BUSY_STATE = 113;
  14528. var FINISH_STATE = 666;
  14529. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  14530. var BS_BLOCK_DONE = 2; /* block flush performed */
  14531. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  14532. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  14533. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  14534. function err(strm, errorCode) {
  14535. strm.msg = msg[errorCode];
  14536. return errorCode;
  14537. }
  14538. function rank(f) {
  14539. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  14540. }
  14541. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14542. /* =========================================================================
  14543. * Flush as much pending output as possible. All deflate() output goes
  14544. * through this function so some applications may wish to modify it
  14545. * to avoid allocating a large strm->output buffer and copying into it.
  14546. * (See also read_buf()).
  14547. */
  14548. function flush_pending(strm) {
  14549. var s = strm.state;
  14550. //_tr_flush_bits(s);
  14551. var len = s.pending;
  14552. if (len > strm.avail_out) {
  14553. len = strm.avail_out;
  14554. }
  14555. if (len === 0) { return; }
  14556. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  14557. strm.next_out += len;
  14558. s.pending_out += len;
  14559. strm.total_out += len;
  14560. strm.avail_out -= len;
  14561. s.pending -= len;
  14562. if (s.pending === 0) {
  14563. s.pending_out = 0;
  14564. }
  14565. }
  14566. function flush_block_only (s, last) {
  14567. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  14568. s.block_start = s.strstart;
  14569. flush_pending(s.strm);
  14570. }
  14571. function put_byte(s, b) {
  14572. s.pending_buf[s.pending++] = b;
  14573. }
  14574. /* =========================================================================
  14575. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  14576. * IN assertion: the stream state is correct and there is enough room in
  14577. * pending_buf.
  14578. */
  14579. function putShortMSB(s, b) {
  14580. // put_byte(s, (Byte)(b >> 8));
  14581. // put_byte(s, (Byte)(b & 0xff));
  14582. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  14583. s.pending_buf[s.pending++] = b & 0xff;
  14584. }
  14585. /* ===========================================================================
  14586. * Read a new buffer from the current input stream, update the adler32
  14587. * and total number of bytes read. All deflate() input goes through
  14588. * this function so some applications may wish to modify it to avoid
  14589. * allocating a large strm->input buffer and copying from it.
  14590. * (See also flush_pending()).
  14591. */
  14592. function read_buf(strm, buf, start, size) {
  14593. var len = strm.avail_in;
  14594. if (len > size) { len = size; }
  14595. if (len === 0) { return 0; }
  14596. strm.avail_in -= len;
  14597. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  14598. if (strm.state.wrap === 1) {
  14599. strm.adler = adler32(strm.adler, buf, len, start);
  14600. }
  14601. else if (strm.state.wrap === 2) {
  14602. strm.adler = crc32(strm.adler, buf, len, start);
  14603. }
  14604. strm.next_in += len;
  14605. strm.total_in += len;
  14606. return len;
  14607. }
  14608. /* ===========================================================================
  14609. * Set match_start to the longest match starting at the given string and
  14610. * return its length. Matches shorter or equal to prev_length are discarded,
  14611. * in which case the result is equal to prev_length and match_start is
  14612. * garbage.
  14613. * IN assertions: cur_match is the head of the hash chain for the current
  14614. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  14615. * OUT assertion: the match length is not greater than s->lookahead.
  14616. */
  14617. function longest_match(s, cur_match) {
  14618. var chain_length = s.max_chain_length; /* max hash chain length */
  14619. var scan = s.strstart; /* current string */
  14620. var match; /* matched string */
  14621. var len; /* length of current match */
  14622. var best_len = s.prev_length; /* best match length so far */
  14623. var nice_match = s.nice_match; /* stop if match long enough */
  14624. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14625. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14626. var _win = s.window; // shortcut
  14627. var wmask = s.w_mask;
  14628. var prev = s.prev;
  14629. /* Stop when cur_match becomes <= limit. To simplify the code,
  14630. * we prevent matches with the string of window index 0.
  14631. */
  14632. var strend = s.strstart + MAX_MATCH;
  14633. var scan_end1 = _win[scan + best_len - 1];
  14634. var scan_end = _win[scan + best_len];
  14635. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14636. * It is easy to get rid of this optimization if necessary.
  14637. */
  14638. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14639. /* Do not waste too much time if we already have a good match: */
  14640. if (s.prev_length >= s.good_match) {
  14641. chain_length >>= 2;
  14642. }
  14643. /* Do not look for matches beyond the end of the input. This is necessary
  14644. * to make deflate deterministic.
  14645. */
  14646. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14647. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14648. do {
  14649. // Assert(cur_match < s->strstart, "no future");
  14650. match = cur_match;
  14651. /* Skip to next match if the match length cannot increase
  14652. * or if the match length is less than 2. Note that the checks below
  14653. * for insufficient lookahead only occur occasionally for performance
  14654. * reasons. Therefore uninitialized memory will be accessed, and
  14655. * conditional jumps will be made that depend on those values.
  14656. * However the length of the match is limited to the lookahead, so
  14657. * the output of deflate is not affected by the uninitialized values.
  14658. */
  14659. if (_win[match + best_len] !== scan_end ||
  14660. _win[match + best_len - 1] !== scan_end1 ||
  14661. _win[match] !== _win[scan] ||
  14662. _win[++match] !== _win[scan + 1]) {
  14663. continue;
  14664. }
  14665. /* The check at best_len-1 can be removed because it will be made
  14666. * again later. (This heuristic is not always a win.)
  14667. * It is not necessary to compare scan[2] and match[2] since they
  14668. * are always equal when the other bytes match, given that
  14669. * the hash keys are equal and that HASH_BITS >= 8.
  14670. */
  14671. scan += 2;
  14672. match++;
  14673. // Assert(*scan == *match, "match[2]?");
  14674. /* We check for insufficient lookahead only every 8th comparison;
  14675. * the 256th check will be made at strstart+258.
  14676. */
  14677. do {
  14678. /*jshint noempty:false*/
  14679. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14680. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14681. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14682. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14683. scan < strend);
  14684. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14685. len = MAX_MATCH - (strend - scan);
  14686. scan = strend - MAX_MATCH;
  14687. if (len > best_len) {
  14688. s.match_start = cur_match;
  14689. best_len = len;
  14690. if (len >= nice_match) {
  14691. break;
  14692. }
  14693. scan_end1 = _win[scan + best_len - 1];
  14694. scan_end = _win[scan + best_len];
  14695. }
  14696. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14697. if (best_len <= s.lookahead) {
  14698. return best_len;
  14699. }
  14700. return s.lookahead;
  14701. }
  14702. /* ===========================================================================
  14703. * Fill the window when the lookahead becomes insufficient.
  14704. * Updates strstart and lookahead.
  14705. *
  14706. * IN assertion: lookahead < MIN_LOOKAHEAD
  14707. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14708. * At least one byte has been read, or avail_in == 0; reads are
  14709. * performed for at least two bytes (required for the zip translate_eol
  14710. * option -- not supported here).
  14711. */
  14712. function fill_window(s) {
  14713. var _w_size = s.w_size;
  14714. var p, n, m, more, str;
  14715. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14716. do {
  14717. more = s.window_size - s.lookahead - s.strstart;
  14718. // JS ints have 32 bit, block below not needed
  14719. /* Deal with !@#$% 64K limit: */
  14720. //if (sizeof(int) <= 2) {
  14721. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14722. // more = wsize;
  14723. //
  14724. // } else if (more == (unsigned)(-1)) {
  14725. // /* Very unlikely, but possible on 16 bit machine if
  14726. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14727. // */
  14728. // more--;
  14729. // }
  14730. //}
  14731. /* If the window is almost full and there is insufficient lookahead,
  14732. * move the upper half to the lower one to make room in the upper half.
  14733. */
  14734. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14735. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14736. s.match_start -= _w_size;
  14737. s.strstart -= _w_size;
  14738. /* we now have strstart >= MAX_DIST */
  14739. s.block_start -= _w_size;
  14740. /* Slide the hash table (could be avoided with 32 bit values
  14741. at the expense of memory usage). We slide even when level == 0
  14742. to keep the hash table consistent if we switch back to level > 0
  14743. later. (Using level 0 permanently is not an optimal usage of
  14744. zlib, so we don't care about this pathological case.)
  14745. */
  14746. n = s.hash_size;
  14747. p = n;
  14748. do {
  14749. m = s.head[--p];
  14750. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14751. } while (--n);
  14752. n = _w_size;
  14753. p = n;
  14754. do {
  14755. m = s.prev[--p];
  14756. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14757. /* If n is not on any hash chain, prev[n] is garbage but
  14758. * its value will never be used.
  14759. */
  14760. } while (--n);
  14761. more += _w_size;
  14762. }
  14763. if (s.strm.avail_in === 0) {
  14764. break;
  14765. }
  14766. /* If there was no sliding:
  14767. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14768. * more == window_size - lookahead - strstart
  14769. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14770. * => more >= window_size - 2*WSIZE + 2
  14771. * In the BIG_MEM or MMAP case (not yet supported),
  14772. * window_size == input_size + MIN_LOOKAHEAD &&
  14773. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14774. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14775. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14776. */
  14777. //Assert(more >= 2, "more < 2");
  14778. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14779. s.lookahead += n;
  14780. /* Initialize the hash value now that we have some input: */
  14781. if (s.lookahead + s.insert >= MIN_MATCH) {
  14782. str = s.strstart - s.insert;
  14783. s.ins_h = s.window[str];
  14784. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14785. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14786. //#if MIN_MATCH != 3
  14787. // Call update_hash() MIN_MATCH-3 more times
  14788. //#endif
  14789. while (s.insert) {
  14790. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14791. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14792. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14793. s.head[s.ins_h] = str;
  14794. str++;
  14795. s.insert--;
  14796. if (s.lookahead + s.insert < MIN_MATCH) {
  14797. break;
  14798. }
  14799. }
  14800. }
  14801. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14802. * but this is not important since only literal bytes will be emitted.
  14803. */
  14804. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14805. /* If the WIN_INIT bytes after the end of the current data have never been
  14806. * written, then zero those bytes in order to avoid memory check reports of
  14807. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14808. * the longest match routines. Update the high water mark for the next
  14809. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14810. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14811. */
  14812. // if (s.high_water < s.window_size) {
  14813. // var curr = s.strstart + s.lookahead;
  14814. // var init = 0;
  14815. //
  14816. // if (s.high_water < curr) {
  14817. // /* Previous high water mark below current data -- zero WIN_INIT
  14818. // * bytes or up to end of window, whichever is less.
  14819. // */
  14820. // init = s.window_size - curr;
  14821. // if (init > WIN_INIT)
  14822. // init = WIN_INIT;
  14823. // zmemzero(s->window + curr, (unsigned)init);
  14824. // s->high_water = curr + init;
  14825. // }
  14826. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14827. // /* High water mark at or above current data, but below current data
  14828. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14829. // * to end of window, whichever is less.
  14830. // */
  14831. // init = (ulg)curr + WIN_INIT - s->high_water;
  14832. // if (init > s->window_size - s->high_water)
  14833. // init = s->window_size - s->high_water;
  14834. // zmemzero(s->window + s->high_water, (unsigned)init);
  14835. // s->high_water += init;
  14836. // }
  14837. // }
  14838. //
  14839. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14840. // "not enough room for search");
  14841. }
  14842. /* ===========================================================================
  14843. * Copy without compression as much as possible from the input stream, return
  14844. * the current block state.
  14845. * This function does not insert new strings in the dictionary since
  14846. * uncompressible data is probably not useful. This function is used
  14847. * only for the level=0 compression option.
  14848. * NOTE: this function should be optimized to avoid extra copying from
  14849. * window to pending_buf.
  14850. */
  14851. function deflate_stored(s, flush) {
  14852. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14853. * to pending_buf_size, and each stored block has a 5 byte header:
  14854. */
  14855. var max_block_size = 0xffff;
  14856. if (max_block_size > s.pending_buf_size - 5) {
  14857. max_block_size = s.pending_buf_size - 5;
  14858. }
  14859. /* Copy as much as possible from input to output: */
  14860. for (;;) {
  14861. /* Fill the window as much as possible: */
  14862. if (s.lookahead <= 1) {
  14863. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14864. // s->block_start >= (long)s->w_size, "slide too late");
  14865. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14866. // s.block_start >= s.w_size)) {
  14867. // throw new Error("slide too late");
  14868. // }
  14869. fill_window(s);
  14870. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14871. return BS_NEED_MORE;
  14872. }
  14873. if (s.lookahead === 0) {
  14874. break;
  14875. }
  14876. /* flush the current block */
  14877. }
  14878. //Assert(s->block_start >= 0L, "block gone");
  14879. // if (s.block_start < 0) throw new Error("block gone");
  14880. s.strstart += s.lookahead;
  14881. s.lookahead = 0;
  14882. /* Emit a stored block if pending_buf will be full: */
  14883. var max_start = s.block_start + max_block_size;
  14884. if (s.strstart === 0 || s.strstart >= max_start) {
  14885. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14886. s.lookahead = s.strstart - max_start;
  14887. s.strstart = max_start;
  14888. /*** FLUSH_BLOCK(s, 0); ***/
  14889. flush_block_only(s, false);
  14890. if (s.strm.avail_out === 0) {
  14891. return BS_NEED_MORE;
  14892. }
  14893. /***/
  14894. }
  14895. /* Flush if we may have to slide, otherwise block_start may become
  14896. * negative and the data will be gone:
  14897. */
  14898. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14899. /*** FLUSH_BLOCK(s, 0); ***/
  14900. flush_block_only(s, false);
  14901. if (s.strm.avail_out === 0) {
  14902. return BS_NEED_MORE;
  14903. }
  14904. /***/
  14905. }
  14906. }
  14907. s.insert = 0;
  14908. if (flush === Z_FINISH) {
  14909. /*** FLUSH_BLOCK(s, 1); ***/
  14910. flush_block_only(s, true);
  14911. if (s.strm.avail_out === 0) {
  14912. return BS_FINISH_STARTED;
  14913. }
  14914. /***/
  14915. return BS_FINISH_DONE;
  14916. }
  14917. if (s.strstart > s.block_start) {
  14918. /*** FLUSH_BLOCK(s, 0); ***/
  14919. flush_block_only(s, false);
  14920. if (s.strm.avail_out === 0) {
  14921. return BS_NEED_MORE;
  14922. }
  14923. /***/
  14924. }
  14925. return BS_NEED_MORE;
  14926. }
  14927. /* ===========================================================================
  14928. * Compress as much as possible from the input stream, return the current
  14929. * block state.
  14930. * This function does not perform lazy evaluation of matches and inserts
  14931. * new strings in the dictionary only for unmatched strings or for short
  14932. * matches. It is used only for the fast compression options.
  14933. */
  14934. function deflate_fast(s, flush) {
  14935. var hash_head; /* head of the hash chain */
  14936. var bflush; /* set if current block must be flushed */
  14937. for (;;) {
  14938. /* Make sure that we always have enough lookahead, except
  14939. * at the end of the input file. We need MAX_MATCH bytes
  14940. * for the next match, plus MIN_MATCH bytes to insert the
  14941. * string following the next match.
  14942. */
  14943. if (s.lookahead < MIN_LOOKAHEAD) {
  14944. fill_window(s);
  14945. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14946. return BS_NEED_MORE;
  14947. }
  14948. if (s.lookahead === 0) {
  14949. break; /* flush the current block */
  14950. }
  14951. }
  14952. /* Insert the string window[strstart .. strstart+2] in the
  14953. * dictionary, and set hash_head to the head of the hash chain:
  14954. */
  14955. hash_head = 0/*NIL*/;
  14956. if (s.lookahead >= MIN_MATCH) {
  14957. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14958. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14959. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14960. s.head[s.ins_h] = s.strstart;
  14961. /***/
  14962. }
  14963. /* Find the longest match, discarding those <= prev_length.
  14964. * At this point we have always match_length < MIN_MATCH
  14965. */
  14966. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14967. /* To simplify the code, we prevent matches with the string
  14968. * of window index 0 (in particular we have to avoid a match
  14969. * of the string with itself at the start of the input file).
  14970. */
  14971. s.match_length = longest_match(s, hash_head);
  14972. /* longest_match() sets match_start */
  14973. }
  14974. if (s.match_length >= MIN_MATCH) {
  14975. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14976. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14977. s.match_length - MIN_MATCH, bflush); ***/
  14978. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14979. s.lookahead -= s.match_length;
  14980. /* Insert new strings in the hash table only if the match length
  14981. * is not too large. This saves time but degrades compression.
  14982. */
  14983. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14984. s.match_length--; /* string at strstart already in table */
  14985. do {
  14986. s.strstart++;
  14987. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14988. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14989. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14990. s.head[s.ins_h] = s.strstart;
  14991. /***/
  14992. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14993. * always MIN_MATCH bytes ahead.
  14994. */
  14995. } while (--s.match_length !== 0);
  14996. s.strstart++;
  14997. } else
  14998. {
  14999. s.strstart += s.match_length;
  15000. s.match_length = 0;
  15001. s.ins_h = s.window[s.strstart];
  15002. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  15003. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  15004. //#if MIN_MATCH != 3
  15005. // Call UPDATE_HASH() MIN_MATCH-3 more times
  15006. //#endif
  15007. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  15008. * matter since it will be recomputed at next deflate call.
  15009. */
  15010. }
  15011. } else {
  15012. /* No match, output a literal byte */
  15013. //Tracevv((stderr,"%c", s.window[s.strstart]));
  15014. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15015. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15016. s.lookahead--;
  15017. s.strstart++;
  15018. }
  15019. if (bflush) {
  15020. /*** FLUSH_BLOCK(s, 0); ***/
  15021. flush_block_only(s, false);
  15022. if (s.strm.avail_out === 0) {
  15023. return BS_NEED_MORE;
  15024. }
  15025. /***/
  15026. }
  15027. }
  15028. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  15029. if (flush === Z_FINISH) {
  15030. /*** FLUSH_BLOCK(s, 1); ***/
  15031. flush_block_only(s, true);
  15032. if (s.strm.avail_out === 0) {
  15033. return BS_FINISH_STARTED;
  15034. }
  15035. /***/
  15036. return BS_FINISH_DONE;
  15037. }
  15038. if (s.last_lit) {
  15039. /*** FLUSH_BLOCK(s, 0); ***/
  15040. flush_block_only(s, false);
  15041. if (s.strm.avail_out === 0) {
  15042. return BS_NEED_MORE;
  15043. }
  15044. /***/
  15045. }
  15046. return BS_BLOCK_DONE;
  15047. }
  15048. /* ===========================================================================
  15049. * Same as above, but achieves better compression. We use a lazy
  15050. * evaluation for matches: a match is finally adopted only if there is
  15051. * no better match at the next window position.
  15052. */
  15053. function deflate_slow(s, flush) {
  15054. var hash_head; /* head of hash chain */
  15055. var bflush; /* set if current block must be flushed */
  15056. var max_insert;
  15057. /* Process the input block. */
  15058. for (;;) {
  15059. /* Make sure that we always have enough lookahead, except
  15060. * at the end of the input file. We need MAX_MATCH bytes
  15061. * for the next match, plus MIN_MATCH bytes to insert the
  15062. * string following the next match.
  15063. */
  15064. if (s.lookahead < MIN_LOOKAHEAD) {
  15065. fill_window(s);
  15066. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15067. return BS_NEED_MORE;
  15068. }
  15069. if (s.lookahead === 0) { break; } /* flush the current block */
  15070. }
  15071. /* Insert the string window[strstart .. strstart+2] in the
  15072. * dictionary, and set hash_head to the head of the hash chain:
  15073. */
  15074. hash_head = 0/*NIL*/;
  15075. if (s.lookahead >= MIN_MATCH) {
  15076. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15077. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15078. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15079. s.head[s.ins_h] = s.strstart;
  15080. /***/
  15081. }
  15082. /* Find the longest match, discarding those <= prev_length.
  15083. */
  15084. s.prev_length = s.match_length;
  15085. s.prev_match = s.match_start;
  15086. s.match_length = MIN_MATCH-1;
  15087. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  15088. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  15089. /* To simplify the code, we prevent matches with the string
  15090. * of window index 0 (in particular we have to avoid a match
  15091. * of the string with itself at the start of the input file).
  15092. */
  15093. s.match_length = longest_match(s, hash_head);
  15094. /* longest_match() sets match_start */
  15095. if (s.match_length <= 5 &&
  15096. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  15097. /* If prev_match is also MIN_MATCH, match_start is garbage
  15098. * but we will ignore the current match anyway.
  15099. */
  15100. s.match_length = MIN_MATCH-1;
  15101. }
  15102. }
  15103. /* If there was a match at the previous step and the current
  15104. * match is not better, output the previous match:
  15105. */
  15106. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  15107. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  15108. /* Do not insert strings in hash table beyond this. */
  15109. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  15110. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  15111. s.prev_length - MIN_MATCH, bflush);***/
  15112. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  15113. /* Insert in hash table all strings up to the end of the match.
  15114. * strstart-1 and strstart are already inserted. If there is not
  15115. * enough lookahead, the last two strings are not inserted in
  15116. * the hash table.
  15117. */
  15118. s.lookahead -= s.prev_length-1;
  15119. s.prev_length -= 2;
  15120. do {
  15121. if (++s.strstart <= max_insert) {
  15122. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15123. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15124. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15125. s.head[s.ins_h] = s.strstart;
  15126. /***/
  15127. }
  15128. } while (--s.prev_length !== 0);
  15129. s.match_available = 0;
  15130. s.match_length = MIN_MATCH-1;
  15131. s.strstart++;
  15132. if (bflush) {
  15133. /*** FLUSH_BLOCK(s, 0); ***/
  15134. flush_block_only(s, false);
  15135. if (s.strm.avail_out === 0) {
  15136. return BS_NEED_MORE;
  15137. }
  15138. /***/
  15139. }
  15140. } else if (s.match_available) {
  15141. /* If there was no match at the previous position, output a
  15142. * single literal. If there was a match but the current match
  15143. * is longer, truncate the previous match to a single literal.
  15144. */
  15145. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15146. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15147. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15148. if (bflush) {
  15149. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  15150. flush_block_only(s, false);
  15151. /***/
  15152. }
  15153. s.strstart++;
  15154. s.lookahead--;
  15155. if (s.strm.avail_out === 0) {
  15156. return BS_NEED_MORE;
  15157. }
  15158. } else {
  15159. /* There is no previous match to compare with, wait for
  15160. * the next step to decide.
  15161. */
  15162. s.match_available = 1;
  15163. s.strstart++;
  15164. s.lookahead--;
  15165. }
  15166. }
  15167. //Assert (flush != Z_NO_FLUSH, "no flush?");
  15168. if (s.match_available) {
  15169. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15170. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15171. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15172. s.match_available = 0;
  15173. }
  15174. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  15175. if (flush === Z_FINISH) {
  15176. /*** FLUSH_BLOCK(s, 1); ***/
  15177. flush_block_only(s, true);
  15178. if (s.strm.avail_out === 0) {
  15179. return BS_FINISH_STARTED;
  15180. }
  15181. /***/
  15182. return BS_FINISH_DONE;
  15183. }
  15184. if (s.last_lit) {
  15185. /*** FLUSH_BLOCK(s, 0); ***/
  15186. flush_block_only(s, false);
  15187. if (s.strm.avail_out === 0) {
  15188. return BS_NEED_MORE;
  15189. }
  15190. /***/
  15191. }
  15192. return BS_BLOCK_DONE;
  15193. }
  15194. /* ===========================================================================
  15195. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  15196. * one. Do not maintain a hash table. (It will be regenerated if this run of
  15197. * deflate switches away from Z_RLE.)
  15198. */
  15199. function deflate_rle(s, flush) {
  15200. var bflush; /* set if current block must be flushed */
  15201. var prev; /* byte at distance one to match */
  15202. var scan, strend; /* scan goes up to strend for length of run */
  15203. var _win = s.window;
  15204. for (;;) {
  15205. /* Make sure that we always have enough lookahead, except
  15206. * at the end of the input file. We need MAX_MATCH bytes
  15207. * for the longest run, plus one for the unrolled loop.
  15208. */
  15209. if (s.lookahead <= MAX_MATCH) {
  15210. fill_window(s);
  15211. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  15212. return BS_NEED_MORE;
  15213. }
  15214. if (s.lookahead === 0) { break; } /* flush the current block */
  15215. }
  15216. /* See how many times the previous byte repeats */
  15217. s.match_length = 0;
  15218. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  15219. scan = s.strstart - 1;
  15220. prev = _win[scan];
  15221. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  15222. strend = s.strstart + MAX_MATCH;
  15223. do {
  15224. /*jshint noempty:false*/
  15225. } while (prev === _win[++scan] && prev === _win[++scan] &&
  15226. prev === _win[++scan] && prev === _win[++scan] &&
  15227. prev === _win[++scan] && prev === _win[++scan] &&
  15228. prev === _win[++scan] && prev === _win[++scan] &&
  15229. scan < strend);
  15230. s.match_length = MAX_MATCH - (strend - scan);
  15231. if (s.match_length > s.lookahead) {
  15232. s.match_length = s.lookahead;
  15233. }
  15234. }
  15235. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  15236. }
  15237. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  15238. if (s.match_length >= MIN_MATCH) {
  15239. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  15240. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  15241. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  15242. s.lookahead -= s.match_length;
  15243. s.strstart += s.match_length;
  15244. s.match_length = 0;
  15245. } else {
  15246. /* No match, output a literal byte */
  15247. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15248. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15249. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15250. s.lookahead--;
  15251. s.strstart++;
  15252. }
  15253. if (bflush) {
  15254. /*** FLUSH_BLOCK(s, 0); ***/
  15255. flush_block_only(s, false);
  15256. if (s.strm.avail_out === 0) {
  15257. return BS_NEED_MORE;
  15258. }
  15259. /***/
  15260. }
  15261. }
  15262. s.insert = 0;
  15263. if (flush === Z_FINISH) {
  15264. /*** FLUSH_BLOCK(s, 1); ***/
  15265. flush_block_only(s, true);
  15266. if (s.strm.avail_out === 0) {
  15267. return BS_FINISH_STARTED;
  15268. }
  15269. /***/
  15270. return BS_FINISH_DONE;
  15271. }
  15272. if (s.last_lit) {
  15273. /*** FLUSH_BLOCK(s, 0); ***/
  15274. flush_block_only(s, false);
  15275. if (s.strm.avail_out === 0) {
  15276. return BS_NEED_MORE;
  15277. }
  15278. /***/
  15279. }
  15280. return BS_BLOCK_DONE;
  15281. }
  15282. /* ===========================================================================
  15283. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  15284. * (It will be regenerated if this run of deflate switches away from Huffman.)
  15285. */
  15286. function deflate_huff(s, flush) {
  15287. var bflush; /* set if current block must be flushed */
  15288. for (;;) {
  15289. /* Make sure that we have a literal to write. */
  15290. if (s.lookahead === 0) {
  15291. fill_window(s);
  15292. if (s.lookahead === 0) {
  15293. if (flush === Z_NO_FLUSH) {
  15294. return BS_NEED_MORE;
  15295. }
  15296. break; /* flush the current block */
  15297. }
  15298. }
  15299. /* Output a literal byte */
  15300. s.match_length = 0;
  15301. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15302. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15303. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15304. s.lookahead--;
  15305. s.strstart++;
  15306. if (bflush) {
  15307. /*** FLUSH_BLOCK(s, 0); ***/
  15308. flush_block_only(s, false);
  15309. if (s.strm.avail_out === 0) {
  15310. return BS_NEED_MORE;
  15311. }
  15312. /***/
  15313. }
  15314. }
  15315. s.insert = 0;
  15316. if (flush === Z_FINISH) {
  15317. /*** FLUSH_BLOCK(s, 1); ***/
  15318. flush_block_only(s, true);
  15319. if (s.strm.avail_out === 0) {
  15320. return BS_FINISH_STARTED;
  15321. }
  15322. /***/
  15323. return BS_FINISH_DONE;
  15324. }
  15325. if (s.last_lit) {
  15326. /*** FLUSH_BLOCK(s, 0); ***/
  15327. flush_block_only(s, false);
  15328. if (s.strm.avail_out === 0) {
  15329. return BS_NEED_MORE;
  15330. }
  15331. /***/
  15332. }
  15333. return BS_BLOCK_DONE;
  15334. }
  15335. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  15336. * the desired pack level (0..9). The values given below have been tuned to
  15337. * exclude worst case performance for pathological files. Better values may be
  15338. * found for specific files.
  15339. */
  15340. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  15341. this.good_length = good_length;
  15342. this.max_lazy = max_lazy;
  15343. this.nice_length = nice_length;
  15344. this.max_chain = max_chain;
  15345. this.func = func;
  15346. };
  15347. var configuration_table;
  15348. configuration_table = [
  15349. /* good lazy nice chain */
  15350. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  15351. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  15352. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  15353. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  15354. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  15355. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  15356. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  15357. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  15358. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  15359. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  15360. ];
  15361. /* ===========================================================================
  15362. * Initialize the "longest match" routines for a new zlib stream
  15363. */
  15364. function lm_init(s) {
  15365. s.window_size = 2 * s.w_size;
  15366. /*** CLEAR_HASH(s); ***/
  15367. zero(s.head); // Fill with NIL (= 0);
  15368. /* Set the default configuration parameters:
  15369. */
  15370. s.max_lazy_match = configuration_table[s.level].max_lazy;
  15371. s.good_match = configuration_table[s.level].good_length;
  15372. s.nice_match = configuration_table[s.level].nice_length;
  15373. s.max_chain_length = configuration_table[s.level].max_chain;
  15374. s.strstart = 0;
  15375. s.block_start = 0;
  15376. s.lookahead = 0;
  15377. s.insert = 0;
  15378. s.match_length = s.prev_length = MIN_MATCH - 1;
  15379. s.match_available = 0;
  15380. s.ins_h = 0;
  15381. }
  15382. function DeflateState() {
  15383. this.strm = null; /* pointer back to this zlib stream */
  15384. this.status = 0; /* as the name implies */
  15385. this.pending_buf = null; /* output still pending */
  15386. this.pending_buf_size = 0; /* size of pending_buf */
  15387. this.pending_out = 0; /* next pending byte to output to the stream */
  15388. this.pending = 0; /* nb of bytes in the pending buffer */
  15389. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15390. this.gzhead = null; /* gzip header information to write */
  15391. this.gzindex = 0; /* where in extra, name, or comment */
  15392. this.method = Z_DEFLATED; /* can only be DEFLATED */
  15393. this.last_flush = -1; /* value of flush param for previous deflate call */
  15394. this.w_size = 0; /* LZ77 window size (32K by default) */
  15395. this.w_bits = 0; /* log2(w_size) (8..16) */
  15396. this.w_mask = 0; /* w_size - 1 */
  15397. this.window = null;
  15398. /* Sliding window. Input bytes are read into the second half of the window,
  15399. * and move to the first half later to keep a dictionary of at least wSize
  15400. * bytes. With this organization, matches are limited to a distance of
  15401. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  15402. * performed with a length multiple of the block size.
  15403. */
  15404. this.window_size = 0;
  15405. /* Actual size of window: 2*wSize, except when the user input buffer
  15406. * is directly used as sliding window.
  15407. */
  15408. this.prev = null;
  15409. /* Link to older string with same hash index. To limit the size of this
  15410. * array to 64K, this link is maintained only for the last 32K strings.
  15411. * An index in this array is thus a window index modulo 32K.
  15412. */
  15413. this.head = null; /* Heads of the hash chains or NIL. */
  15414. this.ins_h = 0; /* hash index of string to be inserted */
  15415. this.hash_size = 0; /* number of elements in hash table */
  15416. this.hash_bits = 0; /* log2(hash_size) */
  15417. this.hash_mask = 0; /* hash_size-1 */
  15418. this.hash_shift = 0;
  15419. /* Number of bits by which ins_h must be shifted at each input
  15420. * step. It must be such that after MIN_MATCH steps, the oldest
  15421. * byte no longer takes part in the hash key, that is:
  15422. * hash_shift * MIN_MATCH >= hash_bits
  15423. */
  15424. this.block_start = 0;
  15425. /* Window position at the beginning of the current output block. Gets
  15426. * negative when the window is moved backwards.
  15427. */
  15428. this.match_length = 0; /* length of best match */
  15429. this.prev_match = 0; /* previous match */
  15430. this.match_available = 0; /* set if previous match exists */
  15431. this.strstart = 0; /* start of string to insert */
  15432. this.match_start = 0; /* start of matching string */
  15433. this.lookahead = 0; /* number of valid bytes ahead in window */
  15434. this.prev_length = 0;
  15435. /* Length of the best match at previous step. Matches not greater than this
  15436. * are discarded. This is used in the lazy match evaluation.
  15437. */
  15438. this.max_chain_length = 0;
  15439. /* To speed up deflation, hash chains are never searched beyond this
  15440. * length. A higher limit improves compression ratio but degrades the
  15441. * speed.
  15442. */
  15443. this.max_lazy_match = 0;
  15444. /* Attempt to find a better match only when the current match is strictly
  15445. * smaller than this value. This mechanism is used only for compression
  15446. * levels >= 4.
  15447. */
  15448. // That's alias to max_lazy_match, don't use directly
  15449. //this.max_insert_length = 0;
  15450. /* Insert new strings in the hash table only if the match length is not
  15451. * greater than this length. This saves time but degrades compression.
  15452. * max_insert_length is used only for compression levels <= 3.
  15453. */
  15454. this.level = 0; /* compression level (1..9) */
  15455. this.strategy = 0; /* favor or force Huffman coding*/
  15456. this.good_match = 0;
  15457. /* Use a faster search when the previous match is longer than this */
  15458. this.nice_match = 0; /* Stop searching when current match exceeds this */
  15459. /* used by trees.c: */
  15460. /* Didn't use ct_data typedef below to suppress compiler warning */
  15461. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  15462. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  15463. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  15464. // Use flat array of DOUBLE size, with interleaved fata,
  15465. // because JS does not support effective
  15466. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  15467. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  15468. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  15469. zero(this.dyn_ltree);
  15470. zero(this.dyn_dtree);
  15471. zero(this.bl_tree);
  15472. this.l_desc = null; /* desc. for literal tree */
  15473. this.d_desc = null; /* desc. for distance tree */
  15474. this.bl_desc = null; /* desc. for bit length tree */
  15475. //ush bl_count[MAX_BITS+1];
  15476. this.bl_count = new utils.Buf16(MAX_BITS+1);
  15477. /* number of codes at each bit length for an optimal tree */
  15478. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  15479. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  15480. zero(this.heap);
  15481. this.heap_len = 0; /* number of elements in the heap */
  15482. this.heap_max = 0; /* element of largest frequency */
  15483. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15484. * The same heap array is used to build all trees.
  15485. */
  15486. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  15487. zero(this.depth);
  15488. /* Depth of each subtree used as tie breaker for trees of equal frequency
  15489. */
  15490. this.l_buf = 0; /* buffer index for literals or lengths */
  15491. this.lit_bufsize = 0;
  15492. /* Size of match buffer for literals/lengths. There are 4 reasons for
  15493. * limiting lit_bufsize to 64K:
  15494. * - frequencies can be kept in 16 bit counters
  15495. * - if compression is not successful for the first block, all input
  15496. * data is still in the window so we can still emit a stored block even
  15497. * when input comes from standard input. (This can also be done for
  15498. * all blocks if lit_bufsize is not greater than 32K.)
  15499. * - if compression is not successful for a file smaller than 64K, we can
  15500. * even emit a stored file instead of a stored block (saving 5 bytes).
  15501. * This is applicable only for zip (not gzip or zlib).
  15502. * - creating new Huffman trees less frequently may not provide fast
  15503. * adaptation to changes in the input data statistics. (Take for
  15504. * example a binary file with poorly compressible code followed by
  15505. * a highly compressible string table.) Smaller buffer sizes give
  15506. * fast adaptation but have of course the overhead of transmitting
  15507. * trees more frequently.
  15508. * - I can't count above 4
  15509. */
  15510. this.last_lit = 0; /* running index in l_buf */
  15511. this.d_buf = 0;
  15512. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  15513. * the same number of elements. To use different lengths, an extra flag
  15514. * array would be necessary.
  15515. */
  15516. this.opt_len = 0; /* bit length of current block with optimal trees */
  15517. this.static_len = 0; /* bit length of current block with static trees */
  15518. this.matches = 0; /* number of string matches in current block */
  15519. this.insert = 0; /* bytes at end of window left to insert */
  15520. this.bi_buf = 0;
  15521. /* Output buffer. bits are inserted starting at the bottom (least
  15522. * significant bits).
  15523. */
  15524. this.bi_valid = 0;
  15525. /* Number of valid bits in bi_buf. All bits above the last valid bit
  15526. * are always zero.
  15527. */
  15528. // Used for window memory init. We safely ignore it for JS. That makes
  15529. // sense only for pointers and memory check tools.
  15530. //this.high_water = 0;
  15531. /* High water mark offset in window for initialized bytes -- bytes above
  15532. * this are set to zero in order to avoid memory check warnings when
  15533. * longest match routines access bytes past the input. This is then
  15534. * updated to the new high water mark.
  15535. */
  15536. }
  15537. function deflateResetKeep(strm) {
  15538. var s;
  15539. if (!strm || !strm.state) {
  15540. return err(strm, Z_STREAM_ERROR);
  15541. }
  15542. strm.total_in = strm.total_out = 0;
  15543. strm.data_type = Z_UNKNOWN;
  15544. s = strm.state;
  15545. s.pending = 0;
  15546. s.pending_out = 0;
  15547. if (s.wrap < 0) {
  15548. s.wrap = -s.wrap;
  15549. /* was made negative by deflate(..., Z_FINISH); */
  15550. }
  15551. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  15552. strm.adler = (s.wrap === 2) ?
  15553. 0 // crc32(0, Z_NULL, 0)
  15554. :
  15555. 1; // adler32(0, Z_NULL, 0)
  15556. s.last_flush = Z_NO_FLUSH;
  15557. trees._tr_init(s);
  15558. return Z_OK;
  15559. }
  15560. function deflateReset(strm) {
  15561. var ret = deflateResetKeep(strm);
  15562. if (ret === Z_OK) {
  15563. lm_init(strm.state);
  15564. }
  15565. return ret;
  15566. }
  15567. function deflateSetHeader(strm, head) {
  15568. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15569. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  15570. strm.state.gzhead = head;
  15571. return Z_OK;
  15572. }
  15573. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  15574. if (!strm) { // === Z_NULL
  15575. return Z_STREAM_ERROR;
  15576. }
  15577. var wrap = 1;
  15578. if (level === Z_DEFAULT_COMPRESSION) {
  15579. level = 6;
  15580. }
  15581. if (windowBits < 0) { /* suppress zlib wrapper */
  15582. wrap = 0;
  15583. windowBits = -windowBits;
  15584. }
  15585. else if (windowBits > 15) {
  15586. wrap = 2; /* write gzip wrapper instead */
  15587. windowBits -= 16;
  15588. }
  15589. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  15590. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  15591. strategy < 0 || strategy > Z_FIXED) {
  15592. return err(strm, Z_STREAM_ERROR);
  15593. }
  15594. if (windowBits === 8) {
  15595. windowBits = 9;
  15596. }
  15597. /* until 256-byte window bug fixed */
  15598. var s = new DeflateState();
  15599. strm.state = s;
  15600. s.strm = strm;
  15601. s.wrap = wrap;
  15602. s.gzhead = null;
  15603. s.w_bits = windowBits;
  15604. s.w_size = 1 << s.w_bits;
  15605. s.w_mask = s.w_size - 1;
  15606. s.hash_bits = memLevel + 7;
  15607. s.hash_size = 1 << s.hash_bits;
  15608. s.hash_mask = s.hash_size - 1;
  15609. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15610. s.window = new utils.Buf8(s.w_size * 2);
  15611. s.head = new utils.Buf16(s.hash_size);
  15612. s.prev = new utils.Buf16(s.w_size);
  15613. // Don't need mem init magic for JS.
  15614. //s.high_water = 0; /* nothing written to s->window yet */
  15615. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  15616. s.pending_buf_size = s.lit_bufsize * 4;
  15617. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  15618. s.d_buf = s.lit_bufsize >> 1;
  15619. s.l_buf = (1 + 2) * s.lit_bufsize;
  15620. s.level = level;
  15621. s.strategy = strategy;
  15622. s.method = method;
  15623. return deflateReset(strm);
  15624. }
  15625. function deflateInit(strm, level) {
  15626. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15627. }
  15628. function deflate(strm, flush) {
  15629. var old_flush, s;
  15630. var beg, val; // for gzip header write only
  15631. if (!strm || !strm.state ||
  15632. flush > Z_BLOCK || flush < 0) {
  15633. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15634. }
  15635. s = strm.state;
  15636. if (!strm.output ||
  15637. (!strm.input && strm.avail_in !== 0) ||
  15638. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15639. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15640. }
  15641. s.strm = strm; /* just in case */
  15642. old_flush = s.last_flush;
  15643. s.last_flush = flush;
  15644. /* Write the header */
  15645. if (s.status === INIT_STATE) {
  15646. if (s.wrap === 2) { // GZIP header
  15647. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15648. put_byte(s, 31);
  15649. put_byte(s, 139);
  15650. put_byte(s, 8);
  15651. if (!s.gzhead) { // s->gzhead == Z_NULL
  15652. put_byte(s, 0);
  15653. put_byte(s, 0);
  15654. put_byte(s, 0);
  15655. put_byte(s, 0);
  15656. put_byte(s, 0);
  15657. put_byte(s, s.level === 9 ? 2 :
  15658. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15659. 4 : 0));
  15660. put_byte(s, OS_CODE);
  15661. s.status = BUSY_STATE;
  15662. }
  15663. else {
  15664. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15665. (s.gzhead.hcrc ? 2 : 0) +
  15666. (!s.gzhead.extra ? 0 : 4) +
  15667. (!s.gzhead.name ? 0 : 8) +
  15668. (!s.gzhead.comment ? 0 : 16)
  15669. );
  15670. put_byte(s, s.gzhead.time & 0xff);
  15671. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15672. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15673. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15674. put_byte(s, s.level === 9 ? 2 :
  15675. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15676. 4 : 0));
  15677. put_byte(s, s.gzhead.os & 0xff);
  15678. if (s.gzhead.extra && s.gzhead.extra.length) {
  15679. put_byte(s, s.gzhead.extra.length & 0xff);
  15680. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15681. }
  15682. if (s.gzhead.hcrc) {
  15683. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15684. }
  15685. s.gzindex = 0;
  15686. s.status = EXTRA_STATE;
  15687. }
  15688. }
  15689. else // DEFLATE header
  15690. {
  15691. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15692. var level_flags = -1;
  15693. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15694. level_flags = 0;
  15695. } else if (s.level < 6) {
  15696. level_flags = 1;
  15697. } else if (s.level === 6) {
  15698. level_flags = 2;
  15699. } else {
  15700. level_flags = 3;
  15701. }
  15702. header |= (level_flags << 6);
  15703. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15704. header += 31 - (header % 31);
  15705. s.status = BUSY_STATE;
  15706. putShortMSB(s, header);
  15707. /* Save the adler32 of the preset dictionary: */
  15708. if (s.strstart !== 0) {
  15709. putShortMSB(s, strm.adler >>> 16);
  15710. putShortMSB(s, strm.adler & 0xffff);
  15711. }
  15712. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15713. }
  15714. }
  15715. //#ifdef GZIP
  15716. if (s.status === EXTRA_STATE) {
  15717. if (s.gzhead.extra/* != Z_NULL*/) {
  15718. beg = s.pending; /* start of bytes to update crc */
  15719. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15720. if (s.pending === s.pending_buf_size) {
  15721. if (s.gzhead.hcrc && s.pending > beg) {
  15722. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15723. }
  15724. flush_pending(strm);
  15725. beg = s.pending;
  15726. if (s.pending === s.pending_buf_size) {
  15727. break;
  15728. }
  15729. }
  15730. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15731. s.gzindex++;
  15732. }
  15733. if (s.gzhead.hcrc && s.pending > beg) {
  15734. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15735. }
  15736. if (s.gzindex === s.gzhead.extra.length) {
  15737. s.gzindex = 0;
  15738. s.status = NAME_STATE;
  15739. }
  15740. }
  15741. else {
  15742. s.status = NAME_STATE;
  15743. }
  15744. }
  15745. if (s.status === NAME_STATE) {
  15746. if (s.gzhead.name/* != Z_NULL*/) {
  15747. beg = s.pending; /* start of bytes to update crc */
  15748. //int val;
  15749. do {
  15750. if (s.pending === s.pending_buf_size) {
  15751. if (s.gzhead.hcrc && s.pending > beg) {
  15752. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15753. }
  15754. flush_pending(strm);
  15755. beg = s.pending;
  15756. if (s.pending === s.pending_buf_size) {
  15757. val = 1;
  15758. break;
  15759. }
  15760. }
  15761. // JS specific: little magic to add zero terminator to end of string
  15762. if (s.gzindex < s.gzhead.name.length) {
  15763. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15764. } else {
  15765. val = 0;
  15766. }
  15767. put_byte(s, val);
  15768. } while (val !== 0);
  15769. if (s.gzhead.hcrc && s.pending > beg) {
  15770. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15771. }
  15772. if (val === 0) {
  15773. s.gzindex = 0;
  15774. s.status = COMMENT_STATE;
  15775. }
  15776. }
  15777. else {
  15778. s.status = COMMENT_STATE;
  15779. }
  15780. }
  15781. if (s.status === COMMENT_STATE) {
  15782. if (s.gzhead.comment/* != Z_NULL*/) {
  15783. beg = s.pending; /* start of bytes to update crc */
  15784. //int val;
  15785. do {
  15786. if (s.pending === s.pending_buf_size) {
  15787. if (s.gzhead.hcrc && s.pending > beg) {
  15788. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15789. }
  15790. flush_pending(strm);
  15791. beg = s.pending;
  15792. if (s.pending === s.pending_buf_size) {
  15793. val = 1;
  15794. break;
  15795. }
  15796. }
  15797. // JS specific: little magic to add zero terminator to end of string
  15798. if (s.gzindex < s.gzhead.comment.length) {
  15799. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15800. } else {
  15801. val = 0;
  15802. }
  15803. put_byte(s, val);
  15804. } while (val !== 0);
  15805. if (s.gzhead.hcrc && s.pending > beg) {
  15806. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15807. }
  15808. if (val === 0) {
  15809. s.status = HCRC_STATE;
  15810. }
  15811. }
  15812. else {
  15813. s.status = HCRC_STATE;
  15814. }
  15815. }
  15816. if (s.status === HCRC_STATE) {
  15817. if (s.gzhead.hcrc) {
  15818. if (s.pending + 2 > s.pending_buf_size) {
  15819. flush_pending(strm);
  15820. }
  15821. if (s.pending + 2 <= s.pending_buf_size) {
  15822. put_byte(s, strm.adler & 0xff);
  15823. put_byte(s, (strm.adler >> 8) & 0xff);
  15824. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15825. s.status = BUSY_STATE;
  15826. }
  15827. }
  15828. else {
  15829. s.status = BUSY_STATE;
  15830. }
  15831. }
  15832. //#endif
  15833. /* Flush as much pending output as possible */
  15834. if (s.pending !== 0) {
  15835. flush_pending(strm);
  15836. if (strm.avail_out === 0) {
  15837. /* Since avail_out is 0, deflate will be called again with
  15838. * more output space, but possibly with both pending and
  15839. * avail_in equal to zero. There won't be anything to do,
  15840. * but this is not an error situation so make sure we
  15841. * return OK instead of BUF_ERROR at next call of deflate:
  15842. */
  15843. s.last_flush = -1;
  15844. return Z_OK;
  15845. }
  15846. /* Make sure there is something to do and avoid duplicate consecutive
  15847. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15848. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15849. */
  15850. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15851. flush !== Z_FINISH) {
  15852. return err(strm, Z_BUF_ERROR);
  15853. }
  15854. /* User must not provide more input after the first FINISH: */
  15855. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15856. return err(strm, Z_BUF_ERROR);
  15857. }
  15858. /* Start a new block or continue the current one.
  15859. */
  15860. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15861. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15862. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15863. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15864. configuration_table[s.level].func(s, flush));
  15865. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15866. s.status = FINISH_STATE;
  15867. }
  15868. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15869. if (strm.avail_out === 0) {
  15870. s.last_flush = -1;
  15871. /* avoid BUF_ERROR next call, see above */
  15872. }
  15873. return Z_OK;
  15874. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15875. * of deflate should use the same flush parameter to make sure
  15876. * that the flush is complete. So we don't have to output an
  15877. * empty block here, this will be done at next call. This also
  15878. * ensures that for a very small output buffer, we emit at most
  15879. * one empty block.
  15880. */
  15881. }
  15882. if (bstate === BS_BLOCK_DONE) {
  15883. if (flush === Z_PARTIAL_FLUSH) {
  15884. trees._tr_align(s);
  15885. }
  15886. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15887. trees._tr_stored_block(s, 0, 0, false);
  15888. /* For a full flush, this empty block will be recognized
  15889. * as a special marker by inflate_sync().
  15890. */
  15891. if (flush === Z_FULL_FLUSH) {
  15892. /*** CLEAR_HASH(s); ***/ /* forget history */
  15893. zero(s.head); // Fill with NIL (= 0);
  15894. if (s.lookahead === 0) {
  15895. s.strstart = 0;
  15896. s.block_start = 0;
  15897. s.insert = 0;
  15898. }
  15899. }
  15900. }
  15901. flush_pending(strm);
  15902. if (strm.avail_out === 0) {
  15903. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15904. return Z_OK;
  15905. }
  15906. }
  15907. }
  15908. //Assert(strm->avail_out > 0, "bug2");
  15909. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15910. if (flush !== Z_FINISH) { return Z_OK; }
  15911. if (s.wrap <= 0) { return Z_STREAM_END; }
  15912. /* Write the trailer */
  15913. if (s.wrap === 2) {
  15914. put_byte(s, strm.adler & 0xff);
  15915. put_byte(s, (strm.adler >> 8) & 0xff);
  15916. put_byte(s, (strm.adler >> 16) & 0xff);
  15917. put_byte(s, (strm.adler >> 24) & 0xff);
  15918. put_byte(s, strm.total_in & 0xff);
  15919. put_byte(s, (strm.total_in >> 8) & 0xff);
  15920. put_byte(s, (strm.total_in >> 16) & 0xff);
  15921. put_byte(s, (strm.total_in >> 24) & 0xff);
  15922. }
  15923. else
  15924. {
  15925. putShortMSB(s, strm.adler >>> 16);
  15926. putShortMSB(s, strm.adler & 0xffff);
  15927. }
  15928. flush_pending(strm);
  15929. /* If avail_out is zero, the application will call deflate again
  15930. * to flush the rest.
  15931. */
  15932. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15933. /* write the trailer only once! */
  15934. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15935. }
  15936. function deflateEnd(strm) {
  15937. var status;
  15938. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15939. return Z_STREAM_ERROR;
  15940. }
  15941. status = strm.state.status;
  15942. if (status !== INIT_STATE &&
  15943. status !== EXTRA_STATE &&
  15944. status !== NAME_STATE &&
  15945. status !== COMMENT_STATE &&
  15946. status !== HCRC_STATE &&
  15947. status !== BUSY_STATE &&
  15948. status !== FINISH_STATE
  15949. ) {
  15950. return err(strm, Z_STREAM_ERROR);
  15951. }
  15952. strm.state = null;
  15953. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15954. }
  15955. /* =========================================================================
  15956. * Copy the source state to the destination state
  15957. */
  15958. //function deflateCopy(dest, source) {
  15959. //
  15960. //}
  15961. exports.deflateInit = deflateInit;
  15962. exports.deflateInit2 = deflateInit2;
  15963. exports.deflateReset = deflateReset;
  15964. exports.deflateResetKeep = deflateResetKeep;
  15965. exports.deflateSetHeader = deflateSetHeader;
  15966. exports.deflate = deflate;
  15967. exports.deflateEnd = deflateEnd;
  15968. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15969. /* Not implemented
  15970. exports.deflateBound = deflateBound;
  15971. exports.deflateCopy = deflateCopy;
  15972. exports.deflateSetDictionary = deflateSetDictionary;
  15973. exports.deflateParams = deflateParams;
  15974. exports.deflatePending = deflatePending;
  15975. exports.deflatePrime = deflatePrime;
  15976. exports.deflateTune = deflateTune;
  15977. */
  15978. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./messages":62,"./trees":63}],58:[function(require,module,exports){
  15979. 'use strict';
  15980. function GZheader() {
  15981. /* true if compressed data believed to be text */
  15982. this.text = 0;
  15983. /* modification time */
  15984. this.time = 0;
  15985. /* extra flags (not used when writing a gzip file) */
  15986. this.xflags = 0;
  15987. /* operating system */
  15988. this.os = 0;
  15989. /* pointer to extra field or Z_NULL if none */
  15990. this.extra = null;
  15991. /* extra field length (valid if extra != Z_NULL) */
  15992. this.extra_len = 0; // Actually, we don't need it in JS,
  15993. // but leave for few code modifications
  15994. //
  15995. // Setup limits is not necessary because in js we should not preallocate memory
  15996. // for inflate use constant limit in 65536 bytes
  15997. //
  15998. /* space at extra (only when reading header) */
  15999. // this.extra_max = 0;
  16000. /* pointer to zero-terminated file name or Z_NULL */
  16001. this.name = '';
  16002. /* space at name (only when reading header) */
  16003. // this.name_max = 0;
  16004. /* pointer to zero-terminated comment or Z_NULL */
  16005. this.comment = '';
  16006. /* space at comment (only when reading header) */
  16007. // this.comm_max = 0;
  16008. /* true if there was or will be a header crc */
  16009. this.hcrc = 0;
  16010. /* true when done reading gzip header (not used when writing a gzip file) */
  16011. this.done = false;
  16012. }
  16013. module.exports = GZheader;
  16014. },{}],59:[function(require,module,exports){
  16015. 'use strict';
  16016. // See state defs from inflate.js
  16017. var BAD = 30; /* got a data error -- remain here until reset */
  16018. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16019. /*
  16020. Decode literal, length, and distance codes and write out the resulting
  16021. literal and match bytes until either not enough input or output is
  16022. available, an end-of-block is encountered, or a data error is encountered.
  16023. When large enough input and output buffers are supplied to inflate(), for
  16024. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  16025. inflate execution time is spent in this routine.
  16026. Entry assumptions:
  16027. state.mode === LEN
  16028. strm.avail_in >= 6
  16029. strm.avail_out >= 258
  16030. start >= strm.avail_out
  16031. state.bits < 8
  16032. On return, state.mode is one of:
  16033. LEN -- ran out of enough output space or enough available input
  16034. TYPE -- reached end of block code, inflate() to interpret next block
  16035. BAD -- error in block data
  16036. Notes:
  16037. - The maximum input bits used by a length/distance pair is 15 bits for the
  16038. length code, 5 bits for the length extra, 15 bits for the distance code,
  16039. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  16040. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  16041. checking for available input while decoding.
  16042. - The maximum bytes that a single length/distance pair can output is 258
  16043. bytes, which is the maximum length that can be coded. inflate_fast()
  16044. requires strm.avail_out >= 258 for each loop to avoid checking for
  16045. output space.
  16046. */
  16047. module.exports = function inflate_fast(strm, start) {
  16048. var state;
  16049. var _in; /* local strm.input */
  16050. var last; /* have enough input while in < last */
  16051. var _out; /* local strm.output */
  16052. var beg; /* inflate()'s initial strm.output */
  16053. var end; /* while out < end, enough space available */
  16054. //#ifdef INFLATE_STRICT
  16055. var dmax; /* maximum distance from zlib header */
  16056. //#endif
  16057. var wsize; /* window size or zero if not using window */
  16058. var whave; /* valid bytes in the window */
  16059. var wnext; /* window write index */
  16060. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  16061. var s_window; /* allocated sliding window, if wsize != 0 */
  16062. var hold; /* local strm.hold */
  16063. var bits; /* local strm.bits */
  16064. var lcode; /* local strm.lencode */
  16065. var dcode; /* local strm.distcode */
  16066. var lmask; /* mask for first level of length codes */
  16067. var dmask; /* mask for first level of distance codes */
  16068. var here; /* retrieved table entry */
  16069. var op; /* code bits, operation, extra bits, or */
  16070. /* window position, window bytes to copy */
  16071. var len; /* match length, unused bytes */
  16072. var dist; /* match distance */
  16073. var from; /* where to copy match from */
  16074. var from_source;
  16075. var input, output; // JS specific, because we have no pointers
  16076. /* copy state to local variables */
  16077. state = strm.state;
  16078. //here = state.here;
  16079. _in = strm.next_in;
  16080. input = strm.input;
  16081. last = _in + (strm.avail_in - 5);
  16082. _out = strm.next_out;
  16083. output = strm.output;
  16084. beg = _out - (start - strm.avail_out);
  16085. end = _out + (strm.avail_out - 257);
  16086. //#ifdef INFLATE_STRICT
  16087. dmax = state.dmax;
  16088. //#endif
  16089. wsize = state.wsize;
  16090. whave = state.whave;
  16091. wnext = state.wnext;
  16092. s_window = state.window;
  16093. hold = state.hold;
  16094. bits = state.bits;
  16095. lcode = state.lencode;
  16096. dcode = state.distcode;
  16097. lmask = (1 << state.lenbits) - 1;
  16098. dmask = (1 << state.distbits) - 1;
  16099. /* decode literals and length/distances until end-of-block or not enough
  16100. input data or output space */
  16101. top:
  16102. do {
  16103. if (bits < 15) {
  16104. hold += input[_in++] << bits;
  16105. bits += 8;
  16106. hold += input[_in++] << bits;
  16107. bits += 8;
  16108. }
  16109. here = lcode[hold & lmask];
  16110. dolen:
  16111. for (;;) { // Goto emulation
  16112. op = here >>> 24/*here.bits*/;
  16113. hold >>>= op;
  16114. bits -= op;
  16115. op = (here >>> 16) & 0xff/*here.op*/;
  16116. if (op === 0) { /* literal */
  16117. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16118. // "inflate: literal '%c'\n" :
  16119. // "inflate: literal 0x%02x\n", here.val));
  16120. output[_out++] = here & 0xffff/*here.val*/;
  16121. }
  16122. else if (op & 16) { /* length base */
  16123. len = here & 0xffff/*here.val*/;
  16124. op &= 15; /* number of extra bits */
  16125. if (op) {
  16126. if (bits < op) {
  16127. hold += input[_in++] << bits;
  16128. bits += 8;
  16129. }
  16130. len += hold & ((1 << op) - 1);
  16131. hold >>>= op;
  16132. bits -= op;
  16133. }
  16134. //Tracevv((stderr, "inflate: length %u\n", len));
  16135. if (bits < 15) {
  16136. hold += input[_in++] << bits;
  16137. bits += 8;
  16138. hold += input[_in++] << bits;
  16139. bits += 8;
  16140. }
  16141. here = dcode[hold & dmask];
  16142. dodist:
  16143. for (;;) { // goto emulation
  16144. op = here >>> 24/*here.bits*/;
  16145. hold >>>= op;
  16146. bits -= op;
  16147. op = (here >>> 16) & 0xff/*here.op*/;
  16148. if (op & 16) { /* distance base */
  16149. dist = here & 0xffff/*here.val*/;
  16150. op &= 15; /* number of extra bits */
  16151. if (bits < op) {
  16152. hold += input[_in++] << bits;
  16153. bits += 8;
  16154. if (bits < op) {
  16155. hold += input[_in++] << bits;
  16156. bits += 8;
  16157. }
  16158. }
  16159. dist += hold & ((1 << op) - 1);
  16160. //#ifdef INFLATE_STRICT
  16161. if (dist > dmax) {
  16162. strm.msg = 'invalid distance too far back';
  16163. state.mode = BAD;
  16164. break top;
  16165. }
  16166. //#endif
  16167. hold >>>= op;
  16168. bits -= op;
  16169. //Tracevv((stderr, "inflate: distance %u\n", dist));
  16170. op = _out - beg; /* max distance in output */
  16171. if (dist > op) { /* see if copy from window */
  16172. op = dist - op; /* distance back in window */
  16173. if (op > whave) {
  16174. if (state.sane) {
  16175. strm.msg = 'invalid distance too far back';
  16176. state.mode = BAD;
  16177. break top;
  16178. }
  16179. // (!) This block is disabled in zlib defailts,
  16180. // don't enable it for binary compatibility
  16181. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16182. // if (len <= op - whave) {
  16183. // do {
  16184. // output[_out++] = 0;
  16185. // } while (--len);
  16186. // continue top;
  16187. // }
  16188. // len -= op - whave;
  16189. // do {
  16190. // output[_out++] = 0;
  16191. // } while (--op > whave);
  16192. // if (op === 0) {
  16193. // from = _out - dist;
  16194. // do {
  16195. // output[_out++] = output[from++];
  16196. // } while (--len);
  16197. // continue top;
  16198. // }
  16199. //#endif
  16200. }
  16201. from = 0; // window index
  16202. from_source = s_window;
  16203. if (wnext === 0) { /* very common case */
  16204. from += wsize - op;
  16205. if (op < len) { /* some from window */
  16206. len -= op;
  16207. do {
  16208. output[_out++] = s_window[from++];
  16209. } while (--op);
  16210. from = _out - dist; /* rest from output */
  16211. from_source = output;
  16212. }
  16213. }
  16214. else if (wnext < op) { /* wrap around window */
  16215. from += wsize + wnext - op;
  16216. op -= wnext;
  16217. if (op < len) { /* some from end of window */
  16218. len -= op;
  16219. do {
  16220. output[_out++] = s_window[from++];
  16221. } while (--op);
  16222. from = 0;
  16223. if (wnext < len) { /* some from start of window */
  16224. op = wnext;
  16225. len -= op;
  16226. do {
  16227. output[_out++] = s_window[from++];
  16228. } while (--op);
  16229. from = _out - dist; /* rest from output */
  16230. from_source = output;
  16231. }
  16232. }
  16233. }
  16234. else { /* contiguous in window */
  16235. from += wnext - op;
  16236. if (op < len) { /* some from window */
  16237. len -= op;
  16238. do {
  16239. output[_out++] = s_window[from++];
  16240. } while (--op);
  16241. from = _out - dist; /* rest from output */
  16242. from_source = output;
  16243. }
  16244. }
  16245. while (len > 2) {
  16246. output[_out++] = from_source[from++];
  16247. output[_out++] = from_source[from++];
  16248. output[_out++] = from_source[from++];
  16249. len -= 3;
  16250. }
  16251. if (len) {
  16252. output[_out++] = from_source[from++];
  16253. if (len > 1) {
  16254. output[_out++] = from_source[from++];
  16255. }
  16256. }
  16257. }
  16258. else {
  16259. from = _out - dist; /* copy direct from output */
  16260. do { /* minimum length is three */
  16261. output[_out++] = output[from++];
  16262. output[_out++] = output[from++];
  16263. output[_out++] = output[from++];
  16264. len -= 3;
  16265. } while (len > 2);
  16266. if (len) {
  16267. output[_out++] = output[from++];
  16268. if (len > 1) {
  16269. output[_out++] = output[from++];
  16270. }
  16271. }
  16272. }
  16273. }
  16274. else if ((op & 64) === 0) { /* 2nd level distance code */
  16275. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16276. continue dodist;
  16277. }
  16278. else {
  16279. strm.msg = 'invalid distance code';
  16280. state.mode = BAD;
  16281. break top;
  16282. }
  16283. break; // need to emulate goto via "continue"
  16284. }
  16285. }
  16286. else if ((op & 64) === 0) { /* 2nd level length code */
  16287. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16288. continue dolen;
  16289. }
  16290. else if (op & 32) { /* end-of-block */
  16291. //Tracevv((stderr, "inflate: end of block\n"));
  16292. state.mode = TYPE;
  16293. break top;
  16294. }
  16295. else {
  16296. strm.msg = 'invalid literal/length code';
  16297. state.mode = BAD;
  16298. break top;
  16299. }
  16300. break; // need to emulate goto via "continue"
  16301. }
  16302. } while (_in < last && _out < end);
  16303. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  16304. len = bits >> 3;
  16305. _in -= len;
  16306. bits -= len << 3;
  16307. hold &= (1 << bits) - 1;
  16308. /* update state and return */
  16309. strm.next_in = _in;
  16310. strm.next_out = _out;
  16311. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  16312. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  16313. state.hold = hold;
  16314. state.bits = bits;
  16315. return;
  16316. };
  16317. },{}],60:[function(require,module,exports){
  16318. 'use strict';
  16319. var utils = require('../utils/common');
  16320. var adler32 = require('./adler32');
  16321. var crc32 = require('./crc32');
  16322. var inflate_fast = require('./inffast');
  16323. var inflate_table = require('./inftrees');
  16324. var CODES = 0;
  16325. var LENS = 1;
  16326. var DISTS = 2;
  16327. /* Public constants ==========================================================*/
  16328. /* ===========================================================================*/
  16329. /* Allowed flush values; see deflate() and inflate() below for details */
  16330. //var Z_NO_FLUSH = 0;
  16331. //var Z_PARTIAL_FLUSH = 1;
  16332. //var Z_SYNC_FLUSH = 2;
  16333. //var Z_FULL_FLUSH = 3;
  16334. var Z_FINISH = 4;
  16335. var Z_BLOCK = 5;
  16336. var Z_TREES = 6;
  16337. /* Return codes for the compression/decompression functions. Negative values
  16338. * are errors, positive values are used for special but normal events.
  16339. */
  16340. var Z_OK = 0;
  16341. var Z_STREAM_END = 1;
  16342. var Z_NEED_DICT = 2;
  16343. //var Z_ERRNO = -1;
  16344. var Z_STREAM_ERROR = -2;
  16345. var Z_DATA_ERROR = -3;
  16346. var Z_MEM_ERROR = -4;
  16347. var Z_BUF_ERROR = -5;
  16348. //var Z_VERSION_ERROR = -6;
  16349. /* The deflate compression method */
  16350. var Z_DEFLATED = 8;
  16351. /* STATES ====================================================================*/
  16352. /* ===========================================================================*/
  16353. var HEAD = 1; /* i: waiting for magic header */
  16354. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  16355. var TIME = 3; /* i: waiting for modification time (gzip) */
  16356. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  16357. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  16358. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  16359. var NAME = 7; /* i: waiting for end of file name (gzip) */
  16360. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  16361. var HCRC = 9; /* i: waiting for header crc (gzip) */
  16362. var DICTID = 10; /* i: waiting for dictionary check value */
  16363. var DICT = 11; /* waiting for inflateSetDictionary() call */
  16364. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16365. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  16366. var STORED = 14; /* i: waiting for stored size (length and complement) */
  16367. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  16368. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  16369. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  16370. var LENLENS = 18; /* i: waiting for code length code lengths */
  16371. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  16372. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  16373. var LEN = 21; /* i: waiting for length/lit/eob code */
  16374. var LENEXT = 22; /* i: waiting for length extra bits */
  16375. var DIST = 23; /* i: waiting for distance code */
  16376. var DISTEXT = 24; /* i: waiting for distance extra bits */
  16377. var MATCH = 25; /* o: waiting for output space to copy string */
  16378. var LIT = 26; /* o: waiting for output space to write literal */
  16379. var CHECK = 27; /* i: waiting for 32-bit check value */
  16380. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  16381. var DONE = 29; /* finished check, done -- remain here until reset */
  16382. var BAD = 30; /* got a data error -- remain here until reset */
  16383. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  16384. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  16385. /* ===========================================================================*/
  16386. var ENOUGH_LENS = 852;
  16387. var ENOUGH_DISTS = 592;
  16388. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16389. var MAX_WBITS = 15;
  16390. /* 32K LZ77 window */
  16391. var DEF_WBITS = MAX_WBITS;
  16392. function ZSWAP32(q) {
  16393. return (((q >>> 24) & 0xff) +
  16394. ((q >>> 8) & 0xff00) +
  16395. ((q & 0xff00) << 8) +
  16396. ((q & 0xff) << 24));
  16397. }
  16398. function InflateState() {
  16399. this.mode = 0; /* current inflate mode */
  16400. this.last = false; /* true if processing last block */
  16401. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16402. this.havedict = false; /* true if dictionary provided */
  16403. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  16404. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  16405. this.check = 0; /* protected copy of check value */
  16406. this.total = 0; /* protected copy of output count */
  16407. // TODO: may be {}
  16408. this.head = null; /* where to save gzip header information */
  16409. /* sliding window */
  16410. this.wbits = 0; /* log base 2 of requested window size */
  16411. this.wsize = 0; /* window size or zero if not using window */
  16412. this.whave = 0; /* valid bytes in the window */
  16413. this.wnext = 0; /* window write index */
  16414. this.window = null; /* allocated sliding window, if needed */
  16415. /* bit accumulator */
  16416. this.hold = 0; /* input bit accumulator */
  16417. this.bits = 0; /* number of bits in "in" */
  16418. /* for string and stored block copying */
  16419. this.length = 0; /* literal or length of data to copy */
  16420. this.offset = 0; /* distance back to copy string from */
  16421. /* for table and code decoding */
  16422. this.extra = 0; /* extra bits needed */
  16423. /* fixed and dynamic code tables */
  16424. this.lencode = null; /* starting table for length/literal codes */
  16425. this.distcode = null; /* starting table for distance codes */
  16426. this.lenbits = 0; /* index bits for lencode */
  16427. this.distbits = 0; /* index bits for distcode */
  16428. /* dynamic table building */
  16429. this.ncode = 0; /* number of code length code lengths */
  16430. this.nlen = 0; /* number of length code lengths */
  16431. this.ndist = 0; /* number of distance code lengths */
  16432. this.have = 0; /* number of code lengths in lens[] */
  16433. this.next = null; /* next available space in codes[] */
  16434. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  16435. this.work = new utils.Buf16(288); /* work area for code table building */
  16436. /*
  16437. because we don't have pointers in js, we use lencode and distcode directly
  16438. as buffers so we don't need codes
  16439. */
  16440. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  16441. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  16442. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  16443. this.sane = 0; /* if false, allow invalid distance too far */
  16444. this.back = 0; /* bits back of last unprocessed length/lit */
  16445. this.was = 0; /* initial length of match */
  16446. }
  16447. function inflateResetKeep(strm) {
  16448. var state;
  16449. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16450. state = strm.state;
  16451. strm.total_in = strm.total_out = state.total = 0;
  16452. strm.msg = ''; /*Z_NULL*/
  16453. if (state.wrap) { /* to support ill-conceived Java test suite */
  16454. strm.adler = state.wrap & 1;
  16455. }
  16456. state.mode = HEAD;
  16457. state.last = 0;
  16458. state.havedict = 0;
  16459. state.dmax = 32768;
  16460. state.head = null/*Z_NULL*/;
  16461. state.hold = 0;
  16462. state.bits = 0;
  16463. //state.lencode = state.distcode = state.next = state.codes;
  16464. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  16465. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  16466. state.sane = 1;
  16467. state.back = -1;
  16468. //Tracev((stderr, "inflate: reset\n"));
  16469. return Z_OK;
  16470. }
  16471. function inflateReset(strm) {
  16472. var state;
  16473. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16474. state = strm.state;
  16475. state.wsize = 0;
  16476. state.whave = 0;
  16477. state.wnext = 0;
  16478. return inflateResetKeep(strm);
  16479. }
  16480. function inflateReset2(strm, windowBits) {
  16481. var wrap;
  16482. var state;
  16483. /* get the state */
  16484. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16485. state = strm.state;
  16486. /* extract wrap request from windowBits parameter */
  16487. if (windowBits < 0) {
  16488. wrap = 0;
  16489. windowBits = -windowBits;
  16490. }
  16491. else {
  16492. wrap = (windowBits >> 4) + 1;
  16493. if (windowBits < 48) {
  16494. windowBits &= 15;
  16495. }
  16496. }
  16497. /* set number of window bits, free window if different */
  16498. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  16499. return Z_STREAM_ERROR;
  16500. }
  16501. if (state.window !== null && state.wbits !== windowBits) {
  16502. state.window = null;
  16503. }
  16504. /* update state and reset the rest of it */
  16505. state.wrap = wrap;
  16506. state.wbits = windowBits;
  16507. return inflateReset(strm);
  16508. }
  16509. function inflateInit2(strm, windowBits) {
  16510. var ret;
  16511. var state;
  16512. if (!strm) { return Z_STREAM_ERROR; }
  16513. //strm.msg = Z_NULL; /* in case we return an error */
  16514. state = new InflateState();
  16515. //if (state === Z_NULL) return Z_MEM_ERROR;
  16516. //Tracev((stderr, "inflate: allocated\n"));
  16517. strm.state = state;
  16518. state.window = null/*Z_NULL*/;
  16519. ret = inflateReset2(strm, windowBits);
  16520. if (ret !== Z_OK) {
  16521. strm.state = null/*Z_NULL*/;
  16522. }
  16523. return ret;
  16524. }
  16525. function inflateInit(strm) {
  16526. return inflateInit2(strm, DEF_WBITS);
  16527. }
  16528. /*
  16529. Return state with length and distance decoding tables and index sizes set to
  16530. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  16531. If BUILDFIXED is defined, then instead this routine builds the tables the
  16532. first time it's called, and returns those tables the first time and
  16533. thereafter. This reduces the size of the code by about 2K bytes, in
  16534. exchange for a little execution time. However, BUILDFIXED should not be
  16535. used for threaded applications, since the rewriting of the tables and virgin
  16536. may not be thread-safe.
  16537. */
  16538. var virgin = true;
  16539. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  16540. function fixedtables(state) {
  16541. /* build fixed huffman tables if first call (may not be thread safe) */
  16542. if (virgin) {
  16543. var sym;
  16544. lenfix = new utils.Buf32(512);
  16545. distfix = new utils.Buf32(32);
  16546. /* literal/length table */
  16547. sym = 0;
  16548. while (sym < 144) { state.lens[sym++] = 8; }
  16549. while (sym < 256) { state.lens[sym++] = 9; }
  16550. while (sym < 280) { state.lens[sym++] = 7; }
  16551. while (sym < 288) { state.lens[sym++] = 8; }
  16552. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  16553. /* distance table */
  16554. sym = 0;
  16555. while (sym < 32) { state.lens[sym++] = 5; }
  16556. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  16557. /* do this just once */
  16558. virgin = false;
  16559. }
  16560. state.lencode = lenfix;
  16561. state.lenbits = 9;
  16562. state.distcode = distfix;
  16563. state.distbits = 5;
  16564. }
  16565. /*
  16566. Update the window with the last wsize (normally 32K) bytes written before
  16567. returning. If window does not exist yet, create it. This is only called
  16568. when a window is already in use, or when output has been written during this
  16569. inflate call, but the end of the deflate stream has not been reached yet.
  16570. It is also called to create a window for dictionary data when a dictionary
  16571. is loaded.
  16572. Providing output buffers larger than 32K to inflate() should provide a speed
  16573. advantage, since only the last 32K of output is copied to the sliding window
  16574. upon return from inflate(), and since all distances after the first 32K of
  16575. output will fall in the output data, making match copies simpler and faster.
  16576. The advantage may be dependent on the size of the processor's data caches.
  16577. */
  16578. function updatewindow(strm, src, end, copy) {
  16579. var dist;
  16580. var state = strm.state;
  16581. /* if it hasn't been done already, allocate space for the window */
  16582. if (state.window === null) {
  16583. state.wsize = 1 << state.wbits;
  16584. state.wnext = 0;
  16585. state.whave = 0;
  16586. state.window = new utils.Buf8(state.wsize);
  16587. }
  16588. /* copy state->wsize or less output bytes into the circular window */
  16589. if (copy >= state.wsize) {
  16590. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  16591. state.wnext = 0;
  16592. state.whave = state.wsize;
  16593. }
  16594. else {
  16595. dist = state.wsize - state.wnext;
  16596. if (dist > copy) {
  16597. dist = copy;
  16598. }
  16599. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16600. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  16601. copy -= dist;
  16602. if (copy) {
  16603. //zmemcpy(state->window, end - copy, copy);
  16604. utils.arraySet(state.window,src, end - copy, copy, 0);
  16605. state.wnext = copy;
  16606. state.whave = state.wsize;
  16607. }
  16608. else {
  16609. state.wnext += dist;
  16610. if (state.wnext === state.wsize) { state.wnext = 0; }
  16611. if (state.whave < state.wsize) { state.whave += dist; }
  16612. }
  16613. }
  16614. return 0;
  16615. }
  16616. function inflate(strm, flush) {
  16617. var state;
  16618. var input, output; // input/output buffers
  16619. var next; /* next input INDEX */
  16620. var put; /* next output INDEX */
  16621. var have, left; /* available input and output */
  16622. var hold; /* bit buffer */
  16623. var bits; /* bits in bit buffer */
  16624. var _in, _out; /* save starting available input and output */
  16625. var copy; /* number of stored or match bytes to copy */
  16626. var from; /* where to copy match bytes from */
  16627. var from_source;
  16628. var here = 0; /* current decoding table entry */
  16629. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16630. //var last; /* parent table entry */
  16631. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16632. var len; /* length to copy for repeats, bits to drop */
  16633. var ret; /* return code */
  16634. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16635. var opts;
  16636. var n; // temporary var for NEED_BITS
  16637. var order = /* permutation of code lengths */
  16638. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16639. if (!strm || !strm.state || !strm.output ||
  16640. (!strm.input && strm.avail_in !== 0)) {
  16641. return Z_STREAM_ERROR;
  16642. }
  16643. state = strm.state;
  16644. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16645. //--- LOAD() ---
  16646. put = strm.next_out;
  16647. output = strm.output;
  16648. left = strm.avail_out;
  16649. next = strm.next_in;
  16650. input = strm.input;
  16651. have = strm.avail_in;
  16652. hold = state.hold;
  16653. bits = state.bits;
  16654. //---
  16655. _in = have;
  16656. _out = left;
  16657. ret = Z_OK;
  16658. inf_leave: // goto emulation
  16659. for (;;) {
  16660. switch (state.mode) {
  16661. case HEAD:
  16662. if (state.wrap === 0) {
  16663. state.mode = TYPEDO;
  16664. break;
  16665. }
  16666. //=== NEEDBITS(16);
  16667. while (bits < 16) {
  16668. if (have === 0) { break inf_leave; }
  16669. have--;
  16670. hold += input[next++] << bits;
  16671. bits += 8;
  16672. }
  16673. //===//
  16674. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16675. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16676. //=== CRC2(state.check, hold);
  16677. hbuf[0] = hold & 0xff;
  16678. hbuf[1] = (hold >>> 8) & 0xff;
  16679. state.check = crc32(state.check, hbuf, 2, 0);
  16680. //===//
  16681. //=== INITBITS();
  16682. hold = 0;
  16683. bits = 0;
  16684. //===//
  16685. state.mode = FLAGS;
  16686. break;
  16687. }
  16688. state.flags = 0; /* expect zlib header */
  16689. if (state.head) {
  16690. state.head.done = false;
  16691. }
  16692. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16693. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16694. strm.msg = 'incorrect header check';
  16695. state.mode = BAD;
  16696. break;
  16697. }
  16698. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16699. strm.msg = 'unknown compression method';
  16700. state.mode = BAD;
  16701. break;
  16702. }
  16703. //--- DROPBITS(4) ---//
  16704. hold >>>= 4;
  16705. bits -= 4;
  16706. //---//
  16707. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16708. if (state.wbits === 0) {
  16709. state.wbits = len;
  16710. }
  16711. else if (len > state.wbits) {
  16712. strm.msg = 'invalid window size';
  16713. state.mode = BAD;
  16714. break;
  16715. }
  16716. state.dmax = 1 << len;
  16717. //Tracev((stderr, "inflate: zlib header ok\n"));
  16718. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16719. state.mode = hold & 0x200 ? DICTID : TYPE;
  16720. //=== INITBITS();
  16721. hold = 0;
  16722. bits = 0;
  16723. //===//
  16724. break;
  16725. case FLAGS:
  16726. //=== NEEDBITS(16); */
  16727. while (bits < 16) {
  16728. if (have === 0) { break inf_leave; }
  16729. have--;
  16730. hold += input[next++] << bits;
  16731. bits += 8;
  16732. }
  16733. //===//
  16734. state.flags = hold;
  16735. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16736. strm.msg = 'unknown compression method';
  16737. state.mode = BAD;
  16738. break;
  16739. }
  16740. if (state.flags & 0xe000) {
  16741. strm.msg = 'unknown header flags set';
  16742. state.mode = BAD;
  16743. break;
  16744. }
  16745. if (state.head) {
  16746. state.head.text = ((hold >> 8) & 1);
  16747. }
  16748. if (state.flags & 0x0200) {
  16749. //=== CRC2(state.check, hold);
  16750. hbuf[0] = hold & 0xff;
  16751. hbuf[1] = (hold >>> 8) & 0xff;
  16752. state.check = crc32(state.check, hbuf, 2, 0);
  16753. //===//
  16754. }
  16755. //=== INITBITS();
  16756. hold = 0;
  16757. bits = 0;
  16758. //===//
  16759. state.mode = TIME;
  16760. /* falls through */
  16761. case TIME:
  16762. //=== NEEDBITS(32); */
  16763. while (bits < 32) {
  16764. if (have === 0) { break inf_leave; }
  16765. have--;
  16766. hold += input[next++] << bits;
  16767. bits += 8;
  16768. }
  16769. //===//
  16770. if (state.head) {
  16771. state.head.time = hold;
  16772. }
  16773. if (state.flags & 0x0200) {
  16774. //=== CRC4(state.check, hold)
  16775. hbuf[0] = hold & 0xff;
  16776. hbuf[1] = (hold >>> 8) & 0xff;
  16777. hbuf[2] = (hold >>> 16) & 0xff;
  16778. hbuf[3] = (hold >>> 24) & 0xff;
  16779. state.check = crc32(state.check, hbuf, 4, 0);
  16780. //===
  16781. }
  16782. //=== INITBITS();
  16783. hold = 0;
  16784. bits = 0;
  16785. //===//
  16786. state.mode = OS;
  16787. /* falls through */
  16788. case OS:
  16789. //=== NEEDBITS(16); */
  16790. while (bits < 16) {
  16791. if (have === 0) { break inf_leave; }
  16792. have--;
  16793. hold += input[next++] << bits;
  16794. bits += 8;
  16795. }
  16796. //===//
  16797. if (state.head) {
  16798. state.head.xflags = (hold & 0xff);
  16799. state.head.os = (hold >> 8);
  16800. }
  16801. if (state.flags & 0x0200) {
  16802. //=== CRC2(state.check, hold);
  16803. hbuf[0] = hold & 0xff;
  16804. hbuf[1] = (hold >>> 8) & 0xff;
  16805. state.check = crc32(state.check, hbuf, 2, 0);
  16806. //===//
  16807. }
  16808. //=== INITBITS();
  16809. hold = 0;
  16810. bits = 0;
  16811. //===//
  16812. state.mode = EXLEN;
  16813. /* falls through */
  16814. case EXLEN:
  16815. if (state.flags & 0x0400) {
  16816. //=== NEEDBITS(16); */
  16817. while (bits < 16) {
  16818. if (have === 0) { break inf_leave; }
  16819. have--;
  16820. hold += input[next++] << bits;
  16821. bits += 8;
  16822. }
  16823. //===//
  16824. state.length = hold;
  16825. if (state.head) {
  16826. state.head.extra_len = hold;
  16827. }
  16828. if (state.flags & 0x0200) {
  16829. //=== CRC2(state.check, hold);
  16830. hbuf[0] = hold & 0xff;
  16831. hbuf[1] = (hold >>> 8) & 0xff;
  16832. state.check = crc32(state.check, hbuf, 2, 0);
  16833. //===//
  16834. }
  16835. //=== INITBITS();
  16836. hold = 0;
  16837. bits = 0;
  16838. //===//
  16839. }
  16840. else if (state.head) {
  16841. state.head.extra = null/*Z_NULL*/;
  16842. }
  16843. state.mode = EXTRA;
  16844. /* falls through */
  16845. case EXTRA:
  16846. if (state.flags & 0x0400) {
  16847. copy = state.length;
  16848. if (copy > have) { copy = have; }
  16849. if (copy) {
  16850. if (state.head) {
  16851. len = state.head.extra_len - state.length;
  16852. if (!state.head.extra) {
  16853. // Use untyped array for more conveniend processing later
  16854. state.head.extra = new Array(state.head.extra_len);
  16855. }
  16856. utils.arraySet(
  16857. state.head.extra,
  16858. input,
  16859. next,
  16860. // extra field is limited to 65536 bytes
  16861. // - no need for additional size check
  16862. copy,
  16863. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16864. len
  16865. );
  16866. //zmemcpy(state.head.extra + len, next,
  16867. // len + copy > state.head.extra_max ?
  16868. // state.head.extra_max - len : copy);
  16869. }
  16870. if (state.flags & 0x0200) {
  16871. state.check = crc32(state.check, input, copy, next);
  16872. }
  16873. have -= copy;
  16874. next += copy;
  16875. state.length -= copy;
  16876. }
  16877. if (state.length) { break inf_leave; }
  16878. }
  16879. state.length = 0;
  16880. state.mode = NAME;
  16881. /* falls through */
  16882. case NAME:
  16883. if (state.flags & 0x0800) {
  16884. if (have === 0) { break inf_leave; }
  16885. copy = 0;
  16886. do {
  16887. // TODO: 2 or 1 bytes?
  16888. len = input[next + copy++];
  16889. /* use constant limit because in js we should not preallocate memory */
  16890. if (state.head && len &&
  16891. (state.length < 65536 /*state.head.name_max*/)) {
  16892. state.head.name += String.fromCharCode(len);
  16893. }
  16894. } while (len && copy < have);
  16895. if (state.flags & 0x0200) {
  16896. state.check = crc32(state.check, input, copy, next);
  16897. }
  16898. have -= copy;
  16899. next += copy;
  16900. if (len) { break inf_leave; }
  16901. }
  16902. else if (state.head) {
  16903. state.head.name = null;
  16904. }
  16905. state.length = 0;
  16906. state.mode = COMMENT;
  16907. /* falls through */
  16908. case COMMENT:
  16909. if (state.flags & 0x1000) {
  16910. if (have === 0) { break inf_leave; }
  16911. copy = 0;
  16912. do {
  16913. len = input[next + copy++];
  16914. /* use constant limit because in js we should not preallocate memory */
  16915. if (state.head && len &&
  16916. (state.length < 65536 /*state.head.comm_max*/)) {
  16917. state.head.comment += String.fromCharCode(len);
  16918. }
  16919. } while (len && copy < have);
  16920. if (state.flags & 0x0200) {
  16921. state.check = crc32(state.check, input, copy, next);
  16922. }
  16923. have -= copy;
  16924. next += copy;
  16925. if (len) { break inf_leave; }
  16926. }
  16927. else if (state.head) {
  16928. state.head.comment = null;
  16929. }
  16930. state.mode = HCRC;
  16931. /* falls through */
  16932. case HCRC:
  16933. if (state.flags & 0x0200) {
  16934. //=== NEEDBITS(16); */
  16935. while (bits < 16) {
  16936. if (have === 0) { break inf_leave; }
  16937. have--;
  16938. hold += input[next++] << bits;
  16939. bits += 8;
  16940. }
  16941. //===//
  16942. if (hold !== (state.check & 0xffff)) {
  16943. strm.msg = 'header crc mismatch';
  16944. state.mode = BAD;
  16945. break;
  16946. }
  16947. //=== INITBITS();
  16948. hold = 0;
  16949. bits = 0;
  16950. //===//
  16951. }
  16952. if (state.head) {
  16953. state.head.hcrc = ((state.flags >> 9) & 1);
  16954. state.head.done = true;
  16955. }
  16956. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16957. state.mode = TYPE;
  16958. break;
  16959. case DICTID:
  16960. //=== NEEDBITS(32); */
  16961. while (bits < 32) {
  16962. if (have === 0) { break inf_leave; }
  16963. have--;
  16964. hold += input[next++] << bits;
  16965. bits += 8;
  16966. }
  16967. //===//
  16968. strm.adler = state.check = ZSWAP32(hold);
  16969. //=== INITBITS();
  16970. hold = 0;
  16971. bits = 0;
  16972. //===//
  16973. state.mode = DICT;
  16974. /* falls through */
  16975. case DICT:
  16976. if (state.havedict === 0) {
  16977. //--- RESTORE() ---
  16978. strm.next_out = put;
  16979. strm.avail_out = left;
  16980. strm.next_in = next;
  16981. strm.avail_in = have;
  16982. state.hold = hold;
  16983. state.bits = bits;
  16984. //---
  16985. return Z_NEED_DICT;
  16986. }
  16987. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16988. state.mode = TYPE;
  16989. /* falls through */
  16990. case TYPE:
  16991. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16992. /* falls through */
  16993. case TYPEDO:
  16994. if (state.last) {
  16995. //--- BYTEBITS() ---//
  16996. hold >>>= bits & 7;
  16997. bits -= bits & 7;
  16998. //---//
  16999. state.mode = CHECK;
  17000. break;
  17001. }
  17002. //=== NEEDBITS(3); */
  17003. while (bits < 3) {
  17004. if (have === 0) { break inf_leave; }
  17005. have--;
  17006. hold += input[next++] << bits;
  17007. bits += 8;
  17008. }
  17009. //===//
  17010. state.last = (hold & 0x01)/*BITS(1)*/;
  17011. //--- DROPBITS(1) ---//
  17012. hold >>>= 1;
  17013. bits -= 1;
  17014. //---//
  17015. switch ((hold & 0x03)/*BITS(2)*/) {
  17016. case 0: /* stored block */
  17017. //Tracev((stderr, "inflate: stored block%s\n",
  17018. // state.last ? " (last)" : ""));
  17019. state.mode = STORED;
  17020. break;
  17021. case 1: /* fixed block */
  17022. fixedtables(state);
  17023. //Tracev((stderr, "inflate: fixed codes block%s\n",
  17024. // state.last ? " (last)" : ""));
  17025. state.mode = LEN_; /* decode codes */
  17026. if (flush === Z_TREES) {
  17027. //--- DROPBITS(2) ---//
  17028. hold >>>= 2;
  17029. bits -= 2;
  17030. //---//
  17031. break inf_leave;
  17032. }
  17033. break;
  17034. case 2: /* dynamic block */
  17035. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  17036. // state.last ? " (last)" : ""));
  17037. state.mode = TABLE;
  17038. break;
  17039. case 3:
  17040. strm.msg = 'invalid block type';
  17041. state.mode = BAD;
  17042. }
  17043. //--- DROPBITS(2) ---//
  17044. hold >>>= 2;
  17045. bits -= 2;
  17046. //---//
  17047. break;
  17048. case STORED:
  17049. //--- BYTEBITS() ---// /* go to byte boundary */
  17050. hold >>>= bits & 7;
  17051. bits -= bits & 7;
  17052. //---//
  17053. //=== NEEDBITS(32); */
  17054. while (bits < 32) {
  17055. if (have === 0) { break inf_leave; }
  17056. have--;
  17057. hold += input[next++] << bits;
  17058. bits += 8;
  17059. }
  17060. //===//
  17061. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  17062. strm.msg = 'invalid stored block lengths';
  17063. state.mode = BAD;
  17064. break;
  17065. }
  17066. state.length = hold & 0xffff;
  17067. //Tracev((stderr, "inflate: stored length %u\n",
  17068. // state.length));
  17069. //=== INITBITS();
  17070. hold = 0;
  17071. bits = 0;
  17072. //===//
  17073. state.mode = COPY_;
  17074. if (flush === Z_TREES) { break inf_leave; }
  17075. /* falls through */
  17076. case COPY_:
  17077. state.mode = COPY;
  17078. /* falls through */
  17079. case COPY:
  17080. copy = state.length;
  17081. if (copy) {
  17082. if (copy > have) { copy = have; }
  17083. if (copy > left) { copy = left; }
  17084. if (copy === 0) { break inf_leave; }
  17085. //--- zmemcpy(put, next, copy); ---
  17086. utils.arraySet(output, input, next, copy, put);
  17087. //---//
  17088. have -= copy;
  17089. next += copy;
  17090. left -= copy;
  17091. put += copy;
  17092. state.length -= copy;
  17093. break;
  17094. }
  17095. //Tracev((stderr, "inflate: stored end\n"));
  17096. state.mode = TYPE;
  17097. break;
  17098. case TABLE:
  17099. //=== NEEDBITS(14); */
  17100. while (bits < 14) {
  17101. if (have === 0) { break inf_leave; }
  17102. have--;
  17103. hold += input[next++] << bits;
  17104. bits += 8;
  17105. }
  17106. //===//
  17107. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  17108. //--- DROPBITS(5) ---//
  17109. hold >>>= 5;
  17110. bits -= 5;
  17111. //---//
  17112. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  17113. //--- DROPBITS(5) ---//
  17114. hold >>>= 5;
  17115. bits -= 5;
  17116. //---//
  17117. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  17118. //--- DROPBITS(4) ---//
  17119. hold >>>= 4;
  17120. bits -= 4;
  17121. //---//
  17122. //#ifndef PKZIP_BUG_WORKAROUND
  17123. if (state.nlen > 286 || state.ndist > 30) {
  17124. strm.msg = 'too many length or distance symbols';
  17125. state.mode = BAD;
  17126. break;
  17127. }
  17128. //#endif
  17129. //Tracev((stderr, "inflate: table sizes ok\n"));
  17130. state.have = 0;
  17131. state.mode = LENLENS;
  17132. /* falls through */
  17133. case LENLENS:
  17134. while (state.have < state.ncode) {
  17135. //=== NEEDBITS(3);
  17136. while (bits < 3) {
  17137. if (have === 0) { break inf_leave; }
  17138. have--;
  17139. hold += input[next++] << bits;
  17140. bits += 8;
  17141. }
  17142. //===//
  17143. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  17144. //--- DROPBITS(3) ---//
  17145. hold >>>= 3;
  17146. bits -= 3;
  17147. //---//
  17148. }
  17149. while (state.have < 19) {
  17150. state.lens[order[state.have++]] = 0;
  17151. }
  17152. // We have separate tables & no pointers. 2 commented lines below not needed.
  17153. //state.next = state.codes;
  17154. //state.lencode = state.next;
  17155. // Switch to use dynamic table
  17156. state.lencode = state.lendyn;
  17157. state.lenbits = 7;
  17158. opts = {bits: state.lenbits};
  17159. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  17160. state.lenbits = opts.bits;
  17161. if (ret) {
  17162. strm.msg = 'invalid code lengths set';
  17163. state.mode = BAD;
  17164. break;
  17165. }
  17166. //Tracev((stderr, "inflate: code lengths ok\n"));
  17167. state.have = 0;
  17168. state.mode = CODELENS;
  17169. /* falls through */
  17170. case CODELENS:
  17171. while (state.have < state.nlen + state.ndist) {
  17172. for (;;) {
  17173. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  17174. here_bits = here >>> 24;
  17175. here_op = (here >>> 16) & 0xff;
  17176. here_val = here & 0xffff;
  17177. if ((here_bits) <= bits) { break; }
  17178. //--- PULLBYTE() ---//
  17179. if (have === 0) { break inf_leave; }
  17180. have--;
  17181. hold += input[next++] << bits;
  17182. bits += 8;
  17183. //---//
  17184. }
  17185. if (here_val < 16) {
  17186. //--- DROPBITS(here.bits) ---//
  17187. hold >>>= here_bits;
  17188. bits -= here_bits;
  17189. //---//
  17190. state.lens[state.have++] = here_val;
  17191. }
  17192. else {
  17193. if (here_val === 16) {
  17194. //=== NEEDBITS(here.bits + 2);
  17195. n = here_bits + 2;
  17196. while (bits < n) {
  17197. if (have === 0) { break inf_leave; }
  17198. have--;
  17199. hold += input[next++] << bits;
  17200. bits += 8;
  17201. }
  17202. //===//
  17203. //--- DROPBITS(here.bits) ---//
  17204. hold >>>= here_bits;
  17205. bits -= here_bits;
  17206. //---//
  17207. if (state.have === 0) {
  17208. strm.msg = 'invalid bit length repeat';
  17209. state.mode = BAD;
  17210. break;
  17211. }
  17212. len = state.lens[state.have - 1];
  17213. copy = 3 + (hold & 0x03);//BITS(2);
  17214. //--- DROPBITS(2) ---//
  17215. hold >>>= 2;
  17216. bits -= 2;
  17217. //---//
  17218. }
  17219. else if (here_val === 17) {
  17220. //=== NEEDBITS(here.bits + 3);
  17221. n = here_bits + 3;
  17222. while (bits < n) {
  17223. if (have === 0) { break inf_leave; }
  17224. have--;
  17225. hold += input[next++] << bits;
  17226. bits += 8;
  17227. }
  17228. //===//
  17229. //--- DROPBITS(here.bits) ---//
  17230. hold >>>= here_bits;
  17231. bits -= here_bits;
  17232. //---//
  17233. len = 0;
  17234. copy = 3 + (hold & 0x07);//BITS(3);
  17235. //--- DROPBITS(3) ---//
  17236. hold >>>= 3;
  17237. bits -= 3;
  17238. //---//
  17239. }
  17240. else {
  17241. //=== NEEDBITS(here.bits + 7);
  17242. n = here_bits + 7;
  17243. while (bits < n) {
  17244. if (have === 0) { break inf_leave; }
  17245. have--;
  17246. hold += input[next++] << bits;
  17247. bits += 8;
  17248. }
  17249. //===//
  17250. //--- DROPBITS(here.bits) ---//
  17251. hold >>>= here_bits;
  17252. bits -= here_bits;
  17253. //---//
  17254. len = 0;
  17255. copy = 11 + (hold & 0x7f);//BITS(7);
  17256. //--- DROPBITS(7) ---//
  17257. hold >>>= 7;
  17258. bits -= 7;
  17259. //---//
  17260. }
  17261. if (state.have + copy > state.nlen + state.ndist) {
  17262. strm.msg = 'invalid bit length repeat';
  17263. state.mode = BAD;
  17264. break;
  17265. }
  17266. while (copy--) {
  17267. state.lens[state.have++] = len;
  17268. }
  17269. }
  17270. }
  17271. /* handle error breaks in while */
  17272. if (state.mode === BAD) { break; }
  17273. /* check for end-of-block code (better have one) */
  17274. if (state.lens[256] === 0) {
  17275. strm.msg = 'invalid code -- missing end-of-block';
  17276. state.mode = BAD;
  17277. break;
  17278. }
  17279. /* build code tables -- note: do not change the lenbits or distbits
  17280. values here (9 and 6) without reading the comments in inftrees.h
  17281. concerning the ENOUGH constants, which depend on those values */
  17282. state.lenbits = 9;
  17283. opts = {bits: state.lenbits};
  17284. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  17285. // We have separate tables & no pointers. 2 commented lines below not needed.
  17286. // state.next_index = opts.table_index;
  17287. state.lenbits = opts.bits;
  17288. // state.lencode = state.next;
  17289. if (ret) {
  17290. strm.msg = 'invalid literal/lengths set';
  17291. state.mode = BAD;
  17292. break;
  17293. }
  17294. state.distbits = 6;
  17295. //state.distcode.copy(state.codes);
  17296. // Switch to use dynamic table
  17297. state.distcode = state.distdyn;
  17298. opts = {bits: state.distbits};
  17299. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  17300. // We have separate tables & no pointers. 2 commented lines below not needed.
  17301. // state.next_index = opts.table_index;
  17302. state.distbits = opts.bits;
  17303. // state.distcode = state.next;
  17304. if (ret) {
  17305. strm.msg = 'invalid distances set';
  17306. state.mode = BAD;
  17307. break;
  17308. }
  17309. //Tracev((stderr, 'inflate: codes ok\n'));
  17310. state.mode = LEN_;
  17311. if (flush === Z_TREES) { break inf_leave; }
  17312. /* falls through */
  17313. case LEN_:
  17314. state.mode = LEN;
  17315. /* falls through */
  17316. case LEN:
  17317. if (have >= 6 && left >= 258) {
  17318. //--- RESTORE() ---
  17319. strm.next_out = put;
  17320. strm.avail_out = left;
  17321. strm.next_in = next;
  17322. strm.avail_in = have;
  17323. state.hold = hold;
  17324. state.bits = bits;
  17325. //---
  17326. inflate_fast(strm, _out);
  17327. //--- LOAD() ---
  17328. put = strm.next_out;
  17329. output = strm.output;
  17330. left = strm.avail_out;
  17331. next = strm.next_in;
  17332. input = strm.input;
  17333. have = strm.avail_in;
  17334. hold = state.hold;
  17335. bits = state.bits;
  17336. //---
  17337. if (state.mode === TYPE) {
  17338. state.back = -1;
  17339. }
  17340. break;
  17341. }
  17342. state.back = 0;
  17343. for (;;) {
  17344. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  17345. here_bits = here >>> 24;
  17346. here_op = (here >>> 16) & 0xff;
  17347. here_val = here & 0xffff;
  17348. if (here_bits <= bits) { break; }
  17349. //--- PULLBYTE() ---//
  17350. if (have === 0) { break inf_leave; }
  17351. have--;
  17352. hold += input[next++] << bits;
  17353. bits += 8;
  17354. //---//
  17355. }
  17356. if (here_op && (here_op & 0xf0) === 0) {
  17357. last_bits = here_bits;
  17358. last_op = here_op;
  17359. last_val = here_val;
  17360. for (;;) {
  17361. here = state.lencode[last_val +
  17362. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17363. here_bits = here >>> 24;
  17364. here_op = (here >>> 16) & 0xff;
  17365. here_val = here & 0xffff;
  17366. if ((last_bits + here_bits) <= bits) { break; }
  17367. //--- PULLBYTE() ---//
  17368. if (have === 0) { break inf_leave; }
  17369. have--;
  17370. hold += input[next++] << bits;
  17371. bits += 8;
  17372. //---//
  17373. }
  17374. //--- DROPBITS(last.bits) ---//
  17375. hold >>>= last_bits;
  17376. bits -= last_bits;
  17377. //---//
  17378. state.back += last_bits;
  17379. }
  17380. //--- DROPBITS(here.bits) ---//
  17381. hold >>>= here_bits;
  17382. bits -= here_bits;
  17383. //---//
  17384. state.back += here_bits;
  17385. state.length = here_val;
  17386. if (here_op === 0) {
  17387. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17388. // "inflate: literal '%c'\n" :
  17389. // "inflate: literal 0x%02x\n", here.val));
  17390. state.mode = LIT;
  17391. break;
  17392. }
  17393. if (here_op & 32) {
  17394. //Tracevv((stderr, "inflate: end of block\n"));
  17395. state.back = -1;
  17396. state.mode = TYPE;
  17397. break;
  17398. }
  17399. if (here_op & 64) {
  17400. strm.msg = 'invalid literal/length code';
  17401. state.mode = BAD;
  17402. break;
  17403. }
  17404. state.extra = here_op & 15;
  17405. state.mode = LENEXT;
  17406. /* falls through */
  17407. case LENEXT:
  17408. if (state.extra) {
  17409. //=== NEEDBITS(state.extra);
  17410. n = state.extra;
  17411. while (bits < n) {
  17412. if (have === 0) { break inf_leave; }
  17413. have--;
  17414. hold += input[next++] << bits;
  17415. bits += 8;
  17416. }
  17417. //===//
  17418. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17419. //--- DROPBITS(state.extra) ---//
  17420. hold >>>= state.extra;
  17421. bits -= state.extra;
  17422. //---//
  17423. state.back += state.extra;
  17424. }
  17425. //Tracevv((stderr, "inflate: length %u\n", state.length));
  17426. state.was = state.length;
  17427. state.mode = DIST;
  17428. /* falls through */
  17429. case DIST:
  17430. for (;;) {
  17431. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  17432. here_bits = here >>> 24;
  17433. here_op = (here >>> 16) & 0xff;
  17434. here_val = here & 0xffff;
  17435. if ((here_bits) <= bits) { break; }
  17436. //--- PULLBYTE() ---//
  17437. if (have === 0) { break inf_leave; }
  17438. have--;
  17439. hold += input[next++] << bits;
  17440. bits += 8;
  17441. //---//
  17442. }
  17443. if ((here_op & 0xf0) === 0) {
  17444. last_bits = here_bits;
  17445. last_op = here_op;
  17446. last_val = here_val;
  17447. for (;;) {
  17448. here = state.distcode[last_val +
  17449. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17450. here_bits = here >>> 24;
  17451. here_op = (here >>> 16) & 0xff;
  17452. here_val = here & 0xffff;
  17453. if ((last_bits + here_bits) <= bits) { break; }
  17454. //--- PULLBYTE() ---//
  17455. if (have === 0) { break inf_leave; }
  17456. have--;
  17457. hold += input[next++] << bits;
  17458. bits += 8;
  17459. //---//
  17460. }
  17461. //--- DROPBITS(last.bits) ---//
  17462. hold >>>= last_bits;
  17463. bits -= last_bits;
  17464. //---//
  17465. state.back += last_bits;
  17466. }
  17467. //--- DROPBITS(here.bits) ---//
  17468. hold >>>= here_bits;
  17469. bits -= here_bits;
  17470. //---//
  17471. state.back += here_bits;
  17472. if (here_op & 64) {
  17473. strm.msg = 'invalid distance code';
  17474. state.mode = BAD;
  17475. break;
  17476. }
  17477. state.offset = here_val;
  17478. state.extra = (here_op) & 15;
  17479. state.mode = DISTEXT;
  17480. /* falls through */
  17481. case DISTEXT:
  17482. if (state.extra) {
  17483. //=== NEEDBITS(state.extra);
  17484. n = state.extra;
  17485. while (bits < n) {
  17486. if (have === 0) { break inf_leave; }
  17487. have--;
  17488. hold += input[next++] << bits;
  17489. bits += 8;
  17490. }
  17491. //===//
  17492. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17493. //--- DROPBITS(state.extra) ---//
  17494. hold >>>= state.extra;
  17495. bits -= state.extra;
  17496. //---//
  17497. state.back += state.extra;
  17498. }
  17499. //#ifdef INFLATE_STRICT
  17500. if (state.offset > state.dmax) {
  17501. strm.msg = 'invalid distance too far back';
  17502. state.mode = BAD;
  17503. break;
  17504. }
  17505. //#endif
  17506. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  17507. state.mode = MATCH;
  17508. /* falls through */
  17509. case MATCH:
  17510. if (left === 0) { break inf_leave; }
  17511. copy = _out - left;
  17512. if (state.offset > copy) { /* copy from window */
  17513. copy = state.offset - copy;
  17514. if (copy > state.whave) {
  17515. if (state.sane) {
  17516. strm.msg = 'invalid distance too far back';
  17517. state.mode = BAD;
  17518. break;
  17519. }
  17520. // (!) This block is disabled in zlib defailts,
  17521. // don't enable it for binary compatibility
  17522. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17523. // Trace((stderr, "inflate.c too far\n"));
  17524. // copy -= state.whave;
  17525. // if (copy > state.length) { copy = state.length; }
  17526. // if (copy > left) { copy = left; }
  17527. // left -= copy;
  17528. // state.length -= copy;
  17529. // do {
  17530. // output[put++] = 0;
  17531. // } while (--copy);
  17532. // if (state.length === 0) { state.mode = LEN; }
  17533. // break;
  17534. //#endif
  17535. }
  17536. if (copy > state.wnext) {
  17537. copy -= state.wnext;
  17538. from = state.wsize - copy;
  17539. }
  17540. else {
  17541. from = state.wnext - copy;
  17542. }
  17543. if (copy > state.length) { copy = state.length; }
  17544. from_source = state.window;
  17545. }
  17546. else { /* copy from output */
  17547. from_source = output;
  17548. from = put - state.offset;
  17549. copy = state.length;
  17550. }
  17551. if (copy > left) { copy = left; }
  17552. left -= copy;
  17553. state.length -= copy;
  17554. do {
  17555. output[put++] = from_source[from++];
  17556. } while (--copy);
  17557. if (state.length === 0) { state.mode = LEN; }
  17558. break;
  17559. case LIT:
  17560. if (left === 0) { break inf_leave; }
  17561. output[put++] = state.length;
  17562. left--;
  17563. state.mode = LEN;
  17564. break;
  17565. case CHECK:
  17566. if (state.wrap) {
  17567. //=== NEEDBITS(32);
  17568. while (bits < 32) {
  17569. if (have === 0) { break inf_leave; }
  17570. have--;
  17571. // Use '|' insdead of '+' to make sure that result is signed
  17572. hold |= input[next++] << bits;
  17573. bits += 8;
  17574. }
  17575. //===//
  17576. _out -= left;
  17577. strm.total_out += _out;
  17578. state.total += _out;
  17579. if (_out) {
  17580. strm.adler = state.check =
  17581. /*UPDATE(state.check, put - _out, _out);*/
  17582. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17583. }
  17584. _out = left;
  17585. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  17586. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  17587. strm.msg = 'incorrect data check';
  17588. state.mode = BAD;
  17589. break;
  17590. }
  17591. //=== INITBITS();
  17592. hold = 0;
  17593. bits = 0;
  17594. //===//
  17595. //Tracev((stderr, "inflate: check matches trailer\n"));
  17596. }
  17597. state.mode = LENGTH;
  17598. /* falls through */
  17599. case LENGTH:
  17600. if (state.wrap && state.flags) {
  17601. //=== NEEDBITS(32);
  17602. while (bits < 32) {
  17603. if (have === 0) { break inf_leave; }
  17604. have--;
  17605. hold += input[next++] << bits;
  17606. bits += 8;
  17607. }
  17608. //===//
  17609. if (hold !== (state.total & 0xffffffff)) {
  17610. strm.msg = 'incorrect length check';
  17611. state.mode = BAD;
  17612. break;
  17613. }
  17614. //=== INITBITS();
  17615. hold = 0;
  17616. bits = 0;
  17617. //===//
  17618. //Tracev((stderr, "inflate: length matches trailer\n"));
  17619. }
  17620. state.mode = DONE;
  17621. /* falls through */
  17622. case DONE:
  17623. ret = Z_STREAM_END;
  17624. break inf_leave;
  17625. case BAD:
  17626. ret = Z_DATA_ERROR;
  17627. break inf_leave;
  17628. case MEM:
  17629. return Z_MEM_ERROR;
  17630. case SYNC:
  17631. /* falls through */
  17632. default:
  17633. return Z_STREAM_ERROR;
  17634. }
  17635. }
  17636. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17637. /*
  17638. Return from inflate(), updating the total counts and the check value.
  17639. If there was no progress during the inflate() call, return a buffer
  17640. error. Call updatewindow() to create and/or update the window state.
  17641. Note: a memory error from inflate() is non-recoverable.
  17642. */
  17643. //--- RESTORE() ---
  17644. strm.next_out = put;
  17645. strm.avail_out = left;
  17646. strm.next_in = next;
  17647. strm.avail_in = have;
  17648. state.hold = hold;
  17649. state.bits = bits;
  17650. //---
  17651. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17652. (state.mode < CHECK || flush !== Z_FINISH))) {
  17653. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17654. state.mode = MEM;
  17655. return Z_MEM_ERROR;
  17656. }
  17657. }
  17658. _in -= strm.avail_in;
  17659. _out -= strm.avail_out;
  17660. strm.total_in += _in;
  17661. strm.total_out += _out;
  17662. state.total += _out;
  17663. if (state.wrap && _out) {
  17664. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17665. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17666. }
  17667. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17668. (state.mode === TYPE ? 128 : 0) +
  17669. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17670. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17671. ret = Z_BUF_ERROR;
  17672. }
  17673. return ret;
  17674. }
  17675. function inflateEnd(strm) {
  17676. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17677. return Z_STREAM_ERROR;
  17678. }
  17679. var state = strm.state;
  17680. if (state.window) {
  17681. state.window = null;
  17682. }
  17683. strm.state = null;
  17684. return Z_OK;
  17685. }
  17686. function inflateGetHeader(strm, head) {
  17687. var state;
  17688. /* check state */
  17689. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17690. state = strm.state;
  17691. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17692. /* save header structure */
  17693. state.head = head;
  17694. head.done = false;
  17695. return Z_OK;
  17696. }
  17697. exports.inflateReset = inflateReset;
  17698. exports.inflateReset2 = inflateReset2;
  17699. exports.inflateResetKeep = inflateResetKeep;
  17700. exports.inflateInit = inflateInit;
  17701. exports.inflateInit2 = inflateInit2;
  17702. exports.inflate = inflate;
  17703. exports.inflateEnd = inflateEnd;
  17704. exports.inflateGetHeader = inflateGetHeader;
  17705. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17706. /* Not implemented
  17707. exports.inflateCopy = inflateCopy;
  17708. exports.inflateGetDictionary = inflateGetDictionary;
  17709. exports.inflateMark = inflateMark;
  17710. exports.inflatePrime = inflatePrime;
  17711. exports.inflateSetDictionary = inflateSetDictionary;
  17712. exports.inflateSync = inflateSync;
  17713. exports.inflateSyncPoint = inflateSyncPoint;
  17714. exports.inflateUndermine = inflateUndermine;
  17715. */
  17716. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./inffast":59,"./inftrees":61}],61:[function(require,module,exports){
  17717. 'use strict';
  17718. var utils = require('../utils/common');
  17719. var MAXBITS = 15;
  17720. var ENOUGH_LENS = 852;
  17721. var ENOUGH_DISTS = 592;
  17722. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17723. var CODES = 0;
  17724. var LENS = 1;
  17725. var DISTS = 2;
  17726. var lbase = [ /* Length codes 257..285 base */
  17727. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17728. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17729. ];
  17730. var lext = [ /* Length codes 257..285 extra */
  17731. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17732. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17733. ];
  17734. var dbase = [ /* Distance codes 0..29 base */
  17735. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17736. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17737. 8193, 12289, 16385, 24577, 0, 0
  17738. ];
  17739. var dext = [ /* Distance codes 0..29 extra */
  17740. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17741. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17742. 28, 28, 29, 29, 64, 64
  17743. ];
  17744. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17745. {
  17746. var bits = opts.bits;
  17747. //here = opts.here; /* table entry for duplication */
  17748. var len = 0; /* a code's length in bits */
  17749. var sym = 0; /* index of code symbols */
  17750. var min = 0, max = 0; /* minimum and maximum code lengths */
  17751. var root = 0; /* number of index bits for root table */
  17752. var curr = 0; /* number of index bits for current table */
  17753. var drop = 0; /* code bits to drop for sub-table */
  17754. var left = 0; /* number of prefix codes available */
  17755. var used = 0; /* code entries in table used */
  17756. var huff = 0; /* Huffman code */
  17757. var incr; /* for incrementing code, index */
  17758. var fill; /* index for replicating entries */
  17759. var low; /* low bits for current root entry */
  17760. var mask; /* mask for low root bits */
  17761. var next; /* next available space in table */
  17762. var base = null; /* base value table to use */
  17763. var base_index = 0;
  17764. // var shoextra; /* extra bits table to use */
  17765. var end; /* use base and extra for symbol > end */
  17766. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17767. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17768. var extra = null;
  17769. var extra_index = 0;
  17770. var here_bits, here_op, here_val;
  17771. /*
  17772. Process a set of code lengths to create a canonical Huffman code. The
  17773. code lengths are lens[0..codes-1]. Each length corresponds to the
  17774. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17775. symbols by length from short to long, and retaining the symbol order
  17776. for codes with equal lengths. Then the code starts with all zero bits
  17777. for the first code of the shortest length, and the codes are integer
  17778. increments for the same length, and zeros are appended as the length
  17779. increases. For the deflate format, these bits are stored backwards
  17780. from their more natural integer increment ordering, and so when the
  17781. decoding tables are built in the large loop below, the integer codes
  17782. are incremented backwards.
  17783. This routine assumes, but does not check, that all of the entries in
  17784. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17785. 1..MAXBITS is interpreted as that code length. zero means that that
  17786. symbol does not occur in this code.
  17787. The codes are sorted by computing a count of codes for each length,
  17788. creating from that a table of starting indices for each length in the
  17789. sorted table, and then entering the symbols in order in the sorted
  17790. table. The sorted table is work[], with that space being provided by
  17791. the caller.
  17792. The length counts are used for other purposes as well, i.e. finding
  17793. the minimum and maximum length codes, determining if there are any
  17794. codes at all, checking for a valid set of lengths, and looking ahead
  17795. at length counts to determine sub-table sizes when building the
  17796. decoding tables.
  17797. */
  17798. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17799. for (len = 0; len <= MAXBITS; len++) {
  17800. count[len] = 0;
  17801. }
  17802. for (sym = 0; sym < codes; sym++) {
  17803. count[lens[lens_index + sym]]++;
  17804. }
  17805. /* bound code lengths, force root to be within code lengths */
  17806. root = bits;
  17807. for (max = MAXBITS; max >= 1; max--) {
  17808. if (count[max] !== 0) { break; }
  17809. }
  17810. if (root > max) {
  17811. root = max;
  17812. }
  17813. if (max === 0) { /* no symbols to code at all */
  17814. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17815. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17816. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17817. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17818. //table.op[opts.table_index] = 64;
  17819. //table.bits[opts.table_index] = 1;
  17820. //table.val[opts.table_index++] = 0;
  17821. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17822. opts.bits = 1;
  17823. return 0; /* no symbols, but wait for decoding to report error */
  17824. }
  17825. for (min = 1; min < max; min++) {
  17826. if (count[min] !== 0) { break; }
  17827. }
  17828. if (root < min) {
  17829. root = min;
  17830. }
  17831. /* check for an over-subscribed or incomplete set of lengths */
  17832. left = 1;
  17833. for (len = 1; len <= MAXBITS; len++) {
  17834. left <<= 1;
  17835. left -= count[len];
  17836. if (left < 0) {
  17837. return -1;
  17838. } /* over-subscribed */
  17839. }
  17840. if (left > 0 && (type === CODES || max !== 1)) {
  17841. return -1; /* incomplete set */
  17842. }
  17843. /* generate offsets into symbol table for each length for sorting */
  17844. offs[1] = 0;
  17845. for (len = 1; len < MAXBITS; len++) {
  17846. offs[len + 1] = offs[len] + count[len];
  17847. }
  17848. /* sort symbols by length, by symbol order within each length */
  17849. for (sym = 0; sym < codes; sym++) {
  17850. if (lens[lens_index + sym] !== 0) {
  17851. work[offs[lens[lens_index + sym]]++] = sym;
  17852. }
  17853. }
  17854. /*
  17855. Create and fill in decoding tables. In this loop, the table being
  17856. filled is at next and has curr index bits. The code being used is huff
  17857. with length len. That code is converted to an index by dropping drop
  17858. bits off of the bottom. For codes where len is less than drop + curr,
  17859. those top drop + curr - len bits are incremented through all values to
  17860. fill the table with replicated entries.
  17861. root is the number of index bits for the root table. When len exceeds
  17862. root, sub-tables are created pointed to by the root entry with an index
  17863. of the low root bits of huff. This is saved in low to check for when a
  17864. new sub-table should be started. drop is zero when the root table is
  17865. being filled, and drop is root when sub-tables are being filled.
  17866. When a new sub-table is needed, it is necessary to look ahead in the
  17867. code lengths to determine what size sub-table is needed. The length
  17868. counts are used for this, and so count[] is decremented as codes are
  17869. entered in the tables.
  17870. used keeps track of how many table entries have been allocated from the
  17871. provided *table space. It is checked for LENS and DIST tables against
  17872. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17873. the initial root table size constants. See the comments in inftrees.h
  17874. for more information.
  17875. sym increments through all symbols, and the loop terminates when
  17876. all codes of length max, i.e. all codes, have been processed. This
  17877. routine permits incomplete codes, so another loop after this one fills
  17878. in the rest of the decoding tables with invalid code markers.
  17879. */
  17880. /* set up for code type */
  17881. // poor man optimization - use if-else instead of switch,
  17882. // to avoid deopts in old v8
  17883. if (type === CODES) {
  17884. base = extra = work; /* dummy value--not used */
  17885. end = 19;
  17886. } else if (type === LENS) {
  17887. base = lbase;
  17888. base_index -= 257;
  17889. extra = lext;
  17890. extra_index -= 257;
  17891. end = 256;
  17892. } else { /* DISTS */
  17893. base = dbase;
  17894. extra = dext;
  17895. end = -1;
  17896. }
  17897. /* initialize opts for loop */
  17898. huff = 0; /* starting code */
  17899. sym = 0; /* starting code symbol */
  17900. len = min; /* starting code length */
  17901. next = table_index; /* current table to fill in */
  17902. curr = root; /* current table index bits */
  17903. drop = 0; /* current bits to drop from code for index */
  17904. low = -1; /* trigger new sub-table when len > root */
  17905. used = 1 << root; /* use root table entries */
  17906. mask = used - 1; /* mask for comparing low */
  17907. /* check available table space */
  17908. if ((type === LENS && used > ENOUGH_LENS) ||
  17909. (type === DISTS && used > ENOUGH_DISTS)) {
  17910. return 1;
  17911. }
  17912. var i=0;
  17913. /* process all codes and make table entries */
  17914. for (;;) {
  17915. i++;
  17916. /* create table entry */
  17917. here_bits = len - drop;
  17918. if (work[sym] < end) {
  17919. here_op = 0;
  17920. here_val = work[sym];
  17921. }
  17922. else if (work[sym] > end) {
  17923. here_op = extra[extra_index + work[sym]];
  17924. here_val = base[base_index + work[sym]];
  17925. }
  17926. else {
  17927. here_op = 32 + 64; /* end of block */
  17928. here_val = 0;
  17929. }
  17930. /* replicate for those indices with low len bits equal to huff */
  17931. incr = 1 << (len - drop);
  17932. fill = 1 << curr;
  17933. min = fill; /* save offset to next table */
  17934. do {
  17935. fill -= incr;
  17936. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17937. } while (fill !== 0);
  17938. /* backwards increment the len-bit code huff */
  17939. incr = 1 << (len - 1);
  17940. while (huff & incr) {
  17941. incr >>= 1;
  17942. }
  17943. if (incr !== 0) {
  17944. huff &= incr - 1;
  17945. huff += incr;
  17946. } else {
  17947. huff = 0;
  17948. }
  17949. /* go to next symbol, update count, len */
  17950. sym++;
  17951. if (--count[len] === 0) {
  17952. if (len === max) { break; }
  17953. len = lens[lens_index + work[sym]];
  17954. }
  17955. /* create new sub-table if needed */
  17956. if (len > root && (huff & mask) !== low) {
  17957. /* if first time, transition to sub-tables */
  17958. if (drop === 0) {
  17959. drop = root;
  17960. }
  17961. /* increment past last table */
  17962. next += min; /* here min is 1 << curr */
  17963. /* determine length of next table */
  17964. curr = len - drop;
  17965. left = 1 << curr;
  17966. while (curr + drop < max) {
  17967. left -= count[curr + drop];
  17968. if (left <= 0) { break; }
  17969. curr++;
  17970. left <<= 1;
  17971. }
  17972. /* check for enough space */
  17973. used += 1 << curr;
  17974. if ((type === LENS && used > ENOUGH_LENS) ||
  17975. (type === DISTS && used > ENOUGH_DISTS)) {
  17976. return 1;
  17977. }
  17978. /* point entry in root table to sub-table */
  17979. low = huff & mask;
  17980. /*table.op[low] = curr;
  17981. table.bits[low] = root;
  17982. table.val[low] = next - opts.table_index;*/
  17983. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17984. }
  17985. }
  17986. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17987. at most one remaining entry, since if the code is incomplete, the
  17988. maximum code length that was allowed to get this far is one bit) */
  17989. if (huff !== 0) {
  17990. //table.op[next + huff] = 64; /* invalid code marker */
  17991. //table.bits[next + huff] = len - drop;
  17992. //table.val[next + huff] = 0;
  17993. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17994. }
  17995. /* set return parameters */
  17996. //opts.table_index += used;
  17997. opts.bits = root;
  17998. return 0;
  17999. };
  18000. },{"../utils/common":52}],62:[function(require,module,exports){
  18001. 'use strict';
  18002. module.exports = {
  18003. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  18004. '1': 'stream end', /* Z_STREAM_END 1 */
  18005. '0': '', /* Z_OK 0 */
  18006. '-1': 'file error', /* Z_ERRNO (-1) */
  18007. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  18008. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  18009. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  18010. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  18011. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  18012. };
  18013. },{}],63:[function(require,module,exports){
  18014. 'use strict';
  18015. var utils = require('../utils/common');
  18016. /* Public constants ==========================================================*/
  18017. /* ===========================================================================*/
  18018. //var Z_FILTERED = 1;
  18019. //var Z_HUFFMAN_ONLY = 2;
  18020. //var Z_RLE = 3;
  18021. var Z_FIXED = 4;
  18022. //var Z_DEFAULT_STRATEGY = 0;
  18023. /* Possible values of the data_type field (though see inflate()) */
  18024. var Z_BINARY = 0;
  18025. var Z_TEXT = 1;
  18026. //var Z_ASCII = 1; // = Z_TEXT
  18027. var Z_UNKNOWN = 2;
  18028. /*============================================================================*/
  18029. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18030. // From zutil.h
  18031. var STORED_BLOCK = 0;
  18032. var STATIC_TREES = 1;
  18033. var DYN_TREES = 2;
  18034. /* The three kinds of block type */
  18035. var MIN_MATCH = 3;
  18036. var MAX_MATCH = 258;
  18037. /* The minimum and maximum match lengths */
  18038. // From deflate.h
  18039. /* ===========================================================================
  18040. * Internal compression state.
  18041. */
  18042. var LENGTH_CODES = 29;
  18043. /* number of length codes, not counting the special END_BLOCK code */
  18044. var LITERALS = 256;
  18045. /* number of literal bytes 0..255 */
  18046. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18047. /* number of Literal or Length codes, including the END_BLOCK code */
  18048. var D_CODES = 30;
  18049. /* number of distance codes */
  18050. var BL_CODES = 19;
  18051. /* number of codes used to transfer the bit lengths */
  18052. var HEAP_SIZE = 2*L_CODES + 1;
  18053. /* maximum heap size */
  18054. var MAX_BITS = 15;
  18055. /* All codes must not exceed MAX_BITS bits */
  18056. var Buf_size = 16;
  18057. /* size of bit buffer in bi_buf */
  18058. /* ===========================================================================
  18059. * Constants
  18060. */
  18061. var MAX_BL_BITS = 7;
  18062. /* Bit length codes must not exceed MAX_BL_BITS bits */
  18063. var END_BLOCK = 256;
  18064. /* end of block literal code */
  18065. var REP_3_6 = 16;
  18066. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  18067. var REPZ_3_10 = 17;
  18068. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  18069. var REPZ_11_138 = 18;
  18070. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  18071. var extra_lbits = /* extra bits for each length code */
  18072. [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];
  18073. var extra_dbits = /* extra bits for each distance code */
  18074. [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];
  18075. var extra_blbits = /* extra bits for each bit length code */
  18076. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  18077. var bl_order =
  18078. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  18079. /* The lengths of the bit length codes are sent in order of decreasing
  18080. * probability, to avoid transmitting the lengths for unused bit length codes.
  18081. */
  18082. /* ===========================================================================
  18083. * Local data. These are initialized only once.
  18084. */
  18085. // We pre-fill arrays with 0 to avoid uninitialized gaps
  18086. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  18087. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  18088. var static_ltree = new Array((L_CODES+2) * 2);
  18089. zero(static_ltree);
  18090. /* The static literal tree. Since the bit lengths are imposed, there is no
  18091. * need for the L_CODES extra codes used during heap construction. However
  18092. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  18093. * below).
  18094. */
  18095. var static_dtree = new Array(D_CODES * 2);
  18096. zero(static_dtree);
  18097. /* The static distance tree. (Actually a trivial tree since all codes use
  18098. * 5 bits.)
  18099. */
  18100. var _dist_code = new Array(DIST_CODE_LEN);
  18101. zero(_dist_code);
  18102. /* Distance codes. The first 256 values correspond to the distances
  18103. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  18104. * the 15 bit distances.
  18105. */
  18106. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  18107. zero(_length_code);
  18108. /* length code for each normalized match length (0 == MIN_MATCH) */
  18109. var base_length = new Array(LENGTH_CODES);
  18110. zero(base_length);
  18111. /* First normalized length for each code (0 = MIN_MATCH) */
  18112. var base_dist = new Array(D_CODES);
  18113. zero(base_dist);
  18114. /* First normalized distance for each code (0 = distance of 1) */
  18115. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  18116. this.static_tree = static_tree; /* static tree or NULL */
  18117. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  18118. this.extra_base = extra_base; /* base index for extra_bits */
  18119. this.elems = elems; /* max number of elements in the tree */
  18120. this.max_length = max_length; /* max bit length for the codes */
  18121. // show if `static_tree` has data or dummy - needed for monomorphic objects
  18122. this.has_stree = static_tree && static_tree.length;
  18123. };
  18124. var static_l_desc;
  18125. var static_d_desc;
  18126. var static_bl_desc;
  18127. var TreeDesc = function(dyn_tree, stat_desc) {
  18128. this.dyn_tree = dyn_tree; /* the dynamic tree */
  18129. this.max_code = 0; /* largest code with non zero frequency */
  18130. this.stat_desc = stat_desc; /* the corresponding static tree */
  18131. };
  18132. function d_code(dist) {
  18133. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  18134. }
  18135. /* ===========================================================================
  18136. * Output a short LSB first on the stream.
  18137. * IN assertion: there is enough room in pendingBuf.
  18138. */
  18139. function put_short (s, w) {
  18140. // put_byte(s, (uch)((w) & 0xff));
  18141. // put_byte(s, (uch)((ush)(w) >> 8));
  18142. s.pending_buf[s.pending++] = (w) & 0xff;
  18143. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  18144. }
  18145. /* ===========================================================================
  18146. * Send a value on a given number of bits.
  18147. * IN assertion: length <= 16 and value fits in length bits.
  18148. */
  18149. function send_bits(s, value, length) {
  18150. if (s.bi_valid > (Buf_size - length)) {
  18151. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18152. put_short(s, s.bi_buf);
  18153. s.bi_buf = value >> (Buf_size - s.bi_valid);
  18154. s.bi_valid += length - Buf_size;
  18155. } else {
  18156. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18157. s.bi_valid += length;
  18158. }
  18159. }
  18160. function send_code(s, c, tree) {
  18161. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  18162. }
  18163. /* ===========================================================================
  18164. * Reverse the first len bits of a code, using straightforward code (a faster
  18165. * method would use a table)
  18166. * IN assertion: 1 <= len <= 15
  18167. */
  18168. function bi_reverse(code, len) {
  18169. var res = 0;
  18170. do {
  18171. res |= code & 1;
  18172. code >>>= 1;
  18173. res <<= 1;
  18174. } while (--len > 0);
  18175. return res >>> 1;
  18176. }
  18177. /* ===========================================================================
  18178. * Flush the bit buffer, keeping at most 7 bits in it.
  18179. */
  18180. function bi_flush(s) {
  18181. if (s.bi_valid === 16) {
  18182. put_short(s, s.bi_buf);
  18183. s.bi_buf = 0;
  18184. s.bi_valid = 0;
  18185. } else if (s.bi_valid >= 8) {
  18186. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  18187. s.bi_buf >>= 8;
  18188. s.bi_valid -= 8;
  18189. }
  18190. }
  18191. /* ===========================================================================
  18192. * Compute the optimal bit lengths for a tree and update the total bit length
  18193. * for the current block.
  18194. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  18195. * above are the tree nodes sorted by increasing frequency.
  18196. * OUT assertions: the field len is set to the optimal bit length, the
  18197. * array bl_count contains the frequencies for each bit length.
  18198. * The length opt_len is updated; static_len is also updated if stree is
  18199. * not null.
  18200. */
  18201. function gen_bitlen(s, desc)
  18202. // deflate_state *s;
  18203. // tree_desc *desc; /* the tree descriptor */
  18204. {
  18205. var tree = desc.dyn_tree;
  18206. var max_code = desc.max_code;
  18207. var stree = desc.stat_desc.static_tree;
  18208. var has_stree = desc.stat_desc.has_stree;
  18209. var extra = desc.stat_desc.extra_bits;
  18210. var base = desc.stat_desc.extra_base;
  18211. var max_length = desc.stat_desc.max_length;
  18212. var h; /* heap index */
  18213. var n, m; /* iterate over the tree elements */
  18214. var bits; /* bit length */
  18215. var xbits; /* extra bits */
  18216. var f; /* frequency */
  18217. var overflow = 0; /* number of elements with bit length too large */
  18218. for (bits = 0; bits <= MAX_BITS; bits++) {
  18219. s.bl_count[bits] = 0;
  18220. }
  18221. /* In a first pass, compute the optimal bit lengths (which may
  18222. * overflow in the case of the bit length tree).
  18223. */
  18224. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  18225. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  18226. n = s.heap[h];
  18227. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  18228. if (bits > max_length) {
  18229. bits = max_length;
  18230. overflow++;
  18231. }
  18232. tree[n*2 + 1]/*.Len*/ = bits;
  18233. /* We overwrite tree[n].Dad which is no longer needed */
  18234. if (n > max_code) { continue; } /* not a leaf node */
  18235. s.bl_count[bits]++;
  18236. xbits = 0;
  18237. if (n >= base) {
  18238. xbits = extra[n-base];
  18239. }
  18240. f = tree[n * 2]/*.Freq*/;
  18241. s.opt_len += f * (bits + xbits);
  18242. if (has_stree) {
  18243. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  18244. }
  18245. }
  18246. if (overflow === 0) { return; }
  18247. // Trace((stderr,"\nbit length overflow\n"));
  18248. /* This happens for example on obj2 and pic of the Calgary corpus */
  18249. /* Find the first bit length which could increase: */
  18250. do {
  18251. bits = max_length-1;
  18252. while (s.bl_count[bits] === 0) { bits--; }
  18253. s.bl_count[bits]--; /* move one leaf down the tree */
  18254. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  18255. s.bl_count[max_length]--;
  18256. /* The brother of the overflow item also moves one step up,
  18257. * but this does not affect bl_count[max_length]
  18258. */
  18259. overflow -= 2;
  18260. } while (overflow > 0);
  18261. /* Now recompute all bit lengths, scanning in increasing frequency.
  18262. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  18263. * lengths instead of fixing only the wrong ones. This idea is taken
  18264. * from 'ar' written by Haruhiko Okumura.)
  18265. */
  18266. for (bits = max_length; bits !== 0; bits--) {
  18267. n = s.bl_count[bits];
  18268. while (n !== 0) {
  18269. m = s.heap[--h];
  18270. if (m > max_code) { continue; }
  18271. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  18272. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  18273. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  18274. tree[m*2 + 1]/*.Len*/ = bits;
  18275. }
  18276. n--;
  18277. }
  18278. }
  18279. }
  18280. /* ===========================================================================
  18281. * Generate the codes for a given tree and bit counts (which need not be
  18282. * optimal).
  18283. * IN assertion: the array bl_count contains the bit length statistics for
  18284. * the given tree and the field len is set for all tree elements.
  18285. * OUT assertion: the field code is set for all tree elements of non
  18286. * zero code length.
  18287. */
  18288. function gen_codes(tree, max_code, bl_count)
  18289. // ct_data *tree; /* the tree to decorate */
  18290. // int max_code; /* largest code with non zero frequency */
  18291. // ushf *bl_count; /* number of codes at each bit length */
  18292. {
  18293. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  18294. var code = 0; /* running code value */
  18295. var bits; /* bit index */
  18296. var n; /* code index */
  18297. /* The distribution counts are first used to generate the code values
  18298. * without bit reversal.
  18299. */
  18300. for (bits = 1; bits <= MAX_BITS; bits++) {
  18301. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  18302. }
  18303. /* Check that the bit counts in bl_count are consistent. The last code
  18304. * must be all ones.
  18305. */
  18306. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  18307. // "inconsistent bit counts");
  18308. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  18309. for (n = 0; n <= max_code; n++) {
  18310. var len = tree[n*2 + 1]/*.Len*/;
  18311. if (len === 0) { continue; }
  18312. /* Now reverse the bits */
  18313. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  18314. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  18315. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  18316. }
  18317. }
  18318. /* ===========================================================================
  18319. * Initialize the various 'constant' tables.
  18320. */
  18321. function tr_static_init() {
  18322. var n; /* iterates over tree elements */
  18323. var bits; /* bit counter */
  18324. var length; /* length value */
  18325. var code; /* code value */
  18326. var dist; /* distance index */
  18327. var bl_count = new Array(MAX_BITS+1);
  18328. /* number of codes at each bit length for an optimal tree */
  18329. // do check in _tr_init()
  18330. //if (static_init_done) return;
  18331. /* For some embedded targets, global variables are not initialized: */
  18332. /*#ifdef NO_INIT_GLOBAL_POINTERS
  18333. static_l_desc.static_tree = static_ltree;
  18334. static_l_desc.extra_bits = extra_lbits;
  18335. static_d_desc.static_tree = static_dtree;
  18336. static_d_desc.extra_bits = extra_dbits;
  18337. static_bl_desc.extra_bits = extra_blbits;
  18338. #endif*/
  18339. /* Initialize the mapping length (0..255) -> length code (0..28) */
  18340. length = 0;
  18341. for (code = 0; code < LENGTH_CODES-1; code++) {
  18342. base_length[code] = length;
  18343. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  18344. _length_code[length++] = code;
  18345. }
  18346. }
  18347. //Assert (length == 256, "tr_static_init: length != 256");
  18348. /* Note that the length 255 (match length 258) can be represented
  18349. * in two different ways: code 284 + 5 bits or code 285, so we
  18350. * overwrite length_code[255] to use the best encoding:
  18351. */
  18352. _length_code[length-1] = code;
  18353. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  18354. dist = 0;
  18355. for (code = 0 ; code < 16; code++) {
  18356. base_dist[code] = dist;
  18357. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  18358. _dist_code[dist++] = code;
  18359. }
  18360. }
  18361. //Assert (dist == 256, "tr_static_init: dist != 256");
  18362. dist >>= 7; /* from now on, all distances are divided by 128 */
  18363. for (; code < D_CODES; code++) {
  18364. base_dist[code] = dist << 7;
  18365. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  18366. _dist_code[256 + dist++] = code;
  18367. }
  18368. }
  18369. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  18370. /* Construct the codes of the static literal tree */
  18371. for (bits = 0; bits <= MAX_BITS; bits++) {
  18372. bl_count[bits] = 0;
  18373. }
  18374. n = 0;
  18375. while (n <= 143) {
  18376. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18377. n++;
  18378. bl_count[8]++;
  18379. }
  18380. while (n <= 255) {
  18381. static_ltree[n*2 + 1]/*.Len*/ = 9;
  18382. n++;
  18383. bl_count[9]++;
  18384. }
  18385. while (n <= 279) {
  18386. static_ltree[n*2 + 1]/*.Len*/ = 7;
  18387. n++;
  18388. bl_count[7]++;
  18389. }
  18390. while (n <= 287) {
  18391. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18392. n++;
  18393. bl_count[8]++;
  18394. }
  18395. /* Codes 286 and 287 do not exist, but we must include them in the
  18396. * tree construction to get a canonical Huffman tree (longest code
  18397. * all ones)
  18398. */
  18399. gen_codes(static_ltree, L_CODES+1, bl_count);
  18400. /* The static distance tree is trivial: */
  18401. for (n = 0; n < D_CODES; n++) {
  18402. static_dtree[n*2 + 1]/*.Len*/ = 5;
  18403. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  18404. }
  18405. // Now data ready and we can init static trees
  18406. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  18407. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  18408. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  18409. //static_init_done = true;
  18410. }
  18411. /* ===========================================================================
  18412. * Initialize a new block.
  18413. */
  18414. function init_block(s) {
  18415. var n; /* iterates over tree elements */
  18416. /* Initialize the trees. */
  18417. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  18418. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  18419. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  18420. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  18421. s.opt_len = s.static_len = 0;
  18422. s.last_lit = s.matches = 0;
  18423. }
  18424. /* ===========================================================================
  18425. * Flush the bit buffer and align the output on a byte boundary
  18426. */
  18427. function bi_windup(s)
  18428. {
  18429. if (s.bi_valid > 8) {
  18430. put_short(s, s.bi_buf);
  18431. } else if (s.bi_valid > 0) {
  18432. //put_byte(s, (Byte)s->bi_buf);
  18433. s.pending_buf[s.pending++] = s.bi_buf;
  18434. }
  18435. s.bi_buf = 0;
  18436. s.bi_valid = 0;
  18437. }
  18438. /* ===========================================================================
  18439. * Copy a stored block, storing first the length and its
  18440. * one's complement if requested.
  18441. */
  18442. function copy_block(s, buf, len, header)
  18443. //DeflateState *s;
  18444. //charf *buf; /* the input data */
  18445. //unsigned len; /* its length */
  18446. //int header; /* true if block header must be written */
  18447. {
  18448. bi_windup(s); /* align on byte boundary */
  18449. if (header) {
  18450. put_short(s, len);
  18451. put_short(s, ~len);
  18452. }
  18453. // while (len--) {
  18454. // put_byte(s, *buf++);
  18455. // }
  18456. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  18457. s.pending += len;
  18458. }
  18459. /* ===========================================================================
  18460. * Compares to subtrees, using the tree depth as tie breaker when
  18461. * the subtrees have equal frequency. This minimizes the worst case length.
  18462. */
  18463. function smaller(tree, n, m, depth) {
  18464. var _n2 = n*2;
  18465. var _m2 = m*2;
  18466. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  18467. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  18468. }
  18469. /* ===========================================================================
  18470. * Restore the heap property by moving down the tree starting at node k,
  18471. * exchanging a node with the smallest of its two sons if necessary, stopping
  18472. * when the heap property is re-established (each father smaller than its
  18473. * two sons).
  18474. */
  18475. function pqdownheap(s, tree, k)
  18476. // deflate_state *s;
  18477. // ct_data *tree; /* the tree to restore */
  18478. // int k; /* node to move down */
  18479. {
  18480. var v = s.heap[k];
  18481. var j = k << 1; /* left son of k */
  18482. while (j <= s.heap_len) {
  18483. /* Set j to the smallest of the two sons: */
  18484. if (j < s.heap_len &&
  18485. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  18486. j++;
  18487. }
  18488. /* Exit if v is smaller than both sons */
  18489. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  18490. /* Exchange v with the smallest son */
  18491. s.heap[k] = s.heap[j];
  18492. k = j;
  18493. /* And continue down the tree, setting j to the left son of k */
  18494. j <<= 1;
  18495. }
  18496. s.heap[k] = v;
  18497. }
  18498. // inlined manually
  18499. // var SMALLEST = 1;
  18500. /* ===========================================================================
  18501. * Send the block data compressed using the given Huffman trees
  18502. */
  18503. function compress_block(s, ltree, dtree)
  18504. // deflate_state *s;
  18505. // const ct_data *ltree; /* literal tree */
  18506. // const ct_data *dtree; /* distance tree */
  18507. {
  18508. var dist; /* distance of matched string */
  18509. var lc; /* match length or unmatched char (if dist == 0) */
  18510. var lx = 0; /* running index in l_buf */
  18511. var code; /* the code to send */
  18512. var extra; /* number of extra bits to send */
  18513. if (s.last_lit !== 0) {
  18514. do {
  18515. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  18516. lc = s.pending_buf[s.l_buf + lx];
  18517. lx++;
  18518. if (dist === 0) {
  18519. send_code(s, lc, ltree); /* send a literal byte */
  18520. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18521. } else {
  18522. /* Here, lc is the match length - MIN_MATCH */
  18523. code = _length_code[lc];
  18524. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  18525. extra = extra_lbits[code];
  18526. if (extra !== 0) {
  18527. lc -= base_length[code];
  18528. send_bits(s, lc, extra); /* send the extra length bits */
  18529. }
  18530. dist--; /* dist is now the match distance - 1 */
  18531. code = d_code(dist);
  18532. //Assert (code < D_CODES, "bad d_code");
  18533. send_code(s, code, dtree); /* send the distance code */
  18534. extra = extra_dbits[code];
  18535. if (extra !== 0) {
  18536. dist -= base_dist[code];
  18537. send_bits(s, dist, extra); /* send the extra distance bits */
  18538. }
  18539. } /* literal or match pair ? */
  18540. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18541. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18542. // "pendingBuf overflow");
  18543. } while (lx < s.last_lit);
  18544. }
  18545. send_code(s, END_BLOCK, ltree);
  18546. }
  18547. /* ===========================================================================
  18548. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18549. * Update the total bit length for the current block.
  18550. * IN assertion: the field freq is set for all tree elements.
  18551. * OUT assertions: the fields len and code are set to the optimal bit length
  18552. * and corresponding code. The length opt_len is updated; static_len is
  18553. * also updated if stree is not null. The field max_code is set.
  18554. */
  18555. function build_tree(s, desc)
  18556. // deflate_state *s;
  18557. // tree_desc *desc; /* the tree descriptor */
  18558. {
  18559. var tree = desc.dyn_tree;
  18560. var stree = desc.stat_desc.static_tree;
  18561. var has_stree = desc.stat_desc.has_stree;
  18562. var elems = desc.stat_desc.elems;
  18563. var n, m; /* iterate over heap elements */
  18564. var max_code = -1; /* largest code with non zero frequency */
  18565. var node; /* new node being created */
  18566. /* Construct the initial heap, with least frequent element in
  18567. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18568. * heap[0] is not used.
  18569. */
  18570. s.heap_len = 0;
  18571. s.heap_max = HEAP_SIZE;
  18572. for (n = 0; n < elems; n++) {
  18573. if (tree[n * 2]/*.Freq*/ !== 0) {
  18574. s.heap[++s.heap_len] = max_code = n;
  18575. s.depth[n] = 0;
  18576. } else {
  18577. tree[n*2 + 1]/*.Len*/ = 0;
  18578. }
  18579. }
  18580. /* The pkzip format requires that at least one distance code exists,
  18581. * and that at least one bit should be sent even if there is only one
  18582. * possible code. So to avoid special checks later on we force at least
  18583. * two codes of non zero frequency.
  18584. */
  18585. while (s.heap_len < 2) {
  18586. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18587. tree[node * 2]/*.Freq*/ = 1;
  18588. s.depth[node] = 0;
  18589. s.opt_len--;
  18590. if (has_stree) {
  18591. s.static_len -= stree[node*2 + 1]/*.Len*/;
  18592. }
  18593. /* node is 0 or 1 so it does not have extra bits */
  18594. }
  18595. desc.max_code = max_code;
  18596. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18597. * establish sub-heaps of increasing lengths:
  18598. */
  18599. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18600. /* Construct the Huffman tree by repeatedly combining the least two
  18601. * frequent nodes.
  18602. */
  18603. node = elems; /* next internal node of the tree */
  18604. do {
  18605. //pqremove(s, tree, n); /* n = node of least frequency */
  18606. /*** pqremove ***/
  18607. n = s.heap[1/*SMALLEST*/];
  18608. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18609. pqdownheap(s, tree, 1/*SMALLEST*/);
  18610. /***/
  18611. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18612. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18613. s.heap[--s.heap_max] = m;
  18614. /* Create a new node father of n and m */
  18615. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18616. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18617. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  18618. /* and insert the new node in the heap */
  18619. s.heap[1/*SMALLEST*/] = node++;
  18620. pqdownheap(s, tree, 1/*SMALLEST*/);
  18621. } while (s.heap_len >= 2);
  18622. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18623. /* At this point, the fields freq and dad are set. We can now
  18624. * generate the bit lengths.
  18625. */
  18626. gen_bitlen(s, desc);
  18627. /* The field len is now set, we can generate the bit codes */
  18628. gen_codes(tree, max_code, s.bl_count);
  18629. }
  18630. /* ===========================================================================
  18631. * Scan a literal or distance tree to determine the frequencies of the codes
  18632. * in the bit length tree.
  18633. */
  18634. function scan_tree(s, tree, max_code)
  18635. // deflate_state *s;
  18636. // ct_data *tree; /* the tree to be scanned */
  18637. // int max_code; /* and its largest code of non zero frequency */
  18638. {
  18639. var n; /* iterates over all tree elements */
  18640. var prevlen = -1; /* last emitted length */
  18641. var curlen; /* length of current code */
  18642. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18643. var count = 0; /* repeat count of the current code */
  18644. var max_count = 7; /* max repeat count */
  18645. var min_count = 4; /* min repeat count */
  18646. if (nextlen === 0) {
  18647. max_count = 138;
  18648. min_count = 3;
  18649. }
  18650. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18651. for (n = 0; n <= max_code; n++) {
  18652. curlen = nextlen;
  18653. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18654. if (++count < max_count && curlen === nextlen) {
  18655. continue;
  18656. } else if (count < min_count) {
  18657. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18658. } else if (curlen !== 0) {
  18659. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18660. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18661. } else if (count <= 10) {
  18662. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18663. } else {
  18664. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18665. }
  18666. count = 0;
  18667. prevlen = curlen;
  18668. if (nextlen === 0) {
  18669. max_count = 138;
  18670. min_count = 3;
  18671. } else if (curlen === nextlen) {
  18672. max_count = 6;
  18673. min_count = 3;
  18674. } else {
  18675. max_count = 7;
  18676. min_count = 4;
  18677. }
  18678. }
  18679. }
  18680. /* ===========================================================================
  18681. * Send a literal or distance tree in compressed form, using the codes in
  18682. * bl_tree.
  18683. */
  18684. function send_tree(s, tree, max_code)
  18685. // deflate_state *s;
  18686. // ct_data *tree; /* the tree to be scanned */
  18687. // int max_code; /* and its largest code of non zero frequency */
  18688. {
  18689. var n; /* iterates over all tree elements */
  18690. var prevlen = -1; /* last emitted length */
  18691. var curlen; /* length of current code */
  18692. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18693. var count = 0; /* repeat count of the current code */
  18694. var max_count = 7; /* max repeat count */
  18695. var min_count = 4; /* min repeat count */
  18696. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18697. if (nextlen === 0) {
  18698. max_count = 138;
  18699. min_count = 3;
  18700. }
  18701. for (n = 0; n <= max_code; n++) {
  18702. curlen = nextlen;
  18703. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18704. if (++count < max_count && curlen === nextlen) {
  18705. continue;
  18706. } else if (count < min_count) {
  18707. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18708. } else if (curlen !== 0) {
  18709. if (curlen !== prevlen) {
  18710. send_code(s, curlen, s.bl_tree);
  18711. count--;
  18712. }
  18713. //Assert(count >= 3 && count <= 6, " 3_6?");
  18714. send_code(s, REP_3_6, s.bl_tree);
  18715. send_bits(s, count-3, 2);
  18716. } else if (count <= 10) {
  18717. send_code(s, REPZ_3_10, s.bl_tree);
  18718. send_bits(s, count-3, 3);
  18719. } else {
  18720. send_code(s, REPZ_11_138, s.bl_tree);
  18721. send_bits(s, count-11, 7);
  18722. }
  18723. count = 0;
  18724. prevlen = curlen;
  18725. if (nextlen === 0) {
  18726. max_count = 138;
  18727. min_count = 3;
  18728. } else if (curlen === nextlen) {
  18729. max_count = 6;
  18730. min_count = 3;
  18731. } else {
  18732. max_count = 7;
  18733. min_count = 4;
  18734. }
  18735. }
  18736. }
  18737. /* ===========================================================================
  18738. * Construct the Huffman tree for the bit lengths and return the index in
  18739. * bl_order of the last bit length code to send.
  18740. */
  18741. function build_bl_tree(s) {
  18742. var max_blindex; /* index of last bit length code of non zero freq */
  18743. /* Determine the bit length frequencies for literal and distance trees */
  18744. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18745. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18746. /* Build the bit length tree: */
  18747. build_tree(s, s.bl_desc);
  18748. /* opt_len now includes the length of the tree representations, except
  18749. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18750. */
  18751. /* Determine the number of bit length codes to send. The pkzip format
  18752. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18753. * 3 but the actual value used is 4.)
  18754. */
  18755. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18756. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18757. break;
  18758. }
  18759. }
  18760. /* Update opt_len to include the bit length tree and counts */
  18761. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18762. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18763. // s->opt_len, s->static_len));
  18764. return max_blindex;
  18765. }
  18766. /* ===========================================================================
  18767. * Send the header for a block using dynamic Huffman trees: the counts, the
  18768. * lengths of the bit length codes, the literal tree and the distance tree.
  18769. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18770. */
  18771. function send_all_trees(s, lcodes, dcodes, blcodes)
  18772. // deflate_state *s;
  18773. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18774. {
  18775. var rank; /* index in bl_order */
  18776. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18777. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18778. // "too many codes");
  18779. //Tracev((stderr, "\nbl counts: "));
  18780. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18781. send_bits(s, dcodes-1, 5);
  18782. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18783. for (rank = 0; rank < blcodes; rank++) {
  18784. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18785. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18786. }
  18787. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18788. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18789. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18790. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18791. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18792. }
  18793. /* ===========================================================================
  18794. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18795. * - TEXT if the two conditions below are satisfied:
  18796. * a) There are no non-portable control characters belonging to the
  18797. * "black list" (0..6, 14..25, 28..31).
  18798. * b) There is at least one printable character belonging to the
  18799. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18800. * - BINARY otherwise.
  18801. * - The following partially-portable control characters form a
  18802. * "gray list" that is ignored in this detection algorithm:
  18803. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18804. * IN assertion: the fields Freq of dyn_ltree are set.
  18805. */
  18806. function detect_data_type(s) {
  18807. /* black_mask is the bit mask of black-listed bytes
  18808. * set bits 0..6, 14..25, and 28..31
  18809. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18810. */
  18811. var black_mask = 0xf3ffc07f;
  18812. var n;
  18813. /* Check for non-textual ("black-listed") bytes. */
  18814. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18815. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18816. return Z_BINARY;
  18817. }
  18818. }
  18819. /* Check for textual ("white-listed") bytes. */
  18820. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18821. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18822. return Z_TEXT;
  18823. }
  18824. for (n = 32; n < LITERALS; n++) {
  18825. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18826. return Z_TEXT;
  18827. }
  18828. }
  18829. /* There are no "black-listed" or "white-listed" bytes:
  18830. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18831. */
  18832. return Z_BINARY;
  18833. }
  18834. var static_init_done = false;
  18835. /* ===========================================================================
  18836. * Initialize the tree data structures for a new zlib stream.
  18837. */
  18838. function _tr_init(s)
  18839. {
  18840. if (!static_init_done) {
  18841. tr_static_init();
  18842. static_init_done = true;
  18843. }
  18844. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18845. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18846. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18847. s.bi_buf = 0;
  18848. s.bi_valid = 0;
  18849. /* Initialize the first block of the first file: */
  18850. init_block(s);
  18851. }
  18852. /* ===========================================================================
  18853. * Send a stored block
  18854. */
  18855. function _tr_stored_block(s, buf, stored_len, last)
  18856. //DeflateState *s;
  18857. //charf *buf; /* input block */
  18858. //ulg stored_len; /* length of input block */
  18859. //int last; /* one if this is the last block for a file */
  18860. {
  18861. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18862. copy_block(s, buf, stored_len, true); /* with header */
  18863. }
  18864. /* ===========================================================================
  18865. * Send one empty static block to give enough lookahead for inflate.
  18866. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18867. */
  18868. function _tr_align(s) {
  18869. send_bits(s, STATIC_TREES<<1, 3);
  18870. send_code(s, END_BLOCK, static_ltree);
  18871. bi_flush(s);
  18872. }
  18873. /* ===========================================================================
  18874. * Determine the best encoding for the current block: dynamic trees, static
  18875. * trees or store, and output the encoded block to the zip file.
  18876. */
  18877. function _tr_flush_block(s, buf, stored_len, last)
  18878. //DeflateState *s;
  18879. //charf *buf; /* input block, or NULL if too old */
  18880. //ulg stored_len; /* length of input block */
  18881. //int last; /* one if this is the last block for a file */
  18882. {
  18883. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18884. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18885. /* Build the Huffman trees unless a stored block is forced */
  18886. if (s.level > 0) {
  18887. /* Check if the file is binary or text */
  18888. if (s.strm.data_type === Z_UNKNOWN) {
  18889. s.strm.data_type = detect_data_type(s);
  18890. }
  18891. /* Construct the literal and distance trees */
  18892. build_tree(s, s.l_desc);
  18893. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18894. // s->static_len));
  18895. build_tree(s, s.d_desc);
  18896. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18897. // s->static_len));
  18898. /* At this point, opt_len and static_len are the total bit lengths of
  18899. * the compressed block data, excluding the tree representations.
  18900. */
  18901. /* Build the bit length tree for the above two trees, and get the index
  18902. * in bl_order of the last bit length code to send.
  18903. */
  18904. max_blindex = build_bl_tree(s);
  18905. /* Determine the best encoding. Compute the block lengths in bytes. */
  18906. opt_lenb = (s.opt_len+3+7) >>> 3;
  18907. static_lenb = (s.static_len+3+7) >>> 3;
  18908. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18909. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18910. // s->last_lit));
  18911. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18912. } else {
  18913. // Assert(buf != (char*)0, "lost buf");
  18914. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18915. }
  18916. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18917. /* 4: two words for the lengths */
  18918. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18919. * Otherwise we can't have processed more than WSIZE input bytes since
  18920. * the last block flush, because compression would have been
  18921. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18922. * transform a block into a stored block.
  18923. */
  18924. _tr_stored_block(s, buf, stored_len, last);
  18925. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18926. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18927. compress_block(s, static_ltree, static_dtree);
  18928. } else {
  18929. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18930. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18931. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18932. }
  18933. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18934. /* The above check is made mod 2^32, for files larger than 512 MB
  18935. * and uLong implemented on 32 bits.
  18936. */
  18937. init_block(s);
  18938. if (last) {
  18939. bi_windup(s);
  18940. }
  18941. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18942. // s->compressed_len-7*last));
  18943. }
  18944. /* ===========================================================================
  18945. * Save the match info and tally the frequency counts. Return true if
  18946. * the current block must be flushed.
  18947. */
  18948. function _tr_tally(s, dist, lc)
  18949. // deflate_state *s;
  18950. // unsigned dist; /* distance of matched string */
  18951. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18952. {
  18953. //var out_length, in_length, dcode;
  18954. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18955. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18956. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18957. s.last_lit++;
  18958. if (dist === 0) {
  18959. /* lc is the unmatched char */
  18960. s.dyn_ltree[lc*2]/*.Freq*/++;
  18961. } else {
  18962. s.matches++;
  18963. /* Here, lc is the match length - MIN_MATCH */
  18964. dist--; /* dist = match distance - 1 */
  18965. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18966. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18967. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18968. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18969. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18970. }
  18971. // (!) This block is disabled in zlib defailts,
  18972. // don't enable it for binary compatibility
  18973. //#ifdef TRUNCATE_BLOCK
  18974. // /* Try to guess if it is profitable to stop the current block here */
  18975. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18976. // /* Compute an upper bound for the compressed length */
  18977. // out_length = s.last_lit*8;
  18978. // in_length = s.strstart - s.block_start;
  18979. //
  18980. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18981. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18982. // }
  18983. // out_length >>>= 3;
  18984. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18985. // // s->last_lit, in_length, out_length,
  18986. // // 100L - out_length*100L/in_length));
  18987. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18988. // return true;
  18989. // }
  18990. // }
  18991. //#endif
  18992. return (s.last_lit === s.lit_bufsize-1);
  18993. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18994. * on 16 bit machines and because stored blocks are restricted to
  18995. * 64K-1 bytes.
  18996. */
  18997. }
  18998. exports._tr_init = _tr_init;
  18999. exports._tr_stored_block = _tr_stored_block;
  19000. exports._tr_flush_block = _tr_flush_block;
  19001. exports._tr_tally = _tr_tally;
  19002. exports._tr_align = _tr_align;
  19003. },{"../utils/common":52}],64:[function(require,module,exports){
  19004. 'use strict';
  19005. function ZStream() {
  19006. /* next input byte */
  19007. this.input = null; // JS specific, because we have no pointers
  19008. this.next_in = 0;
  19009. /* number of bytes available at input */
  19010. this.avail_in = 0;
  19011. /* total number of input bytes read so far */
  19012. this.total_in = 0;
  19013. /* next output byte should be put there */
  19014. this.output = null; // JS specific, because we have no pointers
  19015. this.next_out = 0;
  19016. /* remaining free space at output */
  19017. this.avail_out = 0;
  19018. /* total number of bytes output so far */
  19019. this.total_out = 0;
  19020. /* last error message, NULL if no error */
  19021. this.msg = ''/*Z_NULL*/;
  19022. /* not visible by applications */
  19023. this.state = null;
  19024. /* best guess about the data type: binary or text */
  19025. this.data_type = 2/*Z_UNKNOWN*/;
  19026. /* adler32 value of the uncompressed data */
  19027. this.adler = 0;
  19028. }
  19029. module.exports = ZStream;
  19030. },{}],65:[function(require,module,exports){
  19031. /* Copyright @ 2015 Atlassian Pty Ltd
  19032. *
  19033. * Licensed under the Apache License, Version 2.0 (the "License");
  19034. * you may not use this file except in compliance with the License.
  19035. * You may obtain a copy of the License at
  19036. *
  19037. * http://www.apache.org/licenses/LICENSE-2.0
  19038. *
  19039. * Unless required by applicable law or agreed to in writing, software
  19040. * distributed under the License is distributed on an "AS IS" BASIS,
  19041. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19042. * See the License for the specific language governing permissions and
  19043. * limitations under the License.
  19044. */
  19045. module.exports = function arrayEquals(array) {
  19046. // if the other array is a falsy value, return
  19047. if (!array)
  19048. return false;
  19049. // compare lengths - can save a lot of time
  19050. if (this.length != array.length)
  19051. return false;
  19052. for (var i = 0, l = this.length; i < l; i++) {
  19053. // Check if we have nested arrays
  19054. if (this[i] instanceof Array && array[i] instanceof Array) {
  19055. // recurse into the nested arrays
  19056. if (!arrayEquals.apply(this[i], [array[i]]))
  19057. return false;
  19058. } else if (this[i] != array[i]) {
  19059. // Warning - two different object instances will never be equal:
  19060. // {x:20} != {x:20}
  19061. return false;
  19062. }
  19063. }
  19064. return true;
  19065. };
  19066. },{}],66:[function(require,module,exports){
  19067. /* Copyright @ 2015 Atlassian Pty Ltd
  19068. *
  19069. * Licensed under the Apache License, Version 2.0 (the "License");
  19070. * you may not use this file except in compliance with the License.
  19071. * You may obtain a copy of the License at
  19072. *
  19073. * http://www.apache.org/licenses/LICENSE-2.0
  19074. *
  19075. * Unless required by applicable law or agreed to in writing, software
  19076. * distributed under the License is distributed on an "AS IS" BASIS,
  19077. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19078. * See the License for the specific language governing permissions and
  19079. * limitations under the License.
  19080. */
  19081. exports.Interop = require('./interop');
  19082. },{"./interop":67}],67:[function(require,module,exports){
  19083. /* Copyright @ 2015 Atlassian Pty Ltd
  19084. *
  19085. * Licensed under the Apache License, Version 2.0 (the "License");
  19086. * you may not use this file except in compliance with the License.
  19087. * You may obtain a copy of the License at
  19088. *
  19089. * http://www.apache.org/licenses/LICENSE-2.0
  19090. *
  19091. * Unless required by applicable law or agreed to in writing, software
  19092. * distributed under the License is distributed on an "AS IS" BASIS,
  19093. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19094. * See the License for the specific language governing permissions and
  19095. * limitations under the License.
  19096. */
  19097. /* global RTCSessionDescription */
  19098. /* jshint -W097 */
  19099. "use strict";
  19100. var transform = require('./transform');
  19101. var arrayEquals = require('./array-equals');
  19102. function Interop() {
  19103. /**
  19104. * This map holds the most recent Unified Plan offer/answer SDP that was
  19105. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  19106. * the SDP string as values.
  19107. *
  19108. * @type {{}}
  19109. */
  19110. this.cache = {};
  19111. }
  19112. module.exports = Interop;
  19113. /**
  19114. * Returns the index of the first m-line with the given media type and with a
  19115. * direction which allows sending, in the last Unified Plan description with
  19116. * type "answer" converted to Plan B. Returns {null} if there is no saved
  19117. * answer, or if none of its m-lines with the given type allow sending.
  19118. * @param type the media type ("audio" or "video").
  19119. * @returns {*}
  19120. */
  19121. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  19122. if (!this.cache.answer) {
  19123. return null;
  19124. }
  19125. var session = transform.parse(this.cache.answer);
  19126. if (session && session.media && Array.isArray(session.media)){
  19127. for (var i = 0; i < session.media.length; i++) {
  19128. if (session.media[i].type == type &&
  19129. (!session.media[i].direction /* default to sendrecv */ ||
  19130. session.media[i].direction === 'sendrecv' ||
  19131. session.media[i].direction === 'sendonly')){
  19132. return i;
  19133. }
  19134. }
  19135. }
  19136. return null;
  19137. };
  19138. /**
  19139. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  19140. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  19141. * application.
  19142. *
  19143. * @param desc
  19144. * @returns {*}
  19145. */
  19146. Interop.prototype.toPlanB = function(desc) {
  19147. var self = this;
  19148. //#region Preliminary input validation.
  19149. if (typeof desc !== 'object' || desc === null ||
  19150. typeof desc.sdp !== 'string') {
  19151. console.warn('An empty description was passed as an argument.');
  19152. return desc;
  19153. }
  19154. // Objectify the SDP for easier manipulation.
  19155. var session = transform.parse(desc.sdp);
  19156. // If the SDP contains no media, there's nothing to transform.
  19157. if (typeof session.media === 'undefined' ||
  19158. !Array.isArray(session.media) || session.media.length === 0) {
  19159. console.warn('The description has no media.');
  19160. return desc;
  19161. }
  19162. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  19163. // SDP has a video, an audio and a data "channel" at most.
  19164. if (session.media.length <= 3 && session.media.every(function(m) {
  19165. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19166. })) {
  19167. console.warn('This description does not look like Unified Plan.');
  19168. return desc;
  19169. }
  19170. //#endregion
  19171. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  19172. var sdp = desc.sdp;
  19173. var rewrite = false;
  19174. for (var i = 0; i < session.media.length; i++) {
  19175. var uLine = session.media[i];
  19176. uLine.rtp.forEach(function(rtp) {
  19177. if (rtp.codec === 'NULL')
  19178. {
  19179. rewrite = true;
  19180. var offer = transform.parse(self.cache['offer']);
  19181. rtp.codec = offer.media[i].rtp[0].codec;
  19182. }
  19183. });
  19184. };
  19185. if (rewrite) {
  19186. sdp = transform.write(session);
  19187. }
  19188. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  19189. // -> Unified Plan transformation.
  19190. this.cache[desc.type] = sdp;
  19191. //#region Convert from Unified Plan to Plan B.
  19192. // We rebuild the session.media array.
  19193. var media = session.media;
  19194. session.media = [];
  19195. // Associative array that maps channel types to channel objects for fast
  19196. // access to channel objects by their type, e.g. type2bl['audio']->channel
  19197. // obj.
  19198. var type2bl = {};
  19199. // Used to build the group:BUNDLE value after the channels construction
  19200. // loop.
  19201. var types = [];
  19202. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  19203. media.forEach(function(uLine) {
  19204. // rtcp-mux is required in the Plan B SDP.
  19205. if ((typeof uLine.rtcpMux !== 'string' ||
  19206. uLine.rtcpMux !== 'rtcp-mux') &&
  19207. uLine.direction !== 'inactive') {
  19208. throw new Error('Cannot convert to Plan B because m-lines ' +
  19209. 'without the rtcp-mux attribute were found.');
  19210. }
  19211. if (uLine.type === 'application') {
  19212. session.media.push(uLine);
  19213. types.push(uLine.mid);
  19214. return;
  19215. }
  19216. // If we don't have a channel for this uLine.type, then use this
  19217. // uLine as the channel basis.
  19218. if (typeof type2bl[uLine.type] === 'undefined') {
  19219. type2bl[uLine.type] = uLine;
  19220. }
  19221. // Add sources to the channel and handle a=msid.
  19222. if (typeof uLine.sources === 'object') {
  19223. Object.keys(uLine.sources).forEach(function(ssrc) {
  19224. if (typeof type2bl[uLine.type].sources !== 'object')
  19225. type2bl[uLine.type].sources = {};
  19226. // Assign the sources to the channel.
  19227. type2bl[uLine.type].sources[ssrc] =
  19228. uLine.sources[ssrc];
  19229. if (typeof uLine.msid !== 'undefined') {
  19230. // In Plan B the msid is an SSRC attribute. Also, we don't
  19231. // care about the obsolete label and mslabel attributes.
  19232. //
  19233. // Note that it is not guaranteed that the uLine will
  19234. // have an msid. recvonly channels in particular don't have
  19235. // one.
  19236. type2bl[uLine.type].sources[ssrc].msid =
  19237. uLine.msid;
  19238. }
  19239. // NOTE ssrcs in ssrc groups will share msids, as
  19240. // draft-uberti-rtcweb-plan-00 mandates.
  19241. });
  19242. }
  19243. // Add ssrc groups to the channel.
  19244. if (typeof uLine.ssrcGroups !== 'undefined' &&
  19245. Array.isArray(uLine.ssrcGroups)) {
  19246. // Create the ssrcGroups array, if it's not defined.
  19247. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  19248. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  19249. type2bl[uLine.type].ssrcGroups = [];
  19250. }
  19251. type2bl[uLine.type].ssrcGroups =
  19252. type2bl[uLine.type].ssrcGroups.concat(
  19253. uLine.ssrcGroups);
  19254. }
  19255. if (type2bl[uLine.type] === uLine) {
  19256. // Copy ICE related stuff from the principal media line.
  19257. uLine.candidates = media[0].candidates;
  19258. uLine.iceUfrag = media[0].iceUfrag;
  19259. uLine.icePwd = media[0].icePwd;
  19260. uLine.fingerprint = media[0].fingerprint;
  19261. // Plan B mids are in ['audio', 'video', 'data']
  19262. uLine.mid = uLine.type;
  19263. // Plan B doesn't support/need the bundle-only attribute.
  19264. delete uLine.bundleOnly;
  19265. // In Plan B the msid is an SSRC attribute.
  19266. delete uLine.msid;
  19267. // Used to build the group:BUNDLE value after this loop.
  19268. types.push(uLine.type);
  19269. // Add the channel to the new media array.
  19270. session.media.push(uLine);
  19271. }
  19272. });
  19273. // We regenerate the BUNDLE group with the new mids.
  19274. session.groups.some(function(group) {
  19275. if (group.type === 'BUNDLE') {
  19276. group.mids = types.join(' ');
  19277. return true;
  19278. }
  19279. });
  19280. // msid semantic
  19281. session.msidSemantic = {
  19282. semantic: 'WMS',
  19283. token: '*'
  19284. };
  19285. var resStr = transform.write(session);
  19286. return new RTCSessionDescription({
  19287. type: desc.type,
  19288. sdp: resStr
  19289. });
  19290. //#endregion
  19291. };
  19292. /**
  19293. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  19294. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  19295. * to FF.
  19296. *
  19297. * @param desc
  19298. * @returns {*}
  19299. */
  19300. Interop.prototype.toUnifiedPlan = function(desc) {
  19301. var self = this;
  19302. //#region Preliminary input validation.
  19303. if (typeof desc !== 'object' || desc === null ||
  19304. typeof desc.sdp !== 'string') {
  19305. console.warn('An empty description was passed as an argument.');
  19306. return desc;
  19307. }
  19308. var session = transform.parse(desc.sdp);
  19309. // If the SDP contains no media, there's nothing to transform.
  19310. if (typeof session.media === 'undefined' ||
  19311. !Array.isArray(session.media) || session.media.length === 0) {
  19312. console.warn('The description has no media.');
  19313. return desc;
  19314. }
  19315. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  19316. // a video, an audio and a data "channel" at most.
  19317. if (session.media.length > 3 || !session.media.every(function(m) {
  19318. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19319. })) {
  19320. console.warn('This description does not look like Plan B.');
  19321. return desc;
  19322. }
  19323. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  19324. var mids = [];
  19325. session.media.forEach(function(m) {
  19326. mids.push(m.mid);
  19327. });
  19328. var hasBundle = false;
  19329. if (typeof session.groups !== 'undefined' &&
  19330. Array.isArray(session.groups)) {
  19331. hasBundle = session.groups.every(function(g) {
  19332. return g.type !== 'BUNDLE' ||
  19333. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  19334. });
  19335. }
  19336. if (!hasBundle) {
  19337. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  19338. " are not bundled were found.");
  19339. }
  19340. //#endregion
  19341. //#region Convert from Plan B to Unified Plan.
  19342. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  19343. // rebuild an equivalent Unified Plan offer/answer.
  19344. //
  19345. // For example, if this is a local answer (in Unified Plan style) that we
  19346. // convert to Plan B prior to handing it over to the application (the
  19347. // PeerConnection wrapper called us, for instance, after a successful
  19348. // createAnswer), we want to remember the m-line at which we've seen the
  19349. // (local) SSRC. That's because when the application wants to do call the
  19350. // SLD method, forcing us to do the inverse transformation (from Plan B to
  19351. // Unified Plan), we need to know to which m-line to assign the (local)
  19352. // SSRC. We also need to know all the other m-lines that the original
  19353. // answer had and include them in the transformed answer as well.
  19354. //
  19355. // Another example is if this is a remote offer that we convert to Plan B
  19356. // prior to giving it to the application, we want to remember the mid at
  19357. // which we've seen the (remote) SSRC.
  19358. //
  19359. // In the iteration that follows, we use the cached Unified Plan (if it
  19360. // exists) to assign mids to ssrcs.
  19361. var cached;
  19362. if (typeof this.cache[desc.type] !== 'undefined') {
  19363. cached = transform.parse(this.cache[desc.type]);
  19364. }
  19365. var recvonlySsrcs = {
  19366. audio: {},
  19367. video: {}
  19368. };
  19369. // A helper map that sends mids to m-line objects. We use it later to
  19370. // rebuild the Unified Plan style session.media array.
  19371. var mid2ul = {};
  19372. session.media.forEach(function(bLine) {
  19373. if ((typeof bLine.rtcpMux !== 'string' ||
  19374. bLine.rtcpMux !== 'rtcp-mux') &&
  19375. bLine.direction !== 'inactive') {
  19376. throw new Error("Cannot convert to Unified Plan because m-lines " +
  19377. "without the rtcp-mux attribute were found.");
  19378. }
  19379. if (bLine.type === 'application') {
  19380. mid2ul[bLine.mid] = bLine;
  19381. return;
  19382. }
  19383. // With rtcp-mux and bundle all the channels should have the same ICE
  19384. // stuff.
  19385. var sources = bLine.sources;
  19386. var ssrcGroups = bLine.ssrcGroups;
  19387. var candidates = bLine.candidates;
  19388. var iceUfrag = bLine.iceUfrag;
  19389. var icePwd = bLine.icePwd;
  19390. var fingerprint = bLine.fingerprint;
  19391. var port = bLine.port;
  19392. // We'll use the "bLine" object as a prototype for each new "mLine"
  19393. // that we create, but first we need to clean it up a bit.
  19394. delete bLine.sources;
  19395. delete bLine.ssrcGroups;
  19396. delete bLine.candidates;
  19397. delete bLine.iceUfrag;
  19398. delete bLine.icePwd;
  19399. delete bLine.fingerprint;
  19400. delete bLine.port;
  19401. delete bLine.mid;
  19402. // inverted ssrc group map
  19403. var ssrc2group = {};
  19404. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  19405. ssrcGroups.forEach(function (ssrcGroup) {
  19406. // TODO(gp) find out how to receive simulcast with FF. For the
  19407. // time being, hide it.
  19408. if (ssrcGroup.semantics === 'SIM') {
  19409. return;
  19410. }
  19411. // XXX This might brake if an SSRC is in more than one group
  19412. // for some reason.
  19413. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19414. Array.isArray(ssrcGroup.ssrcs)) {
  19415. ssrcGroup.ssrcs.forEach(function (ssrc) {
  19416. if (typeof ssrc2group[ssrc] === 'undefined') {
  19417. ssrc2group[ssrc] = [];
  19418. }
  19419. ssrc2group[ssrc].push(ssrcGroup);
  19420. });
  19421. }
  19422. });
  19423. }
  19424. // ssrc to m-line index.
  19425. var ssrc2ml = {};
  19426. if (typeof sources === 'object') {
  19427. // Explode the Plan B channel sources with one m-line per source.
  19428. Object.keys(sources).forEach(function(ssrc) {
  19429. // The (unified) m-line for this SSRC. We either create it from
  19430. // scratch or, if it's a grouped SSRC, we re-use a related
  19431. // mline. In other words, if the source is grouped with another
  19432. // source, put the two together in the same m-line.
  19433. var uLine;
  19434. // We assume here that we are the answerer in the O/A, so any
  19435. // offers which we translate come from the remote side, while
  19436. // answers are local. So the check below is to make that we
  19437. // handle receive-only SSRCs in a special way only if they come
  19438. // from the remote side.
  19439. if (desc.type==='offer') {
  19440. // We want to detect SSRCs which are used by a remote peer
  19441. // in an m-line with direction=recvonly (i.e. they are
  19442. // being used for RTCP only).
  19443. // This information would have gotten lost if the remote
  19444. // peer used Unified Plan and their local description was
  19445. // translated to Plan B. So we use the lack of an MSID
  19446. // attribute to deduce a "receive only" SSRC.
  19447. if (!sources[ssrc].msid) {
  19448. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  19449. // Receive-only SSRCs must not create new m-lines. We
  19450. // will assign them to an existing m-line later.
  19451. return;
  19452. }
  19453. }
  19454. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  19455. Array.isArray(ssrc2group[ssrc])) {
  19456. ssrc2group[ssrc].some(function (ssrcGroup) {
  19457. // ssrcGroup.ssrcs *is* an Array, no need to check
  19458. // again here.
  19459. return ssrcGroup.ssrcs.some(function (related) {
  19460. if (typeof ssrc2ml[related] === 'object') {
  19461. uLine = ssrc2ml[related];
  19462. return true;
  19463. }
  19464. });
  19465. });
  19466. }
  19467. if (typeof uLine === 'object') {
  19468. // the m-line already exists. Just add the source.
  19469. uLine.sources[ssrc] = sources[ssrc];
  19470. delete sources[ssrc].msid;
  19471. } else {
  19472. // Use the "bLine" as a prototype for the "uLine".
  19473. uLine = Object.create(bLine);
  19474. ssrc2ml[ssrc] = uLine;
  19475. if (typeof sources[ssrc].msid !== 'undefined') {
  19476. // Assign the msid of the source to the m-line. Note
  19477. // that it is not guaranteed that the source will have
  19478. // msid. In particular "recvonly" sources don't have an
  19479. // msid. Note that "recvonly" is a term only defined
  19480. // for m-lines.
  19481. uLine.msid = sources[ssrc].msid;
  19482. uLine.direction = 'sendrecv';
  19483. delete sources[ssrc].msid;
  19484. }
  19485. // We assign one SSRC per media line.
  19486. uLine.sources = {};
  19487. uLine.sources[ssrc] = sources[ssrc];
  19488. uLine.ssrcGroups = ssrc2group[ssrc];
  19489. // Use the cached Unified Plan SDP (if it exists) to assign
  19490. // SSRCs to mids.
  19491. if (typeof cached !== 'undefined' &&
  19492. typeof cached.media !== 'undefined' &&
  19493. Array.isArray(cached.media)) {
  19494. cached.media.forEach(function (m) {
  19495. if (typeof m.sources === 'object') {
  19496. Object.keys(m.sources).forEach(function (s) {
  19497. if (s === ssrc) {
  19498. uLine.mid = m.mid;
  19499. }
  19500. });
  19501. }
  19502. });
  19503. }
  19504. if (typeof uLine.mid === 'undefined') {
  19505. // If this is an SSRC that we see for the first time
  19506. // assign it a new mid. This is typically the case when
  19507. // this method is called to transform a remote
  19508. // description for the first time or when there is a
  19509. // new SSRC in the remote description because a new
  19510. // peer has joined the conference. Local SSRCs should
  19511. // have already been added to the map in the toPlanB
  19512. // method.
  19513. //
  19514. // Because FF generates answers in Unified Plan style,
  19515. // we MUST already have a cached answer with all the
  19516. // local SSRCs mapped to some m-line/mid.
  19517. if (desc.type === 'answer') {
  19518. throw new Error("An unmapped SSRC was found.");
  19519. }
  19520. uLine.mid = [bLine.type, '-', ssrc].join('');
  19521. }
  19522. // Include the candidates in the 1st media line.
  19523. uLine.candidates = candidates;
  19524. uLine.iceUfrag = iceUfrag;
  19525. uLine.icePwd = icePwd;
  19526. uLine.fingerprint = fingerprint;
  19527. uLine.port = port;
  19528. mid2ul[uLine.mid] = uLine;
  19529. }
  19530. });
  19531. }
  19532. });
  19533. // Rebuild the media array in the right order and add the missing mLines
  19534. // (missing from the Plan B SDP).
  19535. session.media = [];
  19536. mids = []; // reuse
  19537. if (desc.type === 'answer') {
  19538. // The media lines in the answer must match the media lines in the
  19539. // offer. The order is important too. Here we assume that Firefox is
  19540. // the answerer, so we merely have to use the reconstructed (unified)
  19541. // answer to update the cached (unified) answer accordingly.
  19542. //
  19543. // In the general case, one would have to use the cached (unified)
  19544. // offer to find the m-lines that are missing from the reconstructed
  19545. // answer, potentially grabbing them from the cached (unified) answer.
  19546. // One has to be careful with this approach because inactive m-lines do
  19547. // not always have an mid, making it tricky (impossible?) to find where
  19548. // exactly and which m-lines are missing from the reconstructed answer.
  19549. for (var i = 0; i < cached.media.length; i++) {
  19550. var uLine = cached.media[i];
  19551. if (typeof mid2ul[uLine.mid] === 'undefined') {
  19552. // The mid isn't in the reconstructed (unified) answer.
  19553. // This is either a (unified) m-line containing a remote
  19554. // track only, or a (unified) m-line containing a remote
  19555. // track and a local track that has been removed.
  19556. // In either case, it MUST exist in the cached
  19557. // (unified) answer.
  19558. //
  19559. // In case this is a removed local track, clean-up
  19560. // the (unified) m-line and make sure it's 'recvonly' or
  19561. // 'inactive'.
  19562. delete uLine.msid;
  19563. delete uLine.sources;
  19564. delete uLine.ssrcGroups;
  19565. if (!uLine.direction
  19566. || uLine.direction === 'sendrecv')
  19567. uLine.direction = 'recvonly';
  19568. else if (uLine.direction === 'sendonly')
  19569. uLine.direction = 'inactive';
  19570. } else {
  19571. // This is an (unified) m-line/channel that contains a local
  19572. // track (sendrecv or sendonly channel) or it's a unified
  19573. // recvonly m-line/channel. In either case, since we're
  19574. // going from PlanB -> Unified Plan this m-line MUST
  19575. // exist in the cached answer.
  19576. }
  19577. session.media.push(uLine);
  19578. if (typeof uLine.mid === 'string') {
  19579. // inactive lines don't/may not have an mid.
  19580. mids.push(uLine.mid);
  19581. }
  19582. }
  19583. } else {
  19584. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  19585. // under any circumstances. If we are no longer interested in sending a
  19586. // track, we just remove the msid and ssrc attributes and set it to
  19587. // either a=recvonly (as the reofferer, we must use recvonly if the
  19588. // other side was previously sending on the m-section, but we can also
  19589. // leave the possibility open if it wasn't previously in use), or
  19590. // a=inactive.
  19591. if (typeof cached !== 'undefined' &&
  19592. typeof cached.media !== 'undefined' &&
  19593. Array.isArray(cached.media)) {
  19594. cached.media.forEach(function(uLine) {
  19595. mids.push(uLine.mid);
  19596. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  19597. session.media.push(mid2ul[uLine.mid]);
  19598. } else {
  19599. delete uLine.msid;
  19600. delete uLine.sources;
  19601. delete uLine.ssrcGroups;
  19602. if (!uLine.direction
  19603. || uLine.direction === 'sendrecv')
  19604. uLine.direction = 'recvonly';
  19605. if (!uLine.direction
  19606. || uLine.direction === 'sendonly')
  19607. uLine.direction = 'inactive';
  19608. session.media.push(uLine);
  19609. }
  19610. });
  19611. }
  19612. // Add all the remaining (new) m-lines of the transformed SDP.
  19613. Object.keys(mid2ul).forEach(function(mid) {
  19614. if (mids.indexOf(mid) === -1) {
  19615. mids.push(mid);
  19616. if (mid2ul[mid].direction === 'recvonly') {
  19617. // This is a remote recvonly channel. Add its SSRC to the
  19618. // appropriate sendrecv or sendonly channel.
  19619. // TODO(gp) what if we don't have sendrecv/sendonly
  19620. // channel?
  19621. session.media.some(function (uLine) {
  19622. if ((uLine.direction === 'sendrecv' ||
  19623. uLine.direction === 'sendonly') &&
  19624. uLine.type === mid2ul[mid].type) {
  19625. // mid2ul[mid] shouldn't have any ssrc-groups
  19626. Object.keys(mid2ul[mid].sources).forEach(
  19627. function (ssrc) {
  19628. uLine.sources[ssrc] =
  19629. mid2ul[mid].sources[ssrc];
  19630. });
  19631. return true;
  19632. }
  19633. });
  19634. } else {
  19635. session.media.push(mid2ul[mid]);
  19636. }
  19637. }
  19638. });
  19639. }
  19640. // After we have constructed the Plan Unified m-lines we can figure out
  19641. // where (in which m-line) to place the 'recvonly SSRCs'.
  19642. // Note: we assume here that we are the answerer in the O/A, so any offers
  19643. // which we translate come from the remote side, while answers are local
  19644. // (and so our last local description is cached as an 'answer').
  19645. ["audio", "video"].forEach(function (type) {
  19646. if (!session || !session.media || !Array.isArray(session.media))
  19647. return;
  19648. var idx = null;
  19649. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19650. idx = self.getFirstSendingIndexFromAnswer(type);
  19651. if (idx === null){
  19652. // If this is the first offer we receive, we don't have a
  19653. // cached answer. Assume that we will be sending media using
  19654. // the first m-line for each media type.
  19655. for (var i = 0; i < session.media.length; i++) {
  19656. if (session.media[i].type === type) {
  19657. idx = i;
  19658. break;
  19659. }
  19660. }
  19661. }
  19662. }
  19663. if (idx && session.media.length > idx) {
  19664. var mLine = session.media[idx];
  19665. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19666. if (mLine.sources && mLine.sources[ssrc]) {
  19667. console.warn("Replacing an existing SSRC.");
  19668. }
  19669. if (!mLine.sources) {
  19670. mLine.sources = {};
  19671. }
  19672. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19673. });
  19674. }
  19675. });
  19676. // We regenerate the BUNDLE group (since we regenerated the mids)
  19677. session.groups.some(function(group) {
  19678. if (group.type === 'BUNDLE') {
  19679. group.mids = mids.join(' ');
  19680. return true;
  19681. }
  19682. });
  19683. // msid semantic
  19684. session.msidSemantic = {
  19685. semantic: 'WMS',
  19686. token: '*'
  19687. };
  19688. var resStr = transform.write(session);
  19689. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19690. // function.
  19691. this.cache[desc.type] = resStr;
  19692. return new RTCSessionDescription({
  19693. type: desc.type,
  19694. sdp: resStr
  19695. });
  19696. //#endregion
  19697. };
  19698. },{"./array-equals":65,"./transform":68}],68:[function(require,module,exports){
  19699. /* Copyright @ 2015 Atlassian Pty Ltd
  19700. *
  19701. * Licensed under the Apache License, Version 2.0 (the "License");
  19702. * you may not use this file except in compliance with the License.
  19703. * You may obtain a copy of the License at
  19704. *
  19705. * http://www.apache.org/licenses/LICENSE-2.0
  19706. *
  19707. * Unless required by applicable law or agreed to in writing, software
  19708. * distributed under the License is distributed on an "AS IS" BASIS,
  19709. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19710. * See the License for the specific language governing permissions and
  19711. * limitations under the License.
  19712. */
  19713. var transform = require('sdp-transform');
  19714. exports.write = function(session, opts) {
  19715. if (typeof session !== 'undefined' &&
  19716. typeof session.media !== 'undefined' &&
  19717. Array.isArray(session.media)) {
  19718. session.media.forEach(function (mLine) {
  19719. // expand sources to ssrcs
  19720. if (typeof mLine.sources !== 'undefined' &&
  19721. Object.keys(mLine.sources).length !== 0) {
  19722. mLine.ssrcs = [];
  19723. Object.keys(mLine.sources).forEach(function (ssrc) {
  19724. var source = mLine.sources[ssrc];
  19725. Object.keys(source).forEach(function (attribute) {
  19726. mLine.ssrcs.push({
  19727. id: ssrc,
  19728. attribute: attribute,
  19729. value: source[attribute]
  19730. });
  19731. });
  19732. });
  19733. delete mLine.sources;
  19734. }
  19735. // join ssrcs in ssrc groups
  19736. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19737. Array.isArray(mLine.ssrcGroups)) {
  19738. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19739. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19740. Array.isArray(ssrcGroup.ssrcs)) {
  19741. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19742. }
  19743. });
  19744. }
  19745. });
  19746. }
  19747. // join group mids
  19748. if (typeof session !== 'undefined' &&
  19749. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19750. session.groups.forEach(function (g) {
  19751. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19752. g.mids = g.mids.join(' ');
  19753. }
  19754. });
  19755. }
  19756. return transform.write(session, opts);
  19757. };
  19758. exports.parse = function(sdp) {
  19759. var session = transform.parse(sdp);
  19760. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19761. Array.isArray(session.media)) {
  19762. session.media.forEach(function (mLine) {
  19763. // group sources attributes by ssrc
  19764. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19765. mLine.sources = {};
  19766. mLine.ssrcs.forEach(function (ssrc) {
  19767. if (!mLine.sources[ssrc.id])
  19768. mLine.sources[ssrc.id] = {};
  19769. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19770. });
  19771. delete mLine.ssrcs;
  19772. }
  19773. // split ssrcs in ssrc groups
  19774. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19775. Array.isArray(mLine.ssrcGroups)) {
  19776. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19777. if (typeof ssrcGroup.ssrcs === 'string') {
  19778. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19779. }
  19780. });
  19781. }
  19782. });
  19783. }
  19784. // split group mids
  19785. if (typeof session !== 'undefined' &&
  19786. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19787. session.groups.forEach(function (g) {
  19788. if (typeof g.mids === 'string') {
  19789. g.mids = g.mids.split(' ');
  19790. }
  19791. });
  19792. }
  19793. return session;
  19794. };
  19795. },{"sdp-transform":70}],69:[function(require,module,exports){
  19796. var grammar = module.exports = {
  19797. v: [{
  19798. name: 'version',
  19799. reg: /^(\d*)$/
  19800. }],
  19801. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19802. // NB: sessionId will be a String in most cases because it is huge
  19803. name: 'origin',
  19804. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19805. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19806. format: "%s %s %d %s IP%d %s"
  19807. }],
  19808. // default parsing of these only (though some of these feel outdated)
  19809. s: [{ name: 'name' }],
  19810. i: [{ name: 'description' }],
  19811. u: [{ name: 'uri' }],
  19812. e: [{ name: 'email' }],
  19813. p: [{ name: 'phone' }],
  19814. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19815. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19816. //k: [{}], // outdated thing ignored
  19817. t: [{ //t=0 0
  19818. name: 'timing',
  19819. reg: /^(\d*) (\d*)/,
  19820. names: ['start', 'stop'],
  19821. format: "%d %d"
  19822. }],
  19823. c: [{ //c=IN IP4 10.47.197.26
  19824. name: 'connection',
  19825. reg: /^IN IP(\d) (\S*)/,
  19826. names: ['version', 'ip'],
  19827. format: "IN IP%d %s"
  19828. }],
  19829. b: [{ //b=AS:4000
  19830. push: 'bandwidth',
  19831. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19832. names: ['type', 'limit'],
  19833. format: "%s:%s"
  19834. }],
  19835. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19836. // NB: special - pushes to session
  19837. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19838. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19839. names: ['type', 'port', 'protocol', 'payloads'],
  19840. format: "%s %d %s %s"
  19841. }],
  19842. a: [
  19843. { //a=rtpmap:110 opus/48000/2
  19844. push: 'rtp',
  19845. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  19846. names: ['payload', 'codec', 'rate', 'encoding'],
  19847. format: function (o) {
  19848. return (o.encoding) ?
  19849. "rtpmap:%d %s/%s/%s":
  19850. o.rate ?
  19851. "rtpmap:%d %s/%s":
  19852. "rtpmap:%d %s";
  19853. }
  19854. },
  19855. {
  19856. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19857. //a=fmtp:111 minptime=10; useinbandfec=1
  19858. push: 'fmtp',
  19859. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19860. names: ['payload', 'config'],
  19861. format: "fmtp:%d %s"
  19862. },
  19863. { //a=control:streamid=0
  19864. name: 'control',
  19865. reg: /^control:(.*)/,
  19866. format: "control:%s"
  19867. },
  19868. { //a=rtcp:65179 IN IP4 193.84.77.194
  19869. name: 'rtcp',
  19870. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19871. names: ['port', 'netType', 'ipVer', 'address'],
  19872. format: function (o) {
  19873. return (o.address != null) ?
  19874. "rtcp:%d %s IP%d %s":
  19875. "rtcp:%d";
  19876. }
  19877. },
  19878. { //a=rtcp-fb:98 trr-int 100
  19879. push: 'rtcpFbTrrInt',
  19880. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19881. names: ['payload', 'value'],
  19882. format: "rtcp-fb:%d trr-int %d"
  19883. },
  19884. { //a=rtcp-fb:98 nack rpsi
  19885. push: 'rtcpFb',
  19886. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19887. names: ['payload', 'type', 'subtype'],
  19888. format: function (o) {
  19889. return (o.subtype != null) ?
  19890. "rtcp-fb:%s %s %s":
  19891. "rtcp-fb:%s %s";
  19892. }
  19893. },
  19894. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19895. //a=extmap:1/recvonly URI-gps-string
  19896. push: 'ext',
  19897. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19898. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19899. format: function (o) {
  19900. return (o.config != null) ?
  19901. "extmap:%s %s %s":
  19902. "extmap:%s %s";
  19903. }
  19904. },
  19905. {
  19906. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19907. push: 'crypto',
  19908. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19909. names: ['id', 'suite', 'config', 'sessionConfig'],
  19910. format: function (o) {
  19911. return (o.sessionConfig != null) ?
  19912. "crypto:%d %s %s %s":
  19913. "crypto:%d %s %s";
  19914. }
  19915. },
  19916. { //a=setup:actpass
  19917. name: 'setup',
  19918. reg: /^setup:(\w*)/,
  19919. format: "setup:%s"
  19920. },
  19921. { //a=mid:1
  19922. name: 'mid',
  19923. reg: /^mid:([^\s]*)/,
  19924. format: "mid:%s"
  19925. },
  19926. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19927. name: 'msid',
  19928. reg: /^msid:(.*)/,
  19929. format: "msid:%s"
  19930. },
  19931. { //a=ptime:20
  19932. name: 'ptime',
  19933. reg: /^ptime:(\d*)/,
  19934. format: "ptime:%d"
  19935. },
  19936. { //a=maxptime:60
  19937. name: 'maxptime',
  19938. reg: /^maxptime:(\d*)/,
  19939. format: "maxptime:%d"
  19940. },
  19941. { //a=sendrecv
  19942. name: 'direction',
  19943. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19944. },
  19945. { //a=ice-lite
  19946. name: 'icelite',
  19947. reg: /^(ice-lite)/
  19948. },
  19949. { //a=ice-ufrag:F7gI
  19950. name: 'iceUfrag',
  19951. reg: /^ice-ufrag:(\S*)/,
  19952. format: "ice-ufrag:%s"
  19953. },
  19954. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19955. name: 'icePwd',
  19956. reg: /^ice-pwd:(\S*)/,
  19957. format: "ice-pwd:%s"
  19958. },
  19959. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19960. name: 'fingerprint',
  19961. reg: /^fingerprint:(\S*) (\S*)/,
  19962. names: ['type', 'hash'],
  19963. format: "fingerprint:%s %s"
  19964. },
  19965. {
  19966. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19967. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19968. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19969. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  19970. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  19971. push:'candidates',
  19972. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  19973. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  19974. format: function (o) {
  19975. var str = "candidate:%s %d %s %d %s %d typ %s";
  19976. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19977. // NB: candidate has three optional chunks, so %void middles one if it's missing
  19978. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  19979. if (o.generation != null) {
  19980. str += " generation %d";
  19981. }
  19982. return str;
  19983. }
  19984. },
  19985. { //a=end-of-candidates (keep after the candidates line for readability)
  19986. name: 'endOfCandidates',
  19987. reg: /^(end-of-candidates)/
  19988. },
  19989. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19990. name: 'remoteCandidates',
  19991. reg: /^remote-candidates:(.*)/,
  19992. format: "remote-candidates:%s"
  19993. },
  19994. { //a=ice-options:google-ice
  19995. name: 'iceOptions',
  19996. reg: /^ice-options:(\S*)/,
  19997. format: "ice-options:%s"
  19998. },
  19999. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20000. push: "ssrcs",
  20001. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20002. names: ['id', 'attribute', 'value'],
  20003. format: "ssrc:%d %s:%s"
  20004. },
  20005. { //a=ssrc-group:FEC 1 2
  20006. push: "ssrcGroups",
  20007. reg: /^ssrc-group:(\w*) (.*)/,
  20008. names: ['semantics', 'ssrcs'],
  20009. format: "ssrc-group:%s %s"
  20010. },
  20011. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20012. name: "msidSemantic",
  20013. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20014. names: ['semantic', 'token'],
  20015. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20016. },
  20017. { //a=group:BUNDLE audio video
  20018. push: 'groups',
  20019. reg: /^group:(\w*) (.*)/,
  20020. names: ['type', 'mids'],
  20021. format: "group:%s %s"
  20022. },
  20023. { //a=rtcp-mux
  20024. name: 'rtcpMux',
  20025. reg: /^(rtcp-mux)/
  20026. },
  20027. { //a=rtcp-rsize
  20028. name: 'rtcpRsize',
  20029. reg: /^(rtcp-rsize)/
  20030. },
  20031. { // any a= that we don't understand is kepts verbatim on media.invalid
  20032. push: 'invalid',
  20033. names: ["value"]
  20034. }
  20035. ]
  20036. };
  20037. // set sensible defaults to avoid polluting the grammar with boring details
  20038. Object.keys(grammar).forEach(function (key) {
  20039. var objs = grammar[key];
  20040. objs.forEach(function (obj) {
  20041. if (!obj.reg) {
  20042. obj.reg = /(.*)/;
  20043. }
  20044. if (!obj.format) {
  20045. obj.format = "%s";
  20046. }
  20047. });
  20048. });
  20049. },{}],70:[function(require,module,exports){
  20050. var parser = require('./parser');
  20051. var writer = require('./writer');
  20052. exports.write = writer;
  20053. exports.parse = parser.parse;
  20054. exports.parseFmtpConfig = parser.parseFmtpConfig;
  20055. exports.parsePayloads = parser.parsePayloads;
  20056. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  20057. },{"./parser":71,"./writer":72}],71:[function(require,module,exports){
  20058. var toIntIfInt = function (v) {
  20059. return String(Number(v)) === v ? Number(v) : v;
  20060. };
  20061. var attachProperties = function (match, location, names, rawName) {
  20062. if (rawName && !names) {
  20063. location[rawName] = toIntIfInt(match[1]);
  20064. }
  20065. else {
  20066. for (var i = 0; i < names.length; i += 1) {
  20067. if (match[i+1] != null) {
  20068. location[names[i]] = toIntIfInt(match[i+1]);
  20069. }
  20070. }
  20071. }
  20072. };
  20073. var parseReg = function (obj, location, content) {
  20074. var needsBlank = obj.name && obj.names;
  20075. if (obj.push && !location[obj.push]) {
  20076. location[obj.push] = [];
  20077. }
  20078. else if (needsBlank && !location[obj.name]) {
  20079. location[obj.name] = {};
  20080. }
  20081. var keyLocation = obj.push ?
  20082. {} : // blank object that will be pushed
  20083. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20084. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20085. if (obj.push) {
  20086. location[obj.push].push(keyLocation);
  20087. }
  20088. };
  20089. var grammar = require('./grammar');
  20090. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20091. exports.parse = function (sdp) {
  20092. var session = {}
  20093. , media = []
  20094. , location = session; // points at where properties go under (one of the above)
  20095. // parse lines we understand
  20096. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20097. var type = l[0];
  20098. var content = l.slice(2);
  20099. if (type === 'm') {
  20100. media.push({rtp: [], fmtp: []});
  20101. location = media[media.length-1]; // point at latest media line
  20102. }
  20103. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20104. var obj = grammar[type][j];
  20105. if (obj.reg.test(content)) {
  20106. return parseReg(obj, location, content);
  20107. }
  20108. }
  20109. });
  20110. session.media = media; // link it up
  20111. return session;
  20112. };
  20113. var fmtpReducer = function (acc, expr) {
  20114. var s = expr.split('=');
  20115. if (s.length === 2) {
  20116. acc[s[0]] = toIntIfInt(s[1]);
  20117. }
  20118. return acc;
  20119. };
  20120. exports.parseFmtpConfig = function (str) {
  20121. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  20122. };
  20123. exports.parsePayloads = function (str) {
  20124. return str.split(' ').map(Number);
  20125. };
  20126. exports.parseRemoteCandidates = function (str) {
  20127. var candidates = [];
  20128. var parts = str.split(' ').map(toIntIfInt);
  20129. for (var i = 0; i < parts.length; i += 3) {
  20130. candidates.push({
  20131. component: parts[i],
  20132. ip: parts[i + 1],
  20133. port: parts[i + 2]
  20134. });
  20135. }
  20136. return candidates;
  20137. };
  20138. },{"./grammar":69}],72:[function(require,module,exports){
  20139. var grammar = require('./grammar');
  20140. // customized util.format - discards excess arguments and can void middle ones
  20141. var formatRegExp = /%[sdv%]/g;
  20142. var format = function (formatStr) {
  20143. var i = 1;
  20144. var args = arguments;
  20145. var len = args.length;
  20146. return formatStr.replace(formatRegExp, function (x) {
  20147. if (i >= len) {
  20148. return x; // missing argument
  20149. }
  20150. var arg = args[i];
  20151. i += 1;
  20152. switch (x) {
  20153. case '%%':
  20154. return '%';
  20155. case '%s':
  20156. return String(arg);
  20157. case '%d':
  20158. return Number(arg);
  20159. case '%v':
  20160. return '';
  20161. }
  20162. });
  20163. // NB: we discard excess arguments - they are typically undefined from makeLine
  20164. };
  20165. var makeLine = function (type, obj, location) {
  20166. var str = obj.format instanceof Function ?
  20167. (obj.format(obj.push ? location : location[obj.name])) :
  20168. obj.format;
  20169. var args = [type + '=' + str];
  20170. if (obj.names) {
  20171. for (var i = 0; i < obj.names.length; i += 1) {
  20172. var n = obj.names[i];
  20173. if (obj.name) {
  20174. args.push(location[obj.name][n]);
  20175. }
  20176. else { // for mLine and push attributes
  20177. args.push(location[obj.names[i]]);
  20178. }
  20179. }
  20180. }
  20181. else {
  20182. args.push(location[obj.name]);
  20183. }
  20184. return format.apply(null, args);
  20185. };
  20186. // RFC specified order
  20187. // TODO: extend this with all the rest
  20188. var defaultOuterOrder = [
  20189. 'v', 'o', 's', 'i',
  20190. 'u', 'e', 'p', 'c',
  20191. 'b', 't', 'r', 'z', 'a'
  20192. ];
  20193. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  20194. module.exports = function (session, opts) {
  20195. opts = opts || {};
  20196. // ensure certain properties exist
  20197. if (session.version == null) {
  20198. session.version = 0; // "v=0" must be there (only defined version atm)
  20199. }
  20200. if (session.name == null) {
  20201. session.name = " "; // "s= " must be there if no meaningful name set
  20202. }
  20203. session.media.forEach(function (mLine) {
  20204. if (mLine.payloads == null) {
  20205. mLine.payloads = "";
  20206. }
  20207. });
  20208. var outerOrder = opts.outerOrder || defaultOuterOrder;
  20209. var innerOrder = opts.innerOrder || defaultInnerOrder;
  20210. var sdp = [];
  20211. // loop through outerOrder for matching properties on session
  20212. outerOrder.forEach(function (type) {
  20213. grammar[type].forEach(function (obj) {
  20214. if (obj.name in session && session[obj.name] != null) {
  20215. sdp.push(makeLine(type, obj, session));
  20216. }
  20217. else if (obj.push in session && session[obj.push] != null) {
  20218. session[obj.push].forEach(function (el) {
  20219. sdp.push(makeLine(type, obj, el));
  20220. });
  20221. }
  20222. });
  20223. });
  20224. // then for each media line, follow the innerOrder
  20225. session.media.forEach(function (mLine) {
  20226. sdp.push(makeLine('m', grammar.m[0], mLine));
  20227. innerOrder.forEach(function (type) {
  20228. grammar[type].forEach(function (obj) {
  20229. if (obj.name in mLine && mLine[obj.name] != null) {
  20230. sdp.push(makeLine(type, obj, mLine));
  20231. }
  20232. else if (obj.push in mLine && mLine[obj.push] != null) {
  20233. mLine[obj.push].forEach(function (el) {
  20234. sdp.push(makeLine(type, obj, el));
  20235. });
  20236. }
  20237. });
  20238. });
  20239. });
  20240. return sdp.join('\r\n') + '\r\n';
  20241. };
  20242. },{"./grammar":69}],73:[function(require,module,exports){
  20243. /* Copyright @ 2015 Atlassian Pty Ltd
  20244. *
  20245. * Licensed under the Apache License, Version 2.0 (the "License");
  20246. * you may not use this file except in compliance with the License.
  20247. * You may obtain a copy of the License at
  20248. *
  20249. * http://www.apache.org/licenses/LICENSE-2.0
  20250. *
  20251. * Unless required by applicable law or agreed to in writing, software
  20252. * distributed under the License is distributed on an "AS IS" BASIS,
  20253. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20254. * See the License for the specific language governing permissions and
  20255. * limitations under the License.
  20256. */
  20257. var transform = require('sdp-transform');
  20258. var transformUtils = require('./transform-utils');
  20259. var parseSsrcs = transformUtils.parseSsrcs;
  20260. var writeSsrcs = transformUtils.writeSsrcs;
  20261. //region Constants
  20262. var DEFAULT_NUM_OF_LAYERS = 3;
  20263. //endregion
  20264. //region Ctor
  20265. function Simulcast(options) {
  20266. this.options = options ? options : {};
  20267. if (!this.options.numOfLayers) {
  20268. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  20269. }
  20270. this.layers = [];
  20271. }
  20272. //endregion
  20273. //region Stateless private utility functions
  20274. /**
  20275. * Returns a random integer between min (included) and max (excluded)
  20276. * Using Math.round() gives a non-uniform distribution!
  20277. * @returns {number}
  20278. */
  20279. function generateSSRC() {
  20280. var min = 0, max = 0xffffffff;
  20281. return Math.floor(Math.random() * (max - min)) + min;
  20282. };
  20283. function processVideo(session, action) {
  20284. if (session == null || !Array.isArray(session.media)) {
  20285. return;
  20286. }
  20287. session.media.forEach(function (mLine) {
  20288. if (mLine.type === 'video') {
  20289. action(mLine);
  20290. }
  20291. });
  20292. }
  20293. function validateDescription(desc)
  20294. {
  20295. return desc && desc != null
  20296. && desc.type && desc.type != ''
  20297. && desc.sdp && desc.sdp != '';
  20298. }
  20299. function explodeRemoteSimulcast(mLine) {
  20300. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20301. return;
  20302. }
  20303. var sources = parseSsrcs(mLine);
  20304. var order = [];
  20305. // Find the SIM group and explode its sources.
  20306. var j = mLine.ssrcGroups.length;
  20307. while (j--) {
  20308. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  20309. continue;
  20310. }
  20311. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  20312. for (var i = 0; i < simulcastSsrcs.length; i++) {
  20313. var ssrc = simulcastSsrcs[i];
  20314. order.push(ssrc);
  20315. var parts = sources[ssrc].msid.split(' ');
  20316. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  20317. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  20318. // Remove all the groups that this SSRC participates in.
  20319. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20320. if (relatedGroup.semantics === 'SIM') {
  20321. return;
  20322. }
  20323. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20324. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20325. return;
  20326. }
  20327. // Nuke all the related SSRCs.
  20328. relatedSsrcs.forEach(function (relatedSSRC) {
  20329. sources[relatedSSRC].msid = sources[ssrc].msid;
  20330. sources[relatedSSRC].cname = sources[ssrc].cname;
  20331. if (relatedSSRC !== ssrc) {
  20332. order.push(relatedSSRC);
  20333. }
  20334. });
  20335. // Schedule the related group for nuking.
  20336. })
  20337. }
  20338. mLine.ssrcs = writeSsrcs(sources, order);
  20339. mLine.ssrcGroups.splice(j, 1);
  20340. };
  20341. }
  20342. function implodeRemoteSimulcast(mLine) {
  20343. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20344. console.info('Halt: There are no SSRC groups in the remote ' +
  20345. 'description.');
  20346. return;
  20347. }
  20348. var sources = parseSsrcs(mLine);
  20349. // Find the SIM group and nuke it.
  20350. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  20351. if (simulcastGroup.semantics !== 'SIM') {
  20352. return;
  20353. }
  20354. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  20355. // Schedule the SIM group for nuking.
  20356. simulcastGroup.nuke = true;
  20357. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  20358. // Nuke all the higher layer SSRCs.
  20359. for (var i = 1; i < simulcastSsrcs.length; i++) {
  20360. var ssrc = simulcastSsrcs[i];
  20361. delete sources[ssrc];
  20362. // Remove all the groups that this SSRC participates in.
  20363. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20364. if (relatedGroup.semantics === 'SIM') {
  20365. return;
  20366. }
  20367. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20368. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20369. return;
  20370. }
  20371. // Nuke all the related SSRCs.
  20372. relatedSsrcs.forEach(function (relatedSSRC) {
  20373. delete sources[relatedSSRC];
  20374. });
  20375. // Schedule the related group for nuking.
  20376. relatedGroup.nuke = true;
  20377. })
  20378. }
  20379. return;
  20380. });
  20381. mLine.ssrcs = writeSsrcs(sources);
  20382. // Nuke all the scheduled groups.
  20383. var i = mLine.ssrcGroups.length;
  20384. while (i--) {
  20385. if (mLine.ssrcGroups[i].nuke) {
  20386. mLine.ssrcGroups.splice(i, 1);
  20387. }
  20388. }
  20389. }
  20390. function removeGoogConference(mLine) {
  20391. if (!mLine || !Array.isArray(mLine.invalid)) {
  20392. return;
  20393. }
  20394. var i = mLine.invalid.length;
  20395. while (i--) {
  20396. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  20397. mLine.invalid.splice(i, 1);
  20398. }
  20399. }
  20400. }
  20401. function assertGoogConference(mLine) {
  20402. if (!mLine) {
  20403. return;
  20404. }
  20405. if (!Array.isArray(mLine.invalid)) {
  20406. mLine.invalid = [];
  20407. }
  20408. if (!mLine.invalid.some(
  20409. function (i) { return i.value === 'x-google-flag:conference' })) {
  20410. mLine.invalid.push({'value': 'x-google-flag:conference'});
  20411. }
  20412. }
  20413. //endregion
  20414. //region "Private" functions
  20415. /**
  20416. *
  20417. * @param mLine
  20418. * @private
  20419. */
  20420. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  20421. if (!mLine || mLine.type !== 'video') {
  20422. return;
  20423. }
  20424. var sources = parseSsrcs(mLine);
  20425. if (Object.keys(sources).length === 0) {
  20426. // no sources, disable simulcast.
  20427. if (this.layers.length !== 0) {
  20428. this.layers = [];
  20429. }
  20430. return;
  20431. }
  20432. // find the base layer (we'll reuse its msid and cname).
  20433. var baseLayerSSRC = Object.keys(sources)[0];
  20434. var baseLayer = sources[baseLayerSSRC];
  20435. // todo(gp) handle screen sharing.
  20436. // check if base CNAME has changed and reinitialise layers.
  20437. if (this.layers.length > 0
  20438. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  20439. this.layers = [];
  20440. }
  20441. // (re)initialise layers
  20442. if (this.layers.length < 1) {
  20443. // first push the base layer.
  20444. this.layers.push({
  20445. ssrc: baseLayerSSRC,
  20446. msid: baseLayer.msid,
  20447. cname: baseLayer.cname
  20448. });
  20449. var rtx = false; // RFC 4588
  20450. if (Array.isArray(mLine.rtp)) {
  20451. rtx = mLine.rtp.some(
  20452. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  20453. }
  20454. if (rtx) {
  20455. this.layers[0].rtx = generateSSRC();
  20456. }
  20457. // now push additional layers.
  20458. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  20459. var layer = { ssrc: generateSSRC() };
  20460. if (rtx) {
  20461. layer.rtx = generateSSRC();
  20462. }
  20463. this.layers.push(layer);
  20464. }
  20465. }
  20466. };
  20467. /**
  20468. *
  20469. * @param mLine
  20470. * @private
  20471. */
  20472. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  20473. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  20474. var sources = {};
  20475. var msid = this.layers[0].msid;
  20476. var cname = this.layers[0].cname;
  20477. var simulcastSsrcs = [];
  20478. var ssrcGroups = [];
  20479. for (var i = 0; i < this.layers.length; i++) {
  20480. var layer = this.layers[i];
  20481. sources[layer.ssrc] = { msid: msid, cname: cname };
  20482. simulcastSsrcs.push(layer.ssrc);
  20483. if (layer.rtx) {
  20484. sources[layer.rtx] = {
  20485. msid: msid,
  20486. cname: cname
  20487. }
  20488. ssrcGroups.push({
  20489. semantics: 'FID',
  20490. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  20491. });
  20492. }
  20493. }
  20494. ssrcGroups.push({
  20495. semantics: 'SIM',
  20496. ssrcs: simulcastSsrcs.join(' ')
  20497. });
  20498. mLine.ssrcGroups = ssrcGroups;
  20499. mLine.ssrcs = writeSsrcs(sources);
  20500. }
  20501. }
  20502. //endregion
  20503. //region "Public" functions
  20504. Simulcast.prototype.isSupported = function () {
  20505. return window.chrome;
  20506. // TODO this needs improvements. For example I doubt that Chrome in Android
  20507. // has simulcast support. Also, only recent versions of Chromium have native
  20508. // simulcast support.
  20509. }
  20510. /**
  20511. *
  20512. * @param desc
  20513. * @returns {RTCSessionDescription}
  20514. */
  20515. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  20516. if (!validateDescription(desc)) {
  20517. return desc;
  20518. }
  20519. var session = transform.parse(desc.sdp);
  20520. var self = this;
  20521. processVideo(session, function (mLine) {
  20522. // Handle simulcast reception.
  20523. if (self.options.explodeRemoteSimulcast) {
  20524. explodeRemoteSimulcast(mLine);
  20525. } else {
  20526. implodeRemoteSimulcast(mLine);
  20527. }
  20528. // If native simulcast is enabled, we must append the x-goog-conference
  20529. // attribute to the SDP.
  20530. if (self.layers.length < 1) {
  20531. removeGoogConference(mLine);
  20532. } else {
  20533. assertGoogConference(mLine);
  20534. }
  20535. });
  20536. return new RTCSessionDescription({
  20537. type: desc.type,
  20538. sdp: transform.write(session)
  20539. });
  20540. };
  20541. /**
  20542. *
  20543. * @param desc
  20544. * @returns {RTCSessionDescription}
  20545. */
  20546. Simulcast.prototype.mungeLocalDescription = function (desc) {
  20547. if (!validateDescription(desc) || !this.isSupported()) {
  20548. return desc;
  20549. }
  20550. var session = transform.parse(desc.sdp);
  20551. var self = this;
  20552. processVideo(session, function (mLine) {
  20553. // Initialize native simulcast layers, if not already done.
  20554. self._maybeInitializeLayers(mLine);
  20555. // Update the SDP with the simulcast layers.
  20556. self._restoreSimulcastView(mLine);
  20557. });
  20558. return new RTCSessionDescription({
  20559. type: desc.type,
  20560. sdp: transform.write(session)
  20561. });
  20562. };
  20563. //endregion
  20564. module.exports = Simulcast;
  20565. },{"./transform-utils":74,"sdp-transform":76}],74:[function(require,module,exports){
  20566. /* Copyright @ 2015 Atlassian Pty Ltd
  20567. *
  20568. * Licensed under the Apache License, Version 2.0 (the "License");
  20569. * you may not use this file except in compliance with the License.
  20570. * You may obtain a copy of the License at
  20571. *
  20572. * http://www.apache.org/licenses/LICENSE-2.0
  20573. *
  20574. * Unless required by applicable law or agreed to in writing, software
  20575. * distributed under the License is distributed on an "AS IS" BASIS,
  20576. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20577. * See the License for the specific language governing permissions and
  20578. * limitations under the License.
  20579. */
  20580. exports.writeSsrcs = function(sources, order) {
  20581. var ssrcs = [];
  20582. // expand sources to ssrcs
  20583. if (typeof sources !== 'undefined' &&
  20584. Object.keys(sources).length !== 0) {
  20585. if (Array.isArray(order)) {
  20586. for (var i = 0; i < order.length; i++) {
  20587. var ssrc = order[i];
  20588. var source = sources[ssrc];
  20589. Object.keys(source).forEach(function (attribute) {
  20590. ssrcs.push({
  20591. id: ssrc,
  20592. attribute: attribute,
  20593. value: source[attribute]
  20594. });
  20595. });
  20596. }
  20597. } else {
  20598. Object.keys(sources).forEach(function (ssrc) {
  20599. var source = sources[ssrc];
  20600. Object.keys(source).forEach(function (attribute) {
  20601. ssrcs.push({
  20602. id: ssrc,
  20603. attribute: attribute,
  20604. value: source[attribute]
  20605. });
  20606. });
  20607. });
  20608. }
  20609. }
  20610. return ssrcs;
  20611. };
  20612. exports.parseSsrcs = function (mLine) {
  20613. var sources = {};
  20614. // group sources attributes by ssrc.
  20615. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20616. mLine.ssrcs.forEach(function (ssrc) {
  20617. if (!sources[ssrc.id])
  20618. sources[ssrc.id] = {};
  20619. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20620. });
  20621. }
  20622. return sources;
  20623. };
  20624. },{}],75:[function(require,module,exports){
  20625. arguments[4][69][0].apply(exports,arguments)
  20626. },{"dup":69}],76:[function(require,module,exports){
  20627. arguments[4][70][0].apply(exports,arguments)
  20628. },{"./parser":77,"./writer":78,"dup":70}],77:[function(require,module,exports){
  20629. arguments[4][71][0].apply(exports,arguments)
  20630. },{"./grammar":75,"dup":71}],78:[function(require,module,exports){
  20631. arguments[4][72][0].apply(exports,arguments)
  20632. },{"./grammar":75,"dup":72}],79:[function(require,module,exports){
  20633. var MediaStreamType = {
  20634. VIDEO_TYPE: "Video",
  20635. AUDIO_TYPE: "Audio"
  20636. };
  20637. module.exports = MediaStreamType;
  20638. },{}],80:[function(require,module,exports){
  20639. var RTCEvents = {
  20640. RTC_READY: "rtc.ready",
  20641. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20642. LASTN_CHANGED: "rtc.lastn_changed",
  20643. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20644. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20645. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20646. };
  20647. module.exports = RTCEvents;
  20648. },{}],81:[function(require,module,exports){
  20649. var Resolutions = {
  20650. "1080": {
  20651. width: 1920,
  20652. height: 1080,
  20653. order: 7
  20654. },
  20655. "fullhd": {
  20656. width: 1920,
  20657. height: 1080,
  20658. order: 7
  20659. },
  20660. "720": {
  20661. width: 1280,
  20662. height: 720,
  20663. order: 6
  20664. },
  20665. "hd": {
  20666. width: 1280,
  20667. height: 720,
  20668. order: 6
  20669. },
  20670. "960": {
  20671. width: 960,
  20672. height: 720,
  20673. order: 5
  20674. },
  20675. "640": {
  20676. width: 640,
  20677. height: 480,
  20678. order: 4
  20679. },
  20680. "vga": {
  20681. width: 640,
  20682. height: 480,
  20683. order: 4
  20684. },
  20685. "360": {
  20686. width: 640,
  20687. height: 360,
  20688. order: 3
  20689. },
  20690. "320": {
  20691. width: 320,
  20692. height: 240,
  20693. order: 2
  20694. },
  20695. "180": {
  20696. width: 320,
  20697. height: 180,
  20698. order: 1
  20699. }
  20700. };
  20701. module.exports = Resolutions;
  20702. },{}],82:[function(require,module,exports){
  20703. var XMPPEvents = {
  20704. // Designates an event indicating that the connection to the XMPP server
  20705. // failed.
  20706. CONNECTION_FAILED: "xmpp.connection.failed",
  20707. // Designates an event indicating that the media (ICE) connection was
  20708. // interrupted. This should go to the RTC module.
  20709. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20710. // Designates an event indicating that the media (ICE) connection was
  20711. // restored. This should go to the RTC module.
  20712. CONNECTION_RESTORED: "xmpp.connection.restored",
  20713. // Designates an event indicating that an offer (e.g. Jingle
  20714. // session-initiate) was received.
  20715. CALL_INCOMING: "xmpp.callincoming.jingle",
  20716. // Designates an event indicating that we were kicked from the XMPP MUC.
  20717. KICKED: "xmpp.kicked",
  20718. // Designates an event indicating that the userID for a specific JID has
  20719. // changed.
  20720. // Note: currently this event fires every time we receive presence from
  20721. // someone (regardless of whether or not the "userID" changed).
  20722. USER_ID_CHANGED: "xmpp.user_id_changed",
  20723. // Designates an event indicating that we have joined the XMPP MUC.
  20724. MUC_JOINED: "xmpp.muc_joined",
  20725. // Designates an event indicating that a participant joined the XMPP MUC.
  20726. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20727. // Designates an event indicating that a participant left the XMPP MUC.
  20728. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20729. // Designates an event indicating that the MUC role of a participant has
  20730. // changed.
  20731. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20732. // Designates an event indicating that the XMPP MUC was destroyed.
  20733. MUC_DESTROYED: "xmpp.muc_destroyed",
  20734. // Designates an event indicating that the display name of a participant
  20735. // has changed.
  20736. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20737. // Designates an event indicating that we received statistics from a
  20738. // participant in the MUC.
  20739. REMOTE_STATS: "xmpp.remote_stats",
  20740. // Designates an event indicating that our role in the XMPP MUC has changed.
  20741. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20742. // Designates an event indicating that the subject of the XMPP MUC has
  20743. // changed.
  20744. SUBJECT_CHANGED: "xmpp.subject_changed",
  20745. // Designates an event indicating that an XMPP message in the MUC was
  20746. // received.
  20747. MESSAGE_RECEIVED: "xmpp.message_received",
  20748. // Designates an event indicating that we sent an XMPP message to the MUC.
  20749. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20750. // Designates an event indicating that the video type (e.g. 'camera' or
  20751. // 'screen') for a participant has changed.
  20752. // Note: currently this event fires every time we receive presence from
  20753. // someone (regardless of whether or not the "video type" changed).
  20754. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20755. // Designates an event indicating that a participant in the XMPP MUC has
  20756. // advertised that they have audio muted (or unmuted).
  20757. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20758. // Designates an event indicating that a participant in the XMPP MUC has
  20759. // advertised that they have video muted (or unmuted).
  20760. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20761. // Designates an event indicating that the focus has asked us to mute our
  20762. // audio.
  20763. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20764. // Designates an event indicating that a moderator in the room changed the
  20765. // "start muted" settings for the conference.
  20766. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20767. // Designates an event indicating that we should join the conference with
  20768. // audio and/or video muted.
  20769. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20770. // Designates an event indicating that a remote participant's available
  20771. // devices (whether he supports a audio and/or video) changed.
  20772. // Note: currently this event fires every time we receive presence from
  20773. // someone (regardless of whether or not the devices changed).
  20774. DEVICE_AVAILABLE: "xmpp.device_available",
  20775. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20776. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20777. PASSWORD_REQUIRED: "xmpp.password_required",
  20778. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20779. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20780. ETHERPAD: "xmpp.etherpad",
  20781. BRIDGE_DOWN: "xmpp.bridge_down",
  20782. PRESENCE_STATUS: "xmpp.presence_status",
  20783. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20784. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20785. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20786. // TODO: only used in a hack, should probably be removed.
  20787. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20788. // TODO: only used in a hack, should probably be removed.
  20789. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20790. // TODO: only used in a hack, should probably be removed.
  20791. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20792. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20793. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20794. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20795. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20796. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20797. // xmpp is connected and obtained user media
  20798. READY_TO_JOIN: 'xmpp.ready_to_join',
  20799. FOCUS_LEFT: "xmpp.focus_left",
  20800. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  20801. /**
  20802. * Indicates that recording state changed.
  20803. */
  20804. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  20805. /**
  20806. * Indicates that phone number changed.
  20807. */
  20808. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  20809. };
  20810. module.exports = XMPPEvents;
  20811. },{}],83:[function(require,module,exports){
  20812. var AuthenticationEvents = {
  20813. /**
  20814. * Event callback arguments:
  20815. * function(authenticationEnabled, userIdentity)
  20816. * authenticationEnabled - indicates whether authentication has been enabled
  20817. * in this session
  20818. * userIdentity - if user has been logged in then it contains user name. If
  20819. * contains 'null' or 'undefined' then user is not logged in.
  20820. */
  20821. IDENTITY_UPDATED: "authentication.identity_updated"
  20822. };
  20823. module.exports = AuthenticationEvents;
  20824. },{}],84:[function(require,module,exports){
  20825. var DesktopSharingEventTypes = {
  20826. INIT: "ds.init",
  20827. SWITCHING_DONE: "ds.switching_done",
  20828. NEW_STREAM_CREATED: "ds.new_stream_created",
  20829. /**
  20830. * An event which indicates that the jidesha extension for Firefox is
  20831. * needed to proceed with screen sharing, and that it is not installed.
  20832. */
  20833. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20834. };
  20835. module.exports = DesktopSharingEventTypes;
  20836. },{}],85:[function(require,module,exports){
  20837. module.exports = {
  20838. /**
  20839. * An event carrying connection statistics.
  20840. */
  20841. CONNECTION_STATS: "statistics.connectionstats",
  20842. /**
  20843. * FIXME: needs documentation.
  20844. */
  20845. AUDIO_LEVEL: "statistics.audioLevel",
  20846. /**
  20847. * FIXME: needs documentation.
  20848. */
  20849. STOP: "statistics.stop"
  20850. };
  20851. },{}],86:[function(require,module,exports){
  20852. var Constants = {
  20853. LOCAL_JID: 'local'
  20854. };
  20855. module.exports = Constants;
  20856. },{}],87:[function(require,module,exports){
  20857. arguments[4][82][0].apply(exports,arguments)
  20858. },{"dup":82}]},{},[7])(7)
  20859. });